Inheritance: System.Data.Common.DbDataReader
        public void Fact()
        {
            var connection = default (DbConnection);
            var reader = default(DbDataReader);

            try
            {
                connection = KandaXunitProviderFactory.Instance.CreateConnection();
                connection.Open();

                var schema = connection.GetTablesSchema();
                reader = new DataTableReader(schema);

                while (reader.Read())
                {
                    var name = reader.GetString(reader.GetOrdinal(@"TABLE_NAME"));
                    var type = reader.GetString(reader.GetOrdinal(@"TABLE_TYPE"));

                    //this.transformEntity(name, type);
                    this.transformInsertTable(name, type);
                }
            }
            finally
            {
                if (reader != null) { reader.Close(); }
                if (connection != null) { connection.Close(); }
            }
        }
Exemple #2
0
    static void Main()
    {
        var dt = new System.Data.DataTable();

        dt.Columns.Add("ID", typeof(String));
        dt.Columns.Add("Val", typeof(int));

        dt.Rows.Add("1", 10);
        dt.Rows.Add("2", 20);
        dt.Rows.Add("3", 10);
        dt.Rows.Add("4", 20);

        System.Data.DataTableReader dr = dt.CreateDataReader();

        for (int I = 0; I < dr.FieldCount; I++)
        {
            Console.Write(dr.GetName(I) + ",");
        }
        Console.WriteLine();

        while (dr.Read())
        {
            for (int I = 0; I < dr.FieldCount; I++)
            {
                Console.Write(dr[dr.GetName(I)] + ",");
            }
            Console.WriteLine();
        }
    }
        public void TransformTextFact()
        {
            var connection = default(DbConnection);
            var reader = default(DbDataReader);

            try
            {
                connection = this._factory.CreateConnection();
                connection.Open();

                var schema = connection.GetTablesSchema();
                reader = new DataTableReader(schema);

                while (reader.Read())
                {
                    var name = TextTemplateFact.GetTableName(reader);
                    var type = TextTemplateFact.GetTableType(reader);

                    var context = new InsertTableContext(name, type)
                                      {
                                          ProcedureNamePrefix = @"usp_", 
                                          ProcedureNameSuffix = @"", 
                                      };
                    var template = new InsertTableTemplate(context);
                    template.Initialize();
                    var text = template.TransformText();
                    // TODO : 
                }
            }
            finally
            {
                if (reader != null) { reader.Close(); }
                if (connection != null) { connection.Close(); }
            }
        }
        private static void Populate(System.Data.DataTableReader dr, Vare rec)
        {
            var with_1 = rec;

            with_1.VareGrpID         = System.Convert.ToInt32(dr.DBtoInt("VareGrpID"));
            with_1.VareNr            = dr.DBtoString("VareNr");
            with_1.Navn              = dr.DBtoString("Navn");
            with_1.Beskrivelse       = dr.DBtoString("Beskrivelse");
            with_1._CurrencyID       = System.Convert.ToInt32(dr.DBtoInt("CurrencyID"));
            with_1._CurrencyRate     = System.Convert.ToDecimal(dr.DBtoDecimal("CurrencyRate"));
            with_1._Indkobspris      = System.Convert.ToDecimal(dr.DBtoDecimal("Indkobspris"));
            with_1._FragtPct         = System.Convert.ToDecimal(dr.DBtoDecimal("FragtPct"));
            with_1._Fragt            = System.Convert.ToDecimal(dr.DBtoDecimal("Fragt"));
            with_1._KostprisCurrency = System.Convert.ToDecimal(dr.DBtoDecimal("KostprisCurrency"));
            with_1._KostprisDKK      = System.Convert.ToDecimal(dr.DBtoDecimal("KostprisDKK"));
            with_1._DaekningsBidrag  = System.Convert.ToDecimal(dr.DBtoDecimal("DaekningsBidrag"));
            with_1._DaekningsGrad    = System.Convert.ToDecimal(dr.DBtoDecimal("DaekningsGrad"));
            with_1._SalgsPris        = System.Convert.ToDecimal(dr.DBtoDecimal("SalgsPris"));
            with_1.Status            = (RescueTekniq.BOL.VareStatusEnum)(dr.DBtoInt("Status"));
            with_1.FragtID           = System.Convert.ToInt32(dr.DBtoInt("FragtID"));
            with_1.FaktaArkPath      = dr.DBtoString("FaktaArkPath");
            with_1.SupplierItemNo    = dr.DBtoString("SupplierItemNo");
            with_1.SupplierItemName  = dr.DBtoString("SupplierItemName");
            PopulateStandard(dr, rec);
        }
 private void FillPartyName()
 {
     DataTableReader read = new DataTableReader(this.maindataset.Pending);
     while (read.Read())
     {
         txtPartyName.Items.Add(read.GetString(3));
     }
 }
        public void GetColumnAsArrayOf_Int_ReturnsIntArray()
        {
            var expected = new[] {1, 2};

            using (var dr = new DataTableReader(_dt1)) {
                var values = dr.GetColumnAsArrayOf<int>("id");
                Assert.AreEqual(expected, values);
            }
        }
        public void GetColumnNames_Dt1_GetsColumnNames()
        {
            var expected = new[] {"id", "time", "amount", "description"};

            using (var dr = new DataTableReader(_dt1)) {
                var names = dr.GetColumnNames();
                Assert.AreEqual(expected, names);
            }
        }
        public void Databse_ReadLikeQuery_Accept()
        {
            // execute the readLike query on the data
            DataTable testTable = new DataTable();
            testTable = Database.ReadLikeQuery("files", "id", "2", Database.LikeLocation.Before);

            //check if it worked
            DataTableReader reader = new DataTableReader(testTable);
            Assert.True((reader[0] + " ").Equals(@"1 C:\Users\hdizzle\Desktop\Zoodevio Library\attack on titan\Attack on Titan (Shingeki no Kyojin)  S01E16 What Should Be Done.mp4 11/13/2015 1:22:25 AM 11/13/2015 1:22:25 AM"));
        }
