Exemplo n.º 1
0
        /// <summary>
        /// Transform dictionary to SqlDataRecord list
        /// 转化字典到TVP参数列表
        /// </summary>
        /// <param name="dic">Dictionary</param>
        /// <param name="keyType">Key data type</param>
        /// <param name="itemType">Item data type</param>
        /// <param name="keyMaxLength">Char/byte key max length</param>
        /// <param name="valueMaxLength">Char/byte value max length</param>
        /// <returns>TVP list</returns>
        public static IEnumerable <SqlDataRecord> DictionaryToRecords(IDictionary dic, SqlDbType keyType, SqlDbType itemType, long?keyMaxLength = null, long?valueMaxLength = null)
        {
            // SqlDataRecord definition
            var keyMeta  = IsLengthSpecifiedType(keyType) ? new SqlMetaData("key", keyType, keyMaxLength.GetValueOrDefault(40)) : new SqlMetaData("key", keyType);
            var itemMeta = IsLengthSpecifiedType(itemType) ? new SqlMetaData("item", itemType, valueMaxLength.GetValueOrDefault(128)) : new SqlMetaData("item", itemType);
            var sdr      = new SqlDataRecord(keyMeta, itemMeta);

            // List enumerator
            var enumerator = dic.GetEnumerator();

            while (enumerator.MoveNext())
            {
                // Ignore null values
                if (enumerator.Key == null || enumerator.Value == null)
                {
                    yield break;
                }

                // Set value
                sdr.SetValue(0, enumerator.Key);
                sdr.SetValue(1, enumerator.Value);

                // Yield return for the current item
                // Memory saving
                yield return(sdr);
            }
        }
Exemplo n.º 2
0
        public static void GetEnvironmentVars()
        {
            try
            {
                SortedList environment_list = new SortedList();
                foreach (DictionaryEntry de in Environment.GetEnvironmentVariables())
                {
                    environment_list[de.Key] = de.Value;
                }

                SqlDataRecord record = new SqlDataRecord(
                    new SqlMetaData("VarName", SqlDbType.NVarChar, 1024),
                    new SqlMetaData("VarValue", SqlDbType.NVarChar, 4000)
                    );
                SqlContext.Pipe.SendResultsStart(record);
                foreach (DictionaryEntry de in environment_list)
                {
                    record.SetValue(0, de.Key);
                    record.SetValue(1, de.Value);
                    SqlContext.Pipe.SendResultsRow(record);
                }

                SqlContext.Pipe.SendResultsEnd();
            }
            catch (Exception ex)
            {
                SqlContext.Pipe.Send(ex.Message);
            }
        }
Exemplo n.º 3
0
        private List <SqlDataRecord> BuildSqlRecordList(CurrencyModel DataModel)
        {
            string  CurrencyCode;
            decimal CurrencyRate;

            PropertyInfo[] PublicProps;
            Type           ModelType;
            SqlDataRecord  Record;

            SqlMetaData[]        Columns;
            SqlMetaData          C_Code, C_Rate;
            List <SqlDataRecord> CurrencyTable = new List <SqlDataRecord>();

            C_Code  = new SqlMetaData("Code", SqlDbType.NVarChar, 5);
            C_Rate  = new SqlMetaData("Rate", SqlDbType.Decimal, 18, 2);
            Columns = new SqlMetaData[] { C_Code, C_Rate };

            ModelType   = typeof(CurrencyRateModel);
            PublicProps = ModelType.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);
            foreach (PropertyInfo Property in PublicProps)
            {
                CurrencyCode = Property.Name.ToString();
                CurrencyRate = Convert.ToDecimal(Property.GetValue(DataModel.quotes).ToString());
                Record       = new SqlDataRecord(Columns);
                Record.SetValue(Record.GetOrdinal("Code"), CurrencyCode.Substring(3));
                Record.SetValue(Record.GetOrdinal("Rate"), Math.Round(CurrencyRate, 2));
                CurrencyTable.Add(Record);
            }
            Record = new SqlDataRecord(Columns);
            Record.SetValue(Record.GetOrdinal("Code"), DataModel.source);
            Record.SetValue(Record.GetOrdinal("Rate"), 1.00M);
            CurrencyTable.Add(Record);
            return(CurrencyTable);
        }
