.Net Framework

Select First Row In Group using Custom Comparer

We have a requirement for a list of itineraries with multple itinerary items show only single itinerary in the list with details of one of the items selected based on some custom sorting logic. So I needed to group by itinerary ID and sort by custom Comparison and select the first in each group. Below is a LinqPad file that I've used for testing: void Main() { // http://smehrozalam.wordpres... // http://stackoverflow.com/qu...
  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Serializable attribute is not related to XmlSerializer.

.Net has several methods of serialization and sometimes it causes a lot of confusion even for experienced programmers. I believe the best article to describe the different methods is Aaron Skonnard’s Serialization in Windows Communication Foundation(MSDN Magazine > Issues > 2006 > August) (by some reason it’s not highly rated by Google and other articles are coming first for Serialization related requests) There is also a brief comparison table in StackOverflow What are the differences between...
  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Validating an email address

I needed to validate customer email addresses. Many articles suggested to use different regEx , but they are not the same and not easy to identify, which is the best. So i decided to use MailAddress, which throw exception if MS implemented validation failed. It world be good if the class would provide Validate or TryParse method to avoid costly exception. /// <summary> /// //// Validating E-mail address /// </summary> public static class MailHelper { //TODO: use Reflector or find some...
  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Implementations of HTML TidyLib for .Net