Exemple #9
0
        public List <T> ExecuteAndReturn <T>(DbCommand command)
        {
            List <T> result;

            using (System.Data.DataTableReader reader = this.ExecuteDataSet(command).CreateDataReader())
            {
                result = reader.AutoMap <T>();
            }
            return(result);
        }
        public void Setup()
        {
            var schemaTable = new DataTable();
            schemaTable.Locale = CultureInfo.InvariantCulture;

            mockDataReader = new Mock<IDataReader>();
            mockDataReader.Setup(r => r.GetSchemaTable()).Returns(schemaTable);

            actualDataReader = new DataTableReader(BuildDataTable());
        }
Exemple #11
0
        public List <T> ExecuteAndReturn <T>(DbCommand command, Action <T, System.Data.IDataRecord> customMapper, int expectedPropertyMatches) where T : new()
        {
            List <T> result;

            using (System.Data.DataTableReader reader = this.ExecuteDataSet(command).CreateDataReader())
            {
                result = reader.AutoMap(customMapper, expectedPropertyMatches);
            }
            return(result);
        }
        /// <summary>
        /// 現在のカタログのテーブル定義を取得して返します。
        /// </summary>
        /// <param name="connection"></param>
        /// <returns></returns>
        public IEnumerable<TableSchemaEntity> GetTablesSchema(DbConnection connection)
        {
            var schema = connection.GetTablesSchema();
            var reader = new DataTableReader(schema);

            // TODO: KandaDbDataMapper.MapToEnumerableAsync<T>()
            var tables = KandaDbDataMapper.MapToEnumerable<TableSchemaEntity>(reader);

            return tables;
        }
 public DataTableReaderEx(DataTable pTable)
 {
     this.isDisposed = false;
     // Thank you MicroSoft, for making it a sealed class...
     this.reader = new DataTableReader(pTable);
     for (int i = 0; i < pTable.Columns.Count; ++i)
     {
         this.columns.Add(pTable.Columns[i].Caption.ToLower(), i);
     }
 }
Exemple #14
0
        public List <T> ExecuteAndReturn <T>(DbCommand command, Action <T, System.Data.IDataRecord> customMapper, params string[] autoMapColumns) where T : new()
        {
            List <T> result;

            using (System.Data.DataTableReader reader = this.ExecuteDataSet(command).CreateDataReader())
            {
                result = reader.AutoMap(customMapper, autoMapColumns);
            }
            return(result);
        }
Exemple #15
0
        public List <T> ExecuteAndReturn <T>(DbCommand command, params ColumnNameMapping[] customNameMappings) where T : new()
        {
            List <T> result;

            using (System.Data.DataTableReader reader = this.ExecuteDataSet(command).CreateDataReader())
            {
                result = reader.AutoMap <T>(customNameMappings);
            }
            return(result);
        }
 private void SupBillReceived_Load(object sender, EventArgs e)
 {
     // TODO: This line of code loads data into the 'maindataset.mainbill' table. You can move, or remove it, as needed.
     this.mainbillTableAdapter.Fill(this.maindataset.mainbill);
     DataTable table = this.maindataset.Tables["mainbill"];
     DataTableReader read = new DataTableReader(table);
     while (read.Read())
     {
         comboDebitBillNumber.Properties.Items.Add(read.GetInt32(3).ToString());
     }
 }
 private void FillComDebitBillIdIsFalse()
 {
     this.selectlocalbillTableAdapter.Fill(this.lclsupset.selectlocalbill);
     DataTable table = this.lclsupset.Tables["selectlocalbill"];
     DataTableReader read = new DataTableReader(table);
     comboDebitBillNumber.Properties.Items.Clear();
     while (read.Read())
     {
         comboDebitBillNumber.Properties.Items.Add(read.GetInt32(1).ToString());
     }
 }
 internal DataTableReaderListener(DataTableReader reader) {
     if (reader == null)
         throw ExceptionBuilder.ArgumentNull("DataTableReader");
     if (currentDataTable != null) {
         UnSubscribeEvents();
     }
     this.readerWeak = new WeakReference(reader);
     currentDataTable = reader.CurrentDataTable;
     if (currentDataTable != null)
         SubscribeEvents();
 }
        public void GetValue_ValidColumnIdentifiers_ReturnsCorrectType()
        {
            using (var dr = new DataTableReader(_dt1)) {
                dr.Read();
                Assert.AreEqual(1, dr.GetValue<int>("id"), "ID");
                Assert.AreEqual(1L, dr.GetValue<long>("id"), "ID as long");
                Assert.AreEqual(1, dr.GetValue<ushort>("id"), "ID as short");
                Assert.AreEqual(1, dr.GetValue<byte>("id"), "ID as byte");

                Assert.AreEqual(new DateTime(2011, 03, 31, 18, 22, 13), dr.GetValue<DateTime>("time"), "Time");
                Assert.AreEqual(70.41f, dr.GetValue<decimal>("amount"), "Amount");
                Assert.AreEqual("Kaffe", dr.GetValue<string>("description"), "Description");
            }
        }
