Beispiel #1
0
        public static bool CodigoExiste(string qryStr)
        {
            try
            {
                OpenConection();
                command = new FbCommand(qryStr, conexao);
                Reader = command.ExecuteReader();

                if(Reader.HasRows)
                    FlExiste= true;
                else
                    FlExiste= false;

                Reader.Close();

            }
            catch (Exception Ex)
            {
                throw new Exception(Ex.Message.ToString());
            }
            finally
            {
                CloseConection();
            }
            return FlExiste;
        }
		public CommandExecutedEventArgs(FbDataReader dataReader, string commandText, SqlStatementType statementType, int rowsAffected)
		{
			DataReader = dataReader;
			CommandText = commandText;
			StatementType = statementType;
			RowsAffected = rowsAffected;
		}
Beispiel #3
0
		private Granja ReaderToEntidad(FbDataReader AReader){
			Granja pResult = new Granja();
			pResult.Clave  = (int)AReader["CLAVE"];
			pResult.Nombre = (string)AReader["NOMBRE"];
			
			return pResult;
		}
		private Destino ReaderToEntidad(FbDataReader AReader){
			Destino pResult = new Destino();
			pResult.Clave  = (int)AReader["CLAVE"];
			pResult._Destino = (string)AReader["DESTINO"];
			
			return pResult;
		}
 private static string stringify(FbDataReader reader, string parentnodename)
 {
     StringBuilder json = new StringBuilder();
     int columns = reader.FieldCount;
     if (parentnodename.Length > 0) { json.AppendFormat("{{\"{0}\":", parentnodename); }
     while (reader.Read())
     {
         for (int i = 0; i < columns; i++)
         {
             if (i % reader.FieldCount == 0) { json.Append("{"); }
             json.AppendFormat("\"{0}\":{1},", reader.GetName(i).ToLower(), jsonify(reader.GetValue(i)));
             if (i % reader.FieldCount == reader.FieldCount - 1)
             {
                 json.Remove(json.Length - 1, 1);
                 json.Append("},");
             }
         }
     }
     // if nothing (or only the parentnodename is appended to the string builder then the reader was empty and we return nothing. reader.HasRows doesn't work
     if (json.Length == 0 || json.ToString() == string.Format("{{\"{0}\":", parentnodename)) { return ""; }
     json.Remove(json.Length - 1, 1);
     if (parentnodename.Length > 0) { json.Append("}"); }
     // check if the json should contain an array and add array structure if true
     if (Regex.IsMatch(json.ToString(), "},{"))
     {
         json.Insert((parentnodename.Length > 0 ? parentnodename.Length + 4 : 4), "[");
         json.Insert(json.Length - 1, "]");
     }
     return json.ToString();
 }
 private ClasificacionCorte ReaderToEntidad(FbDataReader AReader)
 {
     ClasificacionCorte pResult = new ClasificacionCorte();
     pResult.Id          = (int)AReader["ID"];
     pResult.Descripcion = AReader["DESCRIPCION"] != DBNull.Value ? (string)AReader["DESCRIPCION"] : "";
     pResult.Lotes       = AReader["LOTES"] != DBNull.Value? (string)AReader["LOTES"] : "";
     return pResult;
 }
 private Categoria ReaderToEntidad(FbDataReader AReader)
 {
     Categoria pResult = new Categoria();
     pResult.Id = (int)AReader["ID"];
     pResult.Cat = AReader["CATEGORIA"] != DBNull.Value ? (string)AReader["CATEGORIA"] : "";
     pResult.Activo = AReader["ACTIVO"] != DBNull.Value ? (string)AReader["ACTIVO"] : "";
     return pResult;
 }
 public override void FieldsFromReader(FbDataReader R)
 {
     ID = Guid.Parse(R["ID"].ToString());
     Code = Int32.Parse(R["Code"].ToString());
     Day_Start = DateTime.Parse(R["Day_Start"].ToString());
     Day_End = DateTime.Parse(R["Day_End"].ToString());
     Working_days = R["Working_days"].ToString();
     Id_Employers.SelectOne(Guid.Parse(R["Id_Employers"].ToString()));
 }
 /// <summary>
 /// Creates an instance of CommandExecutedEventArgs class.
 /// </summary>
 /// <param name="dataReader"></param>
 /// <param name="commandText">The CommandText of the <see cref="FbCommand"/> that was executed.</param>
 /// <param name="rowsAffected"></param>
 public CommandExecutedEventArgs(
     FbDataReader dataReader,
     string commandText,
     int rowsAffected)
 {
     this.dataReader = dataReader;
     this.commandText = commandText;
     this.rowsAffected = rowsAffected;
 }
 private ClaseOrdenProduccion ReaderToEntidad(FbDataReader AReader)
 {
     ClaseOrdenProduccion pResult = new ClaseOrdenProduccion();
     pResult.Id = (int)AReader["ID"];
     pResult.Clase   = AReader["CLASE"] != DBNull.Value ? (string)AReader["CLASE"] : "";
     pResult.Activo  = AReader["ACTIVO"] != DBNull.Value ? (string)AReader["ACTIVO"] : "";
     pResult.OcrCode = AReader["OCRCODE"] != DBNull.Value ? (string)AReader["OCRCODE"] : "";
     return pResult;
 }
Beispiel #11
0
 public override void FieldsFromReader(FbDataReader R)
 {
     ID = Guid.Parse(R["ID"].ToString());
     Code = Int32.Parse(R["Code"].ToString());
     Name = R["Name"].ToString();
     Task = R["TASK"].ToString();
     Start_Date = DateTime.Parse(R["START_DATE"].ToString());
     Deadline = DateTime.Parse(R["DEADLINE"].ToString());
 }
Beispiel #12
0
        ///    <summary>
        /// Converts a FbDataReader to a DataSet
        ///    <param name='reader'>
        /// SqlDataReader to convert.</param>
        ///    <returns>
        /// DataSet filled with the contents of the reader.</returns>
        ///    </summary>
        public static DataSet convertDataReaderToDataSet(FbDataReader reader)
        {
            DataSet dataSet = new DataSet();
            do
            {
                // Create new data table

                DataTable schemaTable = reader.GetSchemaTable();
                DataTable dataTable = new DataTable();

                if (schemaTable != null)
                {
                    // A query returning records was executed

                    for (int i = 0; i < schemaTable.Rows.Count; i++)
                    {
                        DataRow dataRow = schemaTable.Rows[i];
                        // Create a column name that is unique in the data table
                        string columnName = (string)dataRow["ColumnName"]; //+ "<C" + i + "/>";
                        // Add the column definition to the data table
                        DataColumn column = new DataColumn(columnName, (Type)dataRow["DataType"]);
                        dataTable.Columns.Add(column);
                    }

                    dataSet.Tables.Add(dataTable);

                    // Fill the data table we just created

                    while (reader.Read())
                    {
                        DataRow dataRow = dataTable.NewRow();

                        for (int i = 0; i < reader.FieldCount; i++)
                            dataRow[i] = reader.GetValue(i);

                        dataTable.Rows.Add(dataRow);
                    }
                }
                else
                {
                    // No records were returned

                    DataColumn column = new DataColumn("RowsAffected");
                    dataTable.Columns.Add(column);
                    dataSet.Tables.Add(dataTable);
                    DataRow dataRow = dataTable.NewRow();
                    dataRow[0] = reader.RecordsAffected;
                    dataTable.Rows.Add(dataRow);
                }
            }
            while (reader.NextResult());
            return dataSet;
        }
        /// <summary>
        /// Lists tables 
        /// </summary>
        /// <returns>List of tables matching tablename-spec</returns>
        public List<string> GetListOfTables()
        {
            List<string> tableList = new List<string>();

            cmd = new FbCommand("select rdb$relation_name from rdb$relations where rdb$view_blr is null and (rdb$system_flag is null or rdb$system_flag = 0);", connection);
            reader = cmd.ExecuteReader();
            while (reader.Read())
            {
                tableList.Add(reader.GetString(0));
            }
            reader.Close();

            return tableList;
        }
Beispiel #14
0
        public FbDataReader StartQuery(String query)
        {
            error = 0;
                try
                {
                    //так проверять состояние соединения (активно или не активно)
                    if (fb.State == ConnectionState.Closed)
                        fb.Open();

                    FbTransaction fbt = fb.BeginTransaction(); //стартуем транзакцию; стартовать транзакцию можно только для открытой базы (т.е. мутод Open() уже был вызван ранее, иначе ошибка)

                    SelectSQL = new FbCommand(query, fb);//"SELECT * FROM CAT", fb); //задаем запрос на выборку

                    SelectSQL.Transaction = fbt; //необходимо проинициализить транзакцию для объекта SelectSQL
                    reader = SelectSQL.ExecuteReader(); //для запросов, которые возвращают результат в виде набора данных надо использоваться метод ExecuteReader()

                    return reader;
                }
                catch (Exception ex)
                {
                    error = 1;
                    MessageBox.Show(ex.Message);
                }
                return reader;
        }
 private UsuarioBascula ReaderToEntidad(FbDataReader AReader)
 {
     UsuarioBascula pResult = new UsuarioBascula();
     pResult.CLAVE          = AReader.GetInt32(0);
     pResult.NOMBRE         = AReader.GetString(1);
     pResult.CONTRASENA     = AReader.GetString(2);
     pResult.TITULAR        = AReader.GetString(3);
     pResult.LOTES          = AReader.GetString(4);
     return pResult;
 }
Beispiel #16
0
 public Tasks(FbDataReader R)
     : this()
 {
     FieldsFromReader(R);
 }
