Search Results

Search found 47 results on 2 pages for 'idatareader'.

Page 2/2 | < Previous Page | 1 2 

  • Getting .NET schema for a stored procedure result

    - by PHeiberg
    I have a couple of stored procedures in T-SQL where each stored procedure has a fixed schema for the result set. I need to map the result sets for each procedure to a POCO object and need the column name and type for each column in the result set. Is there a quick way of accessing the information? The best way I have found so far is accessing each stored procedure from .NET and writing my own extension method on a IDataReader/IDataRecord for dumping the information (column names and types) out. Example, a stored procedure executing the following query: SELECT Id, IntField, NullableIntField, VarcharField, DateField FROM SomeTable would require me to have the mapping information: Id - Guid IntField - System.Int32 NullableIntField - Nullable<System.Int32> VarcharField - String DateField - DateTime

    Read the article

  • SQL use comma-separated values with IN clause

    - by user342944
    I am developing an ASP.NET application and passing a string value like "1,2,3,4" into a procedure to select those values which are IN (1,2,3,4) but its saying "Conversion failed when converting the varchar value '1,2,3,4' to data type int." Here is the aspx code: private void fillRoles() { /*Read in User Profile Data from database */ Database db = DatabaseFactory.CreateDatabase(); DbCommand cmd = db.GetStoredProcCommand("sp_getUserRoles"); db.AddInParameter(cmd, "@pGroupIDs", System.Data.DbType.String); db.SetParameterValue(cmd, "@pGroupIDs", "1,2,3,4"); IDataReader reader = db.ExecuteReader(cmd); DropDownListRole.DataTextField = "Group"; DropDownListRole.DataValueField = "ID"; while (reader.Read()) { DropDownListRole.Items.Add((new ListItem(reader[1].ToString(), reader[0].ToString()))); } reader.Close(); } Here is my procedure: CREATE Procedure [dbo].[sp_getUserRoles](@pGroupIDs varchar(50)) AS BEGIN SELECT * FROM CheckList_Groups Where id in (@pGroupIDs) END

    Read the article

  • Class Mapping Error: 'T' must be a non-abstract type with a public parameterless constructor

    - by Amit Ranjan
    Hi, While mapping class i am getting error 'T' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method. Below is my SqlReaderBase Class public abstract class SqlReaderBase<T> : ConnectionProvider { #region Abstract Methods protected abstract string commandText { get; } protected abstract CommandType commandType { get; } protected abstract Collection<IDataParameter> GetParameters(IDbCommand command); **protected abstract MapperBase<T> GetMapper();** #endregion #region Non Abstract Methods /// <summary> /// Method to Execute Select Queries for Retrieveing List of Result /// </summary> /// <returns></returns> public Collection<T> ExecuteReader() { //Collection of Type on which Template is applied Collection<T> collection = new Collection<T>(); // initializing connection using (IDbConnection connection = GetConnection()) { try { // creates command for sql operations IDbCommand command = connection.CreateCommand(); // assign connection to command command.Connection = connection; // assign query command.CommandText = commandText; //state what type of query is used, text, table or Sp command.CommandType = commandType; // retrieves parameter from IDataParameter Collection and assigns it to command object foreach (IDataParameter param in GetParameters(command)) command.Parameters.Add(param); // Establishes connection with database server connection.Open(); // Since it is designed for executing Select statements that will return a list of results // so we will call command's execute reader method that return a Forward Only reader with // list of results inside. using (IDataReader reader = command.ExecuteReader()) { try { // Call to Mapper Class of the template to map the data to its // respective fields MapperBase<T> mapper = GetMapper(); collection = mapper.MapAll(reader); } catch (Exception ex) // catch exception { throw ex; // log errr } finally { reader.Close(); reader.Dispose(); } } } catch (Exception ex) { throw ex; } finally { connection.Close(); connection.Dispose(); } } return collection; } #endregion } What I am trying to do is , I am executine some command and filling my class dynamically. The class is given below: namespace FooZo.Core { public class Restaurant { #region Private Member Variables private int _restaurantId = 0; private string _email = string.Empty; private string _website = string.Empty; private string _name = string.Empty; private string _address = string.Empty; private string _phone = string.Empty; private bool _hasMenu = false; private string _menuImagePath = string.Empty; private int _cuisine = 0; private bool _hasBar = false; private bool _hasHomeDelivery = false; private bool _hasDineIn = false; private int _type = 0; private string _restaurantImagePath = string.Empty; private string _serviceAvailableTill = string.Empty; private string _serviceAvailableFrom = string.Empty; public string Name { get { return _name; } set { _name = value; } } public string Address { get { return _address; } set { _address = value; } } public int RestaurantId { get { return _restaurantId; } set { _restaurantId = value; } } public string Website { get { return _website; } set { _website = value; } } public string Email { get { return _email; } set { _email = value; } } public string Phone { get { return _phone; } set { _phone = value; } } public bool HasMenu { get { return _hasMenu; } set { _hasMenu = value; } } public string MenuImagePath { get { return _menuImagePath; } set { _menuImagePath = value; } } public string RestaurantImagePath { get { return _restaurantImagePath; } set { _restaurantImagePath = value; } } public int Type { get { return _type; } set { _type = value; } } public int Cuisine { get { return _cuisine; } set { _cuisine = value; } } public bool HasBar { get { return _hasBar; } set { _hasBar = value; } } public bool HasHomeDelivery { get { return _hasHomeDelivery; } set { _hasHomeDelivery = value; } } public bool HasDineIn { get { return _hasDineIn; } set { _hasDineIn = value; } } public string ServiceAvailableFrom { get { return _serviceAvailableFrom; } set { _serviceAvailableFrom = value; } } public string ServiceAvailableTill { get { return _serviceAvailableTill; } set { _serviceAvailableTill = value; } } #endregion public Restaurant() { } } } For filling my class properties dynamically i have another class called MapperBase Class with following methods: public abstract class MapperBase<T> where T : new() { protected T Map(IDataRecord record) { T instance = new T(); string fieldName; PropertyInfo[] properties = typeof(T).GetProperties(); for (int i = 0; i < record.FieldCount; i++) { fieldName = record.GetName(i); foreach (PropertyInfo property in properties) { if (property.Name == fieldName) { property.SetValue(instance, record[i], null); } } } return instance; } public Collection<T> MapAll(IDataReader reader) { Collection<T> collection = new Collection<T>(); while (reader.Read()) { collection.Add(Map(reader)); } return collection; } } There is another class which inherits the SqlreaderBaseClass called DefaultSearch. Code is below public class DefaultSearch: SqlReaderBase<Restaurant> { protected override string commandText { get { return "Select Name from vw_Restaurants"; } } protected override CommandType commandType { get { return CommandType.Text; } } protected override Collection<IDataParameter> GetParameters(IDbCommand command) { Collection<IDataParameter> parameters = new Collection<IDataParameter>(); parameters.Clear(); return parameters; } protected override MapperBase<Restaurant> GetMapper() { MapperBase<Restaurant> mapper = new RMapper(); return mapper; } } But whenever I tried to build , I am getting error 'T' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method. Even T here is Restaurant has a Parameterless Public constructor.

    Read the article

  • NHibernate Pitfalls: Custom Types and Detecting Changes

    - by Ricardo Peres
    This is part of a series of posts about NHibernate Pitfalls. See the entire collection here. NHibernate supports the declaration of properties of user-defined types, that is, not entities, collections or primitive types. These are used for mapping a database columns, of any type, into a different type, which may not even be an entity; think, for example, of a custom user type that converts a BLOB column into an Image. User types must implement interface NHibernate.UserTypes.IUserType. This interface specifies an Equals method that is used for comparing two instances of the user type. If this method returns false, the entity is marked as dirty, and, when the session is flushed, will trigger an UPDATE. So, in your custom user type, you must implement this carefully so that it is not mistakenly considered changed. For example, you can cache the original column value inside of it, and compare it with the one in the other instance. Let’s see an example implementation of a custom user type that converts a Byte[] from a BLOB column into an Image: 1: [Serializable] 2: public sealed class ImageUserType : IUserType 3: { 4: private Byte[] data = null; 5: 6: public ImageUserType() 7: { 8: this.ImageFormat = ImageFormat.Png; 9: } 10: 11: public ImageFormat ImageFormat 12: { 13: get; 14: set; 15: } 16: 17: public Boolean IsMutable 18: { 19: get 20: { 21: return (true); 22: } 23: } 24: 25: public Object Assemble(Object cached, Object owner) 26: { 27: return (cached); 28: } 29: 30: public Object DeepCopy(Object value) 31: { 32: return (value); 33: } 34: 35: public Object Disassemble(Object value) 36: { 37: return (value); 38: } 39: 40: public new Boolean Equals(Object x, Object y) 41: { 42: return (Object.Equals(x, y)); 43: } 44: 45: public Int32 GetHashCode(Object x) 46: { 47: return ((x != null) ? x.GetHashCode() : 0); 48: } 49: 50: public override Int32 GetHashCode() 51: { 52: return ((this.data != null) ? this.data.GetHashCode() : 0); 53: } 54: 55: public override Boolean Equals(Object obj) 56: { 57: ImageUserType other = obj as ImageUserType; 58: 59: if (other == null) 60: { 61: return (false); 62: } 63: 64: if (Object.ReferenceEquals(this, other) == true) 65: { 66: return (true); 67: } 68: 69: return (this.data.SequenceEqual(other.data)); 70: } 71: 72: public Object NullSafeGet(IDataReader rs, String[] names, Object owner) 73: { 74: Int32 index = rs.GetOrdinal(names[0]); 75: Byte[] data = rs.GetValue(index) as Byte[]; 76: 77: this.data = data as Byte[]; 78: 79: if (data == null) 80: { 81: return (null); 82: } 83: 84: using (MemoryStream stream = new MemoryStream(this.data ?? new Byte[0])) 85: { 86: return (Image.FromStream(stream)); 87: } 88: } 89: 90: public void NullSafeSet(IDbCommand cmd, Object value, Int32 index) 91: { 92: if (value != null) 93: { 94: Image data = value as Image; 95: 96: using (MemoryStream stream = new MemoryStream()) 97: { 98: data.Save(stream, this.ImageFormat); 99: value = stream.ToArray(); 100: } 101: } 102: 103: (cmd.Parameters[index] as DbParameter).Value = value ?? DBNull.Value; 104: } 105: 106: public Object Replace(Object original, Object target, Object owner) 107: { 108: return (original); 109: } 110: 111: public Type ReturnedType 112: { 113: get 114: { 115: return (typeof(Image)); 116: } 117: } 118: 119: public SqlType[] SqlTypes 120: { 121: get 122: { 123: return (new SqlType[] { new SqlType(DbType.Binary) }); 124: } 125: } 126: } In this case, we need to cache the original Byte[] data because it’s not easy to compare two Image instances, unless, of course, they are the same.

    Read the article

  • Problem: Sorting for GridView/ObjectDataSource changes depending on page

    - by user148298
    I have a GridView tied to an ObjectDataSource using paging. The paging works fine, except that the sort order changes depending on which page of the results is being viewed. This causes items to reappear on subsequent pages among other issues. I traced the problem to my DAL, which reads a page at a time and then sorts it. Obviously the sorting is going to change as the result set size changes. Is there an improvement to this algorithm. I would like to use a datareader if possible: [System.ComponentModel.DataObjectMethod(System.ComponentModel.DataObjectMethodType.Select)] public static WordsCollection LoadForCriteria(string sqlCriteria, int maximumRows, int startRowIndex, string sortExpression) { //DEFAULT SORT EXPRESSION if (string.IsNullOrEmpty(sortExpression)) sortExpression = "OrderBy"; //CREATE THE DYNAMIC SQL TO LOAD OBJECT StringBuilder selectQuery = new StringBuilder(); selectQuery.Append("SELECT"); if (maximumRows > 0) selectQuery.Append(" TOP " + (startRowIndex + maximumRows).ToString()); selectQuery.Append(" " + Words.GetColumnNames(string.Empty)); selectQuery.Append(" FROM sw_Words"); string whereClause = string.IsNullOrEmpty(sqlCriteria) ? string.Empty : " WHERE " + sqlCriteria; selectQuery.Append(whereClause); selectQuery.Append(" ORDER BY " + sortExpression); Database database = Token.Instance.Database; DbCommand selectCommand = database.GetSqlStringCommand(selectQuery.ToString()); //EXECUTE THE COMMAND WordsCollection results = new WordsCollection(); int thisIndex = 0; int rowCount = 0; using (IDataReader dr = database.ExecuteReader(selectCommand)) { while (dr.Read() && ((maximumRows < 1) || (rowCount < maximumRows))) { if (thisIndex >= startRowIndex) { Words varWords = new Words(); Words.LoadDataReader(varWords, dr); results.Add(varWords); rowCount++; } thisIndex++; } dr.Close(); } return results; }

    Read the article

  • Generating code -- is there an easy way to get a proper string representation of nullable type?

    - by Cory Larson
    So I'm building an application that is going to do a ton of code generation with both C# and VB output (depending on project settings). I've got a CodeTemplateEngine, with two derived classes VBTemplateEngine and CSharpTemplateEngine. This question regards creating the property signatures based on columns in a database table. Using the IDataReader's GetSchemaTable method I gather the CLR type of the column, such as "System.Int32", and whether it IsNullable. However, I'd like to keep the code simple, and instead of having a property that looks like: public System.Int32? SomeIntegerColumn { get; set; } or public Nullable<System.Int32> SomeIntegerColumn { get; set; }, where the property type would be resolved with this function (from my VBTemplateEngine), public override string ResolveCLRType(bool? isNullable, string runtimeType) { Type type = TypeUtils.ResolveType(runtimeType); if (isNullable.HasValue && isNullable.Value == true && type.IsValueType) { return "System.Nullable(Of " + type.FullName + ")"; // or, for example... return type.FullName + "?"; } else { return type.FullName; } }, I would like to generate a simpler property. I hate the idea of building a Type string from nothing, and I would rather have something like: public int? SomeIntegerColumn { get; set; } Is there anything built-in anywhere, such as in the VBCodeProvider or CSharpCodeProvider classes that would somehow take care of this for me? Or is there a way to get a type alias of int? from a type string like System.Nullable'1[System.Int32]? Thanks!

    Read the article

  • .net framework execution aborted while executing CLR sproc?

    - by Sean Ochoa
    I constructed a sproc that does the equivalent of FOR XML AUTO in SQL 2008. Now that I'm testing it, it gives me a really unhelpful error msg. Any idea what this error means? Msg 10329, Level 16, State 49, Procedure ForXML, Line 0 .Net Framework execution was aborted. System.Threading.ThreadAbortException: Thread was being aborted. System.Threading.ThreadAbortException: at System.Runtime.InteropServices.Marshal.PtrToStringUni(IntPtr ptr, Int32 len) at System.Data.SqlServer.Internal.CXVariantBase.WSTRToString() at System.Data.SqlServer.Internal.SqlWSTRLimitedBuffer.GetString(SmiEventSink sink) at System.Data.SqlServer.Internal.RowData.GetString(SmiEventSink sink, Int32 i) at Microsoft.SqlServer.Server.ValueUtilsSmi.GetValue(SmiEventSink_Default sink, ITypedGettersV3 getters, Int32 ordinal, SmiMetaData metaData, SmiContext context) at Microsoft.SqlServer.Server.ValueUtilsSmi.GetValue200(SmiEventSink_Default sink, SmiTypedGetterSetter getters, Int32 ordinal, SmiMetaData metaData, SmiContext context) at System.Data.SqlClient.SqlDataReaderSmi.GetValue(Int32 ordinal) at System.Data.SqlClient.SqlDataReaderSmi.GetValues(Object[] values) at System.Data.ProviderBase.DataReaderContainer.CommonLanguageSubsetDataReader.GetValues(Object[] values) at System.Data.ProviderBase.SchemaMapping.LoadDataRow() at System.Data.Common.DataAdapter.FillLoadDataRow(SchemaMapping mapping) at System.Data.Common.DataAdapter.FillFromReader(DataSet dataset, DataTable datatable, String srcTable, DataReaderContainer dataReader, Int32 startRecord, Int32 maxRecords, DataColumn parentChapterColumn, Object parentChapterValue) at System.Data.Common.DataAdapter.Fill(DataTable[] dataTables, IDataReader dataReader, Int32 startRecord, Int32 maxRecords) at System.Data.Common.DbDataAdapter.FillInternal(DataSet dataset, DataTable[] datatables, Int32 startRecord, Int32 maxRecords, String srcTable, IDbCommand command, CommandBehavior behavior) at System.Data.Common.DbDataAdapter.Fill(DataTable[] dataTables, Int32 startRecord, Int32 maxRecords, IDbCommand command, CommandBehavior behavior) at System.Data.Common.DbDataAdapter.Fill(DataTable dataTable) at ForXML.GetXML...

    Read the article

  • 3 tier application pattern suggestion

    - by Maxim Gershkovich
    I have attempted to make my first 3 tier application. In the process I have run into one problem I am yet to find an optimal solution for. Basically all my objects use an IFillable interface which forces the implementation of a sub as follows Public Sub Fill(ByVal Datareader As Data.IDataReader) Implements IFillable.Fill This sub then expects the Ids from the datareader will be identical to the properties of the object as such. Me.m_StockID = Datareader.GetGuid(Datareader.GetOrdinal("StockID")) In the end I end up with a datalayer that looks something like this. Public Shared Function GetStockByID(ByVal ConnectionString As String, ByVal StockID As Guid) As Stock Dim res As New Stock Using sqlConn As New SqlConnection(ConnectionString) sqlConn.Open() res.Fill(StockDataLayer.GetStockByIDQuery(sqlConn, StockID)) End Using Return res End Function Mostly this pattern seems to make sense. However my problem is, lets say I want to implement a property for Stock called StockBarcodeList. Under the above mentioned pattern any way I implement this property I will need to pass a connectionstring to it which obviously breaks my attempt at layer separation. Does anyone have any suggestions on how I might be able to solve this problem or am I going about this the completely wrong way? Does anyone have any suggestions on how I might improve my implementation? Please note however I am deliberately trying to avoid using the dataset in any form.

    Read the article

  • Is this OleDbDataAdapter bug

    - by ????
    It doesn't look to me OleDbDataAdapter should throw an exception on trying to fill DataSet for a db table column of type decimal(28,3). The message is "The numerical value is too large to fit into a 96 bit decimal". Could you just check this, I have no significant experience with ADO.NET and OLE DB components? The VB.NET code we have in the application is this: Dim dbDataSet As New DataSet Dim dbDataAdapter As OleDbDataAdapter Dim dbCommand As OleDbCommand Dim conn As OleDbConnection Dim connectionString As String 'parts where connectionString is set conn = New OleDbConnection(connectionString) 'part where sqlQuery is set but it ends up being "SELECT Price As 'Price' From PricebookView" - Price is of type decimal(28,3) dbCommand = New OleDbCommand(sqlQuery, conn) dbCommand.CommandTimeout = cmdTimeout dbDataAdapter = New OleDbDataAdapter(dbCommand) dbDataAdapter.Fill(dbDataSet) The last line is where the exception is thrown and the top of the stack trace is: at System.Data.ProviderBase.DbBuffer.ReadNumeric(Int32 offset) at System.Data.OleDb.ColumnBinding.Value_NUMERIC() at System.Data.OleDb.ColumnBinding.Value() at System.Data.OleDb.OleDbDataReader.GetValues(Object[] values) at System.Data.ProviderBase.DataReaderContainer.CommonLanguageSubsetDataReader.GetValues(Object[] values) at System.Data.ProviderBase.SchemaMapping.LoadDataRow() at System.Data.Common.DataAdapter.FillLoadDataRow(SchemaMapping mapping) at System.Data.Common.DataAdapter.FillFromReader(DataSet dataset, DataTable datatable, String srcTable, DataReaderContainer dataReader, Int32 startRecord, Int32 maxRecords, DataColumn parentChapterColumn, Object parentChapterValue) at System.Data.Common.DataAdapter.Fill(DataSet dataSet, String srcTable, IDataReader dataReader, Int32 startRecord, Int32 maxRecords) at System.Data.Common.DbDataAdapter.FillInternal(DataSet dataset, DataTable[] datatables, Int32 startRecord, Int32 maxRecords, String srcTable, IDbCommand command, CommandBehavior behavior) at System.Data.Common.DbDataAdapter.Fill(DataSet dataSet, Int32 startRecord, Int32 maxRecords, String srcTable, IDbCommand command, CommandBehavior behavior) at System.Data.Common.DbDataAdapter.Fill(DataSet dataSet) ... I am not sure why does it try to set the value to Int32. Thank you for the time !

    Read the article

  • .NET framework execution aborted while executing CLR stored procedure?

    - by Sean Ochoa
    I constructed a stored procedure that does the equivalent of FOR XML AUTO in SQL Server 2008. Now that I'm testing it, it gives me a really unhelpful error message. What does this error mean? Msg 10329, Level 16, State 49, Procedure ForXML, Line 0 .NET Framework execution was aborted. System.Threading.ThreadAbortException: Thread was being aborted. System.Threading.ThreadAbortException: at System.Runtime.InteropServices.Marshal.PtrToStringUni(IntPtr ptr, Int32 len) at System.Data.SqlServer.Internal.CXVariantBase.WSTRToString() at System.Data.SqlServer.Internal.SqlWSTRLimitedBuffer.GetString(SmiEventSink sink) at System.Data.SqlServer.Internal.RowData.GetString(SmiEventSink sink, Int32 i) at Microsoft.SqlServer.Server.ValueUtilsSmi.GetValue(SmiEventSink_Default sink, ITypedGettersV3 getters, Int32 ordinal, SmiMetaData metaData, SmiContext context) at Microsoft.SqlServer.Server.ValueUtilsSmi.GetValue200(SmiEventSink_Default sink, SmiTypedGetterSetter getters, Int32 ordinal, SmiMetaData metaData, SmiContext context) at System.Data.SqlClient.SqlDataReaderSmi.GetValue(Int32 ordinal) at System.Data.SqlClient.SqlDataReaderSmi.GetValues(Object[] values) at System.Data.ProviderBase.DataReaderContainer.CommonLanguageSubsetDataReader.GetValues(Object[] values) at System.Data.ProviderBase.SchemaMapping.LoadDataRow() at System.Data.Common.DataAdapter.FillLoadDataRow(SchemaMapping mapping) at System.Data.Common.DataAdapter.FillFromReader(DataSet dataset, DataTable datatable, String srcTable, DataReaderContainer dataReader, Int32 startRecord, Int32 maxRecords, DataColumn parentChapterColumn, Object parentChapterValue) at System.Data.Common.DataAdapter.Fill(DataTable[] dataTables, IDataReader dataReader, Int32 startRecord, Int32 maxRecords) at System.Data.Common.DbDataAdapter.FillInternal(DataSet dataset, DataTable[] datatables, Int32 startRecord, Int32 maxRecords, String srcTable, IDbCommand command, CommandBehavior behavior) at System.Data.Common.DbDataAdapter.Fill(DataTable[] dataTables, Int32 startRecord, Int32 maxRecords, IDbCommand command, CommandBehavior behavior) at System.Data.Common.DbDataAdapter.Fill(DataTable dataTable) at ForXML.GetXML...

    Read the article

  • File is used by another process?

    - by Surya sasidhar
    I get this error (file is being used by another process). Actually I write the code in a button click event like this, i am saving the excel file in a file using file upload, immediately i am fetching the file which i was save just now there i am getting this error. in my point of view i think it take time to save the excel file in that file. this is my code: FileUpload1.PostedFile.SaveAs(Server.MapPath("~/User/Excel/" + name.ToString() + ".xls")); string s = Server.MapPath("~/user/excel/" + name.ToString() + ".xls"); OleDbConnection DBConnection = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + s.ToString() + ";" + "Extended Properties=\"Excel 8.0;HDR=Yes\""); DBConnection.Open(); string SQLString = "SELECT * FROM Contacts"; OleDbCommand DBCommand = new OleDbCommand(SQLString, DBConnection); IDataReader DBReader = DBCommand.ExecuteReader(); mygridOut.DataSource = DBReader; mygridOut.DataBind(); and i am getting error like this: because it is being used by another process.

    Read the article

  • C# How can I get each column type and length and then use the lenght to padright to get the spaces a

    - by svon
    I have a console application that extracts data from a SQL table to a flat file. How can I get each column type and length and then use the lenght of each column to padright(length) to get the spaces at the end of each field. Here is what I have right now that does not include this functionality. Thanks { var destination = args[0]; var command = string.Format("Select * from {0}", Validator.Check(args[1])); var connectionstring = string.Format("Data Source={0}; Initial Catalog=dbname;Integrated Security=SSPI;", args[2]); var helper = new SqlHelper(command, CommandType.Text, connectionstring); using (StreamWriter writer = new StreamWriter(destination)) using (IDataReader reader = helper.ExecuteReader()) { while (reader.Read()) { Object[] values = new Object[reader.FieldCount]; int fieldCount = reader.GetValues(values); for (int i = 0; i < fieldCount; i++) writer.Write(values[i].ToString().PadRight(513)); writer.WriteLine(); } writer.Close(); }

    Read the article

  • C# how to get trailing spaces from the end of a varchar(513) field while exporting SQL table to a fl

    - by svon
    How do I get empty spaces from the end of a varchar(513) field while exporting data from SQL table to a flat file. I have a console application. Here is what I am using to export a SQL table having only one column of varchar(513) to a flat file. But I need to get all the 513 characters including spaces at the end. How do I change this code to incorporate that. Thanks { var destination = args[0]; var command = string.Format("Select * from {0}", Validator.Check(args[1])); var connectionstring = string.Format("Data Source={0}; Initial Catalog=dbname;Integrated Security=SSPI;", args[2]); var helper = new SqlHelper(command, CommandType.Text, connectionstring); using (StreamWriter writer = new StreamWriter(destination)) using (IDataReader reader = helper.ExecuteReader()) { while (reader.Read()) { Object[] values = new Object[reader.FieldCount]; int fieldCount = reader.GetValues(values); for (int i = 0; i < fieldCount; i++) writer.Write(values[i]); writer.WriteLine(); } writer.Close(); }

    Read the article

  • How do I create/use a Fluent NHibernate convention to automap UInt32 properties to an SQL Server 200

    - by dommer
    I'm trying to use a convention to map UInt32 properties to a SQL Server 2008 database. I don't seem to be able to create a solution based on existing web sources, due to updates in the way Fluent NHibernate works - i.e. examples are out of date. I'm trying to have NHibernate generate the schema (via ExposeConfiguration). I'm happy to have NHibernate map it to anything sensible (e.g. bigint). Here's my code as it currently stands (which, when I try to expose the schema, fails due to SQL Server not supporting UInt32). Apologies for the code being a little long, but I'm not 100% sure what is relevant to the problem, so I'm erring on the side of caution. Most of it is based on this post. The error reported is: System.ArgumentException : Dialect does not support DbType.UInt32 I think I'll need a relatively comprehensive example, as I don't seem to be able to pull the pieces together into a working solution, at present. FluentConfiguration configuration = Fluently.Configure() .Database(MsSqlConfiguration.MsSql2008 .ConnectionString(connectionString)) .Mappings(mapping => mapping.AutoMappings.Add( AutoMap.AssemblyOf<Product>() .Conventions.Add<UInt32UserTypeConvention>())); configuration.ExposeConfiguration(x => new SchemaExport(x).Create(false, true)); namespace NHibernateTest { public class UInt32UserTypeConvention : UserTypeConvention<UInt32UserType> { // Empty. } } namespace NHibernateTest { public class UInt32UserType : IUserType { // Public properties. public bool IsMutable { get { return false; } } public Type ReturnedType { get { return typeof(UInt32); } } public SqlType[] SqlTypes { get { return new SqlType[] { SqlTypeFactory.Int32 }; } } // Public methods. public object Assemble(object cached, object owner) { return cached; } public object DeepCopy(object value) { return value; } public object Disassemble(object value) { return value; } public new bool Equals(object x, object y) { return (x != null && x.Equals(y)); } public int GetHashCode(object x) { return x.GetHashCode(); } public object NullSafeGet(IDataReader rs, string[] names, object owner) { int? i = (int?)NHibernateUtil.Int32.NullSafeGet(rs, names[0]); return (UInt32?)i; } public void NullSafeSet(IDbCommand cmd, object value, int index) { UInt32? u = (UInt32?)value; int? i = (Int32?)u; NHibernateUtil.Int32.NullSafeSet(cmd, i, index); } public object Replace(object original, object target, object owner) { return original; } } }

    Read the article

  • How do I create/use a Fluent NHibernate convention to map UInt32 properties to an SQL Server 2008 da

    - by dommer
    I'm trying to use a convention to map UInt32 properties to a SQL Server 2008 database. I don't seem to be able to create a solution based on existing web sources, due to updates in the way Fluent NHibernate works - i.e. examples are out of date. Here's my code as it currently stands (which, when I try to expose the schema, fails due to SQL Server not supporting UInt32). Apologies for the code being a little long, but I'm not 100% sure what is relevant to the problem, so I'm erring on the side of caution. I think I'll need a relatively comprehensive example, as I don't seem to be able to pull the pieces together into a working solution, at present. FluentConfiguration configuration = Fluently.Configure() .Database(MsSqlConfiguration.MsSql2008 .ConnectionString(connectionString)) .Mappings(mapping => mapping.AutoMappings.Add( AutoMap.AssemblyOf<Product>() .Conventions.Add<UInt32UserTypeConvention>())); configuration.ExposeConfiguration(x => new SchemaExport(x).Create(false, true)); namespace NHibernateTest { public class UInt32UserTypeConvention : UserTypeConvention<UInt32UserType> { // Empty. } } namespace NHibernateTest { public class UInt32UserType : IUserType { // Public properties. public bool IsMutable { get { return false; } } public Type ReturnedType { get { return typeof(UInt32); } } public SqlType[] SqlTypes { get { return new SqlType[] { SqlTypeFactory.Int32 }; } } // Public methods. public object Assemble(object cached, object owner) { return cached; } public object DeepCopy(object value) { return value; } public object Disassemble(object value) { return value; } public new bool Equals(object x, object y) { return (x != null && x.Equals(y)); } public int GetHashCode(object x) { return x.GetHashCode(); } public object NullSafeGet(IDataReader rs, string[] names, object owner) { int? i = (int?)NHibernateUtil.Int32.NullSafeGet(rs, names[0]); return (UInt32?)i; } public void NullSafeSet(IDbCommand cmd, object value, int index) { UInt32? u = (UInt32?)value; int? i = (Int32?)u; NHibernateUtil.Int32.NullSafeSet(cmd, i, index); } public object Replace(object original, object target, object owner) { return original; } } }

    Read the article

  • Asyncronous While Loop?

    - by o7th Web Design
    I have a pretty great SqlDataReader wrapper in which I can map the output into a strongly typed list. What I am finding now is that on larger datasets with larger numbers of columns, performance could probably be a bit better if I can optimize my mapping. In thinking about this there is one section in particular that I am concerned about as it seems to be the heaviest hitter: while (_Rdr.Read()) { T newObject = new T(); for (int i = 0; i <= _Rdr.FieldCount - 1; ++i) { PropertyInfo info = (PropertyInfo)_ht[_Rdr.GetName(i).ToUpper()]; if ((info != null) && info.CanWrite) { info.SetValue(newObject, (_Rdr.GetValue(i) is DBNull) ? default(T) : _Rdr.GetValue(i), null); } } _en.Add(newObject); } _Rdr.Close(); What I would really like to know, is if there is a way that I can make this loop asyncronous? I feel that will make all the difference in the world with this beast :) Here is the entire Map method in case anyone can see where I can make further improvements on it... IList<T> Map<T> // Map our datareader object to a strongly typed list private static IList<T> Map<T>(IDataReader _Rdr) where T : new() { try { Type _t = typeof(T); List<T> _en = new List<T>(); Hashtable _ht = new Hashtable(); PropertyInfo[] _props = _t.GetProperties(); Parallel.ForEach(_props, info => { _ht[info.Name.ToUpper()] = info; }); while (_Rdr.Read()) { T newObject = new T(); for (int i = 0; i <= _Rdr.FieldCount - 1; ++i) { PropertyInfo info = (PropertyInfo)_ht[_Rdr.GetName(i).ToUpper()]; if ((info != null) && info.CanWrite) { info.SetValue(newObject, (_Rdr.GetValue(i) is DBNull) ? default(T) : _Rdr.GetValue(i), null); } } _en.Add(newObject); } _Rdr.Close(); return _en; }catch(Exception ex){ _Msg += "Wrapper.Map Exception: " + ex.Message; ErrorReporting.WriteEm.WriteItem(ex, "o7th.Class.Library.Data.Wrapper.Map", _Msg); return default(IList<T>); } }

    Read the article

  • CodePlex Daily Summary for Friday, February 19, 2010

    CodePlex Daily Summary for Friday, February 19, 2010New ProjectsApplication Management Library: Application Management makes your application life easier. It will automatic do memory management, handle and log unhandled exceptions, profiling y...Audio Service - Play Wave Files From Windows Service: This is a windows service that Check a registry key, when the key is updated with a new wave file path the service plays the wave file.Aviamodels: 3d drawing AviamodelsControl of payment proofs program for Greek citizens: This is a program that is used for Greek citizens who want to keep track of their payment proofs.Cover Creator: Cover Creator gives you the possibility to create and print CD covers. Content of CD is taken from http://www.freedb.org/ or can be added/modyfied ...DevBoard: DevBoard is a webbased scrum tool that helps developers/team get a clear overview of the project progress. It's developed in C# and silverlight.Flex AdventureWorks: The is mostly a skunk-works application to help me get acclimated to CodePlex. The long term goal is to integrate a Flex UI with the AdventureWor...GRE Wordlist: An intuitive and customizable word list for GRE aspirants. Developed in Java using a word list similar to Barron's.Indexer: A desktop file Index and Search tool which allows you to choose a list of folders to index, and then search on later. It is based on Lucene.net an...Project Management Office (PMO) for SharePoint: Sample web part for the Code Mastery event in Boston, February 11, 2010.Restart SQL Audit Policy and Job: Resolve SQL 2008 Audit Network Connectivity Issue.Rounded Corners / DIV Container: The RoundedDiv round corners container is a skin-able, CSS compliant UI control. Select which corners should be rounded, collapse and expand the c...Silverlight Google Search Application: The Silverlight Google Search Application uses Google Search API and behaves like Internet Search Application with option to preview desired page i...Weather Forecast Control: MyWeather forecast control pulls up to date weather forecast information from The Weather Channel for your website.New ReleasesApplication Management Library: ApplicationManagement v1.0: First ReleaseAudio Service - Play Wave Files From Windows Service: Audio Service v1.0: This is a working version of the Audio Service. Please use as you need to.AutoMapper: 1.0.1 for Silverlight 3.0 Alpha: AutoMapper for Silverlight 3.0. Features not supported: IDataReader mapping IListSource mapping All other features are supported.Buzz Dot Net: Buzz Dot Net v.1.10219: Buzz Dot Net Library (Parser & Objects) + WPF Example (using MVVM & Threading)Canvas VSDOC Intellisense: V 1.0.0.0a: This release contains two JavaScript files: canvas-utils.js (can be referenced in both runtime and development environment) canvas-vsdoc.js (must ...Control of payment proofs program for Greek citizens: Payment Proofs: source codeCourier: Beta 2: Added Rx Framework support and re-factored how message registration and un-registration works Blog post explaining the updates and re-factoring c...Cover Creator: Initial release: This is initial stable release. For now only in Polish language.Employee Scheduler: Employee Scheduler 2.2: Small Bug found. Small total hour calculation bug. See http://employeescheduler.codeplex.com/WorkItem/View.aspx?WorkItemId=6059 Extract the files...EnhSim: Release v1.9.7.1: Release v1.9.7.1Implemented Dislodged Foreign Object trinket Whispering Fanged Skull now also procs off Flame shock dots You can toggle bloodlust o...Extend SmallBasic: Teaching Extensions v.007: added SimpleSquareTest added Tortoise.Approve() for virtual proctor how to use virtual proctor: change the path in the proctor.txt file (located i...FolderSize: FolderSize.Win32.1.0.1.0: FolderSize.Win32.1.0.1.0 A simple utility intended to be used to scan harddrives for the folders that take most place and display this to the user...GLB Virtual Player Builder: v0.4.0 Beta: Allows for user to import and use archetypes for building players. The archetypes are contained in the file "archetypes.xml". This file is editab...Google Map WebPart from SharePoint List: GMap Stable Release: GMap Stable ReleaseHenge3D Physics Library for XNA: Henge3D Source (2010-02 R2): Fixed a build error related to an assembly attribute in XBOX 360 builds. Tweaked the controls in the sample when targeting the 360. Reduced the...Indexer: Beta Release 1: Just the initial/rough cut.NukeCS: NukeCS 5.2.3 Source Code: update version to 5.2.3ODOS: ODOS STABLE 1.5.0: Thank you for your patience while we develop this version. Not that much has been added, though. Just doing some sub-conscious stuff to make life...PoshBoard: PoshBoard 3.0 Beta 1: Welcome to the first beta release of PoshBoard 3.0 ! IMPORTANT WARNING : this release is absolutly not feature complete and is error-prone. Okay, ...Restart SQL Audit Policy and Job: Restart SQL 2008 Audit Policy and Job: This folder contains three pieces of source code: Server Audit Status (Started).xml - Import this on-schedule policy into your server's Policy-Ba...SAL- Self Artificial Learning: Artificial Learning 2AQV Working Proof Of Concept: This is the Simulation proof of concept version that comes after the 1aq version. AQ stands for Anwering Questions.SharePoint 2010 Word Automation: SP 2010 Word Automation - Workflow Actions 1.1: This release includes two new custom workflow activities for SharePoint designer Convert Folder Convert Library More information about these new...SharePoint Outlook Connector: Version 1.0.1.1: Exception Logging has been improved.Sharpy: Sharpy 1.2 Alpha: This is the third Sharpy release. A change has been made to allow overriding the master page from the controller. The release contains the single ...Silverlight Google Search Application: SL Google Search App Alpha: This is just a first alpha version of the application, as it looks like when I uploaded it to CodePlex. The application works, requires Silverlight...Starter Kit Mytrip.Mvc.Entity: Mytrip.Mvc.Entity 1.0 RC: EF Membership UserManager FileManager Localization Captcha ClientValidation Theme CrossBrowser VS 2010 RC MVC 2 RC db MSSQL2008thinktecture WSCF.blue: WSCF.blue V1 Update (1.0.6): This release is an update for WSCF.blue V1. Below are the bug fixes made since the V1.0.5 release: The data contract type filter was not including...TS3QueryLib.Net: TS3QueryLib.Net Version 0.18.13.0: Changelog Added overloads to all methods of QueryRunenr class handling permission tasks to allow passing of permission name instead of permissionid...Umbraco CMS: Umbraco 4.1 Beta 2: This is the second beta of Umbraco 4.1. Umbraco 4.1 is more advanced than ever, yet faster, lighter and simpler to use than ever. We, on behalf of...VCC: Latest build, v2.1.30218.0: Automatic drop of latest buildZack's Fiasco - Code Generated DAL: v1.2.4: Enhancements: SQL Server CRUD Stored Procedures added option for USE <db> added option to create or not create INSERT sprocs added option to cr...Most Popular ProjectsRawrWBFS ManagerAJAX Control ToolkitMicrosoft SQL Server Product Samples: DatabaseSilverlight ToolkitWindows Presentation Foundation (WPF)Image Resizer Powertoy Clone for WindowsASP.NETMicrosoft SQL Server Community & SamplesDotNetNuke® Community EditionMost Active ProjectsRawrSharpyDinnerNow.netBlogEngine.NETjQuery Library for SharePoint Web ServicesNB_Store - Free DotNetNuke Ecommerce Catalog Modulepatterns & practices – Enterprise LibraryPHPExcelFacebook Developer ToolkitFluent Ribbon Control Suite

    Read the article

  • C#/.NET Little Pitfalls: The Dangers of Casting Boxed Values

    - by James Michael Hare
    Starting a new series to parallel the Little Wonders series.  In this series, I will examine some of the small pitfalls that can occasionally trip up developers. Introduction: Of Casts and Conversions What happens when we try to assign from an int and a double and vice-versa? 1: double pi = 3.14; 2: int theAnswer = 42; 3:  4: // implicit widening conversion, compiles! 5: double doubleAnswer = theAnswer; 6:  7: // implicit narrowing conversion, compiler error! 8: int intPi = pi; As you can see from the comments above, a conversion from a value type where there is no potential data loss is can be done with an implicit conversion.  However, when converting from one value type to another may result in a loss of data, you must make the conversion explicit so the compiler knows you accept this risk.  That is why the conversion from double to int will not compile with an implicit conversion, we can make the conversion explicit by adding a cast: 1: // explicit narrowing conversion using a cast, compiler 2: // succeeds, but results may have data loss: 3: int intPi = (int)pi; So for value types, the conversions (implicit and explicit) both convert the original value to a new value of the given type.  With widening and narrowing references, however, this is not the case.  Converting reference types is a bit different from converting value types.  First of all when you perform a widening or narrowing you don’t really convert the instance of the object, you just convert the reference itself to the wider or narrower reference type, but both the original and new reference type both refer back to the same object. Secondly, widening and narrowing for reference types refers the going down and up the class hierarchy instead of referring to precision as in value types.  That is, a narrowing conversion for a reference type means you are going down the class hierarchy (for example from Shape to Square) whereas a widening conversion means you are going up the class hierarchy (from Square to Shape).  1: var square = new Square(); 2:  3: // implicitly convers because all squares are shapes 4: // (that is, all subclasses can be referenced by a superclass reference) 5: Shape myShape = square; 6:  7: // implicit conversion not possible, not all shapes are squares! 8: // (that is, not all superclasses can be referenced by a subclass reference) 9: Square mySquare = (Square) myShape; So we had to cast the Shape back to Square because at that point the compiler has no way of knowing until runtime whether the Shape in question is truly a Square.  But, because the compiler knows that it’s possible for a Shape to be a Square, it will compile.  However, if the object referenced by myShape is not truly a Square at runtime, you will get an invalid cast exception. Of course, there are other forms of conversions as well such as user-specified conversions and helper class conversions which are beyond the scope of this post.  The main thing we want to focus on is this seemingly innocuous casting method of widening and narrowing conversions that we come to depend on every day and, in some cases, can bite us if we don’t fully understand what is going on!  The Pitfall: Conversions on Boxed Value Types Can Fail What if you saw the following code and – knowing nothing else – you were asked if it was legal or not, what would you think: 1: // assuming x is defined above this and this 2: // assignment is syntactically legal. 3: x = 3.14; 4:  5: // convert 3.14 to int. 6: int truncated = (int)x; You may think that since x is obviously a double (can’t be a float) because 3.14 is a double literal, but this is inaccurate.  Our x could also be dynamic and this would work as well, or there could be user-defined conversions in play.  But there is another, even simpler option that can often bite us: what if x is object? 1: object x; 2:  3: x = 3.14; 4:  5: int truncated = (int) x; On the surface, this seems fine.  We have a double and we place it into an object which can be done implicitly through boxing (no cast) because all types inherit from object.  Then we cast it to int.  This theoretically should be possible because we know we can explicitly convert a double to an int through a conversion process which involves truncation. But here’s the pitfall: when casting an object to another type, we are casting a reference type, not a value type!  This means that it will attempt to see at runtime if the value boxed and referred to by x is of type int or derived from type int.  Since it obviously isn’t (it’s a double after all) we get an invalid cast exception! Now, you may say this looks awfully contrived, but in truth we can run into this a lot if we’re not careful.  Consider using an IDataReader to read from a database, and then attempting to select a result row of a particular column type: 1: using (var connection = new SqlConnection("some connection string")) 2: using (var command = new SqlCommand("select * from employee", connection)) 3: using (var reader = command.ExecuteReader()) 4: { 5: while (reader.Read()) 6: { 7: // if the salary is not an int32 in the SQL database, this is an error! 8: // doesn't matter if short, long, double, float, reader [] returns object! 9: total += (int) reader["annual_salary"]; 10: } 11: } Notice that since the reader indexer returns object, if we attempt to convert using a cast to a type, we have to make darn sure we use the true, actual type or this will fail!  If the SQL database column is a double, float, short, etc this will fail at runtime with an invalid cast exception because it attempts to convert the object reference! So, how do you get around this?  There are two ways, you could first cast the object to its actual type (double), and then do a narrowing cast to on the value to int.  Or you could use a helper class like Convert which analyzes the actual run-time type and will perform a conversion as long as the type implements IConvertible. 1: object x; 2:  3: x = 3.14; 4:  5: // if you want to cast, must cast out of object to double, then 6: // cast convert. 7: int truncated = (int)(double) x; 8:  9: // or you can call a helper class like Convert which examines runtime 10: // type of the value being converted 11: int anotherTruncated = Convert.ToInt32(x); Summary You should always be careful when performing a conversion cast from values boxed in object that you are actually casting to the true type (or a sub-type). Since casting from object is a widening of the reference, be careful that you either know the exact, explicit type you expect to be held in the object, or instead avoid the cast and use a helper class to perform a safe conversion to the type you desire. Technorati Tags: C#,.NET,Pitfalls,Little Pitfalls,BlackRabbitCoder

    Read the article

  • Dynamically creating a Generic Type at Runtime

    - by Rick Strahl
    I learned something new today. Not uncommon, but it's a core .NET runtime feature I simply did not know although I know I've run into this issue a few times and worked around it in other ways. Today there was no working around it and a few folks on Twitter pointed me in the right direction. The question I ran into is: How do I create a type instance of a generic type when I have dynamically acquired the type at runtime? Yup it's not something that you do everyday, but when you're writing code that parses objects dynamically at runtime it comes up from time to time. In my case it's in the bowels of a custom JSON parser. After some thought triggered by a comment today I realized it would be fairly easy to implement two-way Dictionary parsing for most concrete dictionary types. I could use a custom Dictionary serialization format that serializes as an array of key/value objects. Basically I can use a custom type (that matches the JSON signature) to hold my parsed dictionary data and then add it to the actual dictionary when parsing is complete. Generic Types at Runtime One issue that came up in the process was how to figure out what type the Dictionary<K,V> generic parameters take. Reflection actually makes it fairly easy to figure out generic types at runtime with code like this: if (arrayType.GetInterface("IDictionary") != null) { if (arrayType.IsGenericType) { var keyType = arrayType.GetGenericArguments()[0]; var valueType = arrayType.GetGenericArguments()[1]; … } } The GetArrayType method gets passed a type instance that is the array or array-like object that is rendered in JSON as an array (which includes IList, IDictionary, IDataReader and a few others). In my case the type passed would be something like Dictionary<string, CustomerEntity>. So I know what the parent container class type is. Based on the the container type using it's then possible to use GetGenericTypeArguments() to retrieve all the generic types in sequential order of definition (ie. string, CustomerEntity). That's the easy part. Creating a Generic Type and Providing Generic Parameters at RunTime The next problem is how do I get a concrete type instance for the generic type? I know what the type name and I have a type instance is but it's generic, so how do I get a type reference to keyvaluepair<K,V> that is specific to the keyType and valueType above? Here are a couple of things that come to mind but that don't work (and yes I tried that unsuccessfully first): Type elementType = typeof(keyvalue<keyType, valueType>); Type elementType = typeof(keyvalue<typeof(keyType), typeof(valueType)>); The problem is that this explicit syntax expects a type literal not some dynamic runtime value, so both of the above won't even compile. I turns out the way to create a generic type at runtime is using a fancy bit of syntax that until today I was completely unaware of: Type elementType = typeof(keyvalue<,>).MakeGenericType(keyType, valueType); The key is the type(keyvalue<,>) bit which looks weird at best. It works however and produces a non-generic type reference. You can see the difference between the full generic type and the non-typed (?) generic type in the debugger: The nonGenericType doesn't show any type specialization, while the elementType type shows the string, CustomerEntity (truncated above) in the type name. Once the full type reference exists (elementType) it's then easy to create an instance. In my case the parser parses through the JSON and when it completes parsing the value/object it creates a new keyvalue<T,V> instance. Now that I know the element type that's pretty trivial with: // Objects start out null until we find the opening tag resultObject = Activator.CreateInstance(elementType); Here the result object is picked up by the JSON array parser which creates an instance of the child object (keyvalue<K,V>) and then parses and assigns values from the JSON document using the types  key/value property signature. Internally the parser then takes each individually parsed item and adds it to a list of  List<keyvalue<K,V>> items. Parsing through a Generic type when you only have Runtime Type Information When parsing of the JSON array is done, the List needs to be turned into a defacto Dictionary<K,V>. This should be easy since I know that I'm dealing with an IDictionary, and I know the generic types for the key and value. The problem is again though that this needs to happen at runtime which would mean using several Convert.ChangeType() calls in the code to dynamically cast at runtime. Yuk. In the end I decided the easier and probably only slightly slower way to do this is a to use the dynamic type to collect the items and assign them to avoid all the dynamic casting madness: else if (IsIDictionary) { IDictionary dict = Activator.CreateInstance(arrayType) as IDictionary; foreach (dynamic item in items) { dict.Add(item.key, item.value); } return dict; } This code creates an instance of the generic dictionary type first, then loops through all of my custom keyvalue<K,V> items and assigns them to the actual dictionary. By using Dynamic here I can side step all the explicit type conversions that would be required in the three highlighted areas (not to mention that this nested method doesn't have access to the dictionary item generic types here). Static <- -> Dynamic Dynamic casting in a static language like C# is a bitch to say the least. This is one of the few times when I've cursed static typing and the arcane syntax that's required to coax types into the right format. It works but it's pretty nasty code. If it weren't for dynamic that last bit of code would have been a pretty ugly as well with a bunch of Convert.ChangeType() calls to litter the code. Fortunately this type of type convulsion is rather rare and reserved for system level code. It's not every day that you create a string to object parser after all :-)© Rick Strahl, West Wind Technologies, 2005-2011Posted in .NET  CSharp   Tweet (function() { var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true; po.src = 'https://apis.google.com/js/plusone.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s); })();

    Read the article

  • Page_load event firing twice. User control not properly loading

    - by Phil
    Here is the code I am using to pull my usercontrol (content.ascx): Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load 'load module If TheModule = "content" Then Dim control As UserControl = LoadControl("~\Modules\Content.ascx") Controls.Add(control) End If End Sub Within the usercontrol is the following code (data access taken care of by DAAB and ive replaced sql statements with 'sql'): Imports System.Data.SqlClient Imports System.Data Imports System.Web.Configuration Imports Microsoft.Practices.EnterpriseLibrary.Common Imports Microsoft.Practices.EnterpriseLibrary.Data Partial Class Modules_WebUserControl Inherits System.Web.UI.UserControl Dim db As Database = DatabaseFactory.CreateDatabase() Dim command As SqlCommand 'database Dim reader As IDataReader 'general vars Dim pageid As Integer Dim did As Integer Dim contentid As Integer Dim dotpos As String Dim ext As String Dim content As String Dim folder As String Dim downloadstring As String Function getimage(ByVal strin As String) As String If strin > "" Then dotpos = InStrRev(strin, ".") ext = Right(strin, Len(strin) - dotpos) getimage = ext & ".gif" Else getimage = String.Empty End If Return getimage End Function Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load, Me.Load 'test Response.Write("(1 Test from within page_load)") 'get session vars folder = Session("folder") pageid = Session("pageid") did = Session("did") 'main content command = db.GetSqlStringCommand("sql") db.AddInParameter(command, "@pageid", DbType.Int32, pageid) reader = db.ExecuteReader(command) While reader.Read If reader("content") IsNot DBNull.Value Then content = Replace(reader("content"), Chr(38) + Chr(97) + Chr(109) + Chr(112) + Chr(59) + Chr(98) + Chr(104) + Chr(99) + Chr(112) + Chr(61) + Chr(49), "") If reader("id") IsNot DBNull.Value Then contentid = reader("id") End If Else contentid = -1 content = String.Empty End If End While Outputcontent.Text = content 'contacts info If did = 0 Then command = db.GetSqlStringCommand("sql") db.AddInParameter(command, "@contentid", DbType.Int32, contentid) reader = db.ExecuteReader(command) While reader.Read() Contactinforepeater.DataSource = reader Contactinforepeater.DataBind() End While End If If Not did = 0 Then command = (db.GetSqlStringCommand("sql") db.AddInParameter(command, "@contentid", DbType.Int32, contentid) db.AddInParameter(command, "@did", DbType.Int32, did) reader = db.ExecuteReader(command) While reader.Read Contactinforepeater.DataSource = reader Contactinforepeater.DataBind() End While End If 'downloads box command = db.GetSqlStringCommand("sql") db.AddInParameter(command, "@contentid", DbType.Int32, contentid) reader = db.ExecuteReader(command) While reader.Read If reader("filename") IsNot DBNull.Value Then downloadstring += "<a href='/documents/" & folder & "/" & reader("filename") & "'>" downloadstring += "<img src=images/" & getimage(reader("filename")) & " border=0 align=absmiddle />" End If If reader("filesize") IsNot DBNull.Value Then downloadstring += Convert.ToInt32((reader("filesize") / 1000)) & "kb - " End If If reader("filename") IsNot DBNull.Value Then downloadstring += "<a href='/documents/" & Session("folder") & "/" & reader("filename") & "'>" & reader("description") & "</a><br />" End If End While Dim downloadsarray As ArrayList downloadsarray = New ArrayList If downloadstring IsNot Nothing Then downloadsarray.Add(downloadstring) End If If downloadsarray.Count > 0 Then DownloadsRepeater.DataSource = downloadsarray DownloadsRepeater.DataBind() End If 'get links command = db.GetSqlStringCommand("sql") db.AddInParameter(command, "@contentid", DbType.Int32, contentid) reader = db.ExecuteReader(command) While reader.Read Linksrepeater.DataSource = reader Linksrepeater.DataBind() End While End Sub End Class Now instead of seeing my page content and what should be within the repeaters on the page all I get is 2 x the output of Response.Write("(1 Test from within page_load)") (1 Test from within page_load)(1 Test from within page_load) This leads me to believe the page_load is firing twice, but not properly displaying all the information. Please can one of you willing experts help me to get this working? Thanks a lot in advance

    Read the article

  • Thread locking issue with FileHelpers between calling engine.ReadNext() method and readign engine.Li

    - by Rad
    I use producer/consumer pattern with FileHelpers library to import data from one file (which can be huge) using multiple threads. Each thread is supposed to import a chunk of that file and I would like to use LineNumber property of the FileHelperAsyncEngine instance that is reading the file as primary key for imported rows. FileHelperAsyncEngine internally has an IEnumerator IEnumerable.GetEnumerator(); which is iterated over using engine.ReadNext() method. That internally sets LineNumber property (which seems is not thread safe). Consumers will have Producers assiciated with them that will supply DataTables to Consumers which will consume them via SqlBulkLoad class which will use IDataReader implementation which will iterate over a collection of DataTables which are internal to a Consumer instance. Each instance of will have one SqlBulkCopy instance associate with it. I have thread locking issue. Below is how I create multiple Producer threads. I start each thread afterwords. Produce method on a producer instance will be called determining which chunk of input file will be processed. It seems that engine.LineNumber is not thread safe and I doesn't import a proper LineNumber in the database. It seems that by the time engine.LineNumber is read some other thread called engine.ReadNext() and changed engine.LineNumber property. I don't want to lock the loop that is supposed to process a chunk of input file because I loose parallelism. How to reorganize the code to solve this threading issue? Thanks Rad for (int i = 0; i < numberOfProducerThreads; i++) DataConsumer consumer = dataConsumers[i]; //create a new producer DataProducer producer = new DataProducer(); //consumer has already being created consumer.Subscribe(producer); FileHelperAsyncEngine orderDetailEngine = new FileHelperAsyncEngine(recordType); orderDetailEngine.Options.RecordCondition.Condition = RecordCondition.ExcludeIfBegins; orderDetailEngine.Options.RecordCondition.Selector = STR_ORDR; int skipLines = i * numberOfBufferTablesToProcess * DataBuffer.MaxBufferRowCount; Thread newThread = new Thread(() => { producer.Produce(consumer, inputFilePath, lineNumberFieldName, dict, orderDetailEngine, skipLines, numberOfBufferTablesToProcess); consumer.SetEndOfData(producer); }); producerThreads.Add(newThread); thread.Start();} public void Produce(DataConsumer consumer, string inputFilePath, string lineNumberFieldName, Dictionary<string, object> dict, FileHelperAsyncEngine engine, int skipLines, int numberOfBufferTablesToProcess) { lock (this) { engine.Options.IgnoreFirstLines = skipLines; engine.BeginReadFile(inputFilePath); } int rowCount = 1; DataTable buffer = consumer.BufferDataTable; while (engine.ReadNext() != null) { lock (this) { dict[lineNumberFieldName] = engine.LineNumber; buffer.Rows.Add(ObjectFieldsDataRowMapper.MapObjectFieldsToDataRow(engine.LastRecord, dict, buffer)); if (rowCount % DataBuffer.MaxBufferRowCount == 0) { consumer.AddBufferDataTable(buffer); buffer = consumer.BufferDataTable; } if (rowCount % (numberOfBufferTablesToProcess * DataBuffer.MaxBufferRowCount) == 0) { break; } rowCount++; } } if (buffer.Rows.Count > 0) { consumer.AddBufferDataTable(buffer); } engine.Close(); }

    Read the article

  • CodePlex Daily Summary for Monday, March 08, 2010

    CodePlex Daily Summary for Monday, March 08, 2010New Projects38fj4ncg2: 38fj4ncg2Ac#or: A actor framework written in Mono (C#) Make it easy to make multithreaded programs with the actor model.Aerial Phone Book: It's a ASP app that allow more of one user see a contacts on phone book and add new contacts. This way a group of users can maintain a common phon...AmiBroker Plug-Ins with C#: Plug-ins for AmiBroker built with Microsoft .NET Framework and C#.AxUnit: AxUnit is a Unit Testing framework for Microsoft Dynamics Ax (X++). It's an extension to the SysTest framework provided with DAX4.0 and newer versi...Botola PHP Class: Une class en PHP qui vous permet d'avoir les informations qui concernent les équipes de le championnat Marocain du football.Code examples, utilities and misc from Lars Wilhelmsen [MVP]: Misc. stuff from Lars Wilhelmsen.Codename T: Codename T is in the very basic stages of development. It should be ready for beta testing by the start of April.ComBrowser: combrowserCompact Unity: The Compact Unity is a lightweight dependency injection container with support for constructor and property call injection written in .NET Compact ...FAST for Sharepoint MOSS 2010 Query Tool: Tool to query FAST for Sharepoint and Sharepoint 2010 Enterprise Search. It utilizes the search web services to run your queries so you can test y...Icarus Scene Engine: Icarus Scene Engine is a cross-platform 3D eLearning, games and simulation engine, integrating open source APIs into a cohesive cross-platform solu...jQuery.cssLess: jQuery plugin that interprets and loads LESS css files. (http://lesscss.org).Katara Dental Phase II: Second phase of Kdpl.Lunar Phase Silverlight Gadget: Meet the moon phase, percent of illumination and corresponding zodiac sign from your desktop. Reflection Studio: Reflection Studio is a development tool that encapsulate all my work around reflection, performance and WPF. It allows to inject performance traces...RSNetty: RSNetty is a RuneScape Private Server programmed in the Java programming language.Simple WMV/ASF files muxer/demuxer: Simple WMV files muxer/demuxer implemented in C#/C++. It has simple WPF-based UI and allows copy/replace operations on video, audio and script stre...sm: managerTFS Proxy Monitor: TFS Proxy Monitor. A winform application allow administrator can monitor the TFS Server Proxy statistics remotely.umbracoSamplePackageCreator (beta): This is an early version of a simple package creator for Umbraco as a Visual Studio project. Currently with an Xslt extension and a user control. O...WatchersNET.TagCloud: 3D Flash TagCloud Module for DotNetNukeWriterous: A Plug-in For Windows Live Writer: This plug-in for Live Writer allows the user to create their post in Live Writer and then publish to Posterous.comNew Releases.NET Extensions - Extension Methods Library: Release 2010.05: Added a common set of extension methods for IDataReader, DataRow and DataRowView to access field values in a type safe manner using type dedicated ...AmiBroker Plug-Ins with C#: AmiBroker Plug-Ins v0.0.1: This is just a demo plug-in which shows how you can write plug-ins for AmiBroker with fully managed code.AxUnit: Version 1: AxUnit let's you write Unit Test assertions in Dynamics Ax like this: assert.that(2, is.equalTo2)); Installation instructions (Microsoft Dynamics ...BattLineSvc: V2: - Fixed bug where sometimes the line would not show up, even with the 90 second boot-up delay. This was due to the window being created too early ...Botola PHP Class: Botola API: la classe PHPBugTracker.NET: BugTracker.NET 3.4.0: In screen capture app, "Go to website" now goes to the bug you just created. In screen capture app, fixed where the crosshairs weren't always to...Bulk Project Delete: Version 1.1.1: A minor fix to 1.1: fixes a problem that indicated some projects were not found on the server when they were in fact found. This problem only exist...C# Linear Hash Table: Linear Hash Table b3: Remove functionality added. Now IDictionary Compliant, but most functions not yet tested.Code examples, utilities and misc from Lars Wilhelmsen [MVP]: LarsW.MexEdmxFixer 1.0: A quick hack to fix the Edmx files output by mex.exe (a tool in the SQL Modeling suite - November 2009 CTP) so that they can be opened in the desig...Code Snippet With Syntaxhighlighter Support for Windows Live Writer: Version 5.0.2: Minor update. Added brushes for F#, PowerShell and Erlang. Now a Windows Presentation Framework (WPF) application. ComponentFactory.Krypton.Toolki...Compact Unity: Compact Unity 1.0: Release.Compact Unity: CompactUnity 1.0: Release.FAST for Sharepoint MOSS 2010 Query Tool: Version 0.9: The tool is fully functioning. All of the cases for exceptions may not have been caught yet. I wanted to release a version to allow people to use...Fluent Ribbon Control Suite: Fluent Ribbon Control Suite RC (for .NET 4.0 RC): Build for .NET 4.0 RC. Includes Fluent.dll (with .pdb and .xml) and test application compiled with .NET 4.0 RC. BEAWARE! Fluent for .NET 4.0 RC is...FluentNHibernate.Search: 0.2 Beta: 0.2 Beta Fixed : #7275 - Field Mapping without specifying "Name" Fixed : #7271 - StackOverFlow Exception while Configure Embedded Mappings Fixed :...InfoService: InfoService v1.5 Beta 9: InfoService Beta Release Please note this is a BETA. It should be stable, but i can't guarantee that! So use it on your own risk. Please read Plug...jQuery.cssLess: jQuery.cssLess 0.2: Version supports variables, mixins and nested rules. TODO: lower scope variables and mixins should not delete higher scope variables and mixins ...Lunar Phase Silverlight Gadget: Lunar Phase: First public beta for Lunar Phase Silverlight Gadget. It's a stable release but it hasn't auto update state. That will come with the final release ...MapWindow GIS: MapWindow 6.0 msi (March 7): This is an update that fixes a number of problems with the multi-point features, the M and Z features as well as enabling multi-part creation using...Mews: Mews.Application V0.7: Installation InstuctionsNew Features15390 15085 Fixed Issues16173 16552. This happens when the database maintenance process kicks in during sta...sELedit: sELedit v1.0a: Added: Basic exception handlers (load/save/export) Added: List 57 support (no search and replace) Added: MYEN 1.3.1 Client ->CN 1.3.6 Server export...Sem.Sync: 2010-03-07 - End user client for Xing to Outlook: This client does include the binaries for syncing Xing contacts to Microsoft Outlook. It does contain only the binaries to sync from Xing to Outloo...Sem.Sync: 2010-03-07 - Synchronization Manager: This client does provide a more advanced (and more complex) GUI that allows you to select from two included templates (you can add your own, too) a...SharePoint Outlook Connector: Source Code for Version 1.2.3.2: Source Code for Version 1.2.3.2SharePoint Video Player Web Part & SharePoint Video Library: Version 2.0.0: Release Notes: New The new SharePoint Video Player release includes a SharePoint video template to create your own video library Changes The Shar...SilverSprite: SilverSprite 3.0 Alpha 2: These are the latest binaries for SilverSprite. The major changes for this release are that we are now using the XNA namespaces (no more #Iif SILVE...Simple WMV/ASF files muxer/demuxer: Initial release: Initial releaseStarter Master Pages for SharePoint 2010: Starter Master Pages for SP2010 - RC: Release Candidate release of Starter Master Pages for SharePoint 2010 by Randy Drisgill http://blog.drisgill.com _starter.master - Starter Master ...Text Designer Outline Text Library: 11th minor release: New Feature : Reflection!!ToolSuite.ValidationExpression: 01.00.01.002: second release of the validation class; the assembly file is ready to use, the documentation is complete;Truecrafting: Truecrafting 0.51: overhauled truecrafting code: combined all engines into 1 mage engine, made the engine and artificial intelligence support any spec, and achieved a...WatchersNET.TagCloud: WatchersNET.TagCloud 01.00.00: First ReleaseWCF Contrib: WCF Contrib v2.1 Mar07: This release is the final version of v2.1 Beta that was published on February 10th. Below you will find the changes that were made: Changes from v...WillStrohl.LightboxGallery Module for DotNetNuke: WillStrohl.LightboxGallery v1.02.00: This version of the Lightbox Gallery Module adds the following features: New Lightbox provider: Fancybox Thumbnails generated keeping their aspec...Writerous: A Plug-in For Windows Live Writer: Writerous v1.0: This is the first release of Writerous.WSDLGenerator: WSDLGenerator 0.0.0.5: - Use updated CommandLineParser.dll - Code uses 'ServiceDescriptionReflector' instead of custom code. - Added option to support SharePoint 2007 com...Xpress - ASP.NET MVC 个人博客程序: xpress2.1.0.beta.bin: 原 DsJian1.0的升级版本,名字修改为 xpress 此正式版本YSCommander: Version 1.0.1.0: Fixed bug: 1st start with non-existing data file.Most Popular ProjectsMetaSharpWBFS ManagerRawrAJAX Control ToolkitMicrosoft SQL Server Product Samples: DatabaseSilverlight ToolkitWindows Presentation Foundation (WPF)ASP.NETMicrosoft SQL Server Community & SamplesImage Resizer Powertoy Clone for WindowsMost Active ProjectsUmbraco CMSRawrSDS: Scientific DataSet library and toolsBlogEngine.NETjQuery Library for SharePoint Web Servicespatterns & practices – Enterprise LibraryIonics Isapi Rewrite FilterFarseer Physics EngineFluent AssertionsFasterflect - A Fast and Simple Reflection API

    Read the article

< Previous Page | 1 2