Exemple #20
0
 private static string[] GetFromDataBase()
 {
     CheckLane.lanesetTableAdapters.tariff_oceanTableAdapter tableAdapter = new CheckLane.lanesetTableAdapters.tariff_oceanTableAdapter();
     laneset.tariff_oceanDataTable table = new laneset.tariff_oceanDataTable();
     tableAdapter.Fill(table);
     DataTableReader reader = new DataTableReader(table);
     string[] laneid = new string[table.Rows.Count];
     int counter = 0;
     while (reader.Read())
     {
         laneid[counter++] = reader[0].ToString();
     }
     return laneid;
 }
        public void should_map_enums()
        {
            var value = FoobarEnum.Bar;
            using (var table = CreateTable("Enum", value, typeof(int)))
            {
                var mapper = CreateMapper(table, x => x.Value(y => y.Enum));
                using (var reader = new DataTableReader(table))
                {
                    reader.Read();
                    var person = (Foobar)mapper.Map(reader, typeof(Foobar));

                    Assert.That(person.Enum, Is.EqualTo(value));
                }
            }
        }
        public void should_map_ids()
        {
            var value = 1;
            using (var table = CreateTable("Id", value))
            {
                var mapper = CreateMapper(table, x => x.Id(y => y.Id));
                using (var reader = new DataTableReader(table))
                {
                    reader.Read();
                    var person = (Foobar)mapper.Map(reader, typeof(Foobar));

                    Assert.That(person.Id, Is.EqualTo(value));
                }
            }
        }
        public void Database_SimpleStarQuery_Accept()
        {
            //give the database some data
            var rows = new String[] { "id", "path", "date_added", "date_edited" };
            var data = new String[] { "1", "path", "now", "now" };
            Database.SimpleInsertQuery("files", rows, data);

            // execute the satr query on the data
            DataTable testTable = new DataTable();
            testTable = Database.SimpleStarQuery("files");

            //check if it worked
            DataTableReader reader = new DataTableReader(testTable);
            Assert.True((reader[0] + " ").Equals("1 path now now"));
        }
        public void Database_SimpleReadQuery_Accept()
        {
            //give the database some data
            //var rows = new String[] { "id", "path", "date_added", "date_edited" };
            //var data = new String[] { "1", "path", "now", "now" };
            //Database.SimpleInsertQuery("files", rows, data);

            // execute the read query on the data
            DataTable testTable = new DataTable();
            testTable = Database.SimpleReadQuery("files", "id", "1");

            //check if it worked
            DataTableReader reader = new DataTableReader(testTable);
            Assert.True((reader[0] + " ").Equals(@"1 C:\Users\hdizzle\Desktop\Zoodevio Library\attack on titan\Attack on Titan (Shingeki no Kyojin)  S01E16 What Should Be Done.mp4 11/13/2015 1:22:25 AM 11/13/2015 1:22:25 AM"));
        }
        public void should_map_nullable_type_with_value()
        {
            var value = 1;
            using (var table = CreateTable("NullableValueDefaultsToZero", value))
            {
                var mapper = CreateMapper(table, x => x.Value(y => y.NullableValueDefaultsToZero));
                using (var reader = new DataTableReader(table))
                {
                    reader.Read();
                    var person = (Foobar)mapper.Map(reader, typeof(Foobar));

                    Assert.That(person.NullableValueDefaultsToZero, Is.EqualTo(value));
                }
            }
        }
        public void MapUnexistPropertyException_Test()
        {
            ObjectConverter objectConverter = new ObjectConverter();

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

            dt.Rows.Add("QQ");
            var reader = new DataTableReader(dt);
            reader.Read();
            MapWithoutPropertyTestObject1 obj = new MapWithoutPropertyTestObject1();
            objectConverter.MapObject(reader, obj);

            Assert.AreEqual("QQ", obj.Name);
            Assert.AreEqual(100, obj.Age);
        }
        private string GetEntrada(DataTableReader row, string saida)
        {
            var parametros = new List<string>
                                          {
                                              "LAT=" + row["LAT"].ToString(),
                                              "LONG=" + row["LONG"].ToString(),
                                              "ZONA=" + row["ZONA"].ToString(),
                                              "PRIO=" + row["PRIORIDADE"].ToString(),
                                              "DIST_BUSCA=" + row["DIST_BUSCA"].ToString(),
                                              "SIS_Coord=" + row["SISTEMA_COORDERNADA"].ToString(),
                                              "Zona=" + row["Zona"].ToString(),
                                              "F=" + saida
                                          };

            return string.Join("&", parametros);
        }
Exemple #28
0
                public void CtorTest ()
                {
                        dt.Rows [1].Delete ();
                        DataTableReader reader = new DataTableReader (dt);
                        try {
                                
                                int i = 0;
                                while (reader.Read ())
                                        i++;
                                reader.Close ();

                                Assert.AreEqual (2, i, "no. of rows iterated is wrong");
                        } finally {
                                if (reader != null && !reader.IsClosed)
                                        reader.Close ();
                        }
                }
        public string GetResult(DataTableReader row, string saida)
        {
            var parametros = GetEntrada(row,saida);
            var requestUrl = URL + parametros;

            DateTime inicio = DateTime.Now;

            var httpWebRequest = (HttpWebRequest)WebRequest.Create(requestUrl);

            using (var httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse())
            {
                TimeSpan span = DateTime.Now - inicio;
                var streamReader = new StreamReader(httpWebResponse.GetResponseStream(), Encoding.UTF8);

                return streamReader.ReadToEnd();
            }
        }
        private void Write(DataTable dataTable)
        {
            // connect to SQL
            using (var connection = new SqlConnection(connString))
            {
                // set the destination table name
                connection.Open();

                using (var bulkCopy = MakeSqlBulkCopy(connection))
                {               
                    using (var dataTableReader = new DataTableReader(dataTable))
                    {
                        bulkCopy.WriteToServer(dataTableReader);
                    }                    
                }
            }
        }
