Recent Entries 10
- pattern minor 112d agoSimple object comparerCreating a simple object compare function for public system types in a class meaning only looking at the first level of a class no breaking into an object and comparing sub properties. It performs very quickly however I am unsure about the extensibility of it for the future should criteria evolve ``` public static IEnumerable Compare(this T1 Object1, T2 Object2) where T1 : IComparer { if (Object2 == null) throw new NullReferenceException("Parameter object not instantiated"); Type TypeOfObject1 = typeof(T1); PropertyInfo[] Object1Properties = TypeOfObject1.GetProperties(BindingFlags.Public | BindingFlags.Instance); Type TypeOfObject2 = typeof(T2); PropertyInfo[] Object2Properties = TypeOfObject2.GetProperties(BindingFlags.Public | BindingFlags.Instance); if (Object1Properties.Count() == 0 || Object2Properties.Count() == 0) throw new NullReferenceException("No public properties found"); var DifferencesFound = Object1Properties .Join(Object2Properties, Object1Property => Object1Property.Name, Object2Property => Object2Property.Name, (Object1Property, Object2Property) => new { Object1Property = Object1Property, Object2Property = Object2Property }) .Where(x => ((Type.GetTypeCode(x.Object1Property.PropertyType) != TypeCode.Object && Type.GetTypeCode(x.Object2Property.PropertyType) != TypeCode.Object ) && !x.Object1Property.GetValue(Object1).Equals(x.Object2Property.GetValue(Object2))) ) .Select(x => x.Object1Property.GetCustomAttributes(typeof(DisplayNameAttribute), false).SingleOrDefault() as string ?? x.Object1Property.Name) .AsEnumerable(); return DifferencesFound; } ``` Note: Reads `DisplayName` attribute if it is not found then uses name
- pattern minor 112d agoConverting recordsets to POCOThe goal this method was to emulate the way EF or Dapper return to you concrete POCO classes instead of recordsets when querying your db. Our current code is riddled with iterations over recordsets and I want to consolidate to an extension method that can convert the recordset into an `Enumerable`. Review I'm concerned about how efficient this will be. When querying the db for a single or handful of records I'm not concerned but we sometimes query for an entire table (i.e. ~100,000 records) and in that case will the iterations in this start to cause performance issues? Is there a better way to resolve the recordsets to classes without iterating? Any other constructive remarks appreciated. ``` public static IEnumerable AsList(this Recordset rs) where T : new() { IEnumerable props = new List(typeof(T).GetProperties()).Where(p => p.CanWrite); List results = new List(); while (!rs.Eof) { T obj = new T(); foreach (PropertyInfo property in props) { var val = rs[property.Name].Value; if (val != null) property.SetValue(obj, Convert.ChangeType(val, property.PropertyType)); } rs.MoveNext(); results.Add(obj); } return results.AsEnumerable(); } ``` used as... ``` Recordset rs = new Recordset(); rs.Open("select * from Users", connection) IEnumerable results = rs.AsList(); ``` Post Review Update After great feedback from Heslacher and t3chb0t the following code has been finalized. Note there was a change in the requirements and sister method was created `As()` to create a single class instance from a recordset. The feedback from the review has been applied to it as well. ``` public static IList AsList(this Recordset rs) where T : class, new() { var results = new List(); if (rs == null) throw new ArgumentNullException("rs"); if (rs.Eof) return results; IList properties = GetProperties(); while (!rs.Eof) { results.Add(CreateInstance(propertie
- pattern major 112d agoMethod that returns description attribute of enum valueI have the following method in .NET Core that returns the description attribute of an `enum` value. I think this code can be more elegant. I'd appreciate some suggestions. ``` public static string GetDescription(System.Enum input) { Type type = input.GetType(); MemberInfo[] memInfo = type.GetMember(input.ToString()); if (memInfo != null && memInfo.Length > 0) { object[] attrs = (object[])memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false); if (attrs != null && attrs.Length > 0) { return ((DescriptionAttribute)attrs[0]).Description; } } return input.ToString(); } ```
- pattern minor 112d agoSafely order a list of objects by DateTimeI have several lists of various objects that need to be ordered by one of their properties that contains a string representation of `DateTime`, whose property also varies depending on the object. The main issue with the lists is that the contained objects cannot be guaranteed to be valid `DateTime` representations and so simply ordering them (using LINQ) would throw exceptions if the property is null or an invalid format. This means I have to use something like `DateTime.TryParse`. Here's the class method I wrote to do this: ``` static List SafelyOrderListByDateTimeDescending(List list, string propertyName) { DateTime value; PropertyInfo propInfo; string dateTimeString; foreach (T obj in list) { propInfo = obj.GetType().GetProperty(propertyName); dateTimeString = propInfo.GetValue(obj, null) as string; if (!DateTime.TryParse(dateTimeString, out value)) propInfo.SetValue(obj, default(DateTime).ToString(), null); } return list.OrderByDescending(x => DateTime.Parse(x.GetType().GetProperty(propertyName).GetValue(x, null) as string)).ToList(); } ``` Considering there are many thousands of objects per list it's important that the method is not exceedingly inefficient. It seems to perform well in tests but I'd like some feedback on what could be improved or even if there's a better way. I've tried some really neat ways of doing something similar but they all exclude the object if the value isn't successfully parsed whereas I still need the object.
- pattern minor 112d agoSleeping and invoking a task in Python 2.X and Python 3.XI'm writing a program that needs to be compatible for both Python 2.X and Python 3.X. My problem is that, because of the differences between these two versions, I'm duplicating code. ``` try: ### Python 2.X part time.sleep(iterator.next()) if len(arguments) >= len(inspect.getargspec(task).args): task(*arguments) else: print("ERROR: There is a mismatch between the number of" " arguments provided in `arguments` and the ones" " needed by the task function.") except AttributeError: ### Python 3.X part time.sleep(next(iterator)) if len(arguments) >= len(inspect.getfullargspec(task).args): task(*arguments) else: print("ERROR: There is a mismatch between the number of" " arguments provided in `arguments` and the ones" " needed by the task function.") ``` It can be seen that both versions only differ in the usage of `next()`, `inspect.getargspec()` and `inspect.getfullargspec()`, while the other logic remains the same. Is there any way to optimize the execution of the tasks, in `tasks(*arguments)`, and the printing of the error messages, so that I don't have to repeat the same code? This is just sample working code, but I mean my question in a more broader and general case.
- pattern minor 112d agoBuilding a model-view-controller application in PHPI've seen at least two recent PHP questions that would do well from a Model-View-Controller ('MVC' from here-on-out in this question) setup. Now, me, being the horrible person I am, I wanted to build one because it's been a while since I've done any actual PHP work, and as much trash as I have been known to talk about it it's still a very popular and, to be fair, very easy language to use. So, I've built an MVC structure in it. It's very basic, but it does exactly what an MVC application should. Separation of view from code. It all starts with the `.htaccess` file, this file basically allows the use of `/Controller/Action/Id?QueryString` structured URL's, so I feel it's a good starting place: `RewriteEngine on # Rewrite /Controller as /Controller/Index RewriteRule ^([a-zA-Z0-9]+)/?$ index.php?Controller=$1&Action=Index [L,QSA] # Rerwite /Controller/Action(/Id?Querystring) RewriteRule ^([a-zA-Z0-9]+)/([a-zA-Z0-9]+)/?(/([a-zA-Z0-9]+)/?)?$ index.php?Controller=$1&Action=$2&Id=$4 [L,QSA] ` This is pretty self-explanatory, and it should make sense. The next step is directing the user to `index.php`. This is where magic starts happening, and this is where we start making actual MVC decisions: ``` $methodModelMethod(); $methodModel = new $methodModelName(); foreach (get_object_vars($methodModel) as $var => $value) { $methodModel->$var = $_POST[$var]; } echo $controller->$action($methodModel); } else if ($requestType === "GET") { echo $controller->$action($id); } else { die("HTTP request type '{$requestType}' is unsupported."); } ?> ``` Nothing here needs to be modified to use the MVC system, this is the landing so that `index.php` can take all the work and send it away. This next controller is an example, because I want to demonstrate how easy this MVC system is to use: ``` Title = "Test"; $model->Message = "Some awesome message"; $model->Items = $this->items;
- pattern minor 112d agoPython proper abstract class and subclassing with attributes and methodsThe goal of the code below is to have an abstract base class that defines simple methods and attributes for the subclasses. This is part of an application that provides the code base for others to develop their own subclasses such that all methods and attributes are well implemented in a way for the main application to use them. The application shall never create more than one object of each subclass, since they are supposed to implement everything correctly to be called upon. Ideally, instantiating objects of the subclasses would not even be necessary, but is needed as it is in order to check if the abstract methods are implemented. However, Python seems to be different and awkward when it comes to classes in comparison with other programming languages (initialization, attributes, properties), and I am not very sure if the solution below is the most appropriate. It seems too much complicated to achieve the aforementioned purpose. In addition, another function (not in the code below) must be made to properly check (make sure that they are of a certain type) the attributes of the subclasses. Any thoughts? ``` from abc import ABC, abstractmethod class abstract_attribute(object): """taken from http://stackoverflow.com/questions/32536176/how-to-define-lazy-variable-in-python-which-will-raise-notimplementederror-for-a/32536493#32536493""" def __get__(self, obj, type): # Now we will iterate over the names on the class, # and all its superclasses, and try to find the attribute # name for this descriptor # traverse the parents in the method resolution order for cls in type.__mro__: # for each cls thus, see what attributes they set for name, value in cls.__dict__.items(): # we found ourselves here if value is self: # if the property gets accessed as Child.variable, # obj will be done. For this case # If acc
- pattern minor 112d agoAccessing Properties by NameOver the weekend I decided to start work on my own version of FastMember. I began with my take on an implementation of `TypeAccessor` so that I could work with the properties of any type, create an instance of the type, and one or two other little tricks. I've reached a point where I'm out of ideas on how to improve the design of the class further so now I'm looking for feedback. Usage: ``` public class Point2D { public double X { get; set; } public double Y { get; set; } } var pointA = new Point2D { X = 9000.01, Y = 0.0 }; var accessor = TypeAccessor.Create(pointA); var pointB = new Point2D(); // pointB.X should be 0.0 accessor.CloneProperties(pointA, pointB) // pointB.X should now be 9000.01 accessor[pointA, "X"] = 0.0; // sets pointA.X to 0.0 Console.WriteLine(accessor[pointA, "X"]) // prints pointA.X, should be 0.0 accessor.Default(ref pointA); // sets pointA's properties to default the accessor's default values Console.WriteLine(accessor[pointA, "X"]); // prints pointA.X, should be 9000.01 ``` Notes: One of the design goals was to ensure that everything always works as you might expect it to based on the current context. If the `Type` you send to `TypeAccessor` has a property that is read-only then a method like `CloneProperties` will simply ignore that property because it's not cloneable. `GetProperties` returns an actual instance of `Dictionary` because it makes no sense to let the method yield when: - Some nasty behaviors become possible because reference types could be nulled during any yield - Two other options exist for accessing properties one at a time As far as I know, every single "expensive" operation that can be lifted into the constructor has been (which was very important to me for performance). I can't say I'm pleased with the amount of code there but it really doesn't belong anywhere else. I suppose it could be split up into two or three private methods but I'm not sure that would be any better... Dependencies: There are three
- snippet minor 112d agoDynamically convert property to different data typeThe code finds marked attributes and parses them according to the attribute type. Is it possible to simplify this logic? Is there generic way to do it? Please suggest some way to optimise this code. All the data type of `Product` class will be string. I'm getting product input as XML directly converting serialized data to a class with decimal, int, float will not give proper error message. If there is list of items it will throw error in XMl and we won't know which row has caused the error. ``` using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace TestSolution { public interface ICustomParser { bool Parse(string input); } public class DecimalParserAttribute : Attribute, ICustomParser { public bool Parse(string input) { if (input == null) return false; decimal decimalValue; return decimal.TryParse(input, out decimalValue); } } public class intParserAttribute : Attribute, ICustomParser { public bool Parse(string input) { if (input == null) return false; int intValue; return int.TryParse(input, out intValue); } } public class Product { [DecimalParser] public string Weight { get; set; } [intParser] public string NoOfItems { get; set; } [intParser] public string GRodes { get; set; } [intParser] public string WRodes { get; set; } } class Program { static void Main(string[] args) { var sb = Validate(new Product() { NoOfItems = "1", GRodes = "4", Weight = "5", WRodes = "23" }); Console.WriteLine(sb); sb = Validate(new Product() { NoOfItems = "1", GRodes = "4w", Weight = "5", WRodes = "23" }); Console.WriteLine(sb); Console.ReadKey(); }
- pattern major 112d agoGeneric Null/Empty check for each property of a classI have created a method to check for null/empty values of class properties and if any null property is found I'm stopping the checking process and returning the result as true. I've used a solution from here and following is the code I have implemented: ``` /// To check the properties of a class for Null/Empty values /// /// The instance of the class /// Result of the evaluation public static bool IsAnyNullOrEmpty(object obj) { //Step 1: Set the result variable to false; bool result = false; try { //Step 2: Check if the incoming object has values or not. if (obj != null) { //Step 3: Iterate over the properties and check for null values based on the type. foreach (PropertyInfo pi in obj.GetType().GetProperties()) { //Step 4: The null check condition only works if the value of the result is false, whenever the result gets true, the value is returned from the method. if (result == false) { //Step 5: Different conditions to satisfy different types dynamic value; if (pi.PropertyType == typeof(string)) { value = (string)pi.GetValue(obj); result = (string.IsNullOrEmpty(value) ? true : false || string.IsNullOrWhiteSpace(value) ? true : false); } else if (pi.PropertyType == typeof(int)) { value = (int)pi.GetValue(obj); result = (value <= 0 ? true : false || value == null ? true : false); } else if (pi.PropertyType == typeof(bool)) { value = pi.GetValue(obj); result = (value == null ? true : false); } else if (pi.PropertyType == typeof(Guid)) {