Beispiel #17
0
        private void Button_Click_7(object sender, RoutedEventArgs e)
        {
            if (MessageBox.Show(
                    "Сейчас будет загружена техника, принадлежащая заказу. Все раннее выбранные аксессуары и техника будут очищены. Продолжить?",
                    "Важно",
                    MessageBoxButton.YesNo,
                    MessageBoxImage.Warning) == MessageBoxResult.Yes)
            {
                object xamb        = neqqqqq.getParam(neqqqqq.Ambiente, "GetObject", "XAMB");
                object info        = neqqqqq.getParamG(xamb, "INFO");
                object info2       = neqqqqq.getParamG(info, "INFO");
                string _RIFFABRICA = neqqqqq.getParam(info2, "Var", "_RIFFABRICA").ToString();
                if (_RIFFABRICA == "")
                {
                    MessageBox.Show("Заказу не присвоен фабричный номер");
                }
                else
                {
                    log.Add("номер заказа на фабрике = " + _RIFFABRICA);
                    nom_PP = 0;
                    List <texnika> importlist = new List <texnika>();

                    FbConnectionStringBuilder fb_con = new FbConnectionStringBuilder();
                    fb_con.Charset    = "WIN1251";                                   //используемая кодировка
                    fb_con.UserID     = "sysdba";                                    //логин
                    fb_con.Password   = "******";                                    //пароль
                    fb_con.Database   = "172.16.6.155:/usr/interbase/db/resurs.gdb"; //путь к файлу базы данных
                    fb_con.ServerType = 0;                                           //указываем тип сервера (0 - "полноценный Firebird" (classic или super server), 1 - встроенный (embedded))

                    //создаем подключение
                    var fb = new FbConnection(fb_con.ToString()); //передаем нашу строку подключения объекту класса FbConnection

                    fb.Open();                                    //открываем БД



                    if (fb.State == ConnectionState.Closed)
                    {
                        fb.Open();
                    }

                    FbTransaction fbt = fb.BeginTransaction();                                                                                   //стартуем транзакцию; стартовать транзакцию можно только для открытой базы (т.е. мутод Open() уже был вызван ранее, иначе ошибка)

                    FbCommand SelectSQL = new FbCommand("SELECT * FROM CCUSTOMTEXNICS WHERE CUSTOMID=" + _RIFFABRICA + " order by POZ asc", fb); //задаем запрос на выборку

                    SelectSQL.Transaction = fbt;                                                                                                 //необходимо проинициализить транзакцию для объекта SelectSQL
                    FbDataReader reader = SelectSQL.ExecuteReader();                                                                             //для запросов, которые возвращают результат в виде набора данных надо использоваться метод ExecuteReader()


                    while (reader.Read()) //пока не прочли все данные выполняем...
                    {
                        float baseprice = 0;
                        if (reader["WPRICE"].ToString() != "")
                        {
                            baseprice = Convert.ToSingle(reader["WPRICE"].ToString());
                        }

                        int nompp = Convert.ToInt32(reader["POZ"].ToString());

                        //MessageBox.Show(reader["SALONNUMBER"].ToString());
                        importlist.Add(new texnika()
                        {
                            type       = "t",
                            ID         = reader["TPriceID"].ToString(),
                            TName      = reader["NAME"].ToString(),
                            Article    = reader["ARTICLE"].ToString(),
                            UnitsId    = "шт",
                            baseprice  = baseprice,
                            priceredak = baseprice,
                            UnitsName  = "3",
                            Prim       = "",
                            kolvo      = Convert.ToInt32(reader["CNT"].ToString()),
                            OTD        = "",
                            nom_pp     = nompp,


                            //                    GroupName = reader["TexType"].ToString(),
                            //                  Group = reader["TexID"].ToString(),
                            // sort = sort,
                            GROUP_dlyaspicif = "",// reader["TKOEFGROUP_ID"].ToString(),
                        });
                        // MessageBox.Show(reader["CNT"].ToString()+""+ reader["WPRICE"].ToString());

                        if (nom_PP < nompp)
                        {
                            nom_PP = nompp;
                        }

                        //  Grid_select(texnika);
                    }



                    SelectSQL.Dispose(); //в документации написано, что ОЧЕНЬ рекомендуется убивать объекты этого типа, если они больше не нужны
                    fb.Close();


                    //  MessageBox.Show(str_sobr(importlist));
                    pars(str_sobr(importlist));
                }
            }
        }
        private void Ekle_Click(object sender, EventArgs e)
        {
            try
            {
                if ((marka.Text != "" && model.Text != "") && ((imei.Text != "" && imei.Text.Length > 14) || (serino.Text != "")))
                {
                    marka.Text  = marka.Text.Replace("'", "’");
                    model.Text  = model.Text.Replace("'", "’");
                    serino.Text = serino.Text.Replace("'", "’");
                    musadi.Text = musadi.Text.Replace("'", "’");
                    FbConnection baglan  = new FbConnection(fk.Baglanti_Kodu());
                    FbConnection baglan1 = new FbConnection(fk.Baglanti_Kodu());
                    FbConnection baglan2 = new FbConnection(fk.Baglanti_Kodu());
                    FbConnection baglan3 = new FbConnection(fk.Baglanti_Kodu());

                    if (uyeMi.Checked == true)
                    {//üye
                        baglan.Open();
                        FbCommand TakipSor   = new FbCommand("select * from teknik_takip where takip_imei='" + imei.Text + "' or takip_serino='" + serino.Text + "'", baglan);
                        object    TakipVarMi = TakipSor.ExecuteScalar();
                        baglan.Close();
                        if (TakipVarMi == null)
                        {
                            //takibi ekle..
                            baglan.Open();
                            string[]  ads        = musteri.Text.Split(' ');
                            FbCommand MusidSql   = new FbCommand("SELECT Musteri_id FROM Musteriler WHERE Musteri_adi='" + ads[0] + "' and Musteri_soyadi='" + ads[1] + "'", baglan);
                            object    MusKontrol = MusidSql.ExecuteScalar();
                            if (MusKontrol != null)
                            {
                                FbDataReader MusidOku = MusidSql.ExecuteReader(); MusidOku.Read();
                                id = MusidOku["Musteri_id"].ToString();
                                string tarih = DateTime.Now.Year.ToString() + "-" + DateTime.Now.Month.ToString() + "-" + DateTime.Now.Day.ToString();
                                byte   sonuc;
                                sonuc = fk.Ekle("Teknik_Takip", "Takip_no,Takip_musteri,Takip_marka,Takip_model,Takip_imei,Takip_serino,Takip_girisTarih,Takip_durum", "'" + TakipNo + "','" + id + "','" + fk.IlkHarfleriBuyut(marka.Text) + "','" + fk.IlkHarfleriBuyut(model.Text) + "','" + imei.Text + "','" + serino.Text + "','" + tarih + "','1'");
                                if (sonuc == 1)
                                {
                                    MessageBox.Show("Takip başarıyla eklenmiştir", "Bilgilendirme", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                    Random rnd   = new Random();
                                    double sayi  = rnd.Next(0, 99999);
                                    double sayi2 = rnd.Next(0, 99999);
                                    takipno.Text = "TKP" + sayi.ToString() + sayi2.ToString();
                                    TakipNo      = takipno.Text;
                                }
                                else
                                {
                                    MessageBox.Show("Takip eklenemedi ( Hata kodu: T-01 )", "Bilgilendirme", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                }
                            }
                            else
                            {
                                MessageBox.Show("Sistemsel bir hata oluştu, lütfen sağlayıcınıza başvurunuz.", "Bilgilendirme", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                            }
                            baglan.Close();
                        }
                        else
                        {
                            DialogResult Sor = MessageBox.Show("Eklemek istediğiniz cihaz sistemde kayıtlıdır, yeni takip açmak istediğinize emin misiniz?", "Takip Eklensin Mi ?", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                            if (Sor == DialogResult.Yes)
                            {//ekle
                                baglan.Open();
                                string[]  ads        = musteri.Text.Split(' ');
                                FbCommand MusidSql   = new FbCommand("SELECT Musteri_id FROM Musteriler WHERE Musteri_adi='" + ads[0] + "' and Musteri_soyadi='" + ads[1] + "'", baglan);
                                object    MusKontrol = MusidSql.ExecuteScalar();
                                if (MusKontrol != null)
                                {
                                    FbDataReader MusidOku = MusidSql.ExecuteReader(); MusidOku.Read();
                                    id = MusidOku["Musteri_id"].ToString();
                                    string tarih = DateTime.Now.Year.ToString() + "-" + DateTime.Now.Month.ToString() + "-" + DateTime.Now.Day.ToString();
                                    byte   sonuc;
                                    sonuc = fk.Ekle("Teknik_Takip", "Takip_no,Takip_musteri,Takip_marka,Takip_model,Takip_imei,Takip_serino,Takip_girisTarih,Takip_durum", "'" + TakipNo + "','" + id + "','" + fk.IlkHarfleriBuyut(marka.Text) + "','" + fk.IlkHarfleriBuyut(model.Text) + "','" + imei.Text + "','" + serino.Text + "','" + tarih + "','1'");
                                    if (sonuc == 1)
                                    {
                                        MessageBox.Show("Takip başarıyla eklenmiştir", "Bilgilendirme", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                        Random rnd   = new Random();
                                        double sayi  = rnd.Next(0, 99999);
                                        double sayi2 = rnd.Next(0, 99999);
                                        takipno.Text = "TKP" + sayi.ToString() + sayi2.ToString();
                                        TakipNo      = takipno.Text;
                                    }
                                    else
                                    {
                                        MessageBox.Show("Takip eklenemedi ( Hata kodu: T-01 )", "Bilgilendirme", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                    }
                                }
                                else
                                {
                                    MessageBox.Show("Sistemsel bir hata oluştu, lütfen sağlayıcınıza başvurunuz.", "Bilgilendirme", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                                }
                                baglan.Close();
                            }
                            else
                            {//ekleme
                            }
                        }
                    }
                    else
                    {//üye değil
                        if (musadi.Text != "" && musTel.Text != "")
                        {
                            baglan.Open();
                            FbCommand TakipSor   = new FbCommand("select * from teknik_takip where takip_imei='" + imei.Text + "' or takip_serino='" + serino.Text + "'", baglan);
                            object    TakipVarMi = TakipSor.ExecuteScalar();
                            baglan.Close();
                            if (TakipVarMi == null)
                            {//ekle
                                // ekle
                                byte   sonuc;
                                string tarih = DateTime.Now.Year.ToString() + "-" + DateTime.Now.Month.ToString() + "-" + DateTime.Now.Day.ToString();

                                sonuc = fk.Ekle("Teknik_Takip", "Takip_no,Takip_marka,Takip_model,Takip_imei,Takip_serino,Takip_girisTarih,Takip_durum,Takip_kisibilgi,Takip_kisiTel", "'" + TakipNo + "','" + fk.IlkHarfleriBuyut(marka.Text) + "','" + fk.IlkHarfleriBuyut(model.Text) + "','" + imei.Text + "','" + serino.Text + "','" + tarih + "','1','" + fk.IlkHarfleriBuyut(musadi.Text) + "','" + musTel.Text + "'");
                                if (sonuc == 1)
                                {
                                    MessageBox.Show("Takip başarıyla eklenmiştir", "Bilgilendirme", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                    Random rnd   = new Random();
                                    double sayi  = rnd.Next(0, 99999);
                                    double sayi2 = rnd.Next(0, 99999);
                                    takipno.Text = "TKP" + sayi.ToString() + sayi2.ToString();
                                    TakipNo      = takipno.Text;
                                }
                                else
                                {
                                    MessageBox.Show("Takip eklenemedi ( Hata kodu: T-01 )", "Bilgilendirme", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                }
                            }
                            else
                            {//sor
                                DialogResult Sor = MessageBox.Show("Eklemek istediğiniz cihaz sistemde kayıtlıdır, yeni takip açmak istediğinize emin misiniz?", "Takip Eklensin Mi ?", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                                if (Sor == DialogResult.Yes)
                                {//ekle
                                    // ekle
                                    byte   sonuc;
                                    string tarih = DateTime.Now.Year.ToString() + "-" + DateTime.Now.Month.ToString() + "-" + DateTime.Now.Day.ToString();

                                    sonuc = fk.Ekle("Teknik_Takip", "Takip_no,Takip_marka,Takip_model,Takip_imei,Takip_serino,Takip_girisTarih,Takip_durum,Takip_kisibilgi,Takip_kisiTel", "'" + TakipNo + "','" + fk.IlkHarfleriBuyut(marka.Text) + "','" + fk.IlkHarfleriBuyut(model.Text) + "','" + imei.Text + "','" + serino.Text + "','" + tarih + "','1','" + fk.IlkHarfleriBuyut(musadi.Text) + "','" + musTel.Text + "'");
                                    if (sonuc == 1)
                                    {
                                        MessageBox.Show("Takip başarıyla eklenmiştir", "Bilgilendirme", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                        Random rnd   = new Random();
                                        double sayi  = rnd.Next(0, 99999);
                                        double sayi2 = rnd.Next(0, 99999);
                                        takipno.Text = "TKP" + sayi.ToString() + sayi2.ToString();
                                        TakipNo      = takipno.Text;
                                    }
                                    else
                                    {
                                        MessageBox.Show("Takip eklenemedi ( Hata kodu: T-01 )", "Bilgilendirme", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                    }
                                }
                                else
                                {//ekleme
                                }
                            }
                        }
                        else
                        {
                            MessageBox.Show("Müşteri bilgilerini eksiksiz giriniz ( Hata kodu: T-03 )", "Bilgilendirme", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                }
                else
                {
                    MessageBox.Show("Cihaz Bilgilerini eksiksiz giriniz ( Hata kodu: T-02 )", "Bilgilendirme", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception e3)
            {
                MessageBox.Show(e3.Message, "Hata", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Beispiel #19
0
        protected override void Dispose(bool disposing)
        {
            lock (this)
            {
                if (!this.disposed)
                {
                    try
                    {
                        // Release any unmanaged resources
                        this.Release();

                        // release any managed resources
                        this.commandTimeout = 0;
                        this.fetchSize = 0;
                        this.implicitTransaction = false;
                        this.commandText = null;
                        this.connection = null;
                        this.transaction = null;
                        this.parameters = null;
                        this.statement = null;
                        this.activeReader = null;

                        if (this.namedParameters != null)
                        {
                            this.namedParameters.Clear();
                            this.namedParameters = null;
                        }

                        this.disposed = true;
                    }
                    finally
                    {
                        base.Dispose(disposing);
                    }
                }
            }
        }
    protected void Page_Load(object sender, EventArgs e)
    {
        if ((Session["Grupo"] == null) ||
            (Session["CodigoUsuario"] == null))
        {
            Response.Redirect("~/Login.aspx");
        }

        if (Request.QueryString["ID"].ToString() != String.Empty)
        {
            string strID = Request.QueryString["ID"].ToString();

            StringBuilder str = new StringBuilder();
            str.Append("SELECT LANCREL.NR_LANC, LANCREL.DT_REL, LANCREL.NM_CONTATO, ");
            str.Append("LANCREL.CD_CLIENTE, LANCREL.CD_OPERADO, ");
            str.Append("LANCREL.CD_SISTEMA, LANCREL.CD_TIPOREL, ");
            str.Append("LANCREL.ST_FATURA, LANCREL.HR_ENTRADA, ");
            str.Append("LANCREL.HR_DESCONTO, LANCREL.HR_TOTAL, LANCREL.HR_SAIDA, ");
            str.Append("LANCREL.NM_GUERRA, LANCREL.DS_OBS, ACESSO.NM_OPERADO, SISTEMA.DS_SISTEMA, ST_MAQ, DS_MAQUINA ");
            str.Append("FROM LANCREL ");
            str.Append("INNER JOIN ACESSO ON (ACESSO.CD_OPERADO = LANCREL.CD_OPERADO) ");
            str.Append("LEFT JOIN SISTEMA ON (SISTEMA.CD_SISTEMA = LANCREL.CD_SISTEMA) ");
            str.Append("WHERE (NR_LANC = '" + strID + "')");

            FbCommand cmdSelect = (FbCommand)HlpBancoDados.CommandSelect(str.ToString());
            cmdSelect.Connection.Open();

            FbDataReader drVisita = cmdSelect.ExecuteReader();

            DataTable dtVisita = new DataTable("ConsultaVisita");

            dtVisita.Columns.Add("NR_LANC");
            dtVisita.Columns.Add("HR_ENTRADA");
            dtVisita.Columns.Add("HR_SAIDA");
            dtVisita.Columns.Add("HR_DESCONTO");
            dtVisita.Columns.Add("NM_GUERRA");
            dtVisita.Columns.Add("DT_REL");
            dtVisita.Columns.Add("NM_OPERADO");
            dtVisita.Columns.Add("TITULO");
            dtVisita.Columns.Add("NM_CONTATO");
            dtVisita.Columns.Add("DS_OBS");
            dtVisita.Columns.Add("ST_MAQ");
            dtVisita.Columns.Add("DS_MAQUINA");

            DataRow dr;

            if (drVisita.Read())
            {
                dr                = dtVisita.NewRow();
                dr["NR_LANC"]     = drVisita["NR_LANC"];
                dr["HR_ENTRADA"]  = drVisita["HR_ENTRADA"];
                dr["HR_SAIDA"]    = drVisita["HR_SAIDA"];
                dr["HR_DESCONTO"] = drVisita["HR_DESCONTO"];
                dr["NM_GUERRA"]   = drVisita["NM_GUERRA"];
                dr["DT_REL"]      = GetFormataDataRetorno(drVisita["DT_REL"].ToString());
                dr["NM_OPERADO"]  = drVisita["NM_OPERADO"];
                dr["NM_CONTATO"]  = drVisita["NM_CONTATO"];
                if (drVisita["CD_TIPOREL"].ToString() == "4")
                {
                    dr["TITULO"] = "SOFTWARE";
                }
                else if (drVisita["CD_TIPOREL"].ToString() == "3")
                {
                    dr["TITULO"] = "HARDWARE";
                }

                if (!drVisita["DS_OBS"].ToString().Equals(String.Empty))
                {
                    byte[] bt = (byte[])drVisita["DS_OBS"];
                    dr["DS_OBS"] = ASCIIEncoding.Default.GetString(bt);
                }

                if (!drVisita["DS_MAQUINA"].ToString().Equals(String.Empty))
                {
                    byte[] bt = (byte[])drVisita["DS_MAQUINA"];
                    dr["DS_MAQUINA"] = ASCIIEncoding.Default.GetString(bt);
                }

                if (drVisita["ST_MAQ"].ToString() == "1")
                {
                    dr["ST_MAQ"] = "Máquina em Perfeito Estado";
                }
                else
                {
                    dr["ST_MAQ"] = "Máquina com Problema";
                }

                dtVisita.Rows.Add(dr);
            }

            drVisita.Close();
            cmdSelect.Connection.Close();

            StringBuilder strOs = new StringBuilder();
            strOs.Append("SELECT CD_OS, NR_LANC FROM ITLANCREL ");
            strOs.Append("WHERE (NR_LANC = '" + strID + "') ORDER BY CD_OS");

            FbCommand cmdOs = (FbCommand)HlpBancoDados.CommandSelect(strOs.ToString());

            cmdOs.Connection.Open();

            FbDataReader drOs = cmdOs.ExecuteReader();

            DataTable dtOs = new DataTable("OS");
            dtOs.Columns.Add("CD_OS");
            dtOs.Columns.Add("NR_LANCREL");

            DataRow drItensRel;

            while (drOs.Read())
            {
                drItensRel    = dtOs.NewRow();
                drItensRel[0] = drOs[0];
                drItensRel[1] = drOs[1];
                dtOs.Rows.Add(drItensRel);
            }

            drOs.Close();

            cmdOs.Connection.Close();

            rpt.Load(Server.MapPath("crRelVisita.rpt"));
            rpt.SetDataSource(dtVisita);
            rpt.Subreports["crOsRelVisita.rpt"].SetDataSource(dtOs);
            RptVisita.ReportSource = rpt;
            RptVisita.Visible      = true;
        }
    }
        public static List <val> get(string _table, int id, string UserId)
        {
            List <val> b = new List <val> {
            };

            using (ApplicationDbContext db = new ApplicationDbContext())
            {
                FbConnectionStringBuilder fc = new FbConnectionStringBuilder();
                var t = db.tModerator.Where(a => a.tUsers.UserName == UserId);
                if (t.Count() != 0)
                {
                    fc.Database = t.First().tModerator_database;
                    fc.UserID   = t.First().tModerator_userId;
                    fc.Password = t.First().tModerator_password;
                    fc.Pooling  = false;
                    fc.Role     = "R_ADMIN";
                    fc.Charset  = "win1251";

                    using (FbConnection fb = new FbConnection(fc.ConnectionString))
                    {
                        try
                        {
                            fb.Open();
                            using (FbTransaction ft = fb.BeginTransaction())
                            {
                                string com = "";
                                switch (_table)
                                {
                                case "BRANCH":
                                    com = "select id_branch, mnemo from branch order by 2";
                                    break;

                                case "RELEASE_PROJECTS":
                                    com = "select ID_RELEASE_PROJECTS, mnemo from RELEASE_PROJECTS ";
                                    break;

                                case "PROJECTS":
                                    com = "select ID_PROJECTS, mnemo from PROJECTS order by 2";
                                    break;

                                case "SUBSYSTEMS":
                                    com = "select ID_SUBSYSTEM, mnemo from SUBSYSTEMS ";
                                    break;
                                }
                                using (FbCommand fcon = new FbCommand(com, fb, ft))
                                {
                                    switch (_table)
                                    {
                                    case "RELEASE_PROJECTS":
                                        fcon.CommandText += " where id_projects = " + id.ToString() + " order by 2 desc";
                                        break;

                                    case "SUBSYSTEMS":
                                        fcon.CommandText += " where id_projects = " + id.ToString() + " order by 2";
                                        break;
                                    }
                                    using (FbDataReader fr = fcon.ExecuteReader())
                                    {
                                        while (fr.Read())
                                        {
                                            b.Add(new val {
                                                id = (int)fr[0], name = fr[1].ToString()
                                            });
                                        }
                                        fr.Dispose();
                                    }
                                    fcon.Dispose();
                                }
                                ft.Dispose();
                            }
                        }
                        catch
                        {
                            b.Add(new val {
                                id = -1, name = "Не удалось подключиться к БТ"
                            });
                        }
                        finally
                        {
                            fb.Close();
                        }
                        fb.Dispose();
                    }
                    db.Dispose();
                }
                else
                {
                    b.Add(new val {
                        id = -1, name = "Настройте соединение с БТ"
                    });
                }
                return(b);
            }
        }
Beispiel #22
0
        public static FbDataReader qrySeekReader(string sExpressao)
        {
            FbDataReader dr = HlpDbFuncoesGeral.QrySeekReader(HlpDbFuncoesGeral.conexao, sExpressao);

            return(dr);
        }
Beispiel #23
0
        // Yedek alma
        public void YedekAl(string GelenDizin)
        {
            try
            {
                if (GelenDizin == "Standart")
                {
                    FbConnection baglan = new FbConnection(Baglanti_Kodu());
                    // klasör varmı
                    baglan.Open();
                    FbCommand    Cek   = new FbCommand("select yedek_dizin from Ayar", baglan);
                    FbDataReader Oku   = Cek.ExecuteReader(); Oku.Read();
                    string       dizin = Oku["yedek_dizin"].ToString();
                    Oku.Close();
                    baglan.Close();
                    if (dizin == "0" || dizin == "")
                    {
                        dizin = Application.StartupPath + "\\Yedekler";
                        baglan.Open();
                        FbCommand Guncelle = new FbCommand("update Ayar set yedek_dizin='" + dizin + "'", baglan);
                        Guncelle.ExecuteNonQuery();
                        baglan.Close();
                    }

                    if (File.Exists(dizin) == false)
                    {
                        Directory.CreateDirectory(dizin);
                    }
                    izinVer(Environment.UserName, dizin);
                    string Yil = DateTime.Now.Year.ToString();

                    string Ay = DateTime.Now.Month.ToString();

                    string tamTarih = DateTime.Now.ToString("dd-MM-yyyy-h-m-s");
                    if (File.Exists(dizin + "\\" + Yil) == false)
                    {
                        Directory.CreateDirectory(dizin + "\\" + Yil);
                    }
                    izinVer(Environment.UserName, dizin + "\\" + Yil);
                    if (File.Exists(dizin + "\\" + Yil + "\\" + Aylar(byte.Parse(Ay.ToString()))) == false)
                    {
                        Directory.CreateDirectory(dizin + "\\" + Yil + "\\" + Aylar(byte.Parse(Ay.ToString())));
                    }
                    izinVer(Environment.UserName, dizin + "\\" + Yil + "\\" + Aylar(byte.Parse(Ay.ToString())));
                    FbBackup yedekAl = new FbBackup();

                    yedekAl.ConnectionString = baglanti_cumlesi;
                    yedekAl.BackupFiles.Add(new FbBackupFile(dizin + "\\" + Yil + "\\" + Aylar(byte.Parse(Ay.ToString())) + "\\" + tamTarih + ".fbk", 2048));
                    yedekAl.Verbose = true;

                    yedekAl.Options = FbBackupFlags.IgnoreLimbo;

                    yedekAl.Execute();

                    YedekAlmaTarihGuncelle();

                    MessageBox.Show("Yedekleme işlemi yapılmıştır.", "Bilgilendirme", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    string dizin = GelenDizin;

                    if (File.Exists(dizin) == false)
                    {
                        Directory.CreateDirectory(dizin);
                    }

                    string tamTarih = DateTime.Now.ToString("dd-MM-yyyy-h-m-s");

                    FbBackup yedekAl = new FbBackup();

                    yedekAl.ConnectionString = baglanti_cumlesi;
                    yedekAl.BackupFiles.Add(new FbBackupFile(dizin + "\\" + tamTarih + ".fbk", 2048));
                    yedekAl.Verbose = true;

                    yedekAl.Options = FbBackupFlags.IgnoreLimbo;

                    yedekAl.Execute();
                }
            }
            catch (Exception h1)
            {
                MessageBox.Show(h1.Message, "Hata", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Beispiel #24
0
        private static LIS_CLIENTEEntity FillEntityObject(ref FbDataReader DataReader)
        {
            LIS_CLIENTEEntity entity = new LIS_CLIENTEEntity();

            FirebirdGetDbData getData = new FirebirdGetDbData();

            entity.IDCLIENTE              = getData.ConvertDBValueToInt32(DataReader, DataReader.GetOrdinal("IDCLIENTE"));
            entity.NOME                   = getData.ConvertDBValueToStringNullable(DataReader, DataReader.GetOrdinal("NOME"));
            entity.APELIDO                = getData.ConvertDBValueToStringNullable(DataReader, DataReader.GetOrdinal("APELIDO"));
            entity.CONTATO                = getData.ConvertDBValueToStringNullable(DataReader, DataReader.GetOrdinal("CONTATO"));
            entity.DATACADASTRO           = getData.ConvertDBValueToDateTimeNullable(DataReader, DataReader.GetOrdinal("DATACADASTRO"));
            entity.TELEFONE1              = getData.ConvertDBValueToStringNullable(DataReader, DataReader.GetOrdinal("TELEFONE1"));
            entity.TELEFONE2              = getData.ConvertDBValueToStringNullable(DataReader, DataReader.GetOrdinal("TELEFONE2"));
            entity.FAX                    = getData.ConvertDBValueToStringNullable(DataReader, DataReader.GetOrdinal("FAX"));
            entity.RAMAL                  = getData.ConvertDBValueToStringNullable(DataReader, DataReader.GetOrdinal("RAMAL"));
            entity.CNPJ                   = getData.ConvertDBValueToStringNullable(DataReader, DataReader.GetOrdinal("CNPJ"));
            entity.CPF                    = getData.ConvertDBValueToStringNullable(DataReader, DataReader.GetOrdinal("CPF"));
            entity.IE                     = getData.ConvertDBValueToStringNullable(DataReader, DataReader.GetOrdinal("IE"));
            entity.ENDERECO1              = getData.ConvertDBValueToStringNullable(DataReader, DataReader.GetOrdinal("ENDERECO1"));
            entity.COMPLEMENTO1           = getData.ConvertDBValueToStringNullable(DataReader, DataReader.GetOrdinal("COMPLEMENTO1"));
            entity.BAIRRO1                = getData.ConvertDBValueToStringNullable(DataReader, DataReader.GetOrdinal("BAIRRO1"));
            entity.CEP1                   = getData.ConvertDBValueToStringNullable(DataReader, DataReader.GetOrdinal("CEP1"));
            entity.ENDERECO2              = getData.ConvertDBValueToStringNullable(DataReader, DataReader.GetOrdinal("ENDERECO2"));
            entity.COMPLEMENTO2           = getData.ConvertDBValueToStringNullable(DataReader, DataReader.GetOrdinal("COMPLEMENTO2"));
            entity.CIDADE2                = getData.ConvertDBValueToStringNullable(DataReader, DataReader.GetOrdinal("CIDADE2"));
            entity.UF2                    = getData.ConvertDBValueToStringNullable(DataReader, DataReader.GetOrdinal("UF2"));
            entity.CEP2                   = getData.ConvertDBValueToStringNullable(DataReader, DataReader.GetOrdinal("CEP2"));
            entity.REFERENCIA1            = getData.ConvertDBValueToStringNullable(DataReader, DataReader.GetOrdinal("REFERENCIA1"));
            entity.TELEFONEREFERENCIA1    = getData.ConvertDBValueToStringNullable(DataReader, DataReader.GetOrdinal("TELEFONEREFERENCIA1"));
            entity.EMAILCLIENTE           = getData.ConvertDBValueToStringNullable(DataReader, DataReader.GetOrdinal("EMAILCLIENTE"));
            entity.DATANASCIMENTOCLIENTE  = getData.ConvertDBValueToDateTimeNullable(DataReader, DataReader.GetOrdinal("DATANASCIMENTOCLIENTE"));
            entity.FLAGSERASA             = getData.ConvertDBValueToStringNullable(DataReader, DataReader.GetOrdinal("FLAGSERASA"));
            entity.FLAGSPC                = getData.ConvertDBValueToStringNullable(DataReader, DataReader.GetOrdinal("FLAGSPC"));
            entity.FLAGTELECHEQUE         = getData.ConvertDBValueToStringNullable(DataReader, DataReader.GetOrdinal("FLAGTELECHEQUE"));
            entity.FLAGBLOQUEADO          = getData.ConvertDBValueToStringNullable(DataReader, DataReader.GetOrdinal("FLAGBLOQUEADO"));
            entity.REFERENCIA2            = getData.ConvertDBValueToStringNullable(DataReader, DataReader.GetOrdinal("REFERENCIA2"));
            entity.TELEFONEREFERENCIA2    = getData.ConvertDBValueToStringNullable(DataReader, DataReader.GetOrdinal("TELEFONEREFERENCIA2"));
            entity.RENDACLIENTE           = getData.ConvertDBValueToDecimalNullable(DataReader, DataReader.GetOrdinal("RENDACLIENTE"));
            entity.CREDITOCLIENTE         = getData.ConvertDBValueToDecimalNullable(DataReader, DataReader.GetOrdinal("CREDITOCLIENTE"));
            entity.OBSERVACAO             = getData.ConvertDBValueToStringNullable(DataReader, DataReader.GetOrdinal("OBSERVACAO"));
            entity.IDCLASSIFICACAO        = getData.ConvertDBValueToInt32(DataReader, DataReader.GetOrdinal("IDCLASSIFICACAO"));
            entity.NOMECLASSIFICACAO      = getData.ConvertDBValueToStringNullable(DataReader, DataReader.GetOrdinal("NOMECLASSIFICACAO"));
            entity.IDTIPOREGIAO           = getData.ConvertDBValueToInt32(DataReader, DataReader.GetOrdinal("IDTIPOREGIAO"));
            entity.NOMETIPOREGIAO         = getData.ConvertDBValueToStringNullable(DataReader, DataReader.GetOrdinal("NOMETIPOREGIAO"));
            entity.IDPROFISSAOATIVIDADE   = getData.ConvertDBValueToInt32(DataReader, DataReader.GetOrdinal("IDPROFISSAOATIVIDADE"));
            entity.NOMEPROFISSAOATIVIDADE = getData.ConvertDBValueToStringNullable(DataReader, DataReader.GetOrdinal("NOMEPROFISSAOATIVIDADE"));
            entity.IDTRANSPORTADORA       = getData.ConvertDBValueToInt32(DataReader, DataReader.GetOrdinal("IDTRANSPORTADORA"));
            entity.NOMETRANSPORTADORA     = getData.ConvertDBValueToStringNullable(DataReader, DataReader.GetOrdinal("NOMETRANSPORTADORA"));
            entity.IDFUNCIONARIO          = getData.ConvertDBValueToInt32(DataReader, DataReader.GetOrdinal("IDFUNCIONARIO"));
            entity.NOMEFUNCIONARIO        = getData.ConvertDBValueToStringNullable(DataReader, DataReader.GetOrdinal("NOMEFUNCIONARIO"));
            entity.EMPREGOCLIENTE         = getData.ConvertDBValueToStringNullable(DataReader, DataReader.GetOrdinal("EMPREGOCLIENTE"));
            entity.ENDERECOEMPREGOCLIENTE = getData.ConvertDBValueToStringNullable(DataReader, DataReader.GetOrdinal("ENDERECOEMPREGOCLIENTE"));
            entity.TELEFONEEMPREGOCLIENTE = getData.ConvertDBValueToStringNullable(DataReader, DataReader.GetOrdinal("TELEFONEEMPREGOCLIENTE"));
            entity.CARGOCLIENTE           = getData.ConvertDBValueToStringNullable(DataReader, DataReader.GetOrdinal("CARGOCLIENTE"));
            entity.ESTADOCIVIL            = getData.ConvertDBValueToStringNullable(DataReader, DataReader.GetOrdinal("ESTADOCIVIL"));
            entity.NATURALIDADE           = getData.ConvertDBValueToStringNullable(DataReader, DataReader.GetOrdinal("NATURALIDADE"));
            entity.CONJUGE                = getData.ConvertDBValueToStringNullable(DataReader, DataReader.GetOrdinal("CONJUGE"));
            entity.DATANASCCONJUGE        = getData.ConvertDBValueToDateTimeNullable(DataReader, DataReader.GetOrdinal("DATANASCCONJUGE"));
            entity.CPFCONJUGE             = getData.ConvertDBValueToStringNullable(DataReader, DataReader.GetOrdinal("CPFCONJUGE"));
            entity.RGCONJUGE              = getData.ConvertDBValueToStringNullable(DataReader, DataReader.GetOrdinal("RGCONJUGE"));
            entity.RENDACONJUGE           = getData.ConvertDBValueToDecimalNullable(DataReader, DataReader.GetOrdinal("RENDACONJUGE"));
            entity.EMPREGOCONJUGE         = getData.ConvertDBValueToStringNullable(DataReader, DataReader.GetOrdinal("EMPREGOCONJUGE"));
            entity.DATAADMISSAOCONJUGE    = getData.ConvertDBValueToDateTimeNullable(DataReader, DataReader.GetOrdinal("DATAADMISSAOCONJUGE"));
            entity.CARGOCONJUGE           = getData.ConvertDBValueToStringNullable(DataReader, DataReader.GetOrdinal("CARGOCONJUGE"));
            entity.TELEFONCONJUGE         = getData.ConvertDBValueToStringNullable(DataReader, DataReader.GetOrdinal("TELEFONCONJUGE"));
            entity.FILIACAO               = getData.ConvertDBValueToStringNullable(DataReader, DataReader.GetOrdinal("FILIACAO"));
            entity.NOMECONTATO            = getData.ConvertDBValueToStringNullable(DataReader, DataReader.GetOrdinal("NOMECONTATO"));
            entity.ATENDIDOCONTATO        = getData.ConvertDBValueToStringNullable(DataReader, DataReader.GetOrdinal("ATENDIDOCONTATO"));
            entity.DATARETORNOCONTATO     = getData.ConvertDBValueToDateTimeNullable(DataReader, DataReader.GetOrdinal("DATARETORNOCONTATO"));
            entity.DETALHESCONTATO        = getData.ConvertDBValueToStringNullable(DataReader, DataReader.GetOrdinal("DETALHESCONTATO"));
            entity.COD_MUN_IBGE           = getData.ConvertDBValueToInt32(DataReader, DataReader.GetOrdinal("COD_MUN_IBGE"));
            entity.MUNICIPIO              = getData.ConvertDBValueToStringNullable(DataReader, DataReader.GetOrdinal("MUNICIPIO"));
            entity.UF                     = getData.ConvertDBValueToStringNullable(DataReader, DataReader.GetOrdinal("UF"));
            entity.COD_UF_IBGE            = getData.ConvertDBValueToInt32(DataReader, DataReader.GetOrdinal("COD_UF_IBGE"));
            entity.NUMEROENDER            = getData.ConvertDBValueToStringNullable(DataReader, DataReader.GetOrdinal("NUMEROENDER"));


            return(entity);
        }
        public void ehUpdate(int ID)
        {
            ehAlteracao = true;
            IDGado      = ID;
            FbConnection fbConn = new FbConnection(frmHome.strConn);
            string       query  = string.Format("SELECT ID,NUMERO,NOME,DATA_NASCIMENTO_GADO,VENDEDOR,SEXO,PAI,MAE,RACA, LACTACAO, NUMERO_FILHO, NUMERO_DONOS, NUMERO_REGISTRO, FOTO1, FOTO2, LACTACAO_MEDIA, PELAGEM, TIPO_CADASTRO, PRECO, DATA_ENTRADA, CIO, OBS FROM GADO WHERE ID = {0}", ID);
            FbCommand    fbCmd  = new FbCommand(query, fbConn);

            try
            {
                fbConn.Open();

                FbDataReader r = fbCmd.ExecuteReader();
                if (r.Read())
                {
                    txtNomeGado.Text = r["NOME"].ToString();
                    if (r["DATA_NASCIMENTO_GADO"].ToString() != "")
                    {
                        txtDataNascimentoGado.Text = Convert.ToDateTime(r["DATA_NASCIMENTO_GADO"]).ToString("dd/MM/yyyy");
                    }


                    rbSexoMasculino.Checked = (r["SEXO"].ToString() == "M");
                    rbSexoFemea.Checked     = (r["SEXO"].ToString() == "F");

                    txtNomePai.Text             = r["PAI"].ToString();
                    txtNomeMae.Text             = r["MAE"].ToString();
                    txtRacaGado.Text            = r["RACA"].ToString();
                    txtNumeroFilhosGado.Text    = r["NUMERO_FILHO"].ToString();
                    txtQuantidadeDonodGado.Text = r["NUMERO_DONOS"].ToString();
                    txtLactacaoGado.Text        = r["LACTACAO_MEDIA"].ToString();
                    txtPelagemGado.Text         = r["PELAGEM"].ToString();
                    txtNumeroRegistro.Text      = r["NUMERO_REGISTRO"].ToString();
                    txtNumeroGado.Text          = r["NUMERO"].ToString();
                    txtObs.Text = r["OBS"].ToString();

                    if (r["PRECO"].ToString() == "0")
                    {
                        txtPrecoCompraGado.Text = "";
                    }
                    else
                    {
                        txtPrecoCompraGado.Text = r["PRECO"].ToString();
                    }

                    if (r["DATA_ENTRADA"].ToString() != "")
                    {
                        txtDataEntradaGado.Text = Convert.ToDateTime(r["DATA_ENTRADA"]).ToString("dd/MM/yyyy");
                    }

                    rbCompra.Checked   = (r["TIPO_CADASTRO"].ToString() == "Compra");
                    rbJaPossui.Checked = (r["TIPO_CADASTRO"].ToString() == "Ja possui");
                    rbNascido.Checked  = (r["TIPO_CADASTRO"].ToString() == "Nascido");
                    rbTroca.Checked    = (r["TIPO_CADASTRO"].ToString() == "Troca");

                    txtNomeVendedor.Text = r["VENDEDOR"].ToString();
                    if (!((r["FOTO1"]) is DBNull))
                    {
                        pctGado1.Image = bytetoImage((byte[])(r["FOTO1"]));
                    }
                    if (!((r["FOTO2"]) is DBNull))
                    {
                        pctGado2.Image = bytetoImage((byte[])r["FOTO2"]);
                    }
                }
            }
            catch (FbException fbex)
            {
                MessageBox.Show("Erro ao acessar o Banco de Dados:\n" + fbex.Message, "Erro");
            }
            finally
            {
                fbConn.Close();
            }
        }
Beispiel #26
0
        /// <summary>
        /// Starts the ordered execution of the SQL statements that are in <see cref="SqlStatements"/> collection.
        /// </summary>
        /// <param name="autoCommit">Specifies if the transaction should be committed after a DDL command execution</param>
        public void Execute(bool autoCommit = true)
        {
            if (this.SqlStatements == null || this.SqlStatements.Count == 0)
            {
                throw new InvalidOperationException("There are no commands for execution.");
            }

            foreach (string sqlStatement in this.SqlStatements)
            {
                if (string.IsNullOrEmpty(sqlStatement))
                {
                    continue;
                }

                // initializate outputs to default
                int              rowsAffected  = -1;
                FbDataReader     dataReader    = null;
                SqlStatementType statementType = FbBatchExecution.GetStatementType(sqlStatement);

                if (!(statementType == SqlStatementType.Connect ||
                      statementType == SqlStatementType.CreateDatabase ||
                      statementType == SqlStatementType.Disconnect ||
                      statementType == SqlStatementType.DropDatabase ||
                      statementType == SqlStatementType.SetAutoDDL ||
                      statementType == SqlStatementType.SetDatabase ||
                      statementType == SqlStatementType.SetNames ||
                      statementType == SqlStatementType.SetSQLDialect))
                {
                    this.ProvideCommand();
                    this.sqlCommand.CommandText = sqlStatement;
                    if (this.sqlTransaction == null && !(statementType == SqlStatementType.Commit || statementType == SqlStatementType.Rollback))
                    {
                        this.sqlTransaction = this.sqlConnection.BeginTransaction();
                    }
                    this.sqlCommand.Transaction = this.sqlTransaction;
                }

                try
                {
                    switch (statementType)
                    {
                    case SqlStatementType.AlterCharacterSet:
                    case SqlStatementType.AlterDatabase:
                    case SqlStatementType.AlterDomain:
                    case SqlStatementType.AlterException:
                    case SqlStatementType.AlterIndex:
                    case SqlStatementType.AlterProcedure:
                    case SqlStatementType.AlterRole:
                    case SqlStatementType.AlterTable:
                    case SqlStatementType.AlterTrigger:
                    case SqlStatementType.AlterView:
                        this.OnCommandExecuting(this.sqlCommand);

                        rowsAffected = this.ExecuteCommand(autoCommit);
                        this.requiresNewConnection = false;

                        this.OnCommandExecuted(sqlStatement, null, rowsAffected);
                        break;

                    case SqlStatementType.Commit:
                        this.OnCommandExecuting(null);

                        this.CommitTransaction();

                        this.OnCommandExecuted(sqlStatement, null, -1);
                        break;

                    case SqlStatementType.Connect:
                        this.OnCommandExecuting(null);

                        this.ConnectToDatabase(sqlStatement);

                        this.requiresNewConnection = false;

                        this.OnCommandExecuted(sqlStatement, null, -1);
                        break;

                    case SqlStatementType.CreateDatabase:
                        this.OnCommandExecuting(null);

                        this.CreateDatabase(sqlStatement);
                        this.requiresNewConnection = false;

                        this.OnCommandExecuted(sqlStatement, null, -1);
                        break;

                    case SqlStatementType.CommentOn:
                    case SqlStatementType.CreateCollation:
                    case SqlStatementType.CreateDomain:
                    case SqlStatementType.CreateException:
                    case SqlStatementType.CreateGenerator:
                    case SqlStatementType.CreateIndex:
                    case SqlStatementType.CreateProcedure:
                    case SqlStatementType.CreateRole:
                    case SqlStatementType.CreateSequence:
                    case SqlStatementType.CreateShadow:
                    case SqlStatementType.CreateTable:
                    case SqlStatementType.CreateTrigger:
                    case SqlStatementType.CreateView:
                    case SqlStatementType.DeclareCursor:
                    case SqlStatementType.DeclareExternalFunction:
                    case SqlStatementType.DeclareFilter:
                    case SqlStatementType.DeclareStatement:
                    case SqlStatementType.DeclareTable:
                    case SqlStatementType.Delete:
                        this.OnCommandExecuting(this.sqlCommand);

                        rowsAffected = this.ExecuteCommand(autoCommit);
                        this.requiresNewConnection = false;

                        this.OnCommandExecuted(sqlStatement, null, rowsAffected);
                        break;

                    case SqlStatementType.Describe:
                        break;

                    case SqlStatementType.Disconnect:
                        this.OnCommandExecuting(null);

                        this.sqlConnection.Close();
                        FbConnection.ClearPool(this.sqlConnection);
                        this.requiresNewConnection = false;

                        this.OnCommandExecuted(sqlStatement, null, -1);
                        break;

                    case SqlStatementType.DropDatabase:
                        this.OnCommandExecuting(null);

                        FbConnection.DropDatabase(this.connectionString.ToString());
                        this.requiresNewConnection = true;

                        this.OnCommandExecuted(sqlStatement, null, -1);
                        break;

                    case SqlStatementType.DropCollation:
                    case SqlStatementType.DropDomain:
                    case SqlStatementType.DropException:
                    case SqlStatementType.DropExternalFunction:
                    case SqlStatementType.DropFilter:
                    case SqlStatementType.DropGenerator:
                    case SqlStatementType.DropIndex:
                    case SqlStatementType.DropProcedure:
                    case SqlStatementType.DropSequence:
                    case SqlStatementType.DropRole:
                    case SqlStatementType.DropShadow:
                    case SqlStatementType.DropTable:
                    case SqlStatementType.DropTrigger:
                    case SqlStatementType.DropView:
                    case SqlStatementType.EventInit:
                    case SqlStatementType.EventWait:
                    case SqlStatementType.Execute:
                    case SqlStatementType.ExecuteImmediate:
                    case SqlStatementType.ExecuteProcedure:
                        this.ProvideCommand().CommandText = sqlStatement;

                        this.OnCommandExecuting(this.sqlCommand);

                        rowsAffected = this.ExecuteCommand(autoCommit);
                        this.requiresNewConnection = false;

                        this.OnCommandExecuted(sqlStatement, null, rowsAffected);
                        break;

                    case SqlStatementType.ExecuteBlock:
                        this.ProvideCommand().CommandText = sqlStatement;

                        this.OnCommandExecuting(this.sqlCommand);

                        dataReader = this.sqlCommand.ExecuteReader();
                        this.requiresNewConnection = false;

                        this.OnCommandExecuted(sqlStatement, dataReader, -1);
                        if (!dataReader.IsClosed)
                        {
                            dataReader.Close();
                        }
                        break;

                    case SqlStatementType.Fetch:
                        break;

                    case SqlStatementType.Grant:
                    case SqlStatementType.Insert:
                    case SqlStatementType.InsertCursor:
                    case SqlStatementType.Open:
                    case SqlStatementType.Prepare:
                    case SqlStatementType.Revoke:
                        this.OnCommandExecuting(this.sqlCommand);

                        rowsAffected = this.ExecuteCommand(autoCommit);
                        this.requiresNewConnection = false;

                        this.OnCommandExecuted(sqlStatement, null, rowsAffected);
                        break;

                    case SqlStatementType.RecreateProcedure:
                    case SqlStatementType.RecreateTable:
                    case SqlStatementType.RecreateTrigger:
                    case SqlStatementType.RecreateView:
                        this.OnCommandExecuting(this.sqlCommand);

                        rowsAffected = this.ExecuteCommand(autoCommit);
                        this.requiresNewConnection = false;

                        this.OnCommandExecuted(sqlStatement, null, rowsAffected);
                        break;

                    case SqlStatementType.Rollback:
                        this.OnCommandExecuting(null);

                        this.RollbackTransaction();

                        this.OnCommandExecuted(sqlStatement, null, -1);
                        break;

                    case SqlStatementType.Select:
                        this.ProvideCommand().CommandText = sqlStatement;

                        this.OnCommandExecuting(this.sqlCommand);

                        dataReader = this.sqlCommand.ExecuteReader();
                        this.requiresNewConnection = false;

                        this.OnCommandExecuted(sqlStatement, dataReader, -1);
                        if (!dataReader.IsClosed)
                        {
                            dataReader.Close();
                        }
                        break;

                    case SqlStatementType.SetAutoDDL:
                        this.OnCommandExecuting(null);

                        this.SetAutoDdl(sqlStatement, ref autoCommit);
                        this.requiresNewConnection = false;

                        this.OnCommandExecuted(sqlStatement, null, -1);
                        break;

                    case SqlStatementType.SetGenerator:
                    case SqlStatementType.AlterSequence:
                        this.OnCommandExecuting(this.sqlCommand);

                        rowsAffected = this.ExecuteCommand(autoCommit);
                        this.requiresNewConnection = false;

                        this.OnCommandExecuted(sqlStatement, null, rowsAffected);
                        break;

                    case SqlStatementType.SetNames:
                        this.OnCommandExecuting(null);

                        this.SetNames(sqlStatement);
                        this.requiresNewConnection = true;

                        this.OnCommandExecuted(sqlStatement, null, -1);
                        break;

                    case SqlStatementType.SetSQLDialect:
                        this.OnCommandExecuting(null);

                        this.SetSqlDialect(sqlStatement);
                        this.requiresNewConnection = true;

                        this.OnCommandExecuted(sqlStatement, null, -1);
                        break;

                    case SqlStatementType.SetDatabase:
                    case SqlStatementType.SetStatistics:
                    case SqlStatementType.SetTransaction:
                    case SqlStatementType.ShowSQLDialect:
                        throw new NotImplementedException();

                    case SqlStatementType.Update:
                    case SqlStatementType.Whenever:
                        this.OnCommandExecuting(this.sqlCommand);

                        rowsAffected = this.ExecuteCommand(autoCommit);
                        this.requiresNewConnection = false;

                        this.OnCommandExecuted(sqlStatement, null, rowsAffected);
                        break;
                    }
                }
                catch (Exception ex)
                {
                    this.RollbackTransaction();

                    throw new FbException(string.Format("An exception was thrown when executing command: {1}.{0}Batch execution aborted.{0}The returned message was: {2}.",
                                                        Environment.NewLine,
                                                        sqlStatement,
                                                        ex.Message));
                }
            }

            this.CommitTransaction();

            this.sqlConnection.Close();
        }
        public bool DumpToCSVFile(string table, string filename, string separator)
        {
            string query = "SELECT * FROM " + table;
            cmd = new FbCommand(query, connection);
            reader = cmd.ExecuteReader();
            
            List<string> row = new List<string>();
            List<object> rows = new List<object>();

            using(StreamWriter writer = new StreamWriter(filename,false))
            {
                if (!reader.HasRows)
                {
                    writer.Write("Tabellen var tom ved eksport.");
                    writer.Close();
                    return false;
                }
                bool firstTime = true;
                while (reader.Read())
                {
                    if (firstTime)
                    {
                        for (int a = 0; a < reader.FieldCount; a++)
                        {
                            writer.Write(reader.GetName(a).ToString());
                            if (a + 1 < reader.FieldCount)
                                writer.Write(separator);
                        }
                        writer.Write(Environment.NewLine);
                        firstTime = false;
                    }

                    for (int a = 0; a < reader.FieldCount; a++)
                    {
                        try { 
                            writer.Write(reader.GetValue(a).ToString()); 
                        }
                        catch {
                            writer.Write("null");
                        }
                        if (a+1<reader.FieldCount)
                            writer.Write(separator);
                    }
                    writer.WriteLine();
                }
            }
            return true;
        }
Beispiel #28
0
        public float DiferencaFormulas(string fornecedor, string caracteristica, DateTime data, short orcamento, ref string servico)
        {
            string    formula = "", formula_pedido = "";
            float     total_orcamento = 0, total_pedido = 0;
            FbCommand cmd = new FbCommand("select DES_FORMULA,DES_FORMULA_PEDIDO,TXT_SERVICO " +
                                          "from CARACTERISTICAS " +
                                          "where COD_FORNECEDOR='" + fornecedor + "' and " +
                                          "      COD_CARACTERISTICA='" + caracteristica + "'",
                                          Globais.bd);
            FbDataReader reader = cmd.ExecuteReader(CommandBehavior.Default);

            if (reader.Read())
            {
                formula        = !reader.IsDBNull(0) ? reader.GetString(0).Trim() : "";
                formula_pedido = !reader.IsDBNull(1) ? reader.GetString(1).Trim() : "";
                servico        = !reader.IsDBNull(2) ? reader.GetString(2).Trim() : "";
            }
            reader.Close();
            if (formula_pedido.Length == 0)
            {
                return(0f);
            }
            if (formula_pedido.CompareTo(formula) == 0)
            {
                return(0f);
            }

            string sql = "select " +
                         "       a.cod_produto," +
                         "       a.sub_codigo," +
                         "       a.qtd_item," +
                         "       a.vlr_preco," +
                         "       a.vlr_preco_tabela, " +
                         "       a.idt_especial," +
                         "       b.per_ipi " +
                         "from itens a, produtos b " +
                         "where a.cod_fornecedor='" + fornecedor + "' and " +
                         "      a.dat_orcamento='" + data.ToString("M/d/yyyy") + "' and " +
                         "      a.cod_orcamento=" + orcamento + " and " +
                         "      a.cod_fornecedor=b.cod_parceiro and " +
                         "      a.cod_produto=b.cod_produto and " +
                         "      a.sub_codigo=b.sub_codigo " +
                         "order by a.cod_area,a.seq_item";

            cmd    = new FbCommand(sql, Globais.bd);
            reader = cmd.ExecuteReader(CommandBehavior.Default);
            string codigo;
            string sub_codigo;
            short  qtd;
            float  preco_unitario;
            float  preco_tabela;
            bool   especial;
            float  ipi;

            //float fator;
            //float preco;
            while (reader.Read())
            {
                float valor_orcamento = 0, valor_pedido = 0;
                codigo         = reader.GetString(0).Trim();
                sub_codigo     = reader.GetString(1).Trim();
                qtd            = reader.GetInt16(2);
                preco_unitario = reader.GetFloat(3) * qtd;
                preco_tabela   = reader.GetFloat(4) * qtd;
                especial       = reader.GetString(5).Trim().CompareTo("S") == 0;;
                ipi            = reader.GetFloat(6);
                if (especial)
                {
                    // desfaz formula
                    preco_tabela = preco_unitario;
                    Globais.DesfazFormula(ref preco_tabela, formula, ipi, 0, 0);

                    /*
                     * for (int i=formula.Trim().Length-4; i>=0; i-=4)
                     * {
                     *      if (formula[i] == 'x')
                     *      {
                     *              fator = (Globais.StrToFloat(formula.Substring(i+1, 3)) - 1) * 100;
                     *      }
                     *      if (formula.Substring(i, 4).CompareTo("+IPI") == 0)
                     *      {
                     *              fator = ipi;
                     *      }
                     *      else
                     *      {
                     *              fator = Globais.StrToFloat(formula.Substring(i, 4));
                     *      }
                     *      preco_tabela = (preco_tabela * 100) / (100 + fator);
                     * }
                     */
                }
                //if (!especial)
                //{
                valor_orcamento = preco_tabela;
                valor_pedido    = preco_tabela;
                float per_frete = cCaracteristicas.Frete(fornecedor, caracteristica);
                Globais.CalculaFormula(ref valor_orcamento, formula, ipi, per_frete, 0);

                /*
                 * for (int i=0; i<formula.Trim().Length; i+=4)
                 * {
                 *      if (formula[i] == 'x')
                 *      {
                 *              fator = Globais.StrToFloat(formula.Substring(i+1, 3));
                 *              valor_orcamento *= fator;
                 *              continue;
                 *      }
                 *      if (formula.Substring(i, 4).CompareTo("+IPI") == 0)
                 *      {
                 *              fator = ipi;
                 *              valor_orcamento += (valor_orcamento * fator / (float)100);
                 *      }
                 *      else
                 *      {
                 *              fator = Globais.StrToFloat(formula.Substring(i, 4));
                 *              valor_orcamento += (valor_orcamento * fator / (float)100);
                 *      }
                 * }
                 */
                Globais.CalculaFormula(ref valor_pedido, formula_pedido, ipi, per_frete, 0);

                /*
                 * for (int i=0; i<formula_pedido.Trim().Length; i+=4)
                 * {
                 *      if (formula_pedido[i] == 'x')
                 *      {
                 *              fator = Globais.StrToFloat(formula_pedido.Substring(i+1, 3));
                 *              valor_pedido *= fator;
                 *              continue;
                 *      }
                 *      if (formula_pedido.Substring(i, 4).CompareTo("+IPI") == 0)
                 *      {
                 *              fator = ipi;
                 *              valor_pedido += (valor_pedido * fator / (float)100);
                 *      }
                 *      else
                 *      {
                 *              fator = Globais.StrToFloat(formula_pedido.Substring(i, 4));
                 *              valor_pedido += (valor_pedido * fator / (float)100);
                 *      }
                 * }
                 */
/*
 *                              }
 *                              else
 *                              {
 *                                      preco = preco_unitario;
 *                                      valor_orcamento += preco;
 *                                      valor_pedido += preco;
 *                              }
 */
                total_orcamento += valor_orcamento;
                total_pedido    += valor_pedido;
            }
            reader.Close();
            return(total_orcamento - total_pedido);
        }
 public Employers(FbDataReader R)
     : this()
 {
     FieldsFromReader(R);
 }
Beispiel #30
0
        public LIS_EMPRESAEMISSORACollection ReadCollection()
        {
            FbDataReader dataReader = null;

            try
            {
                LIS_EMPRESAEMISSORACollection collection = null;

                //Verificando a existência de um transação aberta
                if (dbTransaction != null)
                {
                    if (dbCnn.State == ConnectionState.Closed)
                    {
                        dbCnn.Open();
                    }

                    dbCommand             = new FbCommand("SELECT * FROM LIS_EMPRESAEMISSORA", dbCnn);
                    dbCommand.Transaction = ((FbTransaction)(dbTransaction));
                }
                else
                {
                    if (dbCnn == null)
                    {
                        dbCnn = ((FbConnection)GetConnectionDB());
                    }

                    if (dbCnn.State == ConnectionState.Closed)
                    {
                        dbCnn.Open();
                    }

                    dbCommand             = new FbCommand("SELECT * FROM LIS_EMPRESAEMISSORA", dbCnn);
                    dbCommand.Transaction = dbCnn.BeginTransaction(IsolationLevel.ReadCommitted);
                }

                // Tipo do comando de banco Procedure ou SQL
                dbCommand.CommandType = CommandType.Text;

                collection = ExecuteReader(ref collection, ref dataReader, dbCommand);

                if (dataReader != null)
                {
                    dataReader.Close();
                    dataReader.Dispose();
                }

                if (dbTransaction == null)
                {
                    dbCommand.Transaction.Commit();
                    dbCnn.Close();
                }

                return(collection);
            }
            catch (Exception ex)
            {
                // Deleta reader
                if (dataReader != null)
                {
                    dataReader.Close();
                    dataReader.Dispose();
                }

                if (dbTransaction != null)
                {
                    this.RollbackTransaction();
                }
                else
                {
                    if (dbCommand.Transaction != null)
                    {
                        dbCommand.Transaction.Rollback();
                    }
                    if (dbCnn.State == ConnectionState.Open)
                    {
                        dbCnn.Close();
                    }
                }

                throw ex;
            }
        }
Beispiel #31
0
        public new FbDataReader ExecuteReader(CommandBehavior behavior)
        {
            lock (this)
            {
                this.CheckCommand();

                try
                {
                    this.ExecuteCommand(behavior, true);
                }
                catch (IscException ex)
                {
                    this.DiscardImplicitTransaction();

                    throw new FbException(ex.Message, ex);
                }
                catch
                {
                    this.DiscardImplicitTransaction();

                    throw;
                }
            }

            this.activeReader = new FbDataReader(this, this.connection, behavior);

            return this.activeReader;
        }
Beispiel #32
0
        public TIPOREGIAOEntity Read(int IDTIPOREGIAO)
        {
            FbDataReader reader = null;

            try
            {
                //Verificando a existência de um transação aberta
                if (dbTransaction != null)
                {
                    if (dbCnn.State == ConnectionState.Closed)
                    {
                        dbCnn.Open();
                    }

                    dbCommand             = new FbCommand("Rea_TIPOREGIAO", dbCnn);
                    dbCommand.Transaction = ((FbTransaction)(dbTransaction));
                }
                else
                {
                    if (dbCnn == null)
                    {
                        dbCnn = ((FbConnection)GetConnectionDB());
                    }

                    if (dbCnn.State == ConnectionState.Closed)
                    {
                        dbCnn.Open();
                    }

                    dbCommand             = new FbCommand("Rea_TIPOREGIAO", dbCnn);
                    dbCommand.Transaction = dbCnn.BeginTransaction(IsolationLevel.ReadCommitted);
                }

                dbCommand.CommandType = CommandType.StoredProcedure;

                dbCommand.Parameters.AddWithValue("@IDTIPOREGIAO", IDTIPOREGIAO);                //PrimaryKey


                reader = dbCommand.ExecuteReader();

                TIPOREGIAOEntity entity = null;
                if (reader.HasRows)
                {
                    while (reader.Read())
                    {
                        entity = FillEntityObject(ref reader);
                    }
                }

                // Deleta reader
                if (reader != null)
                {
                    reader.Close();
                    reader.Dispose();
                }

                // Fecha conexão
                if (dbTransaction == null)
                {
                    dbCommand.Transaction.Commit();
                    if (dbCnn.State == ConnectionState.Open)
                    {
                        dbCnn.Close();
                    }
                }

                return(entity);
            }
            catch (Exception ex)
            {
                // Deleta reader
                if (reader != null)
                {
                    reader.Close();
                    reader.Dispose();
                }

                if (dbTransaction != null)
                {
                    this.RollbackTransaction();
                }
                else
                {
                    if (dbCommand.Transaction != null)
                    {
                        dbCommand.Transaction.Rollback();
                    }
                    if (dbCnn.State == ConnectionState.Open)
                    {
                        dbCnn.Close();
                    }
                }

                throw ex;
            }
        }
Beispiel #33
0
        public void PrepareTest()
        {
            // Create a new test table
            FbCommand create = new FbCommand("create table PrepareTest(test_field varchar(20));", Connection);

            create.ExecuteNonQuery();
            create.Dispose();

            // Insert data using a prepared statement
            FbCommand command = new FbCommand(
                "insert into PrepareTest(test_field) values(@test_field);",
                Connection);

            command.Parameters.Add("@test_field", FbDbType.VarChar).Value = DBNull.Value;
            command.Prepare();

            for (int i = 0; i < 5; i++)
            {
                if (i < 1)
                {
                    command.Parameters[0].Value = DBNull.Value;
                }
                else
                {
                    command.Parameters[0].Value = i.ToString();
                }
                command.ExecuteNonQuery();
            }

            command.Dispose();

            try
            {
                // Check that data is correct
                FbCommand    select = new FbCommand("select * from PrepareTest", Connection);
                FbDataReader reader = select.ExecuteReader();
                int          count  = 0;
                while (reader.Read())
                {
                    if (count == 0)
                    {
                        Assert.AreEqual(DBNull.Value, reader[0], "Invalid value.");
                    }
                    else
                    {
                        Assert.AreEqual(count, reader.GetInt32(0), "Invalid value.");
                    }

                    count++;
                }
                reader.Close();
                select.Dispose();
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                // Drop table
                FbCommand drop = new FbCommand("drop table PrepareTest", Connection);
                drop.ExecuteNonQuery();
                drop.Dispose();
            }
        }
 /// <summary>
 /// The trigger function for <see cref="CommandExecuted"/> event.
 /// </summary>
 /// <param name="commandText">The <see cref="FbCommand.CommandText"/> of the executed SQL command.</param>
 /// <param name="dataReader">The <see cref="FbDataReader"/> instance with the returned data. If the
 /// command executed is not meant to return data (ex: UPDATE, INSERT...) this parameter must be
 /// setled to <b>null</b>.</param>
 /// <param name="rowsAffected">The rows that were affected by the executed SQL command. If the executed
 /// command is not meant to return this kind of information (ex: SELECT) this parameter must
 /// be setled to <b>-1</b>.</param>
 private void OnCommandExecuted(FbDataReader dataReader, string commandText, SqlStatementType statementType, int rowsAffected)
 {
     CommandExecuted?.Invoke(this, new CommandExecutedEventArgs(dataReader, commandText, statementType, rowsAffected));
 }
Beispiel #35
0
        public bool Copia(string novo, string parceiro, string codigo, string formula, string formula_pedido, float consultor, float vendedor, float filial, float limiar, string observacao, string racional, string servico, string ativo, short dias, string venpro, string venser, string conpro, string conser, string filpro, string filser, float frete,
                          string introducao, string fornecimento, string garantia, string condicao, string aceite, string imprime_ipi, ref string msg)
        {
            string sconsultor = consultor.ToString().Replace(',', '.');
            string svendedor  = vendedor.ToString().Replace(',', '.');
            string sfilial    = filial.ToString().Replace(',', '.');
            string slimiar    = limiar.ToString().Replace(',', '.');
            string sfrete     = frete.ToString().Replace(',', '.');
            string sql        = "insert into CARACTERISTICAS values(" +
                                "'" + parceiro + "'," +
                                "'" + novo + "'," +
                                "'" + formula + "'," +
                                sconsultor + "," +
                                svendedor + "," +
                                slimiar + "," +
                                "@observacao," +
                                "@racional," +
                                "'" + ativo + "'," +
                                "'" + formula_pedido + "'," +
                                "'" + servico + "'," +
                                dias + "," +
                                "'" + venpro + "'," +
                                "'" + venser + "'," +
                                "'" + conpro + "'," +
                                "'" + conser + "'," +
                                "'" + filpro + "'," +
                                "'" + filser + "'," +
                                sfilial + "," +
                                sfrete + "," +
                                "'" + introducao + "'," +
                                "'" + fornecimento + "'," +
                                "'" + garantia + "'," +
                                "'" + condicao + "'," +
                                "'" + aceite + "'," +
                                "'" + imprime_ipi + "'" +
                                ")";

            FbCommand cmd = new FbCommand(sql, Globais.bd);

            try
            {
                cmd.Parameters.Add("@observacao", FbDbType.VarChar, 4000);
                cmd.Parameters.Add("@racional", FbDbType.VarChar, 4000);
                cmd.Parameters["@observacao"].Value = observacao;
                cmd.Parameters["@racional"].Value   = racional;
                cmd.Prepare();
                Log.Grava(Globais.sUsuario, cmd.CommandText);
                cmd.ExecuteNonQuery();
            }
            catch (Exception err)
            {
                Log.Grava(Globais.sUsuario, "erro:" + err.Message);
                msg = err.Message;
                StreamWriter sw = new StreamWriter(new FileStream("c:\\soft\\soft.log", FileMode.Create));
                sw.WriteLine(sql);
                sw.WriteLine(msg);
                sw.Close();
                return(false);
            }

            sql = "select QTD_LIMIAR,PER_COMISSAO " +
                  "from COMISSAO_LIMIAR " +
                  "where cod_fornecedor='" + parceiro + "' and " +
                  "      cod_caracteristica='" + codigo + "' " +
                  "order by QTD_LIMIAR";
            cmd = new FbCommand(sql, Globais.bd);
            FbDataReader    reader          = cmd.ExecuteReader(CommandBehavior.Default);
            float           comissao        = 0;
            short           qtd_limiar      = 0;
            cComissaoLimiar comissao_limiar = new cComissaoLimiar();

            while (reader.Read())
            {
                qtd_limiar = reader.GetInt16(0);
                comissao   = reader.GetFloat(1);
                comissao_limiar.Inclui(parceiro, novo, qtd_limiar, comissao, ref msg);
            }
            reader.Close();

            msg = "OK";
            return(true);
        }
Beispiel #36
0
        private async void BtSync_Clicked(object sender, EventArgs e)
        {
            string Password    = "******";
            string TryPassword = await DisplayPromptAsync("verificacion", "Ingrese la contraseña maestra para continuar", "Aceptar", "Cancelar", "Contraseña", 11, null);

            if (Password == TryPassword)
            {
                Preferences.Set("BUSY", false);
                Debug.WriteLine("Timer Stopped");
                App.syncTimer.Stop();
                App.syncTimer.Enabled = false;
                var db = new SQLiteConnection(Preferences.Get("DB_PATH", ""));
                Preferences.Set("IS_SYNC", "true");
                if (Connectivity.NetworkAccess == NetworkAccess.Internet)
                {
                    try
                    {
                        fireBird = new FireBirdData();
                        //Mostramos el popup
                        popupLoadingView.IsVisible = true;

                        pbLoading.IsVisible = true;
                        aiLoading.IsVisible = false;
                        aiLoading.IsRunning = false;
                        lblLoadingText.Text = "Loading...";

                        var querry1 = "";

                        //Vamos a buscar el directorio de la base de datos

                        //Buscamos el Chunk Size
                        var iChunkSize = int.Parse(Preferences.Get("CHUNK_SIZE", "10000"));

                        //Vamos a poner el timeout del http en 20 min seg
                        _client.Timeout = new TimeSpan(0, 40, 0);

                        Debug.WriteLine("Setting timeout to 20 min");

                        string querry           = "";
                        string connectionString = fireBird.connectionString(false);


                        FbCommand cmd;
                        //var Url = "http://" + Preferences.Get("SERVER_IP", "localhost") + ":" + Preferences.Get("SERVER_PORT", "4444")
                        //+ "/?sql=";

                        //TODO: Buscar cuantas cedulas se van a descargar.

                        querry = "select count(p.cedula) as anyCount from padron p";
                        int tries = 0;
                        //string contenido;
                        int maxRegistro = 0;
                        while (true)
                        {
                            try
                            {
                                FbConnection fb = new FbConnection(connectionString);

                                fb.Open();
                                FbCommand command = new FbCommand(
                                    querry,
                                    fb);


                                FbDataReader reader = command.ExecuteReader();

                                if (reader.HasRows)
                                {
                                    while (reader.Read())
                                    {
                                        maxRegistro = Convert.ToInt32(reader[0]);
                                    }
                                }
                                else
                                {
                                    Debug.WriteLine("No rows found.");
                                }
                                reader.Close();

                                fb.Close();
                                fb.Dispose();

                                break;
                            }
                            catch (Exception ex)
                            {
                                Analytics.TrackEvent("Error al conectarse a base de datos " + ex.Message + "\n Escaner: " + Preferences.Get("LECTOR", "N/A"));
                                Debug.WriteLine("Error en Sync");
                                if (tries >= 5)
                                {
                                    throw new Exception("No se pudo conectar con la base de datos.");
                                }
                                var x = ex.Message;
                                tries += 1;
                            }
                        }

                        //var maxRegistroList = JsonConvert.DeserializeObject<List<counterObj>>(contenido);
                        //var maxRegistro = maxRegistroList.First();

                        //Descargar CEDULAS

                        querry = "select p.cedula, p.nombres, p.apellido1, p.apellido2 from padron p";

                        if (maxRegistro > 0)
                        {
                            int    loadedRegistros   = 1;
                            int    commitedRegistros = 0;
                            double progress          = 0.0;
                            var    listPadron        = new List <PADRON>();
                            while (loadedRegistros < maxRegistro)
                            {
                                progress = (double)loadedRegistros / maxRegistro;
                                if (maxRegistro - loadedRegistros < iChunkSize - 1)
                                {
                                    querry1 = querry1 = querry + " ROWS "
                                                        + loadedRegistros.ToString() + " TO " + maxRegistro.ToString();
                                    progress = 1.0;
                                }
                                else
                                {
                                    querry1 = querry + " ROWS "
                                              + loadedRegistros.ToString() + " TO " + (loadedRegistros + iChunkSize - 1).ToString();
                                }

                                await Task.Factory.StartNew(() =>
                                {
                                    listPadron.AddRange(fireBird.DownloadPadron(querry1, false));

                                    //var listPadronTemp = JsonConvert.DeserializeObject<List<PADRON>>(contenidoTBL);
                                    //listPadron = listPadron.Concat(listPadronTemp).ToList();
                                    if (listPadron.Count >= int.Parse(Preferences.Get("COMMIT_SIZE", "1000000")) || maxRegistro - loadedRegistros < iChunkSize - 1)
                                    {
                                        try
                                        {
                                            Device.BeginInvokeOnMainThread(() =>
                                            {
                                                lblLoadingText.Text = "Commited " + commitedRegistros.ToString() + "/" + maxRegistro.ToString() + " CEDULAS";
                                            });
                                            Debug.WriteLine("Se van a insertar: " + listPadron.Count.ToString() + " En la BBDD Local");
                                            //await Task.Factory.StartNew(() =>
                                            //{
                                            db.InsertAll(listPadron);
                                            //});
                                            commitedRegistros = commitedRegistros + listPadron.Count;
                                            //Preferences.Set("TOTAL_CEDULAS_DESCARGADAS", commitedRegistros.ToString());
                                            Device.BeginInvokeOnMainThread(() =>
                                            {
                                                //lblCantidadPadron.Text = $"Cantidad de cedulas descargadas: {Preferences.Get("TOTAL_CEDULAS_DESCARGADAS", commitedRegistros.ToString())}";
                                                Debug.WriteLine($"Cantidad de cedulas descargadas: {Preferences.Get("TOTAL_CEDULAS_DESCARGADAS", commitedRegistros.ToString())}");
                                            });
                                            listPadron.Clear();
                                        }
                                        catch (Exception ea)
                                        {
                                            Debug.WriteLine("Se ha encontrado una excepcion, Error: " + ea.Message);
                                        }
                                    }

                                    Device.BeginInvokeOnMainThread(() =>
                                    {
                                        lblLoadingText.Text = "Downloading CEDULAS: " + loadedRegistros.ToString() + "/" + maxRegistro.ToString();
                                    });
                                    Debug.WriteLine("Downloading CEDULAS: " + loadedRegistros.ToString() + "/" + maxRegistro.ToString());
                                    loadedRegistros = loadedRegistros + iChunkSize;
                                });

                                await pbLoading.ProgressTo(progress, 200, Easing.Linear);
                            }

                            pbLoading.Progress  = 0.0;
                            lblLoadingText.Text = "Guardando Padron";
                            pbLoading.IsVisible = false;
                            aiLoading.IsVisible = true;
                            aiLoading.IsRunning = true;
                            Debug.WriteLine("Se van a insertar: " + listPadron.Count.ToString() + " En la BBDD Local");
                            await Task.Factory.StartNew(() =>
                            {
                                db.InsertAll(listPadron);
                            });

                            pbLoading.IsVisible = true;
                            aiLoading.IsVisible = false;
                            aiLoading.IsRunning = false;
                            lblLoadingText.Text = "Loading...";

                            //Si hay Cedulas para cargar entramos
                        }
                    }
                    catch (Exception ey)
                    {
                        Debug.WriteLine("Error syncronisando: " + ey.Message);
                        popupLoadingView.IsVisible = false;
                        try
                        {
                            var options = new NotificationOptions()
                            {
                                Title       = "Error syncronisando",
                                Description = "Hubo un error en la syncronización, intente nuevamente",
                                IsClickable = false // Set to true if you want the result Clicked to come back (if the user clicks it)
                            };
                            var notification = DependencyService.Get <IToastNotificator>();
                            var result       = notification.Notify(options);
                        }
                        catch (Exception eo)
                        {
                            Debug.WriteLine("Error en notificacion: " + eo.Message);
                        }
                    }
                    finally
                    {
                        db.Dispose();

                        popupLoadingView.IsVisible = false;
                        try
                        {
                            _client.Timeout = new TimeSpan(0, 0, 100);
                        }
                        catch (Exception eu)
                        {
                            Debug.WriteLine("Error devolviendo el time out: " + eu.Message);
                        }
                        Debug.WriteLine("Setting timeout to 100 seconds");
                        Debug.WriteLine("Timer Start");
                        //Preferences.Set("IS_SYNC", "false");
                        App.syncTimer.Enabled = true;
                        App.syncTimer.Start();
                        Preferences.Set("BUSY", true);
                    }
                    //"select b.boleta_id, b.boleta, b.fecha_lectura, null as SUBIDA from boletas b where b.fecha_lectura is NULL"
                }
                else
                {
                    //Si no hay connecion a internet avisar al usuario
                    Debug.WriteLine("NO NETWORK");
                    popupLoadingView.IsVisible = false;
                    var options = new NotificationOptions()
                    {
                        Title       = "No hay conexión",
                        Description = "No se puede sincronizar sin una conexión a la red",
                        IsClickable = false // Set to true if you want the result Clicked to come back (if the user clicks it)
                    };
                    var notification = DependencyService.Get <IToastNotificator>();
                    var result       = notification.Notify(options);
                    Debug.WriteLine("Timer Start");
                    Preferences.Set("IS_SYNC", "false");
                    App.syncTimer.Enabled = true;
                    App.syncTimer.Start();
                }
            }
            else
            {
                await DisplayAlert("Credencial incorrecta", "La credencial ingresada no es valida", "OK");
            }
        }
Beispiel #37
0
        private static TIPOREGIAOCollection ExecuteReader(ref TIPOREGIAOCollection collection, ref FbDataReader dataReader, FbCommand dbCommand)
        {
            using (dataReader = dbCommand.ExecuteReader())
            {
                collection = new TIPOREGIAOCollection();

                if (dataReader.HasRows)
                {
                    while (dataReader.Read())
                    {
                        collection.Add(FillEntityObject(ref dataReader));
                    }
                }

                if (!(dataReader.IsClosed))
                {
                    dataReader.Close();
                }
                dataReader.Dispose();
            }

            return(collection);
        }
 private static string stringify(FbDataReader reader)
 {
     return stringify(reader, string.Empty);
 }
Beispiel #39
0
        public TIPOREGIAOCollection ReadCollectionByParameter(List <RowsFiltro> RowsFiltro, string FieldOrder)
        {
            FbDataReader         dataReader = null;
            TIPOREGIAOCollection collection = null;

            string strSqlCommand = String.Empty;

            try
            {
                if (RowsFiltro != null)
                {
                    if (RowsFiltro.Count > 0)
                    {
                        strSqlCommand = "SELECT * FROM TIPOREGIAO WHERE (";

                        ArrayList _rowsFiltro = new ArrayList();
                        RowsFiltro.ForEach(delegate(RowsFiltro i)
                        {
                            string[] item = { i.Condicao.ToString(), i.Campo.ToString(), i.Tipo.ToString(), i.Operador.ToString(), i.Valor.ToString() };
                            _rowsFiltro.Add(item);
                        });

                        int _count = 1;
                        foreach (string[] item in _rowsFiltro)
                        {
                            strSqlCommand += "(" + item[1] + " " + item[3];
                            switch (item[2])
                            {
                            case ("System.String"):
                                if (item[3].ToUpper() != "LIKE")
                                {
                                    strSqlCommand += " '" + item[4] + "')";
                                }
                                else
                                {
                                    strSqlCommand += " '%" + item[4] + "%')";
                                }
                                break;

                            case ("System.Int16"):
                                if (item[3].ToUpper() != "LIKE")
                                {
                                    strSqlCommand += " " + item[4] + ")";
                                }
                                else
                                {
                                    strSqlCommand += " '%" + item[4] + "%')";
                                }
                                break;

                            case ("System.Int32"):
                                if (item[3].ToUpper() != "LIKE")
                                {
                                    strSqlCommand += " " + item[4] + ")";
                                }
                                else
                                {
                                    strSqlCommand += " '%" + item[4] + "%')";
                                }
                                break;

                            case ("System.Int64"):
                                if (item[3].ToUpper() != "LIKE")
                                {
                                    strSqlCommand += " " + item[4] + ")";
                                }
                                else
                                {
                                    strSqlCommand += " '%" + item[4] + "%')";
                                }
                                break;

                            case ("System.Double"):
                                if (item[3].ToUpper() != "LIKE")
                                {
                                    strSqlCommand += " " + item[4] + ")";
                                }
                                else
                                {
                                    strSqlCommand += " '%" + item[4] + "%')";
                                }
                                break;

                            case ("System.Decimal"):
                                if (item[3].ToUpper() != "LIKE")
                                {
                                    strSqlCommand += " " + item[4] + ")";
                                }
                                else
                                {
                                    strSqlCommand += " '%" + item[4] + "%')";
                                }
                                break;

                            case ("System.Float"):
                                if (item[3].ToUpper() != "LIKE")
                                {
                                    strSqlCommand += " " + item[4] + ")";
                                }
                                else
                                {
                                    strSqlCommand += " '%" + item[4] + "%')";
                                }
                                break;

                            case ("System.Byte"):
                                strSqlCommand += " " + item[4] + ")";
                                break;

                            case ("System.SByte"):
                                strSqlCommand += " " + item[4] + ")";
                                break;

                            case ("System.Char"):
                                if (item[3].ToUpper() != "LIKE")
                                {
                                    strSqlCommand += " '" + item[4] + "')";
                                }
                                else
                                {
                                    strSqlCommand += " '%" + item[4] + "%')";
                                }
                                break;

                            case ("System.DateTime"):
                                if (item[3].ToUpper() != "LIKE")
                                {
                                    strSqlCommand += " '" + item[4] + "')";
                                }
                                else
                                {
                                    strSqlCommand += " '%" + item[4] + "%')";
                                }
                                break;

                            case ("System.Guid"):
                                if (item[3].ToUpper() != "LIKE")
                                {
                                    strSqlCommand += " '" + item[4] + "')";
                                }
                                else
                                {
                                    strSqlCommand += " '%" + item[4] + "%')";
                                }
                                break;

                            case ("System.Boolean"):
                                strSqlCommand += " " + item[4] + ")";
                                break;
                            }
                            if (_rowsFiltro.Count > 1)
                            {
                                if (_count < _rowsFiltro.Count)
                                {
                                    strSqlCommand += " " + item[0] + " ";
                                }
                                _count++;
                            }
                        }
                        strSqlCommand += ")  order by  " + FieldOrder;
                    }
                    else
                    {
                        strSqlCommand = "SELECT * FROM TIPOREGIAO  order by  " + FieldOrder;
                    }
                }
                else
                {
                    strSqlCommand = "SELECT * FROM TIPOREGIAO  order by " + FieldOrder;
                }

                //Verificando a existência de um transação
                if (dbTransaction != null)
                {
                    if (dbCnn.State == ConnectionState.Closed)
                    {
                        dbCnn.Open();
                    }

                    dbCommand             = new FbCommand(strSqlCommand, dbCnn);
                    dbCommand.CommandType = CommandType.Text;
                    dbCommand.Transaction = ((FbTransaction)(dbTransaction));
                }
                else
                {
                    if (dbCnn == null)
                    {
                        dbCnn = new FbConnection(connectionString);
                    }

                    if (dbCnn.State == ConnectionState.Closed)
                    {
                        dbCnn.Open();
                    }

                    dbCommand             = new FbCommand(strSqlCommand, dbCnn);
                    dbCommand.CommandType = CommandType.Text;
                    dbCommand.Transaction = dbCnn.BeginTransaction(IsolationLevel.ReadCommitted);
                }


                collection = ExecuteReader(ref collection, ref dataReader, dbCommand);

                if (dataReader != null)
                {
                    dataReader.Close();
                    dataReader.Dispose();
                }

                if (dbTransaction == null)
                {
                    dbCommand.Transaction.Commit();
                    dbCnn.Close();
                }

                return(collection);
            }
            catch (Exception ex)
            {
                // Deleta reader
                if (dataReader != null)
                {
                    dataReader.Close();
                    dataReader.Dispose();
                }

                if (dbTransaction != null)
                {
                    this.RollbackTransaction();
                }
                else
                {
                    if (dbCommand.Transaction != null)
                    {
                        dbCommand.Transaction.Rollback();
                    }
                    if (dbCnn.State == ConnectionState.Open)
                    {
                        dbCnn.Close();
                    }
                }

                throw ex;
            }
        }
Beispiel #40
0
        /// <summary>
        /// Criação das tabelas de Trace e Web
        /// TRACE
        /// GEN_TRACE
        /// SESSOES
        /// WEB
        /// HISTORICO_SITE
        /// 23/08/2015
        /// </summary>
        /// <returns>true=OK</returns>
        private bool TraceWeb()
        {
            string sql = "";

            try
            {
                sql = "select first 1 SEQ from TRACE";
                FbCommand    cmd    = new FbCommand(sql, Globais.bd);
                FbDataReader reader = cmd.ExecuteReader(CommandBehavior.Default);
                reader.Close();
                return(true);
            }
            catch
            {
                try
                {
                    sql = "create table TRACE("
                          + " SEQ                             INTEGER Not Null"
                          + ",DATAHORA                        TIMESTAMP"
                          + ",USUAARIO                        CHAR(20)"
                          + ",MENSAGEM                        VARCHAR(100))";
                    FbCommand cmd = new FbCommand(sql, Globais.bd);
                    Log.Grava(Globais.sUsuario, cmd.CommandText);
                    cmd.ExecuteNonQuery();

                    sql = "create generator GEN_TRACE";
                    cmd = new FbCommand(sql, Globais.bd);
                    Log.Grava(Globais.sUsuario, cmd.CommandText);
                    cmd.ExecuteNonQuery();

                    sql = "create table SESSOES("
                          + " DAT_ABERTURA                    DATE"
                          + ",COD_SESSAO                      CHAR(32)"
                          + ",COD_USUARIO                     CHAR(20))";
                    cmd = new FbCommand(sql, Globais.bd);
                    Log.Grava(Globais.sUsuario, cmd.CommandText);
                    cmd.ExecuteNonQuery();

                    sql = "create table WEB("
                          + " COD_USUARIO                     CHAR(20) Not Null"
                          + ",DES_SENHA                       CHAR(32)"
                          + ",NRO_ACESSOS                     INTEGER"
                          + ",DAT_ULTIMO_ACESSO               DATE"
                          + ",constraint PK_WEB primary key(COD_USUARIO))";
                    cmd = new FbCommand(sql, Globais.bd);
                    Log.Grava(Globais.sUsuario, cmd.CommandText);
                    cmd.ExecuteNonQuery();

                    sql = "create table HISTORICO_SITE("
                          + " DATA                            TIMESTAMP Not Null"
                          + ",SESSAO                          CHAR(32)"
                          + ",CLIENTE                         CHAR(20)"
                          + ",IP                              CHAR(32)"
                          + ",USUARIO                         CHAR(20)"
                          + ",DATA_SAIDA                      TIMESTAMP"
                          + ",constraint PK_HISTORICO_SITE primary key(DATA, SESSAO))";
                    cmd = new FbCommand(sql, Globais.bd);
                    Log.Grava(Globais.sUsuario, cmd.CommandText);
                    cmd.ExecuteNonQuery();

                    atualizacoes++;
                    return(true);
                }
                catch (Exception e)
                {
                    Log.Grava(Globais.sUsuario, "erro:" + e.Message);
                    MessageBox.Show("Erro na execução do comando:\r\n" + sql + "\r\n" + e.Message,
                                    "Erro na atualização do banco de dados", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return(false);
                }
            }
        }
Beispiel #41
0
        /// <summary>
        /// Criação das tabelas de ações comerciais
        /// ACOES_COMERCIAIS
        /// AGENDAMENTOS_ACOES
        /// PRODUTOS_ACAO
        /// PRODUTOS_POR_ACAO
        /// SITUACOES_ACAO
        /// ORIGENS
        /// GEN_ACAO_COMERCIAL
        /// 23/08/2015
        /// </summary>
        /// <returns>true=OK</returns>
        private bool AcoesComerciais()
        {
            string sql = "";

            try
            {
                sql = "select first 1 SEQ_ACAO from ACOES_COMERCIAIS";
                FbCommand    cmd    = new FbCommand(sql, Globais.bd);
                FbDataReader reader = cmd.ExecuteReader(CommandBehavior.Default);
                reader.Close();
                return(true);
            }
            catch
            {
                try
                {
                    sql = "create table ACOES_COMERCIAIS("
                          + " SEQ_ACAO                        INTEGER Not Null"
                          + ",COD_CLIENTE                     CHAR(20)"
                          + ",DES_OBRA                        CHAR(30)"
                          + ",DAT_PREVISAO                    DATE"
                          + ",COD_VENDEDOR                    CHAR(20)"
                          + ",COD_CONSULTOR                   CHAR(20)"
                          + ",IDT_SITUACAO                    CHAR(2)"
                          + ",TXT_OBSERVACAO                  VARCHAR(4000)"
                          + ",COD_ORIGEM                      CHAR(10)"
                          + ",TXT_CONCORRENTES                VARCHAR(4000)"
                          + ",DAT_PRIM_CONTATO                DATE"
                          + ",DAT_ULT_CONTATO                 DATE"
                          + ",constraint PK_ACOES_COMERCIAIS primary key(SEQ_ACAO))";
                    FbCommand cmd = new FbCommand(sql, Globais.bd);
                    Log.Grava(Globais.sUsuario, cmd.CommandText);
                    cmd.ExecuteNonQuery();

                    sql = "create table AGENDAMENTOS_ACOES("
                          + " SEQ_ACAO                        INTEGER Not Null"
                          + ",COD_USUARIO                     CHAR(20)"
                          + ",DAT_AGENDAMENTO                 TIMESTAMP"
                          + ",constraint PK_AGENDAMENTOS_ACOES primary key(SEQ_ACAO, COD_USUARIO, DAT_AGENDAMENTO))";
                    cmd = new FbCommand(sql, Globais.bd);
                    Log.Grava(Globais.sUsuario, cmd.CommandText);
                    cmd.ExecuteNonQuery();

                    sql = "create table PRODUTOS_ACAO("
                          + " COD_PRODUTO                     CHAR(10) Not Null"
                          + ",DES_PRODUTO                     CHAR(50)"
                          + ",constraint PK_PRODUTOS_ACAO primary key(COD_PRODUTO))";
                    cmd = new FbCommand(sql, Globais.bd);
                    Log.Grava(Globais.sUsuario, cmd.CommandText);
                    cmd.ExecuteNonQuery();

                    sql = "create table PRODUTOS_POR_ACAO("
                          + " SEQ_ACAO                        INTEGER Not Null"
                          + ",COD_PRODUTO                     CHAR(10)"
                          + ",constraint PK_PRODUTOS_POR_ACAO primary key(SEQ_ACAO, COD_PRODUTO))";
                    cmd = new FbCommand(sql, Globais.bd);
                    Log.Grava(Globais.sUsuario, cmd.CommandText);
                    cmd.ExecuteNonQuery();

                    sql = "create table SITUACOES_ACAO("
                          + " COD_SITUACAO                    CHAR(2) Not Null"
                          + ",DES_SITUACAO                    CHAR(50)"
                          + ",IDT_APRESENTA_AUTOM             CHAR(1)"
                          + ",IDT_CONCRETIZADA                CHAR(1)"
                          + ",constraint PK_SITUACOES_ACAO primary key(COD_SITUACAO))";
                    cmd = new FbCommand(sql, Globais.bd);
                    Log.Grava(Globais.sUsuario, cmd.CommandText);
                    cmd.ExecuteNonQuery();

                    sql = "create table ORIGENS("
                          + " COD_ORIGEM                      CHAR(10) Not Null"
                          + ",DES_ORIGEM                      CHAR(50)"
                          + ",constraint PK_ORIGENS primary key(COD_ORIGEM))";
                    cmd = new FbCommand(sql, Globais.bd);
                    Log.Grava(Globais.sUsuario, cmd.CommandText);
                    cmd.ExecuteNonQuery();

                    sql = "create generator GEN_ACAO_COMERCIAL";
                    cmd = new FbCommand(sql, Globais.bd);
                    Log.Grava(Globais.sUsuario, cmd.CommandText);
                    cmd.ExecuteNonQuery();

                    atualizacoes++;
                    return(true);
                }
                catch (Exception e)
                {
                    Log.Grava(Globais.sUsuario, "erro:" + e.Message);
                    MessageBox.Show("Erro na execução do comando:\r\n" + sql + "\r\n" + e.Message,
                                    "Erro na atualização do banco de dados", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return(false);
                }
            }
        }
Beispiel #42
0
        public static string RetornaBlob(string sQuery)
        {
            string texto = "";
            FbConnection Conn = HlpDbFuncoesGeral.conexao;
            FbCommand comando = new FbCommand(sQuery.ToString(), Conn);
            if (Conn.State == ConnectionState.Closed)
            {
                Conn.Open();
            }
            FbDataReader Reader = comando.ExecuteReader();
            Byte[] blob = null;
            MemoryStream ms = new MemoryStream();
            while (Reader.Read())
            {
                blob = new Byte[(Reader.GetBytes(0, 0, null, 0, int.MaxValue))];
                try
                {
                    Reader.GetBytes(0, 0, blob, 0, blob.Length);
                }
                catch
                {
                    texto = "";
                }
                ms = new MemoryStream(blob);
            }
            Conn.Close();

            StreamReader Ler = new StreamReader(ms);
            Ler.ReadLine();
            while (Ler.Peek() != -1)
            {
                texto += Ler.ReadLine();
            }
            if ((Acesso.NM_EMPRESA == "MACROTEX") || (Acesso.NM_EMPRESA == "PAVAX"))
            {
                string sVendedor = string.Empty;
                string sPedidoCliente = string.Empty;

                if (Conn.State != ConnectionState.Open)
                {
                    Conn.Open();
                }
                FbCommand cmd = new FbCommand(sQuery.ToString().Replace("nf.ds_anota ,", ""), Conn);
                cmd.ExecuteNonQuery();
                FbDataReader dr = cmd.ExecuteReader();
                dr.Read();

                sVendedor = dr["nm_vend"].ToString();
                sPedidoCliente = dr["DS_DOCORIG"].ToString();

                if ((Acesso.NM_EMPRESA == "MACROTEX"))
                {
                    if (texto == "")
                    {
                        texto += string.Format("Vendedor.: {0} Pedido N.: {1}",
                                               sVendedor,
                                               sPedidoCliente);

                    }
                    else
                    {
                        texto += string.Format(" Vendedor.: {0} Pedido N.: {1}",
                                               sVendedor,
                                               sPedidoCliente);
                    }
                }
                else
                {
                    if (texto == "")
                    {
                        texto += string.Format("Pedido N.: {0}",
                                               sPedidoCliente);

                    }
                    else
                    {
                        texto += string.Format(" Pedido N.: {0}",
                                               sPedidoCliente);
                    }
                }
            }
            if (((Acesso.NM_EMPRESA == "MOGPLAST") || (Acesso.NM_EMPRESA == "TSA")) && (Acesso.CD_EMPRESA == "003"))
            {
                string sNFOrigem = string.Empty;
                string sEmiOrigem = string.Empty;


                if (Conn.State != ConnectionState.Open)
                {
                    Conn.Open();
                }
                FbCommand cmd = new FbCommand(sQuery.ToString().Replace("nf.ds_anota ,", ""), Conn);
                cmd.ExecuteNonQuery();
                FbDataReader dr = cmd.ExecuteReader();
                dr.Read();

                //Claudinei - o.s. sem - 02/03/2010
                if (dr["cd_nfseq_fat_origem"].ToString() != "")
                {
                    //Fim - Claudinei - o.s. sem - 02/03/2010
                    StringBuilder sSqlNFOrigem = new StringBuilder();
                    sSqlNFOrigem.Append("Select ");
                    sSqlNFOrigem.Append("cd_notafis, ");
                    sSqlNFOrigem.Append("dt_emi ");
                    sSqlNFOrigem.Append("From NF ");
                    sSqlNFOrigem.Append("Where nf.cd_empresa = '");
                    sSqlNFOrigem.Append("001");
                    sSqlNFOrigem.Append("'");
                    sSqlNFOrigem.Append(" and ");
                    sSqlNFOrigem.Append("cd_nfseq = '");
                    sSqlNFOrigem.Append(dr["cd_nfseq_fat_origem"].ToString());
                    sSqlNFOrigem.Append("'");

                    FbCommand cmdNFOrigem = new FbCommand(sSqlNFOrigem.ToString(), Conn);
                    cmdNFOrigem.ExecuteNonQuery();

                    FbDataReader drNFOrigem = cmdNFOrigem.ExecuteReader();

                    drNFOrigem.Read();

                    sNFOrigem = drNFOrigem["cd_notafis"].ToString();
                    sEmiOrigem = System.DateTime.Parse(drNFOrigem["dt_emi"].ToString()).ToString("dd/MM/yyyy");

                    if (texto == "")
                    {
                        texto += string.Format("DEV TOTAL REF A NF {0} DE {1}",
                                               sNFOrigem,
                                               sEmiOrigem);

                    }
                    else
                    {
                        texto += string.Format(" DEV TOTAL REF A NF {0} DE {1}",
                                               sNFOrigem,
                                               sEmiOrigem);
                    }
                }
            }
            return Util.TiraCaracterEstranho(texto).Trim();
        }
		/// <summary>
		/// The trigger function for <see cref="CommandExecuted"/> event.
		/// </summary>
		/// <param name="commandText">The <see cref="FbCommand.CommandText"/> of the executed SQL command.</param>
		/// <param name="dataReader">The <see cref="FbDataReader"/> instance with the returned data. If the
		/// command executed is not meant to return data (ex: UPDATE, INSERT...) this parameter must be
		/// setled to <b>null</b>.</param>
		/// <param name="rowsAffected">The rows that were affected by the executed SQL command. If the executed
		/// command is not meant to return this kind of information (ex: SELECT) this parameter must
		/// be setled to <b>-1</b>.</param>
		protected void OnCommandExecuted(string commandText, FbDataReader dataReader, int rowsAffected)
		{
			CommandExecuted?.Invoke(this, new CommandExecutedEventArgs(dataReader, commandText, rowsAffected));
		}
Beispiel #44
0
        /// <summary>
        /// get all
        /// </summary>
        /// <param name="sBaixa">ABERTO, FECHADO, AMBOS</param>
        /// <param name="sCAMPO"> CD_CONHECI, DT_EMISSAO, DS_DESTINATARIO,CD_NF</param>
        /// <param name="sParametro">IGUAL, MAIOR, MENOR, ENTRE</param>
        /// <param name="sValor1"></param>
        /// <param name="sValor2"></param>
        /// <returns></returns>
        public List <daoConhecimento> GetAll(string sBaixa, string sCAMPO, string sParametro, string sValor1, string sValor2)
        {
            List <daoConhecimento> objListaConhecimento = new List <daoConhecimento>();

            if (sValor1 != null)
            {
                if (sValor1 != "")
                {
                    if (sCAMPO.Equals("CD_NF"))
                    {
                        objListaConhecimento = PesquisaPorNF(sBaixa, sParametro, sValor1, sValor2);
                    }
                    else
                    {
                        #region BUSCA CONHECIMENTOS
                        sValor1 = sValor1.ToUpper();
                        sValor2 = (sValor2 != null ? sValor2.ToUpper() : "");;

                        List <CamposSelect> lCampos = new List <CamposSelect>();
                        StringBuilder       sCampos = new StringBuilder();
                        sCampos.Append("SELECT ");
                        lCampos.Add(new CamposSelect {
                            sCampo = "conhec.NR_LANC", sAlias = "NR_LANC"
                        });
                        lCampos.Add(new CamposSelect {
                            sCampo = "conhec.CD_CONHECI", sAlias = "CD_CONHECI"
                        });
                        lCampos.Add(new CamposSelect {
                            sCampo = "conhec.DT_EMISSAO", sAlias = "DT_EMISSAO"
                        });
                        lCampos.Add(new CamposSelect {
                            sCampo = "dest.nm_social", sAlias = "DS_DESTINATARIO"
                        });
                        lCampos.Add(new CamposSelect {
                            sCampo = "redesp.nm_social", sAlias = "DS_REDESPACHO"
                        });
                        lCampos.Add(new CamposSelect {
                            sCampo = "conhec.CD_RESPONS", sAlias = "CD_RESPONS"
                        });
                        lCampos.Add(new CamposSelect {
                            sCampo = "coalesce(ST_CONHECI,0)", sAlias = "ST_CONHECI"
                        });
                        lCampos.Add(new CamposSelect {
                            sCampo = "coalesce(DT_CANCCON, '')", sAlias = "DT_CANCCON"
                        });
                        lCampos.Add(new CamposSelect {
                            sCampo = "conhec.ST_BAIXA", sAlias = "ST_BAIXA"
                        });
                        lCampos.Add(new CamposSelect {
                            sCampo = "coalesce(conhec.DT_BAIXA,'')", sAlias = "DT_BAIXA"
                        });
                        lCampos.Add(new CamposSelect {
                            sCampo = "conhec.CD_CFOP", sAlias = "CD_CFOP"
                        });
                        lCampos.Add(new CamposSelect {
                            sCampo = "conhec.DS_COLETA", sAlias = "DS_COLETA"
                        });
                        lCampos.Add(new CamposSelect {
                            sCampo = "conhec.CD_UFCOLE", sAlias = "CD_UFCOLE"
                        });
                        lCampos.Add(new CamposSelect {
                            sCampo = "(case when coalesce(conhec.cd_ocor,'0') <> 0 then (select tabocorr.ds_ocor from tabocorr where conhec.cd_ocor = tabocorr.cd_ocor) else '' end)", sAlias = "DS_OCOR"
                        });
                        lCampos.Add(new CamposSelect {
                            sCampo = "coalesce(conhec.ds_texto,'')", sAlias = "DS_TEXTO"
                        });
                        lCampos.Add(new CamposSelect {
                            sCampo = "conhec.DS_ENDENTREGA", sAlias = "DS_ENDENTREGA"
                        });
                        lCampos.Add(new CamposSelect {
                            sCampo = "(case when coalesce(conhec.cd_motoris,0) <> 0 then (select motorista.nm_motoris from motorista where motorista.cd_motoris = conhec.cd_motoris) else 'S/NOME' end)", sAlias = "NM_MOTORIS"
                        });
                        lCampos.Add(new CamposSelect {
                            sCampo = "coalesce(veiculo.cd_cidplac,'')", sAlias = "cd_cidplac"
                        });
                        lCampos.Add(new CamposSelect {
                            sCampo = "coalesce(veiculo.cd_placa,'')", sAlias = "cd_placa"
                        });
                        lCampos.Add(new CamposSelect {
                            sCampo = "coalesce(veiculo.cd_modelo,'') ", sAlias = "cd_modelo"
                        });

                        ConcatCampos(lCampos, sCampos);

                        StringBuilder sFrom = new StringBuilder();
                        sFrom.Append("FROM conhecim conhec left join remetent dest     on conhec.cd_destinat = dest.cd_remetent " + Environment.NewLine);
                        sFrom.Append("                     left join remetent redesp   on conhec.cd_redes = redesp.cd_remetent " + Environment.NewLine);
                        sFrom.Append("                     left join veiculo         on conhec.cd_veiculo = veiculo.cd_veiculo " + Environment.NewLine);

                        StringBuilder sWhere = new StringBuilder();
                        sWhere.Append("Where " + sCAMPO + " ");

                        string sLike    = " Like '%{0}%' ";
                        string soutros  = " {0} '{1}' ";
                        string sBetween = "{0} '{1}' and '{2}' ";


                        if (sCAMPO == "conhec.DT_EMISSAO")
                        {
                            sValor1 = (Convert.ToDateTime(sValor1)).ToString("dd.MM.yyyy");
                            if (sParametro == "between")
                            {
                                sValor2 = (Convert.ToDateTime(sValor2)).ToString("dd.MM.yyyy");
                            }
                        }
                        else if (sCAMPO == "conhec.CD_CONHECI")
                        {
                            sValor1 = sValor1.PadLeft(6, '0');
                            sValor2 = sValor2.PadLeft(6, '0');
                        }

                        switch (sParametro)
                        {
                        case "=":
                        {
                            if (sCAMPO != "conhec.DT_EMISSAO")
                            {
                                sWhere.Append(string.Format(sLike, sValor1));
                            }
                            else
                            {
                                sWhere.Append(string.Format(soutros, sParametro, sValor1));
                            }
                        }
                        break;

                        case ">": { sWhere.Append(string.Format(soutros, sParametro, sValor1)); }
                        break;

                        case "<": { sWhere.Append(string.Format(soutros, sParametro, sValor1)); }
                        break;

                        case "between": { sWhere.Append(string.Format(sBetween, sParametro, sValor1, sValor2)); }
                        break;

                        case "in": { sWhere.Append(string.Format(" in ('{0}','{1}') ", sValor1, sValor2)); }
                        break;
                        }

                        if (sBaixa != "A")
                        {
                            sWhere.Append(" and conhec.ST_BAIXA = '" + sBaixa + "'");
                        }

                        sWhere.Append(" and conhec.cd_remetent  = " + daoStatic.CD_CLIFOR + " ");

                        sWhere.Append(Environment.NewLine + " ORDER by conhec.dt_emissao desc,conhec.CD_CONHECI, conhec.st_baixa " + Environment.NewLine);


                        string sQuery = sCampos.ToString() + sFrom.ToString() + sWhere.ToString();

                        using (FbConnection Conn = new FbConnection(daoStatic.sConn))
                        {
                            try
                            {
                                Conn.Open();
                                using (FbCommand cmd = new FbCommand(sQuery, Conn))
                                {
                                    FbDataReader dr = cmd.ExecuteReader();
                                    while (dr.Read())
                                    {
                                        daoConhecimento objConhec = new daoConhecimento();
                                        objConhec.NR_LANC                       = dr["NR_LANC"].ToString();
                                        objConhec.CD_CONHECI                    = dr["CD_CONHECI"].ToString();
                                        objConhec.DT_EMISSAO                    = Convert.ToDateTime(dr["DT_EMISSAO"].ToString());
                                        objConhec.DS_DESTINATARIO               = dr["DS_DESTINATARIO"].ToString();
                                        objConhec.DS_REDESPACHO                 = dr["DS_REDESPACHO"].ToString();
                                        objConhec.CD_RESPONS                    = dr["CD_RESPONS"].ToString();
                                        objConhec.ST_CONHECI                    = dr["ST_CONHECI"].ToString();
                                        objConhec.DT_CANCCON                    = dr["DT_CANCCON"].ToString();
                                        objConhec.ST_BAIXA                      = dr["ST_BAIXA"].ToString();
                                        objConhec.DT_BAIXA                      = dr["DT_BAIXA"].ToString();
                                        objConhec.DadosAdicionais.DS_TEXTO      = dr["DS_TEXTO"].ToString();
                                        objConhec.DadosAdicionais.DS_OCOR       = dr["DS_OCOR"].ToString();
                                        objConhec.DadosAdicionais.CD_CFOP       = dr["CD_CFOP"].ToString();
                                        objConhec.DadosAdicionais.DS_COLETA     = dr["DS_COLETA"].ToString();
                                        objConhec.DadosAdicionais.CD_UFCOLE     = dr["CD_UFCOLE"].ToString();
                                        objConhec.DadosAdicionais.DS_ENDENTREGA = dr["DS_ENDENTREGA"].ToString();
                                        objConhec.Complemento.NM_MOTORIS        = dr["NM_MOTORIS"].ToString();
                                        objConhec.Complemento.CD_CIDPLAC        = dr["CD_CIDPLAC"].ToString();
                                        objConhec.Complemento.CD_PLACA          = dr["CD_PLACA"].ToString();
                                        objConhec.Complemento.CD_MODELO         = dr["CD_MODELO"].ToString();
                                        objListaConhecimento.Add(objConhec);
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                throw ex;
                            }
                            finally
                            { Conn.Close(); }
                        }
                        #endregion
                    }
                }
            }

            return(objListaConhecimento);
        }
Beispiel #45
0
 private Linea ReaderToEntidad(FbDataReader AReader)
 {
     Linea pResult  		= new Linea();
     pResult.Clave  		= (int)AReader["CLAVE"];
     pResult.Descripcion = (string)AReader["DESCRIPCION"];
     return pResult;
 }
Beispiel #46
0
        public List <daoConhecimento> PesquisaPorNF(string sBaixa, string sParametro, string sValor1, string sValor2)
        {
            List <daoConhecimento> objListaConhecimento = new List <daoConhecimento>();
            StringBuilder          sQuery = new StringBuilder();

            sValor1 = sValor1.PadLeft(6, '0');
            sValor2 = sValor2.PadLeft(6, '0');
            sQuery.Append("Select ");
            sQuery.Append("distinct(conhecim.cd_conheci) cd_conheci ");
            sQuery.Append("from nfconhec INNER JOIN conhecim on nfconhec.nr_lancconhecim = conhecim.nr_lanc ");
            if (sParametro != "between")
            {
                sQuery.Append(string.Format("Where nfconhec.cd_nf {0} '{1}' ", sParametro, sValor1));
            }
            else
            {
                sQuery.Append(string.Format("Where nfconhec.cd_nf {0} '{1}' and '{2}' ", sParametro, sValor1, sValor2));
            }

            sQuery.Append(string.Format("and conhecim.cd_remetent  = '{0}' ", daoStatic.CD_CLIFOR));


            using (FbConnection Conn = new FbConnection(daoStatic.sConn))
            {
                try
                {
                    using (FbCommand cmd = new FbCommand(sQuery.ToString(), Conn))
                    {
                        Conn.Open();
                        FbDataReader dr = cmd.ExecuteReader();

                        List <string> NFs = new List <string>();

                        while (dr.Read())
                        {
                            NFs.Add(dr["cd_conheci"].ToString());
                        }
                        string sNota1;
                        string sNota2;
                        if ((NFs.Count() > 0) && (NFs.Count() > 1))
                        {
                            sNota1 = NFs[0];
                            sNota2 = NFs[NFs.Count() - 1];
                            if (sNota2 == "")
                            {
                                sNota2 = NFs[NFs.Count() - 2];
                            }
                            objListaConhecimento = GetAll(sBaixa, "conhec.CD_CONHECI", "in", sNota1, sNota2);
                        }
                        else if (NFs.Count() == 1)
                        {
                            sNota1 = NFs[0];
                            sNota2 = NFs[NFs.Count() - 1];
                            objListaConhecimento = GetAll(sBaixa, "conhec.CD_CONHECI", "between", sNota1, sNota2);
                        }
                    }
                }
                catch (Exception)
                {
                    throw;
                }
                finally { Conn.Close(); }
            }
            return(objListaConhecimento);
        }
 public int GetRowCountOfTable(string table)
 {
     string query = "SELECT count(*) FROM " + Database + "." + table;
     cmd = new FbCommand(query, connection);
     reader = cmd.ExecuteReader();
     reader.Read();
     int cnt = reader.GetInt32(0);
     reader.Close();
     return cnt;
 }
        public bool Check(Dictionary <string, object> _params)
        {
            int    sendId   = 0;
            int    count    = 0;
            string filename = _params["filename"] as string;
            string connStr  = _params["connStr"] as string;

            using (FbConnection connection = new FbConnection(connStr)) {
                connection.Open();

                string req = "SELECT SENDID " +
                             "FROM SEND " +
                             "WHERE FILENAME LIKE '%" + Path.GetFileName(filename) + "%' " +
                             "ORDER BY SENDID DESC";
                using (FbCommand command = new FbCommand(req, connection)) {
                    using (FbTransaction transaction = connection.BeginTransaction()) {
                        command.Transaction = transaction;
                        using (FbDataReader reader = command.ExecuteReader()) {
                            while (reader.Read())
                            {
                                sendId = reader.GetSafeValue <int>("SENDID");

                                reader.Close();
                                break;
                            }
                            reader.Close();
                        }
                        transaction.Rollback();
                    }
                }
                if (sendId == 0)
                {
                    HasError    = true;
                    ErrorString = "Ошибка: файл '" + filename + "' не найден в БД ИС ОПС Почтовые отправления";
                    return(false);
                }

                req = "SELECT COUNT(SENDID) " +
                      "FROM DOCVAL " +
                      "WHERE SENDID = " + sendId.ToString();
                using (FbCommand command = new FbCommand(req, connection)) {
                    using (FbTransaction transaction = connection.BeginTransaction()) {
                        command.Transaction = transaction;
                        count = (int)command.ExecuteScalar();

                        transaction.Rollback();
                    }
                }
                if (count == 0)
                {
                    HasError    = true;
                    ErrorString = "Ошибка: файл '" + filename + "' не содержит записей";
                    return(false);
                }
            }

            try {
                string data      = string.Empty;
                bool   isArchive = true;

                using (ZipInputStream zip = new ZipInputStream(File.OpenRead(filename))) {
                    ZipEntry zipEntry;
                    try {
                        zipEntry = zip.GetNextEntry();
                        while (zipEntry != null)
                        {
                            if (zipEntry.Name != Path.GetFileName(filename))
                            {
                                HasError    = true;
                                ErrorString = "Ошибка: файл '" + filename + "' еще формируется либо поврежден";
                                return(false);
                            }

                            byte[] buffer = new byte[4096];
                            using (MemoryStream mem = new MemoryStream()) {
                                StreamUtils.Copy(zip, mem, buffer);
                                data = Encoding.Default.GetString(mem.ToArray());
                                break;
                            }
                        }
                    }
                    catch (ZipException) {
                        isArchive = false;
                    }
                    catch {
                        throw;
                    }
                }
                if (!isArchive)
                {
                    data = File.ReadAllText(filename);
                }

                int len = data.Where(x => x == Convert.ToByte('\n')).ToArray().Length;
                len -= 1;
                if (count != len)
                {
                    HasError    = true;
                    ErrorString = "Файл '" + filename + "' содержит не все записи. Записей " + len.ToString() + " из " + count.ToString();
                    return(false);
                }
            }
            catch (Exception error) {
                HasError    = true;
                ErrorString = "Ошибка: файл '" + filename + "' еще формируется либо поврежден. Текст ошибки: " + error.ToString();
                return(false);
            }

            return(true);
        }
 public override void FieldsFromReader(FbDataReader R)
 {
     ID = Guid.Parse(R["ID"].ToString());
     Code = Int32.Parse(R["Code"].ToString());
     Name = R["Name"].ToString();
     Birthday = DateTime.Parse(R["Birthday"].ToString());
     Gender = R["Gender"].ToString();
     Contract = R["Contract"].ToString();
     Date_of_assigment = DateTime.Parse(R["Date_of_assigment"].ToString());
     Date_of_dismissal = DateTime.Parse(R["Date_of_dismissal"].ToString());
     JT.SelectOne(Guid.Parse(R["Id_Jobtitle"].ToString()));
     Skills = R["Skills"].ToString();
 }
Beispiel #50
0
 public abstract void FieldsFromReader(FbDataReader R);
Beispiel #51
0
        /// <summary>
        /// Inclusão dos campos de pedidos na tabela AVISOS
        /// 12/02/2012
        /// </summary>
        /// <returns>true=OK</returns>
        private bool AvisosPedido()
        {
            /*
             * alter table avisos drop DIAS_CONFIRMACAO_ENTREGA;
             * alter table avisos drop FREQUENCIA_CONFIRMACAO_ENTREGA;
             * alter table avisos drop DIA_CONFIRMACAO_ENTREGA;
             * alter table avisos drop DIAS_ENTREGA;
             * alter table avisos drop FREQUENCIA_ENTREGA;
             * alter table avisos drop DIA_ENTREGA;
             * alter table avisos drop DIAS_MONTAGEM;
             * alter table avisos drop FREQUENCIA_MONTAGEM;
             * alter table avisos drop DIA_MONTAGEM;
             * alter table avisos drop DIAS_FATURAMENTO;
             * alter table avisos drop FREQUENCIA_FATURAMENTO;
             * alter table avisos drop DIA_FATURAMENTO;
             *
             * update avisos set ultima_verificacao='02/11/2012';
             * commit;
             */
            string sql = "";

            try
            {
                sql = "select first 1 DIAS_CONFIRMACAO_ENTREGA from AVISOS";
                FbCommand    cmd    = new FbCommand(sql, Globais.bd);
                FbDataReader reader = cmd.ExecuteReader(CommandBehavior.Default);
                reader.Close();
                return(true);
            }
            catch
            {
                try
                {
                    sql = "alter table AVISOS add DIAS_CONFIRMACAO_ENTREGA smallint";
                    FbCommand cmd = new FbCommand(sql, Globais.bd);
                    Log.Grava(Globais.sUsuario, cmd.CommandText);
                    cmd.ExecuteNonQuery();
                    sql = "update AVISOS set DIAS_CONFIRMACAO_ENTREGA=0";
                    cmd = new FbCommand(sql, Globais.bd);
                    Log.Grava(Globais.sUsuario, cmd.CommandText);
                    cmd.ExecuteNonQuery();
                    sql = "alter table AVISOS add FREQUENCIA_CONFIRMACAO_ENTREGA char(1)";
                    cmd = new FbCommand(sql, Globais.bd);
                    Log.Grava(Globais.sUsuario, cmd.CommandText);
                    cmd.ExecuteNonQuery();
                    sql = "update AVISOS set FREQUENCIA_CONFIRMACAO_ENTREGA='S'";
                    cmd = new FbCommand(sql, Globais.bd);
                    Log.Grava(Globais.sUsuario, cmd.CommandText);
                    cmd.ExecuteNonQuery();
                    sql = "alter table AVISOS add DIA_CONFIRMACAO_ENTREGA smallint";
                    cmd = new FbCommand(sql, Globais.bd);
                    Log.Grava(Globais.sUsuario, cmd.CommandText);
                    cmd.ExecuteNonQuery();
                    sql = "update AVISOS set DIA_CONFIRMACAO_ENTREGA=1";
                    cmd = new FbCommand(sql, Globais.bd);
                    Log.Grava(Globais.sUsuario, cmd.CommandText);
                    cmd.ExecuteNonQuery();

                    sql = "alter table AVISOS add DIAS_ENTREGA smallint";
                    cmd = new FbCommand(sql, Globais.bd);
                    Log.Grava(Globais.sUsuario, cmd.CommandText);
                    cmd.ExecuteNonQuery();
                    sql = "update AVISOS set DIAS_ENTREGA=0";
                    cmd = new FbCommand(sql, Globais.bd);
                    Log.Grava(Globais.sUsuario, cmd.CommandText);
                    cmd.ExecuteNonQuery();
                    sql = "alter table AVISOS add FREQUENCIA_ENTREGA char(1)";
                    cmd = new FbCommand(sql, Globais.bd);
                    Log.Grava(Globais.sUsuario, cmd.CommandText);
                    cmd.ExecuteNonQuery();
                    sql = "update AVISOS set FREQUENCIA_ENTREGA='S'";
                    cmd = new FbCommand(sql, Globais.bd);
                    Log.Grava(Globais.sUsuario, cmd.CommandText);
                    cmd.ExecuteNonQuery();
                    sql = "alter table AVISOS add DIA_ENTREGA smallint";
                    cmd = new FbCommand(sql, Globais.bd);
                    Log.Grava(Globais.sUsuario, cmd.CommandText);
                    cmd.ExecuteNonQuery();
                    sql = "update AVISOS set DIA_ENTREGA=1";
                    cmd = new FbCommand(sql, Globais.bd);
                    Log.Grava(Globais.sUsuario, cmd.CommandText);
                    cmd.ExecuteNonQuery();

                    sql = "alter table AVISOS add DIAS_MONTAGEM smallint";
                    cmd = new FbCommand(sql, Globais.bd);
                    Log.Grava(Globais.sUsuario, cmd.CommandText);
                    cmd.ExecuteNonQuery();
                    sql = "update AVISOS set DIAS_MONTAGEM=0";
                    cmd = new FbCommand(sql, Globais.bd);
                    Log.Grava(Globais.sUsuario, cmd.CommandText);
                    cmd.ExecuteNonQuery();
                    sql = "alter table AVISOS add FREQUENCIA_MONTAGEM char(1)";
                    cmd = new FbCommand(sql, Globais.bd);
                    Log.Grava(Globais.sUsuario, cmd.CommandText);
                    cmd.ExecuteNonQuery();
                    sql = "update AVISOS set FREQUENCIA_MONTAGEM='S'";
                    cmd = new FbCommand(sql, Globais.bd);
                    Log.Grava(Globais.sUsuario, cmd.CommandText);
                    cmd.ExecuteNonQuery();
                    sql = "alter table AVISOS add DIA_MONTAGEM smallint";
                    cmd = new FbCommand(sql, Globais.bd);
                    Log.Grava(Globais.sUsuario, cmd.CommandText);
                    cmd.ExecuteNonQuery();
                    sql = "update AVISOS set DIA_MONTAGEM=1";
                    cmd = new FbCommand(sql, Globais.bd);
                    Log.Grava(Globais.sUsuario, cmd.CommandText);
                    cmd.ExecuteNonQuery();

                    sql = "alter table AVISOS add DIAS_FATURAMENTO smallint";
                    cmd = new FbCommand(sql, Globais.bd);
                    Log.Grava(Globais.sUsuario, cmd.CommandText);
                    cmd.ExecuteNonQuery();
                    sql = "update AVISOS set DIAS_FATURAMENTO=0";
                    cmd = new FbCommand(sql, Globais.bd);
                    Log.Grava(Globais.sUsuario, cmd.CommandText);
                    cmd.ExecuteNonQuery();
                    sql = "alter table AVISOS add FREQUENCIA_FATURAMENTO char(1)";
                    cmd = new FbCommand(sql, Globais.bd);
                    Log.Grava(Globais.sUsuario, cmd.CommandText);
                    cmd.ExecuteNonQuery();
                    sql = "update AVISOS set FREQUENCIA_FATURAMENTO='S'";
                    cmd = new FbCommand(sql, Globais.bd);
                    Log.Grava(Globais.sUsuario, cmd.CommandText);
                    cmd.ExecuteNonQuery();
                    sql = "alter table AVISOS add DIA_FATURAMENTO smallint";
                    cmd = new FbCommand(sql, Globais.bd);
                    Log.Grava(Globais.sUsuario, cmd.CommandText);
                    cmd.ExecuteNonQuery();
                    sql = "update AVISOS set DIA_FATURAMENTO=1";
                    cmd = new FbCommand(sql, Globais.bd);
                    Log.Grava(Globais.sUsuario, cmd.CommandText);
                    cmd.ExecuteNonQuery();
                    atualizacoes++;
                    return(true);
                }
                catch (Exception e)
                {
                    Log.Grava(Globais.sUsuario, "erro:" + e.Message);
                    MessageBox.Show("Erro na execução do comando:\r\n" + sql + "\r\n" + e.Message,
                                    "Erro na atualização do banco de dados", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return(false);
                }
            }
        }
 public override void FieldsFromReader(FbDataReader R)
 {
     ID = Guid.Parse(R["ID"].ToString());
     Name = R["Name"].ToString();
     CreationDate = DateTime.Parse(R["CREATION_DATE"].ToString());
 }
		public DateTime GetNullableDateTime(FbDataReader reader, int col)
		{
			return reader.IsDBNull(col) == false ? reader.GetDateTime(col) : DateTime.Parse("1/1/1900");
		}
Beispiel #54
0
 private void ConsultarTipoHorario(FbDataReader dr)
 {
     txtthocodi.Text = dr["THOCODI"].ToString();
     txtthonome.Text = dr["THONOME"].ToString();
 }
Beispiel #55
0
 internal void CloseReader()
 {
     if (this.activeReader != null)
     {
         this.activeReader.Close();
         this.activeReader = null;
     }
 }
Beispiel #56
0
        private void SummaryReportSelect_Shown(object sender, EventArgs e)
        {
            FbConnection fb_con = new FbConnection(ConnectionString);

            if (fb_con.State == System.Data.ConnectionState.Closed)
            {
                fb_con.Open();
            }

            FbTransaction fb_trans = null;

            fb_trans = fb_con.BeginTransaction();

            FbCommand SelectReports = new FbCommand("select id, displayname from reportforms where mask = 2 and visible = 1 order by displayname",
                                                    fb_con, fb_trans);

            FbDataReader readerReports = null;

            try
            {
                try
                {
                    readerReports = SelectReports.ExecuteReader();

                    if (ReportList == null)
                    {
                        ReportList = new List <ReportsFit>();
                    }
                    ReportList.Clear();

                    this.groupBox1.AutoSize = true;
                    this.groupBox1.Controls.Clear();

                    int i = 0;
                    while (readerReports.Read())
                    {
                        RadioButton rb = new RadioButton();
                        rb.Text     = readerReports.GetString(1);
                        rb.Name     = "RadioButton" + i.ToString();
                        rb.Location = new Point(5, 30 * (i + 1));
                        rb.AutoSize = true;
                        // checkedListBox1.Items.Add(readerReports.GetString(1), false);
                        groupBox1.Controls.Add(rb);

                        ReportList.Add(new ReportsFit((int)readerReports[0]));
                        i++;
                    }
                }
                catch (Exception ex)
                {
                    fb_trans.Rollback();
                    MessageBox.Show("Error info (summary) = " + ex.ToString());
                }
            }
            finally
            {
                if (readerReports != null)
                {
                    readerReports.Close();
                }

                if (fb_trans != null)
                {
                    fb_trans.Dispose();
                }

                if (SelectReports != null)
                {
                    SelectReports.Dispose();
                }

                if (fb_con != null && fb_con.State == System.Data.ConnectionState.Open)
                {
                    fb_con.Close();
                }
            }
        }
Beispiel #57
0
        public string BuscaObs(string sNF)
        {
            string sObs = "";

            try
            {
                StringBuilder sQuery = new StringBuilder();
                sQuery.Append("Select ");
                sQuery.Append("nf.ds_anota ");
                if (((Acesso.NM_EMPRESA == "MOGPLAST") || (Acesso.NM_EMPRESA == "TSA")) && (Acesso.CD_EMPRESA == "003"))
                {
                    sQuery.Append(", nf.cd_nfseq_fat_origem ");
                }
                if (Acesso.NM_EMPRESA == "MACROTEX")
                {
                    sQuery.Append(", vendedor.nm_vend, ");
                    sQuery.Append("nf.DS_DOCORIG ");
                }
                sQuery.Append("From NF ");
                sQuery.Append("left join vendedor on (vendedor.cd_vend = nf.cd_vend1) ");
                sQuery.Append("Where ");
                sQuery.Append("(NF.cd_empresa ='");
                sQuery.Append(Acesso.CD_EMPRESA);
                sQuery.Append("')");
                sQuery.Append(" and ");
                sQuery.Append("(nf.cd_nfseq = '");
                sQuery.Append(sNF);
                sQuery.Append("') ");

                FbDataReader dr = BuscaObservacao(sQuery);

                sObs = daoUtil.RetornaBlob(sQuery.ToString());
                if (sObs.IndexOf("\\fs") != -1)
                {
                    sObs = sObs.Substring((sObs.IndexOf("\\fs") + 6), sObs.Length - (sObs.IndexOf("\\fs") + 6));
                }

                if (Acesso.NM_EMPRESA.Equals("LORENZON"))
                {
                    StringBuilder sQueryLorenzon = new StringBuilder();
                    sQueryLorenzon.Append("select prazos.ds_prazo, vendedor.nm_vend , clifor.cd_clifor from nf ");
                    sQueryLorenzon.Append("inner join clifor on nf.cd_clifor = clifor.cd_clifor ");
                    sQueryLorenzon.Append("inner join prazos on nf.cd_prazo = prazos.cd_prazo ");
                    sQueryLorenzon.Append(" inner join vendedor  on nf.cd_vendint = vendedor.cd_vend ");
                    sQueryLorenzon.Append("where nf.cd_nfseq = '" + sNF + "' ");
                    sQueryLorenzon.Append("and nf.cd_empresa = '" + Acesso.CD_EMPRESA + "' ");

                    DataTable dtLorenzon   = HlpDbFuncoes.qrySeekRet(sQueryLorenzon.ToString());
                    string    sMsgLorenzon = "";

                    if (dtLorenzon != null)
                    {
                        foreach (DataRow row in dtLorenzon.Rows)
                        {
                            sMsgLorenzon = "COND.PGTO = " + row["ds_prazo"].ToString() + " | VENDEDOR = " + row["nm_vend"].ToString() + " | COD. CLIENTE = " + row["cd_clifor"].ToString();
                        }
                    }

                    //while (dtLorenzon.Read())
                    //{
                    //    sMsgLorenzon = "COND.PGTO = " + dtLorenzon["ds_prazo"].ToString() + " | VENDEDOR = " + dtLorenzon["nm_vend"].ToString() + " | COD. CLIENTE = " + dtLorenzon["cd_clifor"].ToString();
                    //}

                    sMsgLorenzon = sMsgLorenzon + Environment.NewLine + Environment.NewLine;
                    if (sMsgLorenzon != "")
                    {
                        sObs = sMsgLorenzon + sObs;
                    }
                }

                return(sObs);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Beispiel #58
0
 public static string GetTrimmedString(this FbDataReader dr, int ordinal)
 {
     return(dr.GetString(ordinal)?.Trim());
 }
 /// <summary>
 /// The trigger function for <see cref="CommandExecuted"/> event.
 /// </summary>
 /// <param name="commandText">The <see cref="FbCommand.CommandText"/> of the executed SQL command.</param>
 /// <param name="dataReader">The <see cref="FbDataReader"/> instance with the returned data. If the 
 /// command executed is not meant to return data (ex: UPDATE, INSERT...) this parameter must be 
 /// setled to <b>null</b>.</param>
 /// <param name="rowsAffected">The rows that were affected by the executed SQL command. If the executed 
 /// command is not meant to return this kind of information (ex: SELECT) this parameter must 
 /// be setled to <b>-1</b>.</param>
 protected void OnCommandExecuted(string commandText, FbDataReader dataReader, int rowsAffected)
 {
     if (CommandExecuted != null)
     {
         CommandExecutedEventArgs e = new CommandExecutedEventArgs(dataReader, commandText, rowsAffected);
         CommandExecuted(this, e);
     }
 }
Beispiel #60
0
 private void ConsultaPais(FbDataReader dr)
 {
     txtpaicodi.Text = dr["PAICODI"].ToString();
     txtpainome.Text = dr["PAINOME"].ToString();
 }