Recent Entries 7
- pattern minor 112d agoRead characters slowly (Threading with delay, .NET Framework 2.0)Couple of months ago I was asked to develop a console app to do the following: Write an application that takes an array of ICharacterReader interfaces, accesses them in parallel, and outputs a list of word frequencies ordered by word count and then alphabetically, every 10 seconds. For example, if the stream returns: "It was the best of times, it was the worst of times" then the output will be: it - 2 of - 2 the – 2 times - 2 was - 2 best - 1 worst – 1 The sample project was targeting `.NET Framework 2.0` so I had no access to Linq, Task, async-await, etc. And `ICharacterReader` interface and `SlowCharacterReader` class had to be kept as is. The thing is, I got no feedback related with the code quality afterwards. And going through the archive, I wonder what could have been improved. Can you review the code and let me know in which ways I could possibly improve it? ``` using System; using System.IO; using System.Collections.Generic; using System.Text; using System.Threading; namespace SlowCharacterReader { public interface ICharacterReader : IDisposable { char GetNextChar(); } public class SlowCharacterReader : ICharacterReader { private int m_Pos = 0; private string m_Content = @" Alice was beginning to get very tired of sitting by her sister on the bank, and of having nothing to do: once or twice she had peeped into the book her sister was reading, but it had no pictures or conversations in it, 'and what is the use of a book,' thought Alice `without pictures or conversation?' So she was considering in her own mind (as well as she could, for the hot day made her feel very sleepy and stupid), whether the pleasure of making a daisy-chain would be worth the trouble of getting up and picking the daisies, when suddenly a White Rabbit with pink eyes ran close by her."; Random m_Rnd = new Random(); public char GetNextChar() { System.T
- pattern minor 112d agoReturn a paged DataTableIs there a better way to do it and have it be .Net 2.0 compatible? ``` public static DataTable GetErrorLog(int startRowIndex, int maximumRows, string sortExpression, string logPath) { if (string.IsNullOrEmpty(sortExpression)) { sortExpression = "fileName DESC"; } DataTable errorLog = GetErrorLogDataTable(); string[] filePaths = Directory.GetFiles(logPath); foreach (string filePath in filePaths) { DataRow row = errorLog.NewRow(); row["fileName"] = Path.GetFileName(filePath); row["filePath"] = filePath; errorLog.Rows.Add(row); } DataView dataView = new DataView(errorLog); dataView.Sort = sortExpression; errorLog = dataView.ToTable(); DataTable pagedErrorLog = errorLog.Clone(); for (int i = startRowIndex; i = errorLog.Rows.Count) { break; } pagedErrorLog.ImportRow(errorLog.Rows[i]); } if (pagedErrorLog.Rows.Count <= 0) { return errorLog; } else { return pagedErrorLog; } } private static DataTable GetErrorLogDataTable() { DataTable dataTable = new DataTable(); dataTable.Columns.Add("fileName"); dataTable.Columns.Add("filePath"); return dataTable; } ```
- pattern minor 112d agoCentral Database classI have this web site I inherited as part of my job and it has some old code. I'd like to optimize it, but I don't really have the time to do it right, so I'm looking for some "low hanging fruit" to optimize. Basically I want minimal change with the greatest performance improvement. One of the things I've come across is an old static method used to grab data from a remote database: ``` public static IDataReader GetRS(string sql, string connString) { SqlConnection dbconn = new SqlConnection(); if (connString.ToLower().Trim() == "shop") dbconn.ConnectionString = ConfigurationManager.ConnectionStrings["Shop.DbConnection"].ConnectionString; else dbconn.ConnectionString = connString; dbconn.Open(); SqlCommand cmd = new SqlCommand(sql, dbconn); return cmd.ExecuteReader(CommandBehavior.CloseConnection); } ``` I think this code is contributing to a high number of `NumberOfReclaimedConnections` we are seeing on the servers due to the calling code not cleaning up properly. If I rewrite the above method like the one below, will it help make things more efficient without having to rewrite all the hundreds of instances of calling code? ``` public static IDataReader GetRS(string sql, string connString) { IDataReader ans = null; using (DataTable tbl = new DataTable()) { using (SqlConnection dbconn = new SqlConnection()) { if (connString.ToLower().Trim() == "shop") dbconn.ConnectionString = ConfigurationManager.ConnectionStrings["Shop.DbConnection"].ConnectionString; else dbconn.ConnectionString = connString; using (SqlCommand cmd = new SqlCommand(sql, dbconn)) { using (SqlDataAdapter adapter = new SqlDataAdapter(cmd)) { adapter.Fill(tbl); } } } if (tbl.Rows.Count > 0) { ans = tbl.CreateDataReader(); } } return ans; } ``` I'm pretty sur
- pattern minor 112d agoValidating the value of a property of an objectThis code snippet is intended for validating the value of a property of an object. The min and max range is supplied as an .xml file like Nhibernate .hbm files. Since the data-type of the property is also read from the .xml file, we can only know the type of the property at run-time. Is there any better way of improving the code in C# and .NET 2.0? ``` public static void ValidateMinMax(Property prop, Object value) { Type type = Type.GetType(prop.TypeName); Object minValue = PropertyDataExtractor.GetMinValue(prop); Object maxValue = PropertyDataExtractor.GetMaxValue(prop); Object actualVaue = null; bool minValueOk = false; bool maxValueOk = false; if (minValue != null) { switch (type.Name) { case "Boolean": break; case "SByte": actualVaue = Convert.ToSByte(value); if (actualVaue != null) { minValueOk = ((sbyte)minValue) = ((sbyte)actualVaue); } else { maxValue = true; } break; case "Byte": actualVaue = Convert.ToByte(value); if (actualVaue != null) { maxValueOk = ((byte)minValue) >= ((byte)actualVaue); } else { maxValue = true; } break; case "Byte[]": break; case "DateTime": actualVaue = Convert.ToDateTime(value); if (actualVaue != null) { maxValueOk = ((DateTime)maxValue).Date >= ((DateTime)actualVaue).Date; }
- pattern minor 112d agoRepository Pattern ReviewI have following code for a library management system. - Is the following code a proper implementation of the Repository Pattern? - How can I adapt this code to use generics? - Should I let `MyOracleReservationRepository` and `MyOracleBookRepository` be `DataContracts` if I am consuming this code as a WCF service (business Layer will be called by service layer)? Business Layer ``` namespace LibraryBL { public class ReservationManager { //LibraryDAL.ReservationDAL resDAL = new LibraryDAL.ReservationDAL(); //LibraryDAL.BookDAL bookDAL = new LibraryDAL.BookDAL(); LibraryRepository.IReservationRepository reservationRepository; LibraryRepository.IBookRepository bookRepository; public ReservationManager(LibraryRepository.IReservationRepository resRepositroy, LibraryRepository.IBookRepository bookRepositroy) { reservationRepository = resRepositroy; bookRepository = bookRepositroy; } public List GetAllReservations() { List allReservations = reservationRepository.GetAllReservations(); //Book object inside allReservations has two values as NULL (author and BookTitile). //These values need to be set using foreach loop foreach (LibraryDTO.Reservation reservation in allReservations) { int bookID =reservation.ReservedBook.BookID; LibraryDTO.Book book = bookRepository.GetBookByID(bookID); reservation.ReservedBook = book; } return allReservations; } } } ``` Repository ``` namespace LibraryRepository { public interface IReservationRepository { List GetAllReservations(); } public interface IBookRepository { LibraryDTO.Book GetBookByID(int bookID); } public class MyOracleReservationRepository : IReservationRepository { public List GetAllReservations() {
- pattern moderate 112d agoDatabase Class CreatorOverview I've written a class that will create C# code. The output is a single .cs file for each table in the default database (the database is defined inside a web.config file). I'm looking for a code review on this class alone, not on the generated code. This `DatabaseClassCreator` class uses the `DatabaseAccess` class for some of its database access. The `DatabaseAccess` class can be seen here as I'm asking for a code review of that class as well. If you are not interested in seeing the `DatabaseAccess` class, there is one static method `ExecSQL`, which returns a single `DataTable` with the results of the passed SQL. Two notes: - This was developed and is being used for a ASP.NET project, which is the reason for the `BulletedList`. - This class has to work in a C# .NET 2 environment, so anything that's more modern would be interesting to me, but please note in your answer if the comments/feedback require a newer .NET version. ``` /// /// This class will create c# class files to access spesific /// tables in a database. /// public static class DatabaseClassCreator { /// /// Create class files for all the non-system tables in the current /// default database. /// /// The output location for the class files. This /// is a fully qualified path. public static void CreateAllTables(string OutputPath) { BulletedList bl = new BulletedList(); CreateAllTables(bl, OutputPath); } /// /// Create class files for all the non-system tables in the current /// default database. /// /// A BulletedList where status information can be /// added to. /// The output location for the class files. This /// is a fully qualified path. public static void CreateAllTables(BulletedList StatusBulletList, string OutputPath) { DataTable table = ListDatabaseTables(); if (table == null) { ListItem liRowName = new ListItem(); liRowName.Text = "Database
- pattern minor 112d agoDatabase access classI'm looking for any comments or feedback on my database access class. Security and speed are two things I'm most concerned about. One thing to note is this class has to work in a C# .NET 2 environment, so anything that's more modern would be interesting to me, but please note in the title of your answer if the comments/feedback require a newer .NET version. ``` using Microsoft.Practices.EnterpriseLibrary.Common; using Microsoft.Practices.EnterpriseLibrary.Data; using System.Data; using System.Data.SqlClient; using System.Data.Common; /// /// This is the base class for database access classes. This is the only /// class that should directly talk to the database. Every class or page /// that neads to access the database should be refering to this or a /// derived class. /// public class DatabaseAccess { static string LastDatabaseName = ""; static Database database = null; static int errorCount = 0; /// /// Execute a SQL statement on the default database /// /// The SQL statement to execute /// DataTable of selected results public static DataTable ExecSQL(string SQL) { List Parameters = new List(); return ExecSQL("", SQL, Parameters); } /// /// Execute a SQL statement on the default database /// /// The SQL statement to execute /// The parameters for the SQL statement /// DataTable of selected results public static DataTable ExecSQL(string SQL, List Parameters) { return ExecSQL("", SQL, Parameters); } /// /// Execute a SQL statement on the requested database /// /// The database to execute the SQL on /// The SQL statement to execute /// DataTable of selected results public static DataTable ExecSQL(string DatabaseName, string SQL) { List Parameters = new List(); return ExecSQL(DatabaseName, SQL, Parameters); } /// /// Execute a SQL statement on the requested database /// /// The database