Exemplo n.º 4
0
    private static void FillRecordFromElements(XmlReader inputReader, SqlDataRecord outputRecord, SqlMetaData[] outputColumns,
                                               string rowElementName)
    {
        bool continueReading  = true;
        bool skipRead         = false;
        int  expectedColumnID = 0;

        while (continueReading && (skipRead || inputReader.Read()))
        {
            skipRead = false;
            if (inputReader.NodeType == XmlNodeType.Element)
            {
                //collect nulls for any missing columns - if "XSINIL" was not set when calling
                while (!inputReader.Name.Equals(outputColumns[expectedColumnID].Name))
                {
                    if (expectedColumnID == outputColumns.Length - 1)
                    {
                        //we ran out of columns - thrown an error
                        throw new Exception("Unknown element found! (is it possible you did not specify a schema, did not specify " +
                                            "the \"XSINIL\" option, and had a null value in the first row? This would prevent successful column " +
                                            "auto-detection...");
                    }
                    outputRecord.SetValue(expectedColumnID, null);
                    expectedColumnID++;
                }


                bool valueIsNull = false;
                if (inputReader.HasAttributes &&
                    inputReader.MoveToAttribute("nil", "http://www.w3.org/2001/XMLSchema-instance") &&
                    inputReader.ReadContentAsString().Equals("true")
                    )
                {
                    valueIsNull = true;
                }

                if (valueIsNull)
                {
                    outputRecord.SetValue(expectedColumnID, null);
                }
                else
                {
                    SetRecordValueFromString(outputRecord, outputColumns, expectedColumnID, inputReader.ReadElementContentAsString());
                    skipRead = true;
                }
                expectedColumnID++;
            }
            else if (inputReader.NodeType == XmlNodeType.EndElement && inputReader.Name.Equals(rowElementName))
            {
                continueReading = false;
            }
        }

        //set any missing columns at the end to null
        while (expectedColumnID < outputColumns.Length)
        {
            outputRecord.SetValue(expectedColumnID, null);
            expectedColumnID++;
        }
    }
Exemplo n.º 5
0
        /// <summary>
        /// Rempli la liste de SQL record.
        /// </summary>
        /// <param name="isInsert">True si c'est pour une insertion.</param>
        private void PopulateParamList(bool isInsert)
        {
            _index = new Dictionary <int, T>();
            SqlMetaData[] array = _metadataList.ToArray();
            _dataRecordList = new List <SqlDataRecord>();
            int insertKey = 0;

            foreach (T item in _collection)
            {
                if (isInsert && _beanDefinition.PrimaryKey.GetValue(item) != null)
                {
                    throw new NotSupportedException("La clef primaire doit être nulle.");
                }

                SqlDataRecord record = new SqlDataRecord(array);

                int ordinal = 0;
                foreach (BeanPropertyDescriptor property in _beanDefinition.Properties)
                {
                    object value = GetPropertyValue(item, property);

                    if (property.MemberName == null || property.IsPrimaryKey || property == _insertKeyProp)
                    {
                        if (!isInsert && property.IsPrimaryKey && property.PrimitiveType == typeof(int))
                        {
                            insertKey = (int)(value ?? insertKey);
                        }

                        if (property.MemberName == null || property.PrimitiveType == typeof(int))
                        {
                            continue;
                        }
                    }

                    record.SetValue(ordinal, value);
                    ++ordinal;
                }

                record.SetValue(ordinal, insertKey);
                _dataRecordList.Add(record);
                _index.Add(insertKey, item);
                ++insertKey;
            }

            if (_dataRecordList.Count == 0)
            {
                SqlDataRecord record = new SqlDataRecord(array);
                for (int i = 0; i < array.Length; i++)
                {
                    record.SetValue(i, null);
                }

                _dataRecordList.Add(record);
            }
        }
Exemplo n.º 6
0
        public void GetNullable_InvalidOrdinal_ShouldThrowException()
        {
            var dataRecord = new SqlDataRecord(
                new SqlMetaData("StringProp", SqlDbType.NVarChar, 20),
                new SqlMetaData("IntProp", SqlDbType.Int));

            dataRecord.SetValue(0, "String value.");
            dataRecord.SetValue(1, 123);

            Assert.Throws <IndexOutOfRangeException>(() => dataRecord.GetNullable <string>(3));
        }
