Example #1
0
 /// <summary>
 /// Consumes all rows and result sets from the reader. This allows client to retrieve
 /// parameter values and intercept any store exceptions.
 /// </summary>
 /// <param name="reader">reader to consume</param>
 internal static void ConsumeReader(DbDataReader reader)
 {
     if (null != reader && !reader.IsClosed)
     {
         while (reader.NextResult())
         {
             // Note that we only walk through the result sets. We don't need
             // to walk through individual rows (though underlying provider
             // implementation may do so)
         }
     }
 }
Example #2
0
    protected override DbSpatialDataReader GetDbSpatialDataReader(DbDataReader fromReader, string manifestToken)
    {
      if (fromReader == null)
        throw new ArgumentNullException("fromReader must not be null");      

      EFMySqlDataReader efReader = fromReader as EFMySqlDataReader;
      if (efReader == null)
      {
        throw new ArgumentException(
            string.Format(
                "Spatial readers can only be produced from readers of type EFMySqlDataReader.   A reader of type {0} was provided.",
                fromReader.GetType()));
      }

      return new MySqlSpatialDataReader(efReader);
    }
Example #3
0
        public void GetTByExpression()
        {

            Expression<Func<Customer, bool>> expression = e => e.ID == 1;

            var customer = new Customer
            {
                ID = 1,
                Balance = 0,
                BalanceRate = 0,
                DefaultContactID = 1,
                Name = "Customer1",
                ProfileID = 1
            };

            var reader = new DbDataReader();
            reader.Setup(r => r.Read()).Returns(true);

            var provider = new IProvider();

            var command = new ICommand();

            var schema = new TypeTable(typeof(Customer));

            provider.Setup(p => p.GetSchema(typeof(Customer))).Returns(schema);

            provider.CommandBuilder.Setup(c => c.CreateGetTCommand<Customer>(expression)).Returns(command.Object);
            provider.CommandExecutor.Setup(c => c.ExecuteReader(command.Object)).Returns(reader.Object);

            provider.Mapper.Setup(m => m.GetTMappingMethod<Customer>()).Returns(d => customer);

            var target = new DataSession(provider.Object);

            var actual = target.GetT(expression);

            Assert.AreEqual(actual, customer);
        }
    /// <summary>
    /// 执行有多个参数的存储过程语句,得到DataReader阅读器对象
    /// </summary>
    public DbDataReader ExecuteReaderByProcedure(string storedProcName)
    {
        try
        {
            BuildProcCommand(storedProcName);
            _reader = _command.ExecuteReader(CommandBehavior.CloseConnection);
        }
        catch (DbException)
        {
            throw;
        }

        return _reader;
    }
Example #5
0
        public DataTable ReadData(DatasetConfig datasetConfig, string filter, long Start, int Count, DateTime?FromDate, DateTime?ToDate)
        {
            //try
            //{
            CheckAndEstablishReadConnection();

            readCmd.Connection = readDBConn;

            string where = "";
            if (!string.IsNullOrEmpty(filter))
            {
                where = " WHERE ";
                bool first = true;
                foreach (var rows in datasetConfig.DatasetConfigRows)
                {
                    if (!first)
                    {
                        where += "OR ";
                    }
                    where += rows.DatabaseField + " LIKE '%" + filter + "%' ";
                    first  = false;
                }
            }

            if (FromDate != null)
            {
                if (string.IsNullOrEmpty(where))
                {
                    where = " WHERE ";
                }
                else
                {
                    where += " AND ";
                }

                where += datasetConfig.DateTimeDatabaseField;
                where += " >= '" + FromDate.Value.ToString("yyyyMMdd HH:mm:ss.mmm") + "'";
            }

            if (ToDate != null)
            {
                if (string.IsNullOrEmpty(where))
                {
                    where = " WHERE ";
                }
                else
                {
                    where += " AND ";
                }

                where += datasetConfig.DateTimeDatabaseField;
                where += " <= '" + ToDate.Value.ToString("yyyyMMdd HH:mm:ss.mmm") + "'";
            }

            readCmd.CommandText = "WITH " + datasetConfig.Name + "_withRowNumber AS ( SELECT *, ROW_NUMBER() OVER (ORDER BY id DESC) AS 'RowNumber' FROM " + datasetConfig.Name + where + " ) SELECT * FROM " + datasetConfig.Name + "_withRowNumber WHERE RowNumber BETWEEN " + Start.ToString() + " AND " + (Start + Count).ToString() + ";";
            //readCmd.CommandText = "SELECT *, ROW_NUMBER() OVER(ORDER BY id DESC) AS [RowNum] FROM " + datasetConfig.Name + " WHERE RowNum BETWEEN " + Start.ToString() + " AND " + (Start + Count).ToString();
            //readCmd.CommandText = "SELECT * FROM " + datasetConfig.Name + " ORDER BY id DESC LIMIT " + Count.ToString() + " OFFSET " + Start.ToString();
            DbDataReader akReader = readCmd.ExecuteReader();

            DataTable myTbl = new DataTable();

            myTbl.Load(akReader);
            akReader.Close();

            return(myTbl);
        }
    /// <summary>
    /// 执行一条无参SQL语句,获取DataReader对象阅读器
    /// </summary>
    public DbDataReader ExecuteReader(string sqlStr)
    {
        try
        {
            Open();
            _command.CommandText = sqlStr;
            _reader = _command.ExecuteReader(CommandBehavior.CloseConnection);
        }
        catch (Exception e)
        {
            LogHelper.Append(e.ToString());
        }

        return _reader;
    }
Example #7
0
 public abstract object Read(DbDataReader reader);