Exemple #31
0
 //对下拉列表进行数据绑定
 private void CBoxBind()
 {
     cbox_SheetName.Items.Clear();//清空下拉列表项
     //连接Excel数据库
     OleDbConnection olecon = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + txt_Path.Text + ";Extended Properties=Excel 8.0");
     olecon.Open();//打开数据库连接
     System.Data.DataTable DTable = olecon.GetSchema("Tables");//实例化表对象
     DataTableReader DTReader = new DataTableReader(DTable);//实例化表读取对象
     while (DTReader.Read())//循环读取
     {
         cbox_SheetName.Items.Add(DTReader["Table_Name"].ToString().Replace('$',' ').Trim());//将工作表名添加到下拉列表中
     }
     DTable = null;//清空表对象
     DTReader = null;//清空表读取对象
     olecon.Close();//关闭数据库连接
     cbox_SheetName.SelectedIndex = 0;//设置下拉列表默认选项为第一项
 }
 internal DataTableReaderListener(DataTableReader reader)
 {
     if (reader == null)
     {
         throw ExceptionBuilder.ArgumentNull(nameof(DataTableReader));
     }
     if (_currentDataTable != null)
     {
         UnSubscribeEvents();
     }
     _readerWeak = new WeakReference(reader);
     _currentDataTable = reader.CurrentDataTable;
     if (_currentDataTable != null)
     {
         SubscribeEvents();
     }
 }
        private string GetEntrada(DataTableReader row, string saida)
        {
            var parametros = new List<string>
                                          {
                                              "UF=" + row["UF"].ToString(),
                                              "MUN=" + row["CIDADE"].ToString(),
                                              "LOG=" + row["ENDERECO"].ToString(),
                                              "BAI=" + row["BAIRRO"].ToString(),
                                              "CEP=" + row["CEP"].ToString(),
                                              "POI=" + row["POI"].ToString(),
                                              "CAND=" + row["CANDIDATOS"].ToString(),
                                              "PRIO=" + row["PRIORIDADE"].ToString(),
                                              "SIS_Coord=" + row["SISTEMA_COORDENADA"].ToString(),
                                              "F=" + saida
                                          };

            return string.Join("&", parametros);
        }
Exemple #34
0
        public IFrame Copy(IFrame srcFrame, Guid newFrameId)
        {
            if (!(srcFrame is SimpleFrame))
                throw new ArgumentException("srcFrame");
            SimpleFrame copy = null;
            if (srcFrame is SimpleFrame)
            {
                SimpleFrame srcSimpleFrame = srcFrame as SimpleFrame;
                copy = new SimpleFrame(newFrameId);

                using (DataTableReader reader = new DataTableReader(srcSimpleFrame))
                {
                    copy.Load(reader);
                }
                copy.AcceptChanges();
            }
            return copy;
        }
Exemple #35
0
        private void button1_Click(object sender, EventArgs e)
        {
            //add a reference to our SQL WS
            ws.SQLWS_endpoint SQLWS = new ws.SQLWS_endpoint();

            //Set our default credentials to our Windows one
            SQLWS.Credentials = CredentialCache.DefaultCredentials;

            //Call the sproc through the WS
            System.Data.DataSet dsReturnValue = (System.Data.DataSet)SQLWS.SQLWS("Calling stored proc").GetValue(0);

            //Get the reader associated with our Dataset
            System.Data.DataTableReader drSQL = dsReturnValue.CreateDataReader();

            //Get the result
            string strResult = "";

            while (drSQL.Read())
            {
                strResult = drSQL[0].ToString();
            }

            //Display the results
            MessageBox.Show("Return value from SQL call: " + strResult);

            ws.SqlParameter[] sqlparams = new ws.SqlParameter[0];

            //Send a batch command to SQL
            System.Data.DataSet dsReturnValue1 = (System.Data.DataSet)SQLWS.sqlbatch("SELECT * FROM sys.http_endpoints", ref sqlparams).GetValue(0);

            //Get the reader associated with our Dataset
            System.Data.DataTableReader drSQL1 = dsReturnValue1.CreateDataReader();

            //Get the result
            string strResult1 = "";

            while (drSQL1.Read())
            {
                strResult1 = drSQL1[0].ToString();
            }

            //Display the results
            MessageBox.Show("Return value from SQL call: " + strResult1);
        }
Exemple #36
0
 //获取所有工作表名称
 private List<string> GetSheetName(string P_str_Excel)
 {
     List<string> P_list_SheetName = new List<string>();//实例化泛型集合对象
     //连接Excel数据库
     OleDbConnection olecon = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + P_str_Excel + ";Extended Properties=Excel 8.0");
     olecon.Open();//打开数据库连接
     System.Data.DataTable DTable = olecon.GetSchema("Tables");//实例化表对象
     DataTableReader DTReader = new DataTableReader(DTable);//实例化表读取对象
     while (DTReader.Read())//循环读取
     {
         string P_str_Name = DTReader["Table_Name"].ToString().Replace('$', ' ').Trim();//记录工作表名称
         if (!P_list_SheetName.Contains(P_str_Name))//判断泛型集合中是否已经存在该工作表名称
             P_list_SheetName.Add(P_str_Name);//将工作表名添加到泛型集合中
     }
     DTable = null;//清空表对象
     DTReader = null;//清空表读取对象
     olecon.Close();//关闭数据库连接
     return P_list_SheetName;//返回得到的泛型集合
 }