Exemplo n.º 7
0
        public void GetNullableString_ValidStringValue_ShouldReturnStringValue()
        {
            const string StringValue = "String value.";
            var          dataRecord  = new SqlDataRecord(
                new SqlMetaData("StringProp", SqlDbType.NVarChar, 20),
                new SqlMetaData("IntProp", SqlDbType.Int));

            dataRecord.SetValue(0, StringValue);
            dataRecord.SetValue(1, 123);

            Assert.Equal(StringValue, dataRecord.GetNullable <string>(0));
        }
Exemplo n.º 8
0
        public void GetNullableInt_ValidIntValue_ShouldReturnIntValue()
        {
            const int IntValue   = 123;
            var       dataRecord = new SqlDataRecord(
                new SqlMetaData("StringProp", SqlDbType.NVarChar, 20),
                new SqlMetaData("IntProp", SqlDbType.Int));

            dataRecord.SetValue(0, "String value.");
            dataRecord.SetValue(1, IntValue);

            Assert.Equal(IntValue, dataRecord.GetNullable <int>(1));
        }
Exemplo n.º 9
0
        private void AddToWindow(object[] newTuple, string[] operators, ArrayList resultCollection, ArrayList resultstringCollection, SqlDataRecord record, SqlBoolean isFrameworkMode, int level, DataTable dtResult)
        {
            //Erste Spalte ist die ID
            long?[]  recordInt    = new long?[operators.GetUpperBound(0) + 1];
            string[] recordstring = new string[operators.GetUpperBound(0) + 1];
            DataRow  row          = dtResult.NewRow();

            for (int iCol = 0; iCol <= newTuple.GetUpperBound(0); iCol++)
            {
                //Only the real columns (skyline columns are not output fields)
                if (iCol <= operators.GetUpperBound(0))
                {
                    //LOW und HIGH Spalte in record abfüllen
                    if (operators[iCol].Equals("LOW"))
                    {
                        if (newTuple[iCol] == DBNull.Value)
                        {
                            recordInt[iCol] = null;
                        }
                        else
                        {
                            recordInt[iCol] = (long)newTuple[iCol];
                        }

                        //Check if long value is incomparable
                        if (iCol + 1 <= recordInt.GetUpperBound(0) && operators[iCol + 1].Equals("INCOMPARABLE"))
                        {
                            //Incomparable field is always the next one
                            recordstring[iCol] = (string)newTuple[iCol + 1];
                        }
                    }
                }
                else
                {
                    row[iCol - (operators.GetUpperBound(0) + 1)] = newTuple[iCol];
                    record.SetValue(iCol - (operators.GetUpperBound(0) + 1), newTuple[iCol]);
                }
            }
            row[record.FieldCount - 1] = level;
            record.SetValue(record.FieldCount - 1, level);

            if (isFrameworkMode == true)
            {
                dtResult.Rows.Add(row);
            }
            else
            {
                SqlContext.Pipe.SendResultsRow(record);
            }
            resultCollection.Add(recordInt);
            resultstringCollection.Add(recordstring);
        }
Exemplo n.º 10
0
 private SqlDataRecord SetDbRecord(SqlDataRecord record, object value, int index)
 {
     if (value.IsPrimitive())
     {
         var cValue = Convert.ChangeType(value, record.GetFieldType(index));
         record.SetValue(index, cValue);
     }
     else
     {
         record.SetValue(index, value.ToString());
     }
     return(record);
 }
Exemplo n.º 11
0
		public static IEnumerable<SqlDataRecord> GetSqlDataRecords()
		{
			var sqlRecord = new SqlDataRecord(
				new SqlMetaData("Id",   SqlDbType.Int),
				new SqlMetaData("Name", SqlDbType.NVarChar, 10));

			foreach (var record in TestData)
			{
				sqlRecord.SetValue(0, record.Id);
				sqlRecord.SetValue(1, record.Name);

				yield return sqlRecord;
			}
		}
Exemplo n.º 12
0
        public static void SendDataTable(DataTable dt)
        {
            bool[]        coerceToString; // Do we need to coerce this column to string?
            SqlMetaData[] metaData = ExtractDataTableColumnMetaData(dt, out coerceToString);

            SqlDataRecord record = new SqlDataRecord(metaData);
            SqlPipe       pipe   = SqlContext.Pipe;

            pipe.SendResultsStart(record);
            try
            {
                foreach (DataRow row in dt.Rows)
                {
                    for (int index = 0; index < record.FieldCount; index++)
                    {
                        object value = row[index];
                        if (null != value && coerceToString[index])
                        {
                            value = value.ToString();
                        }
                        record.SetValue(index, value);
                    }

                    pipe.SendResultsRow(record);
                }
            }
            finally
            {
                pipe.SendResultsEnd();
            }
        }