Example #8
0
        /// <summary> Returns the Java source code for a class that represents the specified segment.</summary>
        public static String makeSegment(String name, String version)
        {
            Console.WriteLine("Making segment " + name);
            StringBuilder source = new StringBuilder();

            try
            {
                ArrayList      elements = new ArrayList();
                SegmentElement se;
                String         segDesc = null;
                OdbcConnection conn    = NormativeDatabase.Instance.Connection;
                StringBuilder  sql     = new StringBuilder();
                sql.Append("SELECT HL7SegmentDataElements.seg_code, HL7SegmentDataElements.seq_no, ");
                sql.Append("HL7SegmentDataElements.repetitional, HL7SegmentDataElements.repetitions, ");
                sql.Append("HL7DataElements.description, HL7DataElements.length_old, HL7DataElements.table_id, ");
                sql.Append("HL7SegmentDataElements.req_opt, HL7Segments.description, HL7DataElements.data_structure ");
                sql.Append(
                    "FROM HL7Versions RIGHT JOIN (HL7Segments INNER JOIN (HL7DataElements INNER JOIN HL7SegmentDataElements ");
                sql.Append("ON (HL7DataElements.version_id = HL7SegmentDataElements.version_id) ");
                sql.Append("AND (HL7DataElements.data_item = HL7SegmentDataElements.data_item)) ");
                sql.Append("ON (HL7Segments.version_id = HL7SegmentDataElements.version_id) ");
                sql.Append("AND (HL7Segments.seg_code = HL7SegmentDataElements.seg_code)) ");
                sql.Append("ON (HL7Versions.version_id = HL7Segments.version_id) ");
                sql.Append("WHERE HL7SegmentDataElements.seg_code = '");
                sql.Append(name);
                sql.Append("' and HL7Versions.hl7_version = '");
                sql.Append(version);
                sql.Append("' ORDER BY HL7SegmentDataElements.seg_code, HL7SegmentDataElements.seq_no;");
                DbCommand stmt = SupportClass.TransactionManager.manager.CreateStatement(conn);
                DbCommand temp_OleDbCommand;
                temp_OleDbCommand             = stmt;
                temp_OleDbCommand.CommandText = sql.ToString();
                DbDataReader rs = temp_OleDbCommand.ExecuteReader();

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

                    if (se.repetitions == 0)
                    {
                        if (se.rep == null || !se.rep.ToUpper().Equals("Y".ToUpper()))
                        {
                            se.repetitions = 1;
                        }
                    }
                    se.desc = Convert.ToString(rs[5 - 1]);
                    if (!rs.IsDBNull(6 - 1))
                    {
                        se.length = DetermineLength(rs);
                    }

                    se.table = Convert.ToInt32(rs.GetValue(7 - 1));
                    se.opt   = Convert.ToString(rs[8 - 1]);
                    se.type  = Convert.ToString(rs[10 - 1]);
                    //shorten CE_x to CE
                    if (se.type.StartsWith("CE"))
                    {
                        se.type = "CE";
                    }

                    elements.Add(se);

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

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

                source.Append("namespace ");
                source.Append(PackageManager.GetVersionPackageName(version));
                source.Append("Segment{\r\n\r\n");
                source.Append("///<summary>\r\n");
                source.Append("/// Represents an HL7 ");
                source.Append(name);
                source.Append(" message segment. \r\n");
                source.Append("/// This segment has the following fields:<ol>\r\n");

                PrepareAppendStringsForElementsWithDuplicateDescriptions(name, elements);

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

                //implement interface from Model.control package if required

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

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

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


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

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


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

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

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

                source.Append("\n}");
            }
            catch (DbException sqle)
            {
                SupportClass.WriteStackTrace(sqle, Console.Error);
            }

            return(source.ToString());
        }
Example #9
0
        public void SaveUpdateThrowsUnableToCreateCommandException()
        {
            var customer = new Customer
            {
                ID = 1,
                Balance = 0,
                BalanceRate = 0,
                DefaultContactID = 1,
                Name = "Customer1",
                ProfileID = 1
            };

            var provider = new IProvider();
            var transaction = new Mock<ITransaction>();
            var schema = new TypeTable(typeof(Customer));

            var reader = new DbDataReader();
            reader.Setup(r => r.Read()).Returns(true);


            provider.Setup(p => p.GetSchema(typeof(Customer))).Returns(schema);
            provider.CommandExecutor.Setup(c => c.InitiateTransaction()).Returns(transaction.Object);
            provider.Setup(p => p.GetEntityStatus(customer)).Returns(EntityStatus.Update);
            provider.CommandBuilder.Setup(c => c.CreateUpdateCommand(customer)).Returns(default(Data.ICommand));

            try
            {
                var target = new DataSession(provider.Object);
                target.Save(customer);
            }
            catch (Exception ex)
            {
                Assert.IsTrue(ex is UnableToCreateCommandException);
            }

        }
Example #10
0
        private BasicDocument ReadDocumentFromDataReader(DbDataReader reader)
        {
            int documentId = reader.GetInt32(0);
            string serverFileName = reader.GetString(1);
            string clientFileName = reader.GetString(2);
            string description = reader.GetString(3);
            DocumentType docType = (DocumentType) Enum.Parse(typeof (DocumentType), reader.GetString(4));
            int foreignId = reader.GetInt32(5);
            Int64 fileSize = reader.GetInt64(6);
            int uploadedByPersonId = reader.GetInt32(7);
            DateTime uploadedDateTime = reader.GetDateTime(8);

            return new BasicDocument(documentId, serverFileName, clientFileName, description, docType,
                                     foreignId, fileSize, uploadedByPersonId, uploadedDateTime);
        }
Example #11
0
        /// <summary>
        /// Returns a collection of GlobalCurrencyListDetails objects with the data read from the input DataReader
        /// </summary>
        protected virtual List <GlobalCurrencyListDetails> GetGlobalCurrencyListCollectionFromReader(DbDataReader reader)
        {
            List <GlobalCurrencyListDetails> globalCurrencyLists = new List <GlobalCurrencyListDetails>();

            while (reader.Read())
            {
                globalCurrencyLists.Add(GetGlobalCurrencyListFromReader(reader));
            }
            return(globalCurrencyLists);
        }
Example #12
0
        private static void GetPagedListByPageEnumExpression(int pageSize, Data.Page page, Expression<Func<Customer, bool>> expression)
        {
            var customer1 = new Customer
            {
                ID = 1,
                Balance = 0,
                BalanceRate = 0,
                DefaultContactID = 1,
                Name = "Customer1",
                ProfileID = 1
            };
            var customer2 = new Customer
            {
                ID = 2,
                Balance = 0,
                BalanceRate = 0,
                DefaultContactID = 2,
                Name = "Customer2",
                ProfileID = 2
            };
            var customer3 = new Customer
            {
                ID = 3,
                Balance = 0,
                BalanceRate = 0,
                DefaultContactID = 3,
                Name = "Customer3",
                ProfileID = 3
            };

            var customerQueue = new Queue<Customer>(new[] { customer1, customer2, customer3 });
            var readerResults = new Queue<bool>(new[] { true, true, true, false });

            var reader = new DbDataReader();
            reader.Setup(r => r.Read()).Returns(readerResults.Dequeue);

            var provider = new IProvider();

            var command = new ICommand();

            var schema = new TypeTable(typeof(Customer));

            provider.Setup(p => p.GetSchema(typeof(Customer))).Returns(schema);

            provider.CommandBuilder.Setup(c => c.CreateGetListByPageCommand<Customer>(expression)).Returns(command.Object);
            provider.CommandBuilder.Setup(c => c.CreateCountCommand<Customer>(expression)).Returns(command.Object);
            provider.CommandExecutor.Setup(c => c.ExecuteCount(command.Object)).Returns(3);
            provider.CommandExecutor.Setup(c => c.ExecuteReader(command.Object)).Returns(reader.Object);


            provider.Mapper.Setup(m => m.GetTMappingMethod<Customer>()).Returns(d => customerQueue.Dequeue());

            var target = new DataSession(provider.Object);

            try
            {
                var actual = target.GetPagedList<List<Customer>, Customer>(pageSize, page, expression);

                Assert.IsTrue(actual[0].ID == 1 &&
                    actual[1].ID == 2 && actual[2].ID == 3);
            }
            catch (Exception ex)
            {

                Assert.IsTrue(ex is ArgumentNullException);
            }

        }
Example #13
0
 private static void Mapping(DbDataReader reader, Rank r)
 {
     r.ID   = reader.GetInt32(0);
     r.Pos  = reader.GetInt32(1);
     r.Name = reader.GetString(2);
 }
Example #14
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(LogLevel.Debug);
            loggerFactory.AddDebug(LogLevel.Debug);

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseBrowserLink();
            }
            app.UseAuthentication();
            app.UseWebSockets();