Exemple #37
0
 public Entity.User LoadUserMapData(System.Data.DataSet dataSet)
 {
     //Map the entity data...
     System.Data.DataTableReader reader = dataSet.Tables[(Int32)UserMap.DataSets.entitydata].CreateDataReader();
     Entity.User user = null;
     //Single record...
     if (reader.Read())
     {
         List <Entity.SQLEnumeration> roleTypes = EnumerationMapData(dataSet.Tables[(Int32)UserMap.DataSets.enumeration]);
         user = new User(
             Int32.Parse(reader[UserMap.Names.id].ToString()),
             reader[UserMap.Names.sqlSession].ToString(),
             new UserRole(
                 Int32.Parse(reader[UserMap.Names.roleId].ToString()),
                 reader[UserMap.Names.roleName].ToString(),
                 reader[UserMap.Names.roleDescription].ToString()
                 ),
             new UserIdentity(
                 reader[UserMap.Names.email].ToString(),
                 reader[UserMap.Names.userGreeting].ToString(),
                 reader[UserMap.Names.userName].ToString(),
                 reader[UserMap.Names.firstName].ToString(),
                 reader[UserMap.Names.lastName].ToString(),
                 reader[UserMap.Names.lastLoginText].ToString(),
                 reader[UserMap.Names.createdText].ToString(),
                 reader[UserMap.Names.editedText].ToString(),
                 DateTime.Parse(reader[UserMap.Names.lastLogin].ToString()),
                 DateTime.Parse(reader[UserMap.Names.created].ToString()),
                 DateTime.Parse(reader[UserMap.Names.edited].ToString()),
                 reader[UserMap.Names.editor].ToString(),
                 Boolean.Parse(reader[UserMap.Names.active].ToString())
                 ),
             new UserCredential(),
             roleTypes
             );
     }
     if (reader != null)
     {
         reader.Dispose();
     }
     return(user);
 }
Exemple #38
0
        /// <summary>
        /// Imports article from csv file to db. If article with same number exists, it will be replaced.
        /// </summary>
        /// <param name="db"></param>
        /// <param name="file"></param>
        /// <returns></returns>
        public static bool ImportArticleFromCsv(ISposDb db, string file)
        {
            // read csv file
            DataTable data = ParseCSV(file);
            if (data == null)
            {
                return false;
            }
            // convert data
            DataTableReader reader = new DataTableReader(data);
            if (reader.FieldCount != 5 && !reader.HasRows)
            {
                return false;
            }
            List<SimplePOS.Article.RegularArticle> articleList = new List<SimplePOS.Article.RegularArticle>();
            reader.Read(); // read the header
            while (reader.Read())
            {
                object[] values = new object[5];
                int result = reader.GetValues(values);
                if (result > 0)
                {
                    try
                    {
                        // Text may be empty wich results in a strange object
                        string text;
                        try { text = (string)values[2]; }
                        catch { text = ""; }
                        articleList.Add(new SimplePOS.Article.RegularArticle((string)values[0],
                            (string)values[1], text,
                            Double.Parse((string)values[3]),
                            Double.Parse((string)values[4])));
                    }
                    catch { return false; }
                }
            }

            // import to db
            db.SaveArticleList(articleList);

            return true;
        }
Exemple #39
0
        public List <Entity.User> LoadListMapData(System.Data.DataTable data)
        {
            //Map the entity data...
            System.Data.DataTableReader reader = data.CreateDataReader();
            List <Entity.User>          list   = new List <User>(data.Rows.Count);

            //Record set...
            while (reader.Read())
            {
                list.Add(
                    new User(
                        Int32.Parse(reader[UserMap.Names.id].ToString()),
                        reader[UserMap.Names.sqlSession].ToString(),
                        new UserRole(
                            Int32.Parse(reader[UserMap.Names.roleId].ToString()),
                            reader[UserMap.Names.roleName].ToString(),
                            reader[UserMap.Names.roleDescription].ToString()
                            ),
                        new UserIdentity(
                            reader[UserMap.Names.email].ToString(),
                            reader[UserMap.Names.userGreeting].ToString(),
                            reader[UserMap.Names.userName].ToString(),
                            reader[UserMap.Names.firstName].ToString(),
                            reader[UserMap.Names.lastName].ToString(),
                            reader[UserMap.Names.lastLoginText].ToString(),
                            reader[UserMap.Names.createdText].ToString(),
                            reader[UserMap.Names.editedText].ToString(),
                            DateTime.Parse(reader[UserMap.Names.lastLogin].ToString()),
                            DateTime.Parse(reader[UserMap.Names.created].ToString()),
                            DateTime.Parse(reader[UserMap.Names.edited].ToString()),
                            reader[UserMap.Names.editor].ToString(),
                            Boolean.Parse(reader[UserMap.Names.active].ToString())
                            )));
            }

            if (reader != null)
            {
                reader.Dispose();
            }
            return(list);
        }
Exemple #40
0
 private void RellenaEtiquetasPlaceHolder()
 {
     if (this.idindicator.HasValue)
     {
         try
         {
             using (Clases.cKPI_INDICATOR_ETIQUETAS objEtiquetas = new Clases.cKPI_INDICATOR_ETIQUETAS())
             {
                 objEtiquetas.indicatorid = this.idindicator.Value;
                 System.Data.DataTableReader dtrValores = objEtiquetas.ObtenerDatos().CreateDataReader();
                 while (dtrValores.Read())
                 {
                     HyperLink NuevoEnlace = new HyperLink();
                     NuevoEnlace.Text        = dtrValores.GetValue(2).ToString();
                     NuevoEnlace.NavigateUrl = "~/search.aspx?tagstring=" + dtrValores.GetValue(2).ToString();
                     NuevoEnlace.CssClass    = "tag";
                     PlaceHolderEtiquetas.Controls.Add(NuevoEnlace);
                 }
             }
         }
         catch (Exception excp)
         {
             ExceptionUtility.LogException(excp, "Error en la función << RellenaEtiquetasPlaceHolder() >>");
         }
         finally
         {
             if (PlaceHolderEtiquetas.Controls.Count > 0)
             {
                 lbNumEtiquetasNoEditable.Text = PlaceHolderEtiquetas.Controls.Count.ToString();
             }
             else
             {
                 PanelEtiquetasNoEditable.Visible = false;
             }
         }
     }
     else
     {
         Response.Redirect("~/errors/notfound.aspx");
     }
 }