Exemplo n.º 13
0
        public List <SqlDataRecord> ConvertListParameterValue(object value, SqlListParamPlaceHolder lph)
        {
            var list = value as IList;

            if (list == null || list.Count == 0)
            {
                return(null); //it should null, not DbNull.Value
            }
            bool isEnum      = lph.ElementType.IsEnum;
            var  records     = new List <SqlDataRecord>();
            var  rowMetaData = new SqlMetaData("Value", SqlDbType.Variant);

            foreach (object elem in list)
            {
                var rec = new SqlDataRecord(rowMetaData);
                var v1  = isEnum ? ConvertHelper.EnumValueToInt(elem, lph.ElementType) : elem;
                rec.SetValue(0, v1);
                records.Add(rec);
            }
            if (records.Count == 0)
            {
                return(null); // with 0 rows throws error, advising to send NULL
            }
            return(records);
        }
Exemplo n.º 14
0
            IEnumerator <SqlDataRecord> IEnumerable <SqlDataRecord> .GetEnumerator()
            {
                List <SqlMetaData> records = new List <SqlMetaData>();
                var properties             = typeof(T).GetProperties();

                foreach (var prop in properties)
                {
                    SqlDbType sdbtyp = GetSqlType(prop.PropertyType);
                    if (sdbtyp == SqlDbType.VarChar)
                    {
                        records.Add(new SqlMetaData(prop.Name, sdbtyp, 8000));
                    }
                    else
                    {
                        records.Add(new SqlMetaData(prop.Name, sdbtyp));
                    }
                }
                SqlDataRecord ret = new SqlDataRecord(records.ToArray());

                foreach (T data in this)
                {
                    for (int i = 0; i < properties.Length; i++)
                    {
                        ret.SetValue(i, properties[i].GetValue(data, null));
                    }
                    yield return(ret);
                }
            }
Exemplo n.º 15
0
        /// <summary>
        ///		Create sql data record collection for bulk insert.
        ///		It creates meta data from insert procedure mapping  customattribute
        /// </summary>
        /// <typeparam name="T">
        ///     Any type which implements Framework.Common.Models.IModel interface.
        /// </typeparam>
        /// <param name="modelCollection">
        ///     A collection of model items to be bulk inserted.
        /// </param>
        /// <returns>
        ///		A collection of SqlDataRecord object for bulk insert.
        /// </returns>
        public List <SqlDataRecord> CreateSqlDataRecordCollection <T>(List <T> modelCollection) where T : IModel
        {
            List <SqlDataRecord> recordCollection = null;

            ModelParameterMap[] modelInsertParameters = new ModelParameterMap[this.map.Parameters.Count];
            SqlMetaData[]       metaDataCollection    = new SqlMetaData[this.map.Parameters.Count];

            foreach (ArrayList parameterMap in this.map.Parameters.Values)
            {
                ModelParameterMap[] parameters = (ModelParameterMap[])parameterMap.ToArray(typeof(ModelParameterMap));
                if (parameters != null && parameters.Length > 0)
                {
                    for (int i = 0; i < parameters.Length; i++)
                    {
                        ModelParameterMap mp = parameters[i];
                        if (mp.ParameterAction == DBProcedureType.INSERT)
                        {
                            // create meta data for insert parameter.
                            SqlMetaData metaData = this.CreateSQLMetaData(mp.ParameterName, mp.DatabaseType);
                            metaDataCollection[mp.ParameterIndex - 1]    = metaData;
                            modelInsertParameters[mp.ParameterIndex - 1] = mp;
                        }
                    }
                }
            }

            List <SqlMetaData> metaDataList = new List <SqlMetaData>();

            for (int counter = 0; counter < metaDataCollection.Length; counter++)
            {
                if (metaDataCollection[counter] != null)
                {
                    metaDataList.Add(metaDataCollection[counter]);
                }
            }

            // create one sql data record object for each model in the collection
            // and add that object to list
            recordCollection = new List <SqlDataRecord>();
            foreach (IModel model in modelCollection)
            {
                SqlDataRecord dataRecord = new SqlDataRecord(metaDataList.ToArray());

                // assign value for each property in the data record.
                for (int index = 0; index < modelInsertParameters.Length; index++)
                {
                    if (modelInsertParameters[index] != null)
                    {
                        ModelParameterMap mp = modelInsertParameters[index];

                        // this.SetDataRecordValue(dataRecord, mp.DatabaseType, mp.Property.GetValue(model, null), index);
                        dataRecord.SetValue(index, mp.Property.GetValue(model, null));
                    }
                }

                recordCollection.Add(dataRecord);
            }

            return(recordCollection);
        }