#if UseOptions
            #region UseWebSocketsOptions
            var webSocketOptions = new WebSocketOptions()
            {
                KeepAliveInterval = TimeSpan.FromSeconds(120),
                ReceiveBufferSize = 4 * 1024
            };
            app.UseWebSockets(webSocketOptions);
            #endregion
#endif

            #region AcceptWebSocket
            app.Use(async(context, next) =>
            {
                if (context.Request.Path == "/subserver/ws")//这里可以定义路径的格式
                {
                    if (context.WebSockets.IsWebSocketRequest)
                    {
                        WebSocket webSocket = await context.WebSockets.AcceptWebSocketAsync();

                        var buffer = new byte[1024 * 4];
                        WebSocketReceiveResult webSocketReceiveResult = await webSocket.ReceiveAsync(new ArraySegment <byte>(buffer), CancellationToken.None);

                        string restring = Encoding.ASCII.GetString(buffer);

                        JObject jObject = (JObject)JsonConvert.DeserializeObject(restring);//序列化结果

                        //  string PiToken = jObject["PiToken"].ToString();
                        //验证PiToken
                        string subserverId = jObject["SubserverID"].ToString();

                        macAvailable          = true;
                        ErrorRootobject error = new ErrorRootobject
                        {
                            ReturnCode = "1001",
                            msg        = "JSON format error"
                        };
                        string serial = JsonConvert.SerializeObject(error);

                        result = (JObject)JsonConvert.DeserializeObject(serial);

                        if (macAvailable)
                        {
                            var conn = new MySqlConnection(Configuration.GetConnectionString("DefaultConnection"));

                            conn.Open();
                            var command  = conn.CreateCommand();
                            string query = "SELECT  Username"
                                           + " FROM UserToSubserver "
                                           + "WHERE SubserverID = '" + subserverId + "'";

                            command.CommandText       = query;
                            DbDataReader BindedReader = await command.ExecuteReaderAsync();

                            if (BindedReader.HasRows)
                            {
                                //如果查询到被绑定
                                //我担心会查出一个MAC地址绑定了多个用户的情况
                                //后期可以设置让MAC地址为主键
                                BindedReader.Read();
                                string buser     = BindedReader["Username"].ToString();
                                error.ReturnCode = "1005";
                                error.msg        = " This Subserver is owned by " + buser;

                                serial      = JsonConvert.SerializeObject(error);
                                result      = (JObject)JsonConvert.DeserializeObject(serial);
                                var buffer1 = Encoding.ASCII.GetBytes(serial);
                                //将
                                await webSocket.SendAsync(new ArraySegment <byte>(buffer1), webSocketReceiveResult.MessageType, webSocketReceiveResult.EndOfMessage, CancellationToken.None);
                                conn.Close();//关闭连接

                                //加入到字典中
                                WebsocketClient.AddToDictionary(subserverId, webSocket);
                            }
                            else
                            {
                                var buffer1      = new byte[1024 * 4];
                                error.ReturnCode = "1006";
                                error.msg        = " SubserverID is not bound  ";

                                serial  = JsonConvert.SerializeObject(error);
                                result  = (JObject)JsonConvert.DeserializeObject(serial);
                                buffer1 = Encoding.ASCII.GetBytes(serial);
                                //将
                                int a = result.Count;

                                await webSocket.SendAsync(new ArraySegment <byte>(buffer1), webSocketReceiveResult.MessageType, webSocketReceiveResult.EndOfMessage, CancellationToken.None);
                            }
                            conn.Close();
                        }
                        //启动监听
                        await ListenToSubserver(context, webSocket);
                    }
                    else
                    {
                        context.Response.StatusCode = 400;
                    }
                }
                else
                {
                    await next();
                }
            });
            #endregion
            app.UseFileServer();

            app.UseStaticFiles();



            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
 public static long?LongOrNull(this DbDataReader dataReader, int index)
 {
     if (dataReader.IsDBNull(index))
     {
         return(default);
 public DbFieldReader(QueryExecutor executor, DbDataReader reader)
 {
     this.executor = executor;
     this.reader   = reader;
     this.Init();
 }
Example #17
0
 protected internal abstract IndexDocumentData GetIndexDocumentDataFromReader(DbDataReader reader);
		public object ReadObject(Type type, DbDataReader reader, IList<string> propertyNames, IDictionary<string, IDbObject> objectGraph)
		{
			var o = (IDbObject) Activator.CreateInstance(type);
			var classMetadata = ClassMetaDataManager.Instace.GetClassMetaData(type);
			var properties = classMetadata.Properties;
			var relations = classMetadata.RelationProperties;
			o.Id = reader.GetInt64(reader.GetOrdinal("Id"));
			string key = type.FullName + o.Id;
			if (objectGraph.ContainsKey(key))
			{
				return objectGraph[key];
			}
			objectGraph.Add(key, o);
			for (var i = 1; i < propertyNames.Count; i++) //index 0 is Id
			{
				var propertyName = propertyNames[i];
				if (properties.ContainsKey(propertyName))
				{
					var mappingInfo = properties[propertyName];
					var mappingField = mappingInfo.MappingField;
					var propertyInfo = mappingInfo.PropertyInfo;
					var propertyType = propertyInfo.PropertyType;
					if (propertyType.IsPrimitive || propertyType == typeof(string) || propertyType == typeof(DateTime) || propertyType == typeof(decimal))
					{
						var propertyValue = reader.GetValue(reader.GetOrdinal(mappingField));
						propertyInfo.SetValue(o, propertyValue, null);	
					}
					else
					{
						var rawData = DbSerializerHelper.ReadBlob(mappingField, reader);
						if (rawData != null)
						{
							object propertyValue = null;
							using (var stream = new MemoryStream(rawData))
							{
								var formatter = new BinaryFormatter();
								propertyValue = formatter.Deserialize(stream);
							}
							propertyInfo.SetValue(o, propertyValue, null);	
						}
					}
				}
				else if (relations.ContainsKey(propertyName))
				{
					using (var connection = dbObjectContainer.ConnectionManager.GetReadConnection())
					{
						var relation = relations[propertyName];
						var propertyInfo = relation.PropertyInfo;
						if (relation.RelationKind == RelationInfo.RELATION_1_1)
						{
							var elementType = propertyInfo.PropertyType;
							var command = connection.CreateCommand();
							command.CommandText = "SELECT * FROM " + relation.MappingTable + " WHERE `" + relation.OriginalKey + "` = " + o.Id;
							using (var relationReader = command.ExecuteReader(CommandBehavior.SingleRow))
							{
								if (relationReader.Read())
								{
									var propertyValue = ReadObject(elementType, relationReader, classMetadata.AllPropertiesName, objectGraph);
									propertyInfo.SetValue(o, propertyValue, null);
								}
							}
						}
						else if (relation.RelationKind == RelationInfo.RELATION_1_N)
						{
							var elementType = propertyInfo.PropertyType.GetGenericArguments()[0];
							var listObject = Activator.CreateInstance(typeof (List<>).MakeGenericType(elementType));
							var addMethod = typeof (ICollection<>).MakeGenericType(elementType).GetMethod("Add");
							var command = connection.CreateCommand();
							command.CommandText = "SELECT * FROM " + relation.MappingTable + " WHERE `" + relation.OriginalKey + "` = " + o.Id;
							using (var relationReader = command.ExecuteReader())
							{
								while (relationReader.Read())
								{
									var propertyValue = ReadObject(elementType, relationReader, classMetadata.AllPropertiesName, objectGraph);
									addMethod.Invoke(listObject, new[] {propertyValue});
								}
							}
							if (((IList) listObject).Count > 0)
							{
								propertyInfo.SetValue(o, listObject, null);
							}
						}
						else if (relation.RelationKind == RelationInfo.RELATION_N_N)
						{
							var elementType = propertyInfo.PropertyType.GetGenericArguments()[0];
							var listObject = Activator.CreateInstance(typeof(List<>).MakeGenericType(elementType));
							var addMethod = typeof(ICollection<>).MakeGenericType(elementType).GetMethod("Add");
							var command = connection.CreateCommand();
							command.CommandText = "SELECT `" + relation.PartnerKey +  "` FROM " + relation.MappingTable + " WHERE `" + relation.OriginalKey + "` = " + o.Id;
							var otherIds = new List<long>();
							using (var relationReader = command.ExecuteReader())
							{
								while (relationReader.Read())
								{
									otherIds.Add(relationReader.GetInt64(0));
								}
							}
							for (var j = 0; j < otherIds.Count; j++)
							{
								var propertyValue = dbObjectContainer.QueryExecutor.SelectById(elementType, otherIds[j], null,
								                                                               SelectQuery.ALL_PROPS);
								addMethod.Invoke(listObject, new[] { propertyValue });
							}
							if (((IList)listObject).Count > 0)
							{
								propertyInfo.SetValue(o, listObject, null);
							}						
						}
					}
				}
				else
				{
					throw new ArgumentException("Cannot regconize property: " + propertyName);
				}
			}
			return o;
		}
Example #19
0
 protected int? GetIntegerValue(DbDataReader dataReader, String fieldName)
 {
     if (dataReader[fieldName] is DBNull) return null;
     return (int)dataReader[fieldName];
 }
Example #20
0
 private static ADate BoxingDate(DbDataReader reader)
 {
     ADate date = new ADate();
     date.Text = reader["Text"].ToString();
     date.color = (int)reader["Color"];
     date.StartTime = (DateTime)reader["StartTime"];
     date.EndTime = (DateTime)reader["EndTime"];
     date.Id = (int)reader["IdCalendar"];
     return date;
 }
Example #21
0
        public void Read(DbDataReader reader, IIdentityMap map)
        {
            var result = _handler.Handle(reader, map, Stats);

            Completion.SetResult(result);
        }
Example #22
0
 /// <summary>
 /// Loads a record given a DataReader containing data from the News table in the database.
 /// You should find that Load(Sql) or LoadID(id) cover most scenarios but you can use this method if you need to.
 /// When using a DataReader be careful to ensure you close it using reader.Close() to avoid connection leaks.
 /// If found in the cache, record will be loaded from the cache.
 /// </summary>
 /// <example>var g = GenTest.Load(reader);</example>
 /// <param name="sql"></param>
 /// <returns>An instance of News containing the data in the record</returns>
 public static News Load(DbDataReader reader)
 {
     return(ActiveRecordLoader.Load <News>(reader, "News"));
 }
Example #23
0
 protected String GetStringValue(DbDataReader dataReader, String fieldName)
 {
     if (dataReader[fieldName] is DBNull) return null;
     return (String)dataReader[fieldName];
 }
        public override void CreateOrModify_TablesAndFields(string dataTable, DatasetConfig datasetConfig)
        {
            if (!string.IsNullOrEmpty(datasetConfig.DatasetTableName)) //Add the posibility to use a specific table_name (for using the table more then ones)
                this.dataTable = datasetConfig.DatasetTableName;
            else
                this.dataTable = dataTable;
            
            this.datasetConfig = datasetConfig;
            this.fieldList = datasetConfig.DatasetConfigRows;
            
            string sql = "";
            try
            {
                sql = "CREATE DATABASE " + myConfig.Database + ";";
                myCmd.Connection = myDBConn;
                myCmd.CommandText = sql;
                myCmd.ExecuteNonQuery();
            }
            catch (MySqlException ex)
            {
                if (ex.Number != 1007)
                {
                    Logging.LogText("Database could not be created. Storage: " + myConfig.Name, ex, Logging.LogLevel.Error);
                    throw ex;
                }
            }

            myDBConn.ChangeDatabase(myConfig.Database);

            //Look if Table exists, when not, create it!
            try
            {
                sql = "SELECT * FROM " + dataTable + ";";
                myCmd.Connection = myDBConn;
                myCmd.CommandText = sql;
                myReader = myCmd.ExecuteReader();

            }
            catch (MySqlException ex)
            {
                if (ex.Number == 1146)
                {
                    try
                    {
                        sql = "CREATE TABLE " + dataTable + " (";
                        sql += "id BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY); ";
                                                
                        myCmd.CommandText = sql;
                        myCmd.ExecuteNonQuery();

                        sql = "SELECT * FROM " + dataTable + ";";                        
                        myCmd.CommandText = sql;
                        myReader = myCmd.ExecuteReader();
                    }
                    catch (Exception ex_ex)
                    {
                        Logging.LogText("Database-table could not be created. Storage: " + myConfig.Name + ", Table: " + dataTable, ex, Logging.LogLevel.Error);
                        throw ex_ex;
                    }
                }
                else
                {
                    Logging.LogText("Error accessing Table. Storage: " + myConfig.Name, ex, Logging.LogLevel.Error);
                    throw ex;
                }
            }            
            
            //Look for the Fields, create or alter them!
            List<String> existDBFelderliste = new List<string>();

            for (int n = 0; n < myReader.FieldCount; n++)
            {
                existDBFelderliste.Add(myReader.GetName(n));
            }
            myReader.Close();

            foreach (DatasetConfigRow myFeld in fieldList)
            {
                foreach (string existMyFeld in existDBFelderliste)
                {
                    if (myFeld.DatabaseField.ToLower() == existMyFeld.ToLower())
                    {
                        goto nextFeld;
                    }
                }

                //Feld existiert nicht -> erzeugen
                string dbfieldtype = myFeld.DatabaseFieldType;

                switch (dbfieldtype)
                {
                    case "bigint":
                        dbfieldtype = "bigint NOT NULL default 0";
                        break;
                    case "real":
                        dbfieldtype = "real NOT NULL default 0";
                        break;
                    case "datetime":
                        dbfieldtype = "TIMESTAMP NOT NULL";
                        break;
                    case "varchar":
                        dbfieldtype = "VARCHAR(" + myFeld.DatabaseFieldSize + ") NOT NULL DEFAULT ''";
                        break;
                }



                sql = "ALTER TABLE " + dataTable + " ADD COLUMN " + QuoteField(myFeld.DatabaseField) + " " + dbfieldtype;

                try
                {
                    myCmd.Connection = myDBConn;
                    myCmd.CommandText = sql;
                    myCmd.ExecuteNonQuery();

                }
                catch (Exception ex)
                {
                    throw ex;
                }

                nextFeld:
                //Irgendeine anweisung, da sonst der Sprung nicht geht...
                {
                }
            }


            //Create Insert Command
            string wertliste = "", felderliste = "", updateliste = "";
            foreach (DatasetConfigRow myFeld in fieldList)
            {
                if (wertliste != "")
                {
                    wertliste += ",";
                    felderliste += ",";

                    updateliste += ",";
                }

                felderliste += QuoteField(myFeld.DatabaseField);
                wertliste += "?" + ValueName(myFeld.DatabaseField);

                updateliste += QuoteField(myFeld.DatabaseField) + "= ?" + ValueName(myFeld.DatabaseField);
            }
            insertCommand = "INSERT INTO " + this.dataTable + "(" + felderliste + ") values(" + wertliste + ")";

            updateCommand = "UPDATE " + this.dataTable + " SET " + updateliste;
        }
Example #25
0
 public static News Load(DbDataReader reader, Otherwise otherwise)
 {
     return(ActiveRecordLoader.Load <News>(reader, "News", otherwise));
 }
Example #26
0
 protected DateTime? GetDateTimeValue(DbDataReader dataReader, String fieldName)
 {
     if (dataReader[fieldName] is DBNull) return null;
     return (DateTime)dataReader[fieldName];
 }
Example #27
0
 public void ExecuteFinish(IDbCommand profiledDbCommand, SqlExecuteType executeType, DbDataReader reader) =>
     GetProfiler()?.ExecuteFinish(profiledDbCommand, executeType, reader);
Example #28
0
 public Cargo(DbDataReader reader)
 {
     id   = (int)reader["id"];
     name = (string)reader["name"];
 }
Example #29
0
        /// <summary>
        /// 获取查询信息
        /// </summary>
        /// <typeparam name="valueType">对象类型</typeparam>
        /// <typeparam name="modelType">模型类型</typeparam>
        /// <param name="sqlTool">SQL操作工具</param>
        /// <param name="connection"></param>
        /// <param name="query">查询信息</param>
        /// <returns>对象集合</returns>
        internal virtual LeftArray <valueType> Select <valueType, modelType>(Sql.Table <valueType, modelType> sqlTool, ref DbConnection connection, ref SelectQuery <modelType> query)
            where valueType : class, modelType
            where modelType : class
        {
            try
            {
                if (query.Sql != null)
                {
                    if (connection == null)
                    {
                        connection = GetConnection();
                    }
                    if (connection != null)
                    {
                        if (query.IndexFieldName != null)
                        {
                            sqlTool.CreateIndex(connection, query.IndexFieldName, false);
                            query.IndexFieldName = null;
                        }
                        using (DbCommand command = getCommand(connection, query.Sql))
                        {
                            DbDataReader reader = null;
                            try
                            {
                                reader = command.ExecuteReader(CommandBehavior.SingleResult);
                            }
                            catch (Exception error)
                            {
                                sqlTool.Log.Add(AutoCSer.Log.LogType.Error, error, query.Sql);
                            }
                            if (reader != null)
                            {
                                using (reader)
                                {
                                    int skipCount = query.SkipCount;
                                    while (skipCount != 0 && reader.Read())
                                    {
                                        --skipCount;
                                    }
                                    if (skipCount == 0)
                                    {
                                        LeftArray <valueType> array = new LeftArray <valueType>();
                                        while (reader.Read())
                                        {
                                            valueType value = AutoCSer.Emit.Constructor <valueType> .New();

                                            DataModel.Model <modelType> .Setter.Set(reader, value, query.MemberMap);

                                            array.Add(value);
                                        }
                                        return(array);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            finally { query.Free(); }
            return(default(LeftArray <valueType>));
        }
Example #30
0
 public override object Read(DbDataReader reader)
 {
     return(reader.GetString(0));
 }
Example #31
0
        public static void SelectNestedFunctions()
        {
#if DEBUG
            //System.Threading.Thread.Sleep(1000 * 8);
#endif

            string tblname = "RDBMS_Table_ADONET_RegressionTest_" + Guid.NewGuid().ToString().Replace("-", "");

            System.Data.Common.DbProviderFactory fact = DbProviderFactories.GetFactory("Qizmt_DataProvider");

            DbConnection conn = fact.CreateConnection();
            conn.ConnectionString = "Data Source = localhost";
            conn.Open();
            try
            {
                DbCommand cmd = conn.CreateCommand();

                //Create table
                {
                    cmd.CommandText = "CREATE TABLE " + tblname + " (num INT, str CHAR(40), X LONG, Y DOUBLE, Z DOUBLE)";
                    int rows = cmd.ExecuteNonQuery();
                }

                //Insert data
                {
                    cmd.CommandText = "INSERT INTO " + tblname + " VALUES(11388275,'a{BC54AFDD-34AE-445b-820A-BFCBC716FF77}',312111,-11223344,3111);";
                    cmd.ExecuteNonQuery();
                    cmd.CommandText = "INSERT INTO " + tblname + " VALUES(11388276,'B{745B9042-77B2-4633-B765-59A1B0DA7194}',312111, 0       ,3111);";
                    cmd.ExecuteNonQuery();
                    cmd.CommandText = "INSERT INTO " + tblname + " VALUES(11388277,'c{512441F2-0AFE-42d3-A4BA-9DD26A9E553A}',312111, 11223344,3111);";
                    cmd.ExecuteNonQuery();
                }

                {
                    cmd.CommandText = "SELECT MIN(ABS(y)) FROM " + tblname + " WHERE x = 312111 GROUP BY x;";
                    DbDataReader reader   = cmd.ExecuteReader();
                    int          rowcount = 0;
                    bool         ok       = false;
                    while (reader.Read())
                    {
                        rowcount++;
                        if ((double)reader["MIN(ABS(y))"] == 0)
                        {
                            ok = true;
                        }
                    }
                    reader.Close();
                    if (rowcount != 1)
                    {
                        throw new Exception("Expected exactly 1 row output");
                    }
                    if (!ok)
                    {
                        throw new Exception("Did not find expected value");
                    }
                }

                {
                    cmd.CommandText = "SELECT LOWER(MAX(UPPER(str))) FROM " + tblname + " WHERE x = 312111 GROUP BY x;";
                    DbDataReader reader   = cmd.ExecuteReader();
                    int          rowcount = 0;
                    bool         ok       = false;
                    while (reader.Read())
                    {
                        rowcount++;
                        if ((string)reader["LOWER(MAX(UPPER(str)))"] == "c{512441f2-0afe-42d3-a4ba-9dd26a9e553a}")
                        {
                            ok = true;
                        }
                    }
                    reader.Close();
                    if (rowcount != 1)
                    {
                        throw new Exception("Expected exactly 1 row output");
                    }
                    if (!ok)
                    {
                        throw new Exception("Did not find expected value");
                    }
                }

                {
                    cmd.CommandText = "SELECT x,MIN(num),UPPER(MAX(str)),x,SIGN(x) FROM " + tblname + " WHERE x = 312111 GROUP BY x;";
                    DbDataReader reader   = cmd.ExecuteReader();
                    int          rowcount = 0;
                    bool         ok       = false;
                    while (reader.Read())
                    {
                        rowcount++;
                        if ((string)reader["UPPER(MAX(str))"] == "C{512441F2-0AFE-42D3-A4BA-9DD26A9E553A}" &&
                            (Int32)reader["MIN(num)"] == 11388275)
                        {
                            ok = true;
                        }
                    }
                    reader.Close();
                    if (rowcount != 1)
                    {
                        throw new Exception("Expected exactly 1 row output");
                    }
                    if (!ok)
                    {
                        throw new Exception("Did not find expected values");
                    }
                }

                {
                    cmd.CommandText = "SELECT x,MIN(num),UPPER(MAX(str)),x,ROUND(PI(),2) FROM " + tblname + " WHERE x = 312111 GROUP BY x;";
                    DbDataReader reader   = cmd.ExecuteReader();
                    int          rowcount = 0;
                    bool         ok       = false;
                    while (reader.Read())
                    {
                        rowcount++;
                        if ((string)reader["UPPER(MAX(str))"] == "C{512441F2-0AFE-42D3-A4BA-9DD26A9E553A}" &&
                            (Int32)reader["MIN(num)"] == 11388275 &&
                            (double)reader["ROUND(PI(),2)"] == 3.14)
                        {
                            ok = true;
                        }
                    }
                    reader.Close();
                    if (rowcount != 1)
                    {
                        throw new Exception("Expected exactly 1 row output");
                    }
                    if (!ok)
                    {
                        throw new Exception("Did not find expected values");
                    }
                }

                {
                    cmd.CommandText = "SELECT   x ,  Min  (  num  )  ,  Min  ( LOWER ( str )  )  ,  x    FROM " + tblname + " WHERE x = 312111 GROUP BY x;";
                    DbDataReader reader   = cmd.ExecuteReader();
                    int          rowcount = 0;
                    bool         ok       = false;
                    while (reader.Read())
                    {
                        rowcount++;
                        if ((string)reader["MIN(LOWER(str))"] == "a{bc54afdd-34ae-445b-820a-bfcbc716ff77}" &&
                            (Int32)reader["MIN(num)"] == 11388275)
                        {
                            ok = true;
                        }
                    }
                    reader.Close();
                    if (rowcount != 1)
                    {
                        throw new Exception("Expected exactly 1 row output");
                    }
                    if (!ok)
                    {
                        throw new Exception("Did not find expected values");
                    }
                }

                {
                    // All literal values!
                    cmd.CommandText = "SELECT 88 , -909 , 'foo''bar baz' , 4503599627370496, 11.1, 'i' FROM " + tblname + " WHERE x = 312111 GROUP BY x;";
                    DbDataReader reader   = cmd.ExecuteReader();
                    int          rowcount = 0;
                    bool         ok       = false;
                    while (reader.Read())
                    {
                        rowcount++;
                        if ((Int32)reader["88"] == 88 &&
                            (Int32)reader["-909"] == -909 &&
                            (string)reader["'foo''bar baz'"] == "foo'bar baz" &&
                            (Int64)reader["4503599627370496"] == 4503599627370496 &&
                            (double)reader["11.1"] == 11.1 &&
                            (string)reader["'i'"] == "i")
                        {
                            ok = true;
                        }
                    }
                    reader.Close();
                    if (rowcount != 1)
                    {
                        throw new Exception("Expected exactly 1 row output");
                    }
                    if (!ok)
                    {
                        throw new Exception("Did not find expected values");
                    }
                }
            }
            finally
            {
                try
                {
                    conn.Close();
                }
                catch (Exception e)
                {
                    Console.Error.WriteLine(" *** Close error: {0}", e.Message);
                }
            }
        }
Example #32
0
        public static void DbAggregators_MAX(string tablename)
        {
            {
                System.Data.Common.DbProviderFactory fact = DbProviderFactories.GetFactory("DSpace_DataProvider");
                DbConnection conn = fact.CreateConnection();
                try
                {
                    conn.ConnectionString = "Data Source = localhost";
                    conn.Open();

                    {
                        Console.WriteLine("Testing MAX(datetime)...");
                        DbCommand cmd = conn.CreateCommand();
                        cmd.CommandText = "select id, MAX(bday) from " + tablename + " group by id";

                        Dictionary <int, DateTime> expected = new Dictionary <int, DateTime>();
                        expected[10] = DateTime.Parse("1/2/2000 10:00:00 AM");
                        expected[20] = DateTime.Parse("3/4/2001 7:00:00 PM");
                        expected[30] = DateTime.Parse("9/10/2008 9:00:00 PM");

                        Dictionary <int, int> resultCount = new Dictionary <int, int>();

                        DbDataReader reader = cmd.ExecuteReader();
                        while (reader.Read())
                        {
                            int      id  = reader.GetInt32(0);
                            DateTime max = reader.GetDateTime(1);
                            if (!expected.ContainsKey(id))
                            {
                                throw new Exception("id returned from max group by is invalid.");
                            }
                            if (expected[id] != max)
                            {
                                throw new Exception("Expected max: " + expected[id].ToString() + ", but got " + max.ToString() + " instead.");
                            }
                            if (!resultCount.ContainsKey(id))
                            {
                                resultCount[id] = 0;
                            }
                            resultCount[id]++;
                        }
                        reader.Close();

                        int cnt = 0;
                        foreach (int c in resultCount.Values)
                        {
                            cnt += c;
                        }

                        if (cnt != 3)
                        {
                            throw new Exception("Expected row count: 3, but got " + cnt.ToString() + " instead.");
                        }
                        Console.WriteLine("Expected results received.");
                    }
                }
                finally
                {
                    conn.Close();
                }
            }
        }
Example #33
0
 public SqlQueryResultCollectionEnumerator(DbDataReader reader, Func <IDataRecord, TResult> convert)
 {
     _Reader  = Check.NotNull(nameof(reader), reader);
     _Convert = Check.NotNull(nameof(convert), convert);
 }
Example #34
0
        protected override void CreateOrModify_TablesAndFields(string dataTable, DatasetConfig datasetConfig)
        {
            this.datasetConfig = datasetConfig;
            this.dataTable     = dataTable;
            this.fieldList     = datasetConfig.DatasetConfigRows;

            List <DatasetConfigRow> createFieldList;

            //Look if Table exists, when not, create it!
            try
            {
                string sql = "SELECT * FROM " + dataTable + ";";
                myCmd.Connection  = myDBConn;
                myCmd.CommandText = sql;
                myReader          = myCmd.ExecuteReader();
            }
            catch (SqlException ex)
            {
                if (ex.Number == 208)
                {
                    try
                    {
                        string sql = "CREATE TABLE " + dataTable + " (id int IDENTITY(1,1)PRIMARY KEY CLUSTERED); ";

                        myCmd.CommandText = sql;
                        myCmd.ExecuteNonQuery();

                        sql = "SELECT * FROM " + dataTable + ";";
                        myCmd.CommandText = sql;
                        myReader          = myCmd.ExecuteReader();
                    }
                    catch (SqlException ex_ex)
                    {
                        throw ex_ex;
                    }
                }
                else
                {
                    throw ex;
                }
            }

            //Look for the Fields, create or alter them!
            List <String> existDBFelderliste = new List <string>();

            for (int n = 0; n < myReader.FieldCount; n++)
            {
                existDBFelderliste.Add(myReader.GetName(n));
            }
            myReader.Close();


            //Wenn Date Time Feld gesetzt...
            dateFieldName   = datasetConfig.DateTimeDatabaseField;
            createFieldList = new List <DatasetConfigRow>(fieldList);
            if (!string.IsNullOrEmpty(datasetConfig.DateTimeDatabaseField))
            {
                createFieldList.Add(new DatasetConfigRow()
                {
                    DatabaseField = dateFieldName, DatabaseFieldType = "datetime"
                });
            }


            foreach (DatasetConfigRow myFeld in createFieldList)
            {
                foreach (string existMyFeld in existDBFelderliste)
                {
                    if (myFeld.DatabaseField.ToLower() == existMyFeld.ToLower())
                    {
                        goto nextFeld;
                    }
                }

                //Feld existiert nicht -> erzeugen

                string sql = "ALTER TABLE " + dataTable + " ADD " + myFeld.DatabaseField + " " + myFeld.DatabaseFieldType;

                try
                {
                    myCmd.Connection  = myDBConn;
                    myCmd.CommandText = sql;
                    myCmd.ExecuteNonQuery();
                }
                catch (SqlException ex)
                {
                    throw ex;
                }

nextFeld:
                //Irgendeine anweisung, da sonst der Sprung nicht geht...
                {
                }
            }


            //Create Insert Command
            string wertliste = "", felderliste = "";

            foreach (DatasetConfigRow myFeld in createFieldList)
            {
                if (wertliste != "")
                {
                    wertliste   += ",";
                    felderliste += ",";
                }

                felderliste += myFeld.DatabaseField;
                wertliste   += "@" + myFeld.DatabaseField;
            }
            insertCommand = "INSERT INTO " + dataTable + "(" + felderliste + ") values(" + wertliste + ")";
        }
Example #35
0
 public void Dispose()
 {
     _Reader?.Close();
     _Reader?.Dispose();
     _Reader = null;
 }
Example #36
0
    /// <summary>
    /// 执行一条带多个参数的SQL语句,获取DataReader对象阅读器
    /// </summary>
    public DbDataReader ExecuteReaderWithParams(string sqlStr)
    {
        try
        {
            BuildTextCommand(sqlStr);
            _reader = _command.ExecuteReader(CommandBehavior.CloseConnection);
        }
        catch (DbException)
        {
            throw;
        }

        return _reader;
    }
 public ClassHandlerIdentityTable Get(ClassHandlerIdentityTable entity,
                                      DbDataReader reader)
 {
     ++GetMethodCallCount;
     return(entity);
 }
		public object ReadObject(Type type, DbDataReader reader, IList<string> propertyNames, IDictionary<string, IDbObject> objectGraph)
		{
			var dbFunctionHelper = GetDbFunctionHelper(type);
			return dbFunctionHelper.ReadObject(type, reader, propertyNames, objectGraph);
		}
Example #39
0
        /// <summary>
        /// Returns a new PurchaseOrderStatusDetails instance filled with the DataReader's current record data
        /// </summary>
        protected virtual PurchaseOrderStatusDetails GetPurchaseOrderStatusFromReader(DbDataReader reader)
        {
            PurchaseOrderStatusDetails purchaseOrderStatus = new PurchaseOrderStatusDetails();

            if (reader.HasRows)
            {
                purchaseOrderStatus.PurchaseOrderStatusId = GetReaderValue_Int32(reader, "PurchaseOrderStatusId", 0); //From: [Table]
                purchaseOrderStatus.Name = GetReaderValue_String(reader, "Name", "");                                 //From: [Table]
            }
            return(purchaseOrderStatus);
        }
Example #40
0
 private void FillInfoToClinicForm(DbDataReader reader, bool onlyInfo)
 {
     lblClinicRoomId.Text = reader["Idpatient"].ToString();
     txtBoxClinicRoomAddress.Text = reader["Address"].ToString();
     if (String.IsNullOrEmpty(txtBoxClinicRoomWeight.Text)) txtBoxClinicRoomWeight.Text = reader["Weight"].ToString();
     if (String.IsNullOrEmpty(txtBoxClinicRoomHeight.Text)) txtBoxClinicRoomHeight.Text = reader["Height"].ToString();
     dateTimePickerBirthDay.Text = reader["Birthday"].ToString();
     comboBoxClinicRoomName.Text = reader["name"].ToString();
     // dateTimePickerNgayKham.Text = reader["Day"].ToString(); //we update new Date
     if (!onlyInfo)
     {
         txtBoxClinicRoomSymptom.Text = reader["Symptom"].ToString();
         txtBoxClinicRoomDiagnose.Text = reader["Diagnose"].ToString();
         if (String.IsNullOrEmpty(textBoxClinicNhietDo.Text)) textBoxClinicNhietDo.Text = reader[DatabaseContants.history.temperature].ToString();
         if (String.IsNullOrEmpty(textBoxHuyetAp.Text)) textBoxHuyetAp.Text = reader[DatabaseContants.history.huyetap].ToString();
     }
     textBoxClinicPhone.Text = reader["phone"].ToString();
 }
Example #41
0
        /// <summary>
        /// Returns a collection of PurchaseOrderStatusDetails objects with the data read from the input DataReader
        /// </summary>
        protected virtual List <PurchaseOrderStatusDetails> GetPurchaseOrderStatusCollectionFromReader(DbDataReader reader)
        {
            List <PurchaseOrderStatusDetails> purchaseOrderStatuss = new List <PurchaseOrderStatusDetails>();

            while (reader.Read())
            {
                purchaseOrderStatuss.Add(GetPurchaseOrderStatusFromReader(reader));
            }
            return(purchaseOrderStatuss);
        }
Example #42
0
        public void SaveUpdate()
        {
            var customer = new Customer
            {
                ID = 1,
                Balance = 0,
                BalanceRate = 0,
                DefaultContactID = 1,
                Name = "Customer1",
                ProfileID = 1
            };

            var provider = new IProvider();
            var transaction = new Mock<ITransaction>();
            var command = new ICommand();
            var schema = new TypeTable(typeof(Customer));

            var reader = new DbDataReader();
            reader.Setup(r => r.Read()).Returns(true);


            provider.Setup(p => p.GetSchema(typeof(Customer))).Returns(schema);
            provider.CommandExecutor.Setup(c => c.InitiateTransaction()).Returns(transaction.Object);
            provider.Setup(p => p.GetEntityStatus(customer)).Returns(EntityStatus.Update);
            provider.CommandBuilder.Setup(c => c.CreateUpdateCommand(customer)).Returns(command.Object);
            provider.CommandExecutor.Setup(c => c.ExecuteReader(command.Object, transaction.Object)).Returns(
                reader.Object);

            provider.Mapper.Setup(m => m.GetObjectMappingMethod(typeof(Customer))).Returns(d => customer);

            var target = new DataSession(provider.Object);
            target.Save(customer);

            provider.CommandExecutor.Verify(c => c.InitiateTransaction());
            provider.CommandExecutor.Verify(c => c.CommitTransaction(transaction.Object));

            Assert.IsTrue(customer.ID == 1);
        }
        public object NullSafeGet(DbDataReader rs, string[] names, ISessionImplementor session, object owner)
        {
            StateUserTypeConverter converter = GetConverter();

            return(converter.Get(rs, names, session));
        }
Example #44
0
        public void GetTByProcedure()
        {
            var procedure = new Mock<Procedure>("TestProcedure");

            var customer = new Customer
            {
                ID = 1,
                Balance = 0,
                BalanceRate = 0,
                DefaultContactID = 1,
                Name = "Customer1",
                ProfileID = 1
            };

            var reader = new DbDataReader();
            reader.Setup(r => r.Read()).Returns(true);

            var provider = new IProvider();

            var command = new ICommand();

            var schema = new TypeTable(typeof(Customer));

            provider.Setup(p => p.GetSchema(typeof(Customer))).Returns(schema);

            provider.CommandBuilder.Setup(c => c.CreateCommandFromProcedure(procedure.Object)).Returns(command.Object);

            provider.CommandExecutor.Setup(c => c.ExecuteReader(command.Object)).Returns(reader.Object);

            provider.Mapper.Setup(m => m.GetTMappingMethod<Customer>()).Returns(d => customer);

            var target = new DataSession(provider.Object);

            var actual = target.GetT<Customer>(procedure.Object);

            Assert.AreEqual(actual, customer);

        }
Example #45
0
 public override object Get(DbDataReader rs, string name)
 {
     return(Get(rs, rs.GetOrdinal(name)));
 }
Example #46
0
        public void GetPagedListByExpression()
        {
            Expression<Func<Customer, bool>> expression = e => e.ID < 4;

            var customer1 = new Customer
            {
                ID = 1,
                Balance = 0,
                BalanceRate = 0,
                DefaultContactID = 1,
                Name = "Customer1",
                ProfileID = 1
            };
            var customer2 = new Customer
            {
                ID = 2,
                Balance = 0,
                BalanceRate = 0,
                DefaultContactID = 2,
                Name = "Customer2",
                ProfileID = 2
            };
            var customer3 = new Customer
            {
                ID = 3,
                Balance = 0,
                BalanceRate = 0,
                DefaultContactID = 3,
                Name = "Customer3",
                ProfileID = 3
            };

            var customerQueue = new Queue<Customer>(new[] { customer1, customer2, customer3 });
            var readerResults = new Queue<bool>(new[] { true, true, true, false });

            var reader = new DbDataReader();
            reader.Setup(r => r.Read()).Returns(readerResults.Dequeue);

            var provider = new IProvider();

            var command = new ICommand();

            var schema = new TypeTable(typeof(Customer));

            provider.Setup(p => p.GetSchema(typeof(Customer))).Returns(schema);

            provider.CommandBuilder.Setup(c => c.CreateGetListByPageCommand<Customer>(expression)).Returns(command.Object);
            provider.CommandExecutor.Setup(c => c.ExecuteReader(command.Object)).Returns(reader.Object);

            provider.Mapper.Setup(m => m.GetTMappingMethod<Customer>()).Returns(d => customerQueue.Dequeue());

            var target = new DataSession(provider.Object);

            var actual = target.GetPagedList<List<Customer>, Customer>(10, 1, expression);

            Assert.IsTrue(actual[0].ID == 1 &&
                actual[1].ID == 2 && actual[2].ID == 3);

        }
Example #47
0
 internal SAPDataReaderEventType(DbDataReader reader)
 {
     _reader = reader;
 }
Example #48
0
        /// <summary>
        /// Executes a query and reads and returns the first <see cref="Int32"/> value
        /// </summary>
        /// <param name="query"></param>
        /// <param name="arg"></param>
        /// <returns>True, if the first <see cref="Int32"/> value is above zero</returns>
        public virtual bool QueryBool(string query, params object[] arg)
        {
            query = string.Format(query, arg);

            var result = false;
            LastException = null;
            if (query.Length == 0) {
                return false;
            }

            try {
                Open();
                Command = Connection.CreateCommand();
                Command.CommandText = query;

                Reader = Command.ExecuteReader();
                while (Reader.Read()) {
                    result = (Reader.GetInt32(0) > 0);
                }
                Reader.Close();
            } catch (Exception ex) {
                System.Diagnostics.Debug.WriteLine(ex);
                LastException = ex;
                return false;
            }

            return result;
        }
Example #49
0
 internal virtual EntityDataReader CreateEntityDataReader(
     EntityCommand entityCommand, DbDataReader storeDataReader, CommandBehavior behavior)
 {
     return(new EntityDataReader(entityCommand, storeDataReader, behavior));
 }
    private Dictionary<string, List<string>> BuildColumnList(DbDataReader r, bool IncludeDb )
    {      
      Dictionary<string, List<string>> dicColumns = new Dictionary<string, List<string>>();
      List<string> cols = null;
      string prevTbl = "";
      while (r.Read())
      {
        string dbName = r.GetString(0)/*.ToLower() */;
        string tableName = r.GetString(1) /*.ToLower() */;
        string colName = r.GetString(2);
        string finalTableName = IncludeDb ? string.Format("{0}.{1}", dbName, tableName) :
          string.Format("{0}", tableName);

        if (prevTbl != finalTableName)
        {
          if (!string.IsNullOrEmpty(prevTbl))
          {
            dicColumns.Add(prevTbl, cols);
          }
          cols = new List<string>();
          prevTbl = finalTableName;
        }
        cols.Add(colName);
      }
      if (!string.IsNullOrEmpty(prevTbl))
      {
        dicColumns.Add(prevTbl, cols);
      }
      return dicColumns;
    }
Example #51
0
 protected abstract T ToDTO(DbDataReader __reader);
Example #52
0
        public async Task Read(DbDataReader reader, IIdentityMap map, CancellationToken token)
        {
            var result = await _handler.HandleAsync(reader, map, Stats, token).ConfigureAwait(false);

            Completion.SetResult(result);
        }
Example #53
0
        public ImportRecordRow GetImportRecordRow(DbDataReader reader)
        {
            ImportRecordRow row = new ImportRecordRow();

            row.Id = Convert.ToInt64(reader.GetValue(reader.GetOrdinal(C_Id)));
            row.TradeDate = Convert.ToString(reader.GetValue(reader.GetOrdinal(C_TradeDate)));
            row.TableName = Convert.ToString(reader.GetValue(reader.GetOrdinal(C_TableName)));
            row.SourceType = (ESourceType)Convert.ToInt32(reader.GetValue(reader.GetOrdinal(C_SourceType)));
            row.ImportState = (EImportStatus)Convert.ToInt32(reader.GetValue(reader.GetOrdinal(C_ImportState)));
            row.ImportCount = Convert.ToInt32(reader.GetValue(reader.GetOrdinal(C_ImportCount)));
            row.TotalCount = Convert.ToInt32(reader.GetValue(reader.GetOrdinal(C_TotalCount)));
            row.ImportDate = Convert.ToDateTime(reader.GetValue(reader.GetOrdinal(C_ImportDate)));
            row.Comment = Convert.ToString(reader.GetValue(reader.GetOrdinal(C_Comment)));

            return row;
        }