Exemple #41
0
        public List <Entity.SQLEnumeration> EnumerationMapData(System.Data.DataTable data)
        {
            System.Data.DataTableReader  reader = data.CreateDataReader();
            List <Entity.SQLEnumeration> list   = new List <SQLEnumeration>(data.Rows.Count);

            while (reader.Read())
            {
                list.Add(new SQLEnumeration(
                             Int16.Parse(reader[UserMap.Names.enumValue].ToString()),
                             reader[UserMap.Names.enumName].ToString(),
                             reader[UserMap.Names.enumDescription].ToString(),
                             Int16.Parse(reader[UserMap.Names.enumSort].ToString())
                             ));
            }

            if (reader != null)
            {
                reader.Dispose();
            }
            return(list);
        }
Exemple #42
0
        public Entity.User SaveUserMapData(System.Data.DataTable data)
        {
            //Map the entity data...
            System.Data.DataTableReader reader = data.CreateDataReader();
            Entity.User user = null;
            //Single record...
            if (reader.Read())
            {
                user = new User(
                    Int32.Parse(reader[UserMap.Names.id].ToString()),
                    reader[UserMap.Names.sqlSession].ToString(),
                    new UserRole(
                        Int32.Parse(reader[UserMap.Names.roleId].ToString()),
                        reader[UserMap.Names.roleName].ToString(),
                        reader[UserMap.Names.roleDescription].ToString()
                        ),
                    new UserIdentity(
                        reader[UserMap.Names.email].ToString(),
                        reader[UserMap.Names.userGreeting].ToString(),
                        reader[UserMap.Names.userName].ToString(),
                        reader[UserMap.Names.firstName].ToString(),
                        reader[UserMap.Names.lastName].ToString(),
                        reader[UserMap.Names.lastLoginText].ToString(),
                        reader[UserMap.Names.createdText].ToString(),
                        reader[UserMap.Names.editedText].ToString(),
                        DateTime.Parse(reader[UserMap.Names.lastLogin].ToString()),
                        DateTime.Parse(reader[UserMap.Names.created].ToString()),
                        DateTime.Parse(reader[UserMap.Names.edited].ToString()),
                        reader[UserMap.Names.editor].ToString(),
                        Boolean.Parse(reader[UserMap.Names.active].ToString())
                        ));
            }

            if (reader != null)
            {
                reader.Dispose();
            }
            return(user);
        }
Exemple #43
0
    private void RellenaEtiquetasEditables()
    {
        if (this.idindicator.HasValue)
        {
            string sComa        = string.Empty;
            string sKeywords    = string.Empty;
            int    NumEtiquetas = 0;

            try
            {
                using (Clases.cKPI_INDICATOR_ETIQUETAS objEtiquetas = new Clases.cKPI_INDICATOR_ETIQUETAS())
                {
                    objEtiquetas.indicatorid = this.idindicator.Value;
                    System.Data.DataTableReader dtrValores = objEtiquetas.ObtenerDatos().CreateDataReader();
                    while (dtrValores.Read())
                    {
                        sKeywords += sComa + dtrValores.GetValue(2).ToString();
                        sComa      = ", ";
                        NumEtiquetas++;
                    }
                }
            }
            catch (Exception excp)
            {
                ExceptionUtility.LogException(excp, "Error en la función << RellenaEtiquetasEditables() >>");
            }
            finally
            {
                txtEtiquetasEditable.Text   = sKeywords;
                Page.MetaKeywords           = sKeywords;
                lbNumEtiquetasEditable.Text = NumEtiquetas.ToString();
            }
        }
        else
        {
            Response.Redirect("~/errors/notfound.aspx");
        }
    }
Exemple #44
0
        public Entity.Session <NullT> InitializeMapData(System.Data.DataTable data)
        {
            //Map the entity data...
            System.Data.DataTableReader reader = data.CreateDataReader();
            Entity.Session <NullT>      init   = new Session <NullT>();
            //Single record...
            if (reader.Read())
            {
                init.SessionOk        = false;
                init.ClientMessage    = String.Empty;
                init.ServerMessage    = String.Empty;
                init.SqlKey           = reader[UserMap.Names.privateKey].ToString();
                init.AppOnline        = Boolean.Parse(reader[UserMap.Names.appOnline].ToString());
                init.SqlAuthorization = Boolean.Parse(reader[UserMap.Names.sqlAuthorization].ToString());
                init.WinAuthorization = Boolean.Parse(reader[UserMap.Names.winAuthorization].ToString());
            }

            if (reader != null)
            {
                reader.Dispose();
            }
            return(init);
        }
Exemple #45
0
    public void Process()
    {
        // use the following method to update the status on the AsyncProcessorDetail
        // in the AsyncProcessManager
        AsyncProcessManager.GetProcessorDetail(ProcessorDetail.ID).UpdateStatusText("Processing has started");

        try
        {
            int datasets   = 0;
            int errorCount = 0;
            int processed  = 0;
            int total      = 0;

            //PRIMER PASO
            //Nos aseguramos que el usuario que va a subir la información tiene una sesión abierta
            System.Web.Security.MembershipUser usr = System.Web.Security.Membership.GetUser();
            if (usr == null)
            {
                AsyncProcessManager.FinalizeProcess(ProcessorDetail.ID);
            }

            //SEGUNDO PASO
            //Comprobamos que en los parámetros de importación están definidos el campo Fecha e Indicador así como
            //evaluar los atributos definidos para la importación
            int?colFecha = null;
            int?colValor = null;
            List <importColumns>   jsonDimensions = (List <importColumns>)Newtonsoft.Json.JsonConvert.DeserializeObject <List <importColumns> >(ProcessorDetail.Info);
            List <DimensionPrompt> vDimensions    = new List <DimensionPrompt>();
            foreach (importColumns elem in jsonDimensions)
            {
                switch (elem.attrid)
                {
                case -3:
                    colValor = elem.column;
                    break;

                case -2:
                    colFecha = elem.column;
                    break;

                case -1:
                    break;

                default:
                    DimensionPrompt NuevaDimension = new DimensionPrompt();
                    NuevaDimension.tablecolumn = elem.column;
                    NuevaDimension.dimensionid = elem.attrid;
                    NuevaDimension.tablename   = elem.name;
                    NuevaDimension.importmode  = 0;
                    vDimensions.Add(NuevaDimension);
                    break;
                }
            }
            List <importAttributes> jsonAttributes = (List <importAttributes>)Newtonsoft.Json.JsonConvert.DeserializeObject <List <importAttributes> >(ProcessorDetail.Atributtes);
            foreach (importAttributes elem in jsonAttributes)
            {
                DimensionPrompt NuevaDimension = new DimensionPrompt();
                NuevaDimension.dimensionid = elem.id;
                NuevaDimension.valor       = elem.name;
                NuevaDimension.importmode  = 1;
                vDimensions.Add(NuevaDimension);
            }

            //Nos aseguramos que existe el campo Fecha y el campo valor
            if ((!colValor.HasValue) || (!colFecha.HasValue))
            {
                AsyncProcessManager.FinalizeProcess(ProcessorDetail.ID);
            }

            //TERCER PASO
            //Comprobamos que el fichero se subió correctamente y que por lo tanto existe en el disco
            //duro para leer
            string path = System.Web.Hosting.HostingEnvironment.MapPath("~/uploads/imports/" + usr.ProviderUserKey.ToString() + "/" + ProcessorDetail.FileName);
            if (!System.IO.File.Exists(path))
            {
                AsyncProcessManager.FinalizeProcess(ProcessorDetail.ID);
            }

            System.Data.DataSet TablaOriginal = new System.Data.DataSet();
            TablaOriginal.ReadXml(path);
            System.Data.DataTableReader dtrDatos = TablaOriginal.Tables[0].CreateDataReader();

            DateTime?dFechaActual = null;
            decimal? dValorActual = null;
            string   sSelectA, sSelectB, sComa, sNombre;

            while (dtrDatos.Read())
            {
                //Nueva fila a procesar
                total++;

                //Inicializamos la búsqueda
                sSelectA = string.Empty;
                sSelectB = string.Empty;
                sNombre  = string.Empty;
                sComa    = string.Empty;

                //Para cada dimension especificada buscamos aquellos datasets en las que coinciden todas sus dimensiones
                using (Clases.cKPI_DATASETS objDataset = new Clases.cKPI_DATASETS())
                {
                    foreach (DimensionPrompt DimensionActual in vDimensions)
                    {
                        if (DimensionActual.importmode == 0)
                        {
                            DimensionActual.valor = dtrDatos[DimensionActual.tablecolumn].ToString().Replace("'", "");
                            sNombre = sNombre + sComa + DimensionActual.tablename + " = " + dtrDatos[DimensionActual.tablecolumn].ToString().Replace("'", "");
                        }
                        else if (DimensionActual.importmode == 1)
                        {
                            sNombre = sNombre + sComa + DimensionActual.valor;
                        }
                        sSelectA = sSelectA + DimensionActual.DimensionSelect();
                        sSelectB = sSelectB + sComa + DimensionActual.dimensionid.ToString();
                        sComa    = ", ";
                    }

                    objDataset.indicatorid = ProcessorDetail.IndicatorId;
                    objDataset.userid      = Convert.ToInt32(usr.ProviderUserKey);
                    if (!objDataset.bExiste(sSelectA, sSelectB))
                    {
                        datasets++;
                        objDataset.indicatorid = ProcessorDetail.IndicatorId;
                        objDataset.userid      = Convert.ToInt32(usr.ProviderUserKey);
                        objDataset.nombre      = sNombre;
                        objDataset.dimension   = "L";
                        objDataset.importid    = ProcessorDetail.ID;
                        if (objDataset.bInsertar())
                        {
                            foreach (DimensionPrompt DimensionActual in vDimensions)
                            {
                                using (Clases.cKPI_DIMENSION_VALUES objDimensionValues = new Clases.cKPI_DIMENSION_VALUES())
                                {
                                    objDimensionValues.datasetid   = objDataset.datasetid;
                                    objDimensionValues.dimensionid = DimensionActual.dimensionid;
                                    objDimensionValues.codigo      = DimensionActual.valor;
                                    objDimensionValues.bInsertarFromImport();
                                }
                            }
                        }
                    }
                    using (Clases.cKPI_DATASET_VALUES objValor = new Clases.cKPI_DATASET_VALUES())
                    {
                        objValor.indicatorid = ProcessorDetail.IndicatorId;
                        objValor.datasetid   = objDataset.datasetid.Value;
                        objValor.userid      = Convert.ToInt32(usr.ProviderUserKey);
                        objValor.importid    = ProcessorDetail.ID;
                        dFechaActual         = ConvertirStringToFecha(dtrDatos[colFecha.Value].ToString());
                        dValorActual         = ConvertirStringToDecimal(dtrDatos[colValor.Value].ToString());
                        if ((dFechaActual.HasValue) && (dValorActual.HasValue))
                        {
                            switch (objDataset.dimension)
                            {
                            case "D":
                                objValor.fecha = dFechaActual;
                                objValor.valor = dValorActual;
                                if (objValor.bGuardarLibre(ProcessorDetail.Modo))
                                {
                                    processed++;
                                }
                                else
                                {
                                    errorCount++;
                                }
                                break;

                            case "s":
                                objValor.ejercicio = dFechaActual.Value.Year;
                                objValor.mes       = dFechaActual.Value.Month;
                                if (dFechaActual.Value.Day < 8)
                                {
                                    objValor.semana = 1;
                                }
                                else if (dFechaActual.Value.Day < 15)
                                {
                                    objValor.semana = 2;
                                }
                                else if (dFechaActual.Value.Day < 22)
                                {
                                    objValor.semana = 3;
                                }
                                else
                                {
                                    objValor.semana = 4;
                                }
                                objValor.valor = dValorActual;
                                if (objValor.bGuardarSemana(ProcessorDetail.Modo))
                                {
                                    processed++;
                                }
                                else
                                {
                                    errorCount++;
                                }
                                break;

                            case "Q":
                                objValor.ejercicio = dFechaActual.Value.Year;
                                objValor.mes       = dFechaActual.Value.Month;
                                objValor.quincena  = dFechaActual.Value.Day < 16 ? 1 : 2;
                                objValor.valor     = dValorActual;
                                if (objValor.bGuardarQuincena(ProcessorDetail.Modo))
                                {
                                    processed++;
                                }
                                else
                                {
                                    errorCount++;
                                }
                                break;

                            case "M":
                                objValor.ejercicio = dFechaActual.Value.Year;
                                objValor.mes       = dFechaActual.Value.Month;
                                objValor.valor     = dValorActual;
                                if (objValor.bGuardarMes(ProcessorDetail.Modo))
                                {
                                    processed++;
                                }
                                else
                                {
                                    errorCount++;
                                }
                                break;

                            case "T":
                                objValor.ejercicio = dFechaActual.Value.Year;
                                if (dFechaActual.Value.Month < 4)
                                {
                                    objValor.trimestre = 1;
                                }
                                else if (dFechaActual.Value.Month < 7)
                                {
                                    objValor.trimestre = 2;
                                }
                                else if (dFechaActual.Value.Month < 10)
                                {
                                    objValor.trimestre = 3;
                                }
                                else
                                {
                                    objValor.trimestre = 4;
                                }
                                objValor.valor = dValorActual;
                                if (objValor.bGuardarTrimestre(ProcessorDetail.Modo))
                                {
                                    processed++;
                                }
                                else
                                {
                                    errorCount++;
                                }
                                break;

                            case "S":
                                objValor.ejercicio = dFechaActual.Value.Year;
                                objValor.semestre  = dFechaActual.Value.Month < 7 ? 1 : 2;
                                objValor.valor     = dValorActual;
                                if (objValor.bGuardarSemestre(ProcessorDetail.Modo))
                                {
                                    processed++;
                                }
                                else
                                {
                                    errorCount++;
                                }
                                break;

                            case "A":
                                objValor.ejercicio = dFechaActual.Value.Year;
                                objValor.valor     = dValorActual;
                                if (objValor.bGuardarEjercicio(ProcessorDetail.Modo))
                                {
                                    processed++;
                                }
                                else
                                {
                                    errorCount++;
                                }
                                break;

                            case "L":
                                objValor.fecha = dFechaActual;
                                objValor.valor = dValorActual;
                                if (objValor.bGuardarLibre(ProcessorDetail.Modo))
                                {
                                    processed++;
                                }
                                else
                                {
                                    errorCount++;
                                }
                                break;
                            }
                        }
                        else
                        {
                            errorCount++;
                            if (!dFechaActual.HasValue)
                            {
                                InsertaDetalleError(total, dtrDatos[colFecha.Value].ToString(), "El valor especificado no es un campo de FECHA válido");
                            }
                            if (!dValorActual.HasValue)
                            {
                                InsertaDetalleError(total, dtrDatos[colValor.Value].ToString(), "El valor especificado no es un campo de NÚMERO válido");
                            }
                        }
                    }
                }
                // in loops, call the UpdateStatus method to determine if you should update the counts
                // on the current iteration. This will save processing time so your not updating the
                // counts on every iteration
                if (UpdateStatus(processed, total))
                {
                    // use the following method to update the counts on the AsyncProcessorDetail
                    // in the AsyncProcessManager. This should be included inside any worker loops
                    // you may have or between code blocks to update the user
                    AsyncProcessManager.GetProcessorDetail(ProcessorDetail.ID).UpdateCounts(processed, errorCount, 0, total);
                }
            }
            using (Clases.cKPI_IMPORTS objImport = new Clases.cKPI_IMPORTS())
            {
                objImport.importid       = ProcessorDetail.ID;
                objImport.num_datasets   = datasets;
                objImport.num_data_ok    = processed;
                objImport.num_data_error = errorCount;
                objImport.finalizado     = true;
                objImport.bModificar();
            }

            // check to see if the process has been cancelled by calling AsyncProcessManager.Continue
            // this method should be called within an UpdateStatus condition within any loops you have
            // and should be followed by a break;
            if (!AsyncProcessManager.Continue(ProcessorDetail.ID))
            {
                AsyncProcessManager.GetProcessorDetail(ProcessorDetail.ID).UpdateStatusText("Processing cancelled");
            }

            AsyncProcessManager.GetProcessorDetail(ProcessorDetail.ID).UpdateStatusText("Processing is complete");
        }
        catch (Exception ex)
        {
            string error = ex.Message + ex.StackTrace;
        }

        AsyncProcessManager.FinalizeProcess(ProcessorDetail.ID);
    }