I was considering to add the HtmlValidator class to codeplex, but noticed that there are a few different implementations of HTML TidyLib for .Net. Not sure if any of them support my requirement to validate only structural errors, i.e. unmatched(not closed) open tags and unmatched(extra) close tags. But standard Tidy functionality will be good for most of users. 1. TidyManaged (https://github.com/markbea... Recent development (June 12, 2010), Positive reviews(e.g. here),Not much user...
  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

JavaScriptSerializer extension DeserializeDictionary

When I've tried to deserialize dictionary whis strongly typed(and not string) keys, I've got an exception similar to the following Type 'System.Collections.Generic... System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d5... mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934... is not supported for serialization/deserialization of a dictionary, keys must be strings or objects. // Type Dictionary`2...
  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

IsSubsetOf List extension

I've created IsSubsetOf List extension based on discussion at http://stackoverflow.com/qu... /// <summary> /// Determines whether a System.Collections.Generic.... object is a subset of the specified collection. /// http://stackoverflow.com/qu... /// </summary> /// <param name="list"></param> /// <param name="listToFind"></p...
  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

FromToRange template class

In many scenarios I found useful to store data in FromToRange template class. It is more descriptive than generic Tuple Class /// <summary> /// Summary description for FromToRange. /// </summary> public class FromToRange<T> { public T From; public T To; /// <summary> /// </summary> /// <param name="from"></param> /// <param name="to"></param> public FromToRange(T from, T to) { From = from; To = to; } #region Static Public methods #endregion //Static...
  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Prevent Jet.OLEDB provider to converts strings to decimals

I have an utility, that reads a CSV files into ADO.Net , modifies it and Saves as another .CSV file. Unfortunately Microsoft.Jet.OLEDB provider corrupts some string column, incorrectly interpreting them as decimals. Thanks to the article http://www.aspdotnetcodes.c... I was able to specify schemaIni before reading the file using the function public static void SaveSchemaIni(string path, string schemaIniContent) { FileInfo fileinfo = new FileInfo(path); string...
  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

string RemoveBefore helper function

// <summary> ///if sToFind not found, then original string should be returned /// Otherwise removeBefore /// </summary> /// <param name="str"></param> /// <param name="sToFind"></para... /// <returns></returns... public static string RemoveBefore(this string str, string sToFind) { int num1 = str.IndexOf(sToFind); if (num1 > 0) { return str.Remove(0, num1); } else { return str; } }...
  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

IsStringContainsAnyFromList helper function

/// <summary> /// Returns true, if string contains any of substring from the list (case insensitive) /// See similar (with SqlLikeMatch support) in ResponseMessagePatternsCache /// </summary> /// <returns></returns... public static bool IsStringContainsAnyFromList( string stringToSearch,List<Stri... stringsToFind) { //TODO: create overloads with exact match or case sencitive if (stringsToFind.IsNullOrEmpt... { return false; } else { stringToSearch = stringToSearch.ToUpper();...
  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

IsNullOrDefault generic helper function for nullable types

I've wrote IsNullOrDefault generic helper function public static bool IsNullOrDefault<T>(this Nullable<T> param) where T : struct { T deflt = default(T); if (!param.HasValue) return true; else if (param.Value.Equals(deflt)) return true; return false; } , but then realized that there is more short implementation on stackoverflow submitted by Josh public static bool IsNullOrDefault<T>(this Nullable<T> value) where T : struct { return default(T).Equals( value.GetValueOrDefault()...
  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

How to "cast" from generic List<> to ArrayList

We are writing new code using generic List<> , e.g. List<MyClass>. However we have legacy functions, that are expect ArrayList as a parameter. It is a second time, when I and my colleague asked, how to "cast" generic List<MyClass> to ArrayList. The answer is simple- just use ArrayList constructor with ICollection parameter. Note that it is not real cast, it copies references to ArrayList. var list=new List<MyClass>(); //Fill list items ArrayList al=new ArrayList(list);//"cast"-...
  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

DDD Melbourne -lessons learned

I've attended DDD Melbourne and want to list the interesting points, that I've learned and want to follow. To read more: * Moles-Mocking Isolation framework for .NET. Documentation is here. (See also Mocking frameworks comparison created October 4, 2009 ) * WebFormsMVP * PluralSight http://www.pluralsight-trai... * ELMAH: Error Logging Modules and Handlers Great for new sites or sites without error logging/monitoring. However if you site already have working error...
  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

SQL's "like" patterns to compare in .Net

I wanted to use SQL's "like" patterns to compare in .Net. I found the good C# implementation of function in thread Using Regex to create a SQL's "like" like function. The function IsSqlLikeMatch works fine, but I've noticed that the search is case-sensitive. It's also doesn't match % if there are multiple lines. But it was easy to change by modifying IsMatch call to return Regex.IsMatch(input, pattern, RegexOptions.IgnoreCase | RegexOptions.Singleline); Note that it could be very serious performance...
  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

LongestCommonPrefix function for 2 strings

The function that finds Common Prefix for 2 strings //converted from http://stackoverflow.com/qu... public static string LongestCommonPrefix(string str1, string str2) { int minLen = Math.Min(str1.Length, str2.Length); for (int i = 0; i < minLen; i++) { if (str1[i] != str2[i]) { return str1.Substring( 0, i); } } return str1.Substring( 0, minLen); }...
  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Declare local variable within the loop instead of using loop variable in Linq methods

I've noticed in my LINQ code Resharper Warning "'Access to modified closure'". The search pointed that there is very confusing potential error. If for/foreach loop variable is used only in Linq methods (more general, only as a parameter for delegates) , only the last value of the variable will be used for all calls. It always required to create local variable inside loop and use the local variable instead of loop variable. More about the issue: Linq: Beware of the 'Access to modified closure' demon...
  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Implement Copy constructor using Serialization or Reflecton

Some time ago I wrote a post No Copy Constructor support in .Net framework. and was adviced by Tim Hibbard to use reflection like this. I've created Copy method to copy Fields(not only properties, and found that the private fields of any base class are not copied. The article Where are my fields? « Andrew Smith explains that it's required to iterate base classes. But when looking in the Google for the solution,I've found the suggestion for serializable objects: MemberInfo [] sm = FormatterServices...
  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

MSDN documentation -methods that have corresponding operators shouldn't be called directly

In our old code I'vew noticed a few examples of code like the following: MyFortune = Decimal.Add(MyFortune, .01m); I was wandered, why they didn't use "+" sign, and didn't find any explanation. The MSDN reference documentation doesn't explain, that methods like Add, Subtract,Multiply,Divide usually should not be called explicitely. Instead of using Add method it's simpler to use + sign ( Addition Operator ). E.g. MyFortune = Decimal.Add(MyFortune, .01m); can be rewritten as MyFortune += .01m; Comment...
  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Call eventTimer_Elapsed method asyncronoulsy OnStart of Windows Service

We have eventTimer in Windows Service (similar as described in Timer Objects in Windows Services with C#.NET and Using Timers in a Windows Service) to run the relatively long-running process repeatedly. NOTE: It is NOT a good idea to Use a Windows Service just to run a scheduled process, but I have to maintain a legacy application, that was written as a Windows Service . The process called each time when eventTimer_Elapsed. But I want to run it immediately(not to wait until timer will elapsed) when...
  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

LINQ to XML -How to use XPass for elements selection

I am just starting to work with LINQ to XML and tried to find child document similar to the following: xml.Element("client/child"); But it throw exception System.Xml.XmlException: The '/' character, hexadecimal value 0x2F, cannot be included in a name. The reason is that LINQ to XML doesn't directly support XPAth Fortunately there are extensions, that allow to use XPath for XElement search/selection. using System.Xml.XPath; and then var clients = xml.XPathSelectElements ( "client/child" ); Consider,...
  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Full .Net Framework Archive

«February»
SunMonTueWedThuFriSat
2930311234
567891011
12131415161718
19202122232425
26272829123
45678910