Exemplo n.º 16
0
        /// <summary>
        /// Send the result back to the client
        /// </summary>
        /// <param name="dt"></param>
        public static void PipeDataTable(DataTable dt)
        {

            var md = ExtractDataTableColumnMetaData(dt);
            var r = new SqlDataRecord(md);
            var p = SqlContext.Pipe;

            //---------------------------------------------------------------------------------------
            //  First is invoked ‘SendResultsStart.’ 
            // ‘SendResultStart’ marks the beginning of a result set to be sent back to the client, 
            //  and uses the r parameter to construct the metadata that describes the result set
            //---------------------------------------------------------------------------------------
            p?.SendResultsStart(r);
            try
            {
                foreach (DataRow row in dt.Rows)
                {
                    for (var i = 0; i < r.FieldCount; i++)
                    {
                        var v = row[i];
                        v = DBNull.Value != v ? (object) v.ToString() : DBNull.Value;
                        r.SetValue(i, v);
                    }

                    p?.SendResultsRow(r);
                }
            }
            finally
            {
                //
                // 'SendResultEnd’ marks the end of a result set and returns the SqlPipe instance to the initial state.
                //
                p?.SendResultsEnd();
            }
        }
Exemplo n.º 17
0
        // Used for sending lists in SqlParameter, to use in SQL clauses like 'WHERE x IN (@P0)"
        // @P0 should be declarate as VITA_ArrayAsTable data type.
        // We can use DataTable as a container, but DataTable is not supported by .NET core;
        // we use alternative: IEnumerable<SqlDataRecord>, it is supported.
        // TODO: review the method and optimize it.
        internal static object ConvertListToRecordList(object value)
        {
            var  list      = value as System.Collections.IEnumerable;
            var  valueType = value.GetType();
            Type elemType;

            Util.Check(valueType.IsListOfDbPrimitive(out elemType),
                       "Value must be list of DB primitives. Value type: {0} ", valueType);
            if (elemType.IsNullableValueType())
            {
                elemType = Nullable.GetUnderlyingType(elemType);
            }
            bool isEnum  = elemType.IsEnum;
            var  records = new List <SqlDataRecord>();
            var  colData = new SqlMetaData("Value", SqlDbType.Variant);

            foreach (object v in list)
            {
                var rec = new SqlDataRecord(colData);
                var v1  = isEnum ? (int)v : v;
                rec.SetValue(0, v1);
                records.Add(rec);
            }
            if (records.Count == 0)
            {
                return(null); // with 0 rows throws error, advising to send NULL
            }
            return(records);
        }
Exemplo n.º 18
0
        /// <summary>
        /// Guid items to records
        /// 转化Guid项目到TVP参数列表
        /// </summary>
        /// <param name="items">Items</param>
        /// <returns>Result</returns>
        public static IEnumerable <SqlDataRecord> GuidItemToRecords(IEnumerable <GuidItem> items, long?maxLength = null)
        {
            // SqlDataRecord definition
            var sdr = new SqlDataRecord(new SqlMetaData("Id", SqlDbType.UniqueIdentifier), new SqlMetaData("Item", SqlDbType.VarChar, maxLength ?? 128));

            foreach (var item in items)
            {
                // Set value
                sdr.SetValue(0, item.Id);
                sdr.SetValue(1, item.Label);

                // Yield return for the current item
                // Memory saving
                yield return(sdr);
            }
        }
Exemplo n.º 19
0
        public static void CreateGeometryDartboard(SqlGeometry centre, double radius, int numrings)
        {
            int srid = (int)centre.STSrid;

            List <SqlDataRecord> Grid = new List <SqlDataRecord>();

            SqlMetaData[] Columns =
            {
                new SqlMetaData("CellId", SqlDbType.Int),
                new SqlMetaData("Cell",   SqlDbType.Udt, typeof(SqlGeometry))
            };

            for (int x = 0; x < numrings; x++)
            {
                SqlGeometry Ring = centre.STBuffer(radius * (x + 1));
                SqlGeometry Hole = centre.STBuffer(radius * x);
                Ring = Ring.STDifference(Hole);

                SqlDataRecord rec = new SqlDataRecord(Columns);
                rec.SetInt32(0, x);
                rec.SetValue(1, Ring);
                Grid.Add(rec);
            }

            SqlContext.Pipe.SendResultsStart(new SqlDataRecord(Columns));
            foreach (SqlDataRecord d in Grid)
            {
                SqlContext.Pipe.SendResultsRow(d);
            }
            SqlContext.Pipe.SendResultsEnd();
        }
Exemplo n.º 20
0
 public static void AddParameters(this SqlCommand command, IDictionary <string, object> parameterDictionary)
 {
     if (parameterDictionary != null)
     {
         foreach (var param in parameterDictionary)
         {
             if (param.Value is string[] stringArray)
             {
                 SqlParameter sqlParam = command.CreateParameter();
                 sqlParam.ParameterName = param.Key;
                 sqlParam.SqlDbType     = SqlDbType.Structured;
                 sqlParam.TypeName      = "dbo.NvarcharTable";
                 if (stringArray.Length == 0)
                 {
                     sqlParam.Value = _emptyNvarcharTableParam;
                 }
                 else
                 {
                     sqlParam.Value = stringArray.Select(str =>
                     {
                         SqlMetaData meta     = new SqlMetaData("value", SqlDbType.NVarChar, 1000);
                         SqlDataRecord record = new SqlDataRecord(meta);
                         record.SetValue(0, str);
                         return(record);
                     });
                 }
                 command.Parameters.Add(sqlParam);
             }
             else
             {
                 command.Parameters.AddWithValue(param.Key, param.Value);
             }
         }
     }
 }
Exemplo n.º 21
0
        public static void GetSkyline(SqlString strQuery, SqlString strOperators, SqlInt32 numberOfRecords,
                                      SqlInt32 sortType, SqlInt32 count, SqlInt32 dimension, SqlString algorithm, SqlBoolean hasIncomparable)
        {
            try
            {
                Type strategyType = Type.GetType("prefSQL.SQLSkyline." + algorithm.ToString());

                if (!typeof(SkylineStrategy).IsAssignableFrom(strategyType))
                {
                    throw new Exception("passed algorithm is not of type SkylineStrategy.");
                }

                var strategy = (SkylineStrategy)Activator.CreateInstance(strategyType);

                strategy.Provider                   = Helper.ProviderClr;
                strategy.ConnectionString           = Helper.CnnStringSqlclr;
                strategy.RecordAmountLimit          = numberOfRecords.Value;
                strategy.HasIncomparablePreferences = hasIncomparable.Value;
                strategy.SortType                   = sortType.Value;

                var skylineSample = new SkylineSampling
                {
                    SubsetCount      = count.Value,
                    SubsetDimension  = dimension.Value,
                    SelectedStrategy = strategy
                };

                DataTable     dataTableReturn    = skylineSample.GetSkylineTable(strQuery.ToString(), strOperators.ToString());
                SqlDataRecord dataRecordTemplate = skylineSample.DataRecordTemplateForStoredProcedure;

                //throw new Exception(dataTableReturn.Rows[0].Table.Columns.Count.ToString());

                if (SqlContext.Pipe != null)
                {
                    SqlContext.Pipe.SendResultsStart(dataRecordTemplate);

                    foreach (DataRow recSkyline in dataTableReturn.Rows)
                    {
                        for (var i = 0; i < recSkyline.Table.Columns.Count; i++)
                        {
                            dataRecordTemplate.SetValue(i, recSkyline[i]);
                        }
                        SqlContext.Pipe.SendResultsRow(dataRecordTemplate);
                    }
                    SqlContext.Pipe.SendResultsEnd();
                }
            }
            catch (Exception ex)
            {
                //Pack Errormessage in a SQL and return the result
                var strError = "Error in prefSQL_SkylineSampling: ";
                strError += ex.Message;

                if (SqlContext.Pipe != null)
                {
                    SqlContext.Pipe.Send(strError);
                }
            }
        }
Exemplo n.º 22
0
        internal void WriteTo(SqlDataRecord record, object row)
        {
            var ordinal      = record.GetOrdinal(ColumnName);
            var value        = _accessor[row, PropertyName];
            var valueToWrite = ToDatabase(value);

            record.SetValue(ordinal, valueToWrite);
        }
        public static IEnumerable <SqlDataRecord> ConvertToTvp <T>(this IEnumerable <T> data) where T : new()
        {
            SqlMetaData[]  record;
            PropertyInfo[] properties;

            if (Tipler.ContainsKey(typeof(T)))
            {
                record = Tipler[typeof(T)];
                if (Props.ContainsKey(typeof(T)))
                {
                    properties = Props[typeof(T)];
                }
                else
                {
                    properties = typeof(T).GetTypeInfo().GetProperties();
                    Props.TryAdd(typeof(T), properties);
                }
            }
            else
            {
                var records = new List <SqlMetaData>();
                if (Props.ContainsKey(typeof(T)))
                {
                    properties = Props[typeof(T)];
                }
                else
                {
                    properties = typeof(T).GetTypeInfo().GetProperties();
                    Props.TryAdd(typeof(T), properties);
                }

                foreach (var prop in properties)
                {
                    var pt     = prop.PropertyType;
                    var sdbtyp = prop.PropertyType.GetSqlDbType();
                    records.Add(pt.Name.Equals("String")
                        ? new SqlMetaData(prop.Name, sdbtyp, 4000)
                        : new SqlMetaData(prop.Name, sdbtyp));
                }

                record = records.ToArray();
                Tipler.TryAdd(typeof(T), record);
            }

            var ret = new SqlDataRecord(record);

            foreach (var d in data)
            {
                for (var i = 0; i < properties.Length; i++)
                {
                    var im = properties[i];
                    ret.SetValue(i, properties[i].GetValue(d, null));
                }

                yield return(ret);
            }
        }
Exemplo n.º 24
0
        private static void SetRecordValues(SqlDataRecord record, ITuple tuple, BindingParameterConverter[] converters)
        {
            for (int i = 0; i < record.FieldCount; i++)
            {
                object value = converters[i]?.Invoke(tuple[i].Value) ?? tuple[i].Value;

                record.SetValue(i, value);
            }
        }
Exemplo n.º 25
0
            public static SqlDataRecord Convert(T obj)
            {
                var tableRow = new SqlDataRecord(TableSchema);

                for (int i = 0; i < Properties.Length; i++)
                {
                    tableRow.SetValue(i, Properties[i].GetGetMethod().Invoke(obj, new object[0]));
                }
                return(tableRow);
            }
Exemplo n.º 26
0
        public void GetNullableInt_DbNullDataRecordValue_ShouldReturnZero()
        {
            var dataRecord = new SqlDataRecord(
                new SqlMetaData("StringProp", SqlDbType.NVarChar, 20),
                new SqlMetaData("IntProp", SqlDbType.Int));

            dataRecord.SetValue(0, "String value.");

            Assert.Equal(0, dataRecord.GetNullable <int>(1));
        }
Exemplo n.º 27
0
        public void GetNullableString_DbNullDataRecordValue_ShouldReturnNull()
        {
            var dataRecord = new SqlDataRecord(
                new SqlMetaData("StringProp", SqlDbType.NVarChar, 20),
                new SqlMetaData("IntProp", SqlDbType.Int));

            dataRecord.SetValue(1, 123);

            Assert.Equal(null, dataRecord.GetNullable <string>(0));
        }
Exemplo n.º 28
0
    public IEnumerator <SqlDataRecord> GetEnumerator()
    {
        SqlDataRecord ret = new SqlDataRecord(new SqlMetaData("value", this.DbType));

        foreach (var data in this)
        {
            ret.SetValue(0, data);
            yield return(ret);
        }
    }
        public void GetXXX_ReturnValue(SqlDbType dbType, object value, Func <SqlDataRecord, object> getXXX)
        {
            SqlMetaData[] metaData = new SqlMetaData[]
            {
                new SqlMetaData("col1", dbType)
            };
            SqlDataRecord record = new SqlDataRecord(metaData);

            record.SetValue(0, value);
            Assert.Equal(value, getXXX(record));
        }
        public void GetXXX_ThrowsIfBadType(Func <SqlDataRecord, object> getXXX)
        {
            SqlMetaData[] metaData = new SqlMetaData[]
            {
                new SqlMetaData("col1", SqlDbType.NVarChar, 1)
            };
            SqlDataRecord record = new SqlDataRecord(metaData);

            record.SetValue(0, "a");
            Assert.Throws <InvalidCastException>(() => getXXX(record));
        }