Geeks With Blogs

News My Blog has been MOVED to https://mfreidge.wordpress.com
Michael Freidgeim's OLD Blog My Blog has been MOVED to https://mfreidge.wordpress.com .Net Framework
Links for RazorEngine development.
We are using RazorEngine to generate emails based on .cshtml templates. Below are a few links that I used when develop ithttps://antaris.github.io... http://www.blozinek.cz/2014... ......

Posted On Friday, February 19, 2016 9:45 PM

Case insensitive StringHelper.EnsureEndsWith
I've created an extension method for string public static string EnsureEndsWith(this string str,string sEndValue,bool ignoreCase=true) { if (!str.EndsWith(sEndValue, ignoreCase, CultureInfo.InvariantCulture)) { str = str + sEndValue; } return str; }By some reason content of the post is not shown ......

Posted On Wednesday, February 17, 2016 10:51 PM

Read CSV files with multiple lines
I needed to read CSV files with columns, containing strings in double quotes. The problem was that there were new lines within the column. Fortunately I found the article that reads the strings with multiple lines http://www.blackbeltcoder.c... article that I considered ,but haven't used ishttp://blogs.msdn.com/b/e... ......

Posted On Sunday, January 24, 2016 5:31 PM

Methods to verify, are DataTables or DataSets the same.
I wanted to verify, are DataTables in DataSets the same. I found a few similar implementations on StackOverflow, but the one that I've selected (http://stackoverflow.com/q... didn't work and returned unexpectedly false, when comparing two cells with the same values tbl1.Rows[i][c] 2 object {long} tbl2.Rows[i][c] 2 object {long} tbl1.Rows[i][c] == tbl2.Rows[i][c] false I found, that it should be used Equals instead of ==. Equals(tbl1.Rows[i][c], ......

Posted On Tuesday, August 27, 2013 9:49 PM

Number of Unit test projects in Visual Studio solution
Some time ago I have discussion with my co-worker how to organize test projects. Should we have a single test project that does all sorts of things and references every project?It is good to have one integration test dll, but for unit tests, what is the point merging everything into one.In ideal world I agree that small independent projects are better. Unfortunately we have solution size limitations From http://stackoverflow.com/qu... ......

Posted On Sunday, June 9, 2013 12:11 PM

PostSharp deployment to build machine- use Setup installation, not NuGet package.
PostSharp has well documented different methods of installation. I've chosen installing NuGet packages, because according to Deploying PostSharp into a Source Repository NuGet is the easiest way to add PostSharp to a project without installing the product on every machine. However it didn't work well for me. I've added PostSharp NuGet package to one project in the solution. When I wanted to use PostSharp in other project, Visual Studio tab showed that PostSharp is not enabled for this project I've ......

Posted On Wednesday, October 17, 2012 10:04 PM

Convert collections of enums to collection of strings and vice versa
Recently I needed to convert collections of strings, that represent enum names, to collection of enums, and opposite, to convert collections of enums to collection of strings. I didn’t find standard LINQ extensions.However, in our big collection of helper extensions I found what I needed - just with different names: /// <summary> /// Safe conversion, ignore any unexpected strings/// Consider to name as Convert extension /// </summary> /// <typeparam name="EnumType"></typ... ......

Posted On Saturday, July 7, 2012 9:10 PM

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... ......

Posted On Monday, September 19, 2011 6:43 AM

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 ......

Posted On Friday, September 16, 2011 11:40 PM

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 ......

Posted On Wednesday, June 8, 2011 7:13 AM

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 ......

Posted On Wednesday, June 8, 2011 6:44 AM

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 ......

Posted On Friday, June 3, 2011 7:34 AM

Serialization error when property is declared as base class, but populated by derived class
I've receive quite generic error Message : Type 'MyclassType' with data contract name 'MyclassType:http://schemas... is not expected. Consider using a DataContractResolver or add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to DataContractSerializer.Type : System.Runtime.Serializatio... mscorlib, Version=4.0.0.0, Culture=neutral, ......

Posted On Sunday, June 2, 2013 9:08 PM

Upgrading PostSharp from ver 2.1 to new version 3.0
I was upgrading our solutions from PostSharp 2 to PostSharp 3. The small solution based on cache attribute from http://cache.codeplex.com/ was upgraded without any problems.Upgrading my main solution by installing nuget package PostSharp also was quite well. The only annoying thing was that installer added RequiresPostsharp.cs file to all projects, that already had SkipPostSharp=true setting and I had manually remove themThe issue was reported athttp://support.sharpcraft... ......

Posted On Sunday, June 2, 2013 2:17 PM

AddIfNotNull collection extensions
I want to post a few recently created collection extensions to write in one line, what otherwise takes 2 or more public static void AddIfNotNull( this IList coll, T newItem) where T : class { if (newItem != null) { coll.Add(newItem); } } public static void AddRangeIfNotNullOrEmpty( this List coll, IEnumerable newItems) where T : class { if (!newItems.IsNullOrEmptySeq... { coll.AddRange(newItems); } } public static void AddIfNotContains( this Dictionary dictionary, TKey key, TValue value) { if ......

Posted On Saturday, May 25, 2013 10:20 AM

EntLIb editor corrupts config files
I've tried to use Microsoft Enterprise Library(EntLIb) editor, as it was suggested in http://weblogs.asp.net/suku... but after changes all comments in config files were removed. Always consider to move any Enterprise Library configurations to a separate file before editing ......

Posted On Saturday, February 16, 2013 3:45 PM

Using PostSharp.Toolkit.Diagnostics, when not all developers have Pro licenses.
We have only couple of developers who are using PostSharp.Toolkit.Diagnostics and having PostSharp Pro license .However ther are much more developers , who are building our solution, but do not required Toolkit.Diagnostics XmlMulticast features, that are referred in %ProjName%.psproj file.As a workaround I've suggested to to replace locally psproj file with dummy, that doesn't have XmlMulticast(PostSharp feature that available only in Pro edition).If a developer doesn't have PostSharp Pro license, ......

Posted On Saturday, February 16, 2013 2:57 PM

VAB ValidationResults Extensions
We've started to actively used Microsoft Enterprise Library Validation Enterprise Block ( VAB) and I was surprised , that a few commonly used operations are not supplied(or I haven't found them) out of the box.See two extensions, that make use of VAB simplerpublic static class ValidationResultsExtensions { public static string CombinedMessage( this ValidationResults results) { string errorMessage = ( from res in results select String.Format(" {0}:{1} ", res.Key, res.Message)).ToDelimitedSt... ";"); ......

Posted On Saturday, February 16, 2013 2:46 PM

Using CollectionNotEmptyValidator
We recently started to use Microsoft Enterprise Library Validation Enterprise Block (VAB) to check interfaces between modules. One of the properties to validate is array of values, that should be not empty, and shoul include one of expected values. I found CollectionNotEmptyValidator at http://www.eggheadcafe.com/... that allows to validate the property to satisfy part of requirements. The class ......

Posted On Saturday, February 16, 2013 2:35 PM

Do NOT Change "Copy Local” project references to false, unless understand subsequences.
To optimize performance of visual studio build I've found multiple recommendations to change CopyLocal property for dependent dlls to false,e.g. From http://stackoverflow.com/qu... CopyLocal? For sure turn this offhttp://stackoverflow.com... set the Copy Local property to false and enforce this via a custom msbuild stephttp://codebetter.com/p... ......

Posted On Sunday, December 9, 2012 1:15 PM

Adding PostSharp to new projects, when it's installed for some projects in solution.
Recently I've posted my experience with installation of PostSharp Once PostSharp is installed in solution's packages folder for some project(s), I often need to add PostSharp to another project in the same solutionSection "Adding PostSharp to your project using PostSharp HQ" of documentation described the process quite well.I only want to add that the actual location of PostSharp HQ ( if it was installed from NuGet) is[solution root ]packages\PostSharp.2.1.7.1... ......

Posted On Sunday, November 4, 2012 6:59 PM

Helper method to Replace/Remove characters that do not match the Regular Expression
I have a few fields, that use regEx for validation. In case if provided field has unaccepted characters, I don't want to reject the whole field, as most of validators do, but just remove invalid characters. I am expecting to keep only Character Classes for allowed characters and created a helper method to strip unaccepted characters. The allowed pattern should be in Regex format, expect them wrapped in square brackets. function will insert a tilde after opening squere bracket , according to http://stackoverflow.com/qu... ......

Posted On Sunday, October 28, 2012 1:30 PM

C# tip: do not use “is” type, if you will need cast “as” later
We have a debate with one of my collegues, is it agood style to check, if the object of particular style, and then cast as this type. The perfect answer of Jon Skeet and answers in Cast then check or check then cast? confirmed my point.//good var coke = cola as CocaCola; if (coke != null) { // some unique coca-cola only code } //worse if (cola is CocaCola) { var coke = cola as CocaCola; // some unique coca-cola only code here. } ......

Posted On Saturday, June 9, 2012 7:35 PM

Code review recommendations and Code Smells
Some time ago Twitter told that I am similar to Boris Lipschitz . Indeed he is also .Net programmer from Russia living in Australia. I‘ve read his list of Code Review points and found them quite comprehensive. A few points were not clear for me, and it forced me for a further reading.In particular the statement “Exception should not be used to return a status or an error code.” wasn’t fully clear for me, because sometimes we store an exception as an object with all error details and I believe it’s ......

Posted On Saturday, June 9, 2012 6:19 PM

IsNullOrEmpty generic method for Array to avoid Re-Sharper warning
I’ve used the following extension method in many places. public static bool IsNullOrEmpty(this Object[] myArr) { return (myArr == null || myArr.Length == 0); }Recently I’ve noticed that Resharper shows warning covariant array conversion to object[] may cause an exception for the following codeObjectsOfMyClass.IsNull... resolved the issue by creating generic extension method public static bool IsNullOrEmpty<T>(this T[] myArr) { return (myArr == null || myArr.Length == 0); }Related ......

Posted On Tuesday, May 29, 2012 10:52 PM

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... ......

Posted On Friday, May 13, 2011 10:09 PM

Case-insensitive Contains extension for list of strings
I wanted to have case-insensitive Contains method for list of strings.Overload Enumerable.Contains<TSou... Method (IEnumerable<TSource>, TSource, IEqualityComparer<TSourc... expects custom IEqualityComparer class.I was about to create my own class IgnoreCaseEqualityComparer : IEqualityComparer<string... then found StringComparer.Create Method, that allow to use standard class.public static bool ContainsString(this IEnumerable<string> collection, string toFind, bool ......

Posted On Wednesday, April 18, 2012 10:29 PM

ReplaceBetweenTags function with delegate to describe transformation
I've created a function that allow to replace content between XML tags with data, that depend on original content within tag, in particular to MAsk credit card number.The function uses MidBetween extension from My StringHelper class /// <summary> /// /// </summary> /// <param name="thisString"></p... /// <param name="openTag"></para... /// <param name="closeTag"></par... /// <param name="transform"></pa... /// <returns></returns... ......

Posted On Sunday, April 15, 2012 1:01 PM

Code style Tip: Case insensitive string comparison
Goodif (String.Compare(myString, ALL_TEXT, StringComparison.OrdinalIgn... == 0) { return true; }OK(not obvious what true means) if (String.Compare(myString, ALL_TEXT, true) == 0) { return true; }BAD: (non null safe) if (myString.ToLower()==ALL_TE... { return true; } ......

Posted On Sunday, April 15, 2012 12:34 PM

Dump an arbitrary object To Html String
For debugging purposes me and my collegue wanted to dump details of the arbitrary object, and created function that uses LINQPad Dump functionality (thanks to http://stackoverflow.com/a/... and original http://linqpad.uservoice.co... discussion) public static string DumpToHtmlString<T>(this T objectToSerialize) { string strHTML = ""; try { var writer = LINQPad.Util.CreateXhtmlWri... ......

Posted On Saturday, April 14, 2012 2:50 PM

CodePlex downloads without strong name for an assembly
I wanted to use http://cache.codeplex.com/ in my solution, but it caused compile errorAssembly generation failed -- Referenced assembly does not have a strong nameREASON: When you compile an assembly with a strong name, any referenced assemblies must also have strong name.I could sign Cache project using Visual Studio or using commands as described in “Tip related to strong name”. But It also required to sign referenced DLLs, like BplusTree from http://bplusdotnet.sourcefo... I’ve ......

Posted On Saturday, March 10, 2012 11:31 PM

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 ......

Posted On Friday, May 13, 2011 8:26 PM

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 ......

Posted On Thursday, May 12, 2011 6:46 AM

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; } } ......

Posted On Thursday, May 12, 2011 6:30 AM

Misleading error message when NullReferenceException thrown within Comparer
We've got an error messgae from custom comparer: IComparer (or the IComparable methods it relies upon) did not return zero when Array.Sort called x. CompareTo(x). After investigation it was found, that the error was caused by NullReferenceException, thrown within Comparer. I've suggested to Microsoft , that the actual NullReferenceException error message should be shown instead of this misleading one. See also similar feedback https://connect.microsoft.c... ......

Posted On Wednesday, May 20, 2009 9:35 PM

EnsureDirectoryExists helper function
Below is a simple EnsureDirectoryExists helper function: public static void EnsureDirectoryExists(string targetPath) { string dir = Path.GetDirectoryName(targe... if (!Directory.Exists(dir)) { Directory.CreateDirectory(d... } } ......

Posted On Sunday, May 17, 2009 5:58 PM

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(); ......

Posted On Thursday, May 12, 2011 6:27 AM

Compile DVR-MS Editor in .Net 2.0
I've downloaded (from Fun with DVR-MS article on MSDN) and rebuild DVR-MS Editor in VS 2005. It works great.The only issue in migrating is to resolve ambiguous references and explicitely specify namespace for ProgressChangedEventArgs and ProgressChangedEventHandler as Toub.MediaCenter.Dvrms.Conv... and Toub.MediaCenter.Dvrms.Conv... I also noticed that a link to extended version of tools is available from DVR-MS: Adventures in Closed Captioning ......

Posted On Thursday, March 1, 2007 8:19 AM

"Configure Data Source" Wizard reads assemblies from BIN directory regardless of specified Build Output Path in VB WAP project
Today I wanted to add Object Data Source(located in another DLL) to User Control in VB WAP project."Configure Data Source"Wizard showed me "Choose your Business Object" drop-down list with some objects from my DLL, but not the newest, that I've created recently. I've rebuild my projects a few times,cleaned solution,closed and re-opened Visua Studio -it didn't help. My new data classes were not included in the combo-box. When I added class typemanually in the markup view, Wizard reported, that class ......

Posted On Friday, February 9, 2007 8:04 PM

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() ......

Posted On Friday, June 11, 2010 6:42 PM

LogCategory combo-box in Enterprise Library Exception Handling Application Block.
I've tried to create Enterprise Library Exception Handling Policy similar to described in Take Exception To Critical Errors With Custom Application Blocks , but I wanted to use standard Logging Exception Handler.However the LogCategory combo-box was empty and I wasn't able even save the configuration file due to error:"the value for LogCategory can not be null".It wasn't obvious for me that I have to create “Category source“ under “Logging Application Block“ first.It is not ......

Posted On Monday, October 16, 2006 4:34 PM

Unable to call parameterized constructor for type arguments in Generic class.
I've tried to define a generic class, that uses a type argument derive from the specified base class without parameterless constructor.The sample code is the following: public class KeywordsSearchTestGeneric&l... where T : Keywords//',new() { // Methods public void ExactMatchCases() { T keywords1 = new T("string"); } } public class Keywords { // Methods public Keywords() { throw new NotSupportedException(); } public Keywords(string connString) { Debug.WriteLine("Keywords " + connString); } } ......

Posted On Monday, October 2, 2006 12:41 PM

DataSetHelper.SelectDistinct method for multiple columns
UPDATE: In .Net 2.0 there is DataView.ToTable Method (String, Boolean, String[]) that does, what my function (and MS KB article 326176) was created to address. The article is now obsolete. UPDATE: there is also optimized for performance class in CodeProject DataTable with SelectDistinct in VB . I was using a DataSetHelper class based on MS kb article 326176 HOW TO: Implement a DataSet SELECT DISTINCT Helper Class. However SelectDistinct function from the article works only if you select distinct ......

Posted On Friday, September 15, 2006 12:19 PM

Handling missing source columns in DataSetHelper.InsertInto method
I am using a DataSetHelper class from MS kb article 326009 HOW TO: Implement a DataSet SELECT INTO Helper Class in Visual C# .NET Recetly I've noticed that InsertInto method throws exception if the source table doesn't have some columns from the target. It will be better to set columns to null or default. The changed code is the following: /// /// Sample of call /// dsHelper.InsertInto(ds.Tabl... ds.Tables["Employees"], "FirstName FName,LastName LName,BirthDate", "EmployeeID<5", "BirthDate") ......

Posted On Monday, September 11, 2006 8:33 AM

Difference in HybridDictionary and Generic Dictionary Item behavior if the specified key is not found
In .Net 1.1 I've used HybridDictionary.Item and my code expected that if the specified key is not found, attempting to get it returns a null reference.But in .Net 2.0 Generic Dictionary.Item if the specified key is not found, a get operation throws a KeyNotFoundException and I have to use Dictionary.TryGetValue or check ContainsKey before calling Item. ......

Posted On Wednesday, August 16, 2006 11:38 AM

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"- ......

Posted On Saturday, June 5, 2010 9:10 PM

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 ......

Posted On Tuesday, May 18, 2010 7:47 AM

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 ......

Posted On Tuesday, December 22, 2009 4:18 AM

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); } ......

Posted On Wednesday, September 9, 2009 11:15 PM

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 ......

Posted On Saturday, July 18, 2009 7:47 AM

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 ......

Posted On Friday, July 17, 2009 6:01 PM

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 ......

Posted On Friday, June 19, 2009 8:02 PM

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 ......

Posted On Sunday, June 7, 2009 3:41 AM

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, ......

Posted On Wednesday, May 20, 2009 9:58 PM

Use HashSet instead of "seen" Hashtable.
In our code (originally created in .Net 1.1) there are a few examples of "seen" Hashtable pattern Hashtable seen = new Hashtable(); for (int i = 0; i < nCount; i++) { if (seen[key] == null) { //Do the changes seen.Add(key, key); } } It's better to use type-safe HashSet: HashSet<string> seen = new HashSet<string>(); for (int i = 0; i < nCount; i++) { if (!seen.Contains(key)) { //Do the changes seen.Add(key); } } ......

Posted On Wednesday, May 13, 2009 12:09 AM

Don't Repeat Yourself(DRY principle) when modifying existing function
If there is an existing non-trivial function and you need to change it , do NOT copy and paste it , but modify to satisfy new requirements. You may be need to split a big function into small ones and call them in different order or with different parameters. Often you need just to add extra parameter to the function and have if-else branches depending on a new parameter. In some cases new change is actually a fix of the problem, that applicable to all usages of the function. Remember that "Copy and ......

Posted On Wednesday, May 13, 2009 12:03 AM

Typed DataTable's base class in VS008
I have a typed Dataset, generated by VS Designer. Resently I've added a new column to one of the tables, and suddently in different DLLs where the dataset was used, I've started to get Error 22 The type 'System.Data.TypedTableBase... is defined in an assembly that is not referenced. You must add a reference to assembly 'System.Data.DataSetExtensi... Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934... Apparently VS 2008 changed the base class for Typed DataTables 3.5 : public ......

Posted On Sunday, May 10, 2009 9:50 AM

Safe Save DateTime to SQL Database.
When I tried to save DateTime data to SQL database, I've got SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM. The problem is described in http://blogs.vertigosoftwar... I've had to create a function object SafeSqlDateTime(DateTime dtValue) { object theValue = dtValue; if (dtValue <(DateTime) SqlDateTime.MinValue) // January 1, 1753. { theValue = null; } return theValue; } For opposite SqlDateTime to DateTime Conversion ......

Posted On Sunday, May 3, 2009 9:13 PM

TryXmlSerialize function
I was using XmlSerialize method from http://codebetter.com/blogs... a while.Recently I found that sometimes it's safer to use TryXmlSerialize: /// <summary> /// Serialize an object into XML /// </summary> /// <param name="serializableObject"&g... that can be serialized</param> /// <returns>Serial XML representation</returns> public static bool TryXmlSerialize(object objectToSerialize, out string strXml) { bool bRet=true; ......

Posted On Sunday, March 22, 2009 10:17 AM

3-D Secure credit card verification Links
Overview: http://en.wikipedia.org/wik... The Process Flow described in "3-D Secure. Further Technical Information" "Submitting Transactions in the XML Direct Model with 3 D Secure Guide" and "Verified by Visa Introduction"(chapter 4) The UPG Guide for 3D Secure Transaction Delivery Technical Details: Verified by Visa's "Merchant Implementation Guide" Concerns : http://www.computing.co.uk/... Verified by Visa and MasterCard SecureCode:or, How Not to Design ......

Posted On Sunday, February 22, 2009 12:29 PM

Validate eMail address using MailAddress.ParseValue
We have Regular Expression validator to validate the eMail address, specified by the users. It usually warn user about some common mistakes. But sometimes eMail address passes validation , but later causes exception in MailAddress.ParseValue called from MailAddress constructor. I decided to call MailAddress.ParseValue as a part of UI validator, but it's private. (I've asked MS to change it) So I had to open constructor inside try block and catch exceptions in case if format is wrong. Alternatively ......

Posted On Monday, February 2, 2009 10:27 PM

Error: "Cannot perform 'Like' operation on System.Int64 and System.String"
I've had a code similar to the following: string sSql = String.Format("Column1 LIKE '%{0}%'", StringValue); fareRows = dataset.Table.Select(sSql); And DataTable.Select method returned me "Cannot perform 'Like' operation on System.Int64 and System.String". System.Data.EvaluateException: Cannot perform 'Like' operation on System.Int64 and System.String. at System.Data.BinaryNode.SetT... op, Type left, Type right) at System.Data.LikeNode.Eval(D... row, DataRowVersion version) at ......

Posted On Sunday, July 15, 2007 11:39 AM

Code reviews and coding recommendations
We don't have code reviews, but sometimes I have to tell the team quite obvious coding recommendations. There are a few examples: 1. We should do the check if array element is available before access it: E.g. BAD: string departureCity = Flight[0].StartPoint; GOOD: if (Flight.Rows.Count <= 0) { WarningMessageEvent.Raise("... <= 0"); return; } string departureCity = Flight[0].StartPoint; 2. Keep separate functionality in small functions, rather than add morre code to existing functions, ......

Posted On Thursday, January 22, 2009 8:58 PM

"Edit and continue" not working in functions with LINQ
I've started to use LINQ and feel that query expression are very powerfull. Unfortunately , when in debugger I've tried to Edit and continue, it gave me an error Modifying a 'method' which contains a query expression will prevent the debug session from continuing while Edit and Continue is enabled. The post Orcas - Edit and continued not working when linq used - MSDN Forums explains that "it is a limitation of the environment in which Edit and Continue operates". I've submitted suggession to MS - ......

Posted On Wednesday, January 7, 2009 10:25 PM

Helper functions to find pattern contaned in string from pattern List
Below are a few helper functions for List<string> generic class. They could be modified to be extension methods. //See also StringArrayHelper.cs, CollectionsHelper.cs public static class ListOfStringsHelper { public static bool StringContainsAnyFromList(L... patternsList, string sMsg) { bool bFound = patternsList.Exists( delegate(string pattern) { return sMsg.Contains(pattern); } ); return bFound; } public static string FindFirstListItemContainedI... patternsList, ......

Posted On Friday, December 12, 2008 10:39 PM

ToString function for Generic List
Below is the method to output Generic list of objects as string. UPDATE: I've replaced my original function with the code suggested by James Curran (see his comment below). public static string ToString<T>(IEnumerab... messages, string sComment) { StringBuilder sRet = new StringBuilder(sComment); if (messages != null) { foreach (T msg in messages) { sRet.AppendLine(msg.ToStrin... } } return sRet.ToString(); } /// <summary> /// /// </summary> /// <typeparam name="T"></typeparam> ......

Posted On Friday, December 12, 2008 10:34 PM

Access to Relative To Application Root File
Sometimes you have a file relative to the root of application, that you want to read from your code. However when your code is build on development machine, the binary files are located in "\bin\debug","\bin\release" or just "\bin"(for VB or Web projects). And you need to make copy of files relative to bin/debug folder. The function below helps to find the file, even if it was not copied to bin subfolder. (Should I name it ResolvePath smilar to Page.ResolveUrl?) Note, that in most cases Visual Studio ......

Posted On Friday, December 12, 2008 10:22 PM

Debugging Windows Services with "Edit & Continue"
I needed to debug Windows Services. But I didn't like suggested in multiple articles Debugger.Launch. Thanks to post "Debugging Windows Services is a Pain" (and article CodeProject: Debugging Windows Services under Visual Studio .NET) I was able 1. To download Service Debugging Helper (Binary) (or Service Debugging Helper (Binary + Source)) 2. Add in my service project a Reference to AndersonImes.ServiceProcess... 3. Change in the Main() function //ServiceBase.Run(ServicesT... ServicesLoader.StartService... ......

Posted On Monday, December 8, 2008 9:35 PM

Avoid throwing exception from asynchronous delegate.
I am using delegate to invoke asyncronous call of the function. Sometimes the function can throw exception. As described in thread Re: exception handling with events , article "Handling Exceptions Thrown from an Asynchronous Delegate"(and in many other places) "You should call EndInvoke in a try/catch block to catch any exceptions your asynchronous method threw". I followed the same approach in my Asynchronous long-running tasks in ASP.NET application The code is like the following: RecalculateDelegate ......

Posted On Wednesday, December 3, 2008 10:45 PM

Helper functions to get last element in collection
Below are couple simple helper functions to get last element in collection: public static Object LastElement(Object[] myArr) { if( IsNullOrEmpty(myArr)) { return null; } return myArr[myArr.Length-1]; } public static DataRow GetLastRow(DataTable tbl) { if (tbl == null) { throw new NullReferenceException("tbl is null"); } if (tbl.Rows.Count == 0) { return null; } return tbl.Rows[tbl.Rows.Count - 1]; } ......

Posted On Wednesday, December 3, 2008 10:06 PM

Generics function to work with the list of rows of Typed Dataset
I wanted to create common function, that will work with the list of rows of Typed Dataset, e.g. List<MyTypedDataSet.MyTa... I've created a function that expects as a parameter List of base DataRow objects, i.e. List<DataRow>. But compiler showed error, that it unable to cast List<MyTypedDataSet.MyTa... to List<DataRow>. It does make sense, but what are the valid options? The one, that I've used, is actually collect MyTableDataRow into the list of base DataRow records. ......

Posted On Saturday, October 4, 2008 10:52 PM

Developer should not use "Hide extensions for known file types" in Windows Explorer
One my colleague got a new PC and had a problem opening file using simple code(just from MSDN example ): FileInfo fi1 = new FileInfo(relativePath); if (!fi1.Exists) .... It showed that file doesn't exist. We've tried also File.Exists(relativePath), changed the path to absolule- the same result- file is visible in Windows Explorer, but doesn't exist in code. Note that directory was shown in debugger as existing. We've created(using Windows Explorer) a new Text file, named "test.txt" and tried to open ......

Posted On Thursday, August 14, 2008 12:22 AM

Convert DataSet and DataTable to Xml String helper functions
I created 2 helper functions(can be modified as extensions in .Net Framework 3.5) to output/trace content of DataSet or DataTable public static string ToStringAsXml(DataSet ds) { StringWriter sw = new StringWriter(); ds.WriteXml(sw, XmlWriteMode.IgnoreSchema); string s = sw.ToString(); return s; } public static string ToStringAsXml(DataTable dt) { StringWriter sw = new StringWriter(); dt.WriteXml(sw, XmlWriteMode.IgnoreSchema); string s = sw.ToString(); return s; } ......

Posted On Thursday, August 14, 2008 12:02 AM

DataRow.SetParentRow Method
I've noticed an existence of DataRow.SetParentRow Method. MSDN documentation is quite brief: Sets the parent row of a DataRow with specified new parent DataRow. It wasn't clear does the functions fills foreign key values in the child row from the parent one. Thanks to Reflector, I confirmed, that it does SetKeyValues . Please note that from performance point of view it is important to call SetParentRow first and add the childRow to the child table later ......

Posted On Friday, July 25, 2008 8:06 PM

Disk Cleanup Utility should delete temporary .Net files.
I noticed that one of our servers with low disk space had a lot of security.config.cch files(or security.config.cch.number) in individual user folders, as well as in .Net.Framework config directories. According to the thread http://www.pcreview.co.uk/f... -it seems they are safe to delete. But why they are located in config folder, not in some temporary directory, like NET\Framework\{version}\Tem... ASP.NET Files folders? And they should be suggested for deletion by standard ......

Posted On Friday, July 18, 2008 10:24 PM

Min and Max methods for DateTime
Math.Max Method doesn't have overload for DateTime So I've created public static DateTime Min(DateTime t1, DateTime t2) { if (DateTime.Compare(t1, t2) > 0) { return t2; } return t1; } public static DateTime Max(DateTime t1, DateTime t2) { if (DateTime.Compare(t1, t2) < 0) { return t2; } return t1; } ......

Posted On Thursday, February 21, 2008 4:50 PM

Call Synchronous Web Services Methods Asynchronously
I need to asynchronously call a few web services at the same time. VS 2005/2008 Web services proxy generator creates several proxy class methods , including synchronous MyWebMethod(parameters) and asynchronous pair BeginMyWebMethod(parameters) and EndMyWebMethod(parameters) The way to use Begin/End methods is described in article "Calling Web Services Asynchronously " Even if I am going to use asynchronous method in the real application, for unit testing(including TestHarness ) it is much easier ......

Posted On Friday, July 18, 2008 9:23 PM

Store custom objects configuration in separate custom configuration files
We are going to have a windows service that will run a few workflow(WF) instances. I want to have configuration information to be stored in separate config files for each WF instance. I remembered that EntLib has helper classes to store custom objects configuration in separate custom configuration file, but finding good examples in Google wasn't easy(probably I didn't find good search keywords). The links that I finally found(more relevant to the task first) Tom Hollander 'post External configuration ......

Posted On Tuesday, June 10, 2008 12:55 AM

Naming Guidelines: Names for embedded Enum and Property of the enum type
Property Naming Guidelines recommends to consider creating a property with the same name as its underlying type. For example, if you declare a property named Color, the type of the property should likewise be Color. Enumeration Type Naming Guidelines recommends do not use an Enum suffix on Enum type names. I found this recommendation conflicting if I want to declare Enum within class and have a property of the type of this enum. I've tried to create something like the following:. public class Control ......

Posted On Tuesday, May 27, 2008 12:52 AM

AppendIfNotContains string helper method
I've created a helper function, that allows me to set extra CSS class name(space separated) public static string AppendIfNotContains(string str, string sToAppend, string delimeter) { if (!str.Contains(sToAppend)) { str = AppendWithDelimeter(str, sToAppend, delimeter); } return str; } public static string AppendWithDelimeter(string str, string sToAppend, string delimeter) { if ((!str.EndsWith(delimeter) & !String.IsNullOrEmpty(str)) & !String.IsNullOrEmpty(sToAp... { str = str + delimeter; ......

Posted On Sunday, March 2, 2008 3:00 PM

Passing null parameters to String.Format is safe
I wanted to use String.Format with parameters that can be null. Firstly i decided to put some conditional code like if(arg1!=null) but then desided to check, if it is handled automatically. And from Reflector it looks that it handles nulls if (str2 == null) { str2 = string.Empty; } So it safe to write code like String.Format("({0}{1})", a1,a2 ) , even if some parameters are null ......

Posted On Wednesday, January 9, 2008 3:54 PM

use Activator.CreateInstance to dynamically load the concrete class and avoid Circular references
I have a Factory class that creates number of classes to handle different XML responses, returned by Web Service. All of them are derived from some base class GwsResponse and created depending on the top name element name. Previously factory and all created object classes were located in the same DLL. Now we need to increase number of handled responses, but we want new classes to create in separate extension DLL. We are going to use Activator.CreateInstance to dynamically load the concrete class ......

Posted On Monday, May 5, 2008 11:36 PM

TypeLoadExceptionHolder object can be inserted during unsuccessful Bynary Deserialization
I am using Binary Serialization to save and then reload state ot the object. In my post Issues using binary serialization to store object state for unit tests I described why I have to use it and how I tried to avoid versioning problems. I was able to read the object and access different properties of it withowt any warnings, but later, when the object was tried to be stored in Session, I've got the following error: System.Web.HttpException: Unable to serialize the session state. In 'StateServer' ......

Posted On Thursday, May 1, 2008 11:13 PM

Problems after Installing VS 2008 side-by-side with VS 2005
I have Visual Studio 2005 environment and decided to try VS 2008. I've read some articles(e.g. here) about site-by-site installation and had an impression, that making a copy of solution is enough. NOTE: If you are using TFS, before conversion of the existing solution, obtain and install Team Explorer Client . VS 2005 is using TFS Source Control, but VS 2008 shows no Source Control plug-in installed. . After installing of VS 2008 I've copied my existing solution as MySolution2008 and opened it in ......

Posted On Monday, January 28, 2008 11:59 AM

Insert new lines in XML text using Visual Studio.
UPDATE: I've recently was adviced that I can use VS command Edit/Advanced/Format Document(Ctrl-K,Ctrl-D) and it does better formating. I 've got XML files as one long string, not formatted. IE explorer shows them nicely with all indentation and ablility to collapse parts. However to edit or compare files using Windiff or Winmerge it will be convinient to have them with short lines, e.g. each element in a new line. Fortunately VS has ability to insert new lines in replace operation. 1.Click Ctrl-H ......

Posted On Monday, January 21, 2008 7:48 PM

SQL Server Reporting Services Notes
I am doing some work with "SQL Server Reporting Services" at the moment. So I am updating this post with different links, which makes the post quite messy. "Report Parameters" are not visible in XML code view .It seems that they are stored in database, but not in XML definition. See also Reporting Services Report Parameters CountRows Function -Returns a count of rows within the specified scope-the dataset, grouping, or data region. The "Every Other Page Is Blank" Feature -reduce size of Body to fit ......

Posted On Sunday, November 25, 2007 7:55 PM

DataView.Sort doesn't accept long name for direction
According to the documentation DataView.Sort is a string that contains the column name followed by "ASC" (ascending) or "DESC" (descending). Columns are sorted ascending by default. Multiple columns can be separated by commas. If you pass long name: Descending or Ascending (from System.Web.UI.WebControls.S... enum) the error is reported: System.IndexOutOfRangeExcep... Cannot find column LastName Descending. at System.Data.DataTable.Parse... sortString) at System.Data.DataView.Update... ......

Posted On Monday, October 22, 2007 8:06 PM

EnitySpaces: the same Query can be used to save multiple tables
I wanted to minimize number of calls to the database, but get back results of dynamic query for small number of columns, as well as detailed data(e.g Itinerary table and Itinerary joined with Itinerary items) .In EntitySpaces I've created a where condition, filled Query and loaded detailed data, then saved the returned table to DataSet. Then for the same query I've specified distinct select columns and Load it again(When LINQ will be available, it could be done in memory without extra database call). ......

Posted On Sunday, October 21, 2007 3:01 PM

Issues using binary serialization to store object state for unit tests
To save object state for unit tests we use binary serialization. The object state saved to data file and at the start of the test is loaded from the file. It works OK until the object will be changed in a new version. Fortunately There is no problem when a new field is added, but if a field is deleted or removed, it most likely will cause deserialization exception(see Version Tolerant Serialization, Net Serialization FAQ, Solving Binary serialization versioning conflicts articles for details). Also ......

Posted On Saturday, October 20, 2007 3:18 PM

Generic function to Find Duplicates in Generic List
I've created a new function to Find Duplicates in Generic List similar to Generic function to removeDuplicates from Generic List as well as bool AreValuesUnique. ]]> public static List<GenericType> FindDuplicates<GenericTy... inputList) { Dictionary<GenericType, int> uniqueStore = new Dictionary<GenericType, int>(); List<GenericType> finalList = new List<GenericType>(); foreach (GenericType currValue in inputList) { if (uniqueStore.ContainsKey(cu... ......

Posted On Thursday, October 18, 2007 4:02 PM

Stop background find in "visual studio" not always stops search
In VS 2005 (I have SP1) it is a toolbar icon called “Stops a background Find”, that suppose to cancel the find . However I noticed on my machine and on my colleage's machine, that sometimes VS hangs on searching(shows the search as processing, but doesn't change the filename on status bar).The button nether shortcut (Alt-F3,S) doesn't stop search and you need to close VS to re-enable searching. I don't have enough details to reproduce the problem, so it is pointless to report to MS Feedback site ......

Posted On Sunday, October 14, 2007 8:15 PM

Helper Classes that I am using.
I've posted a few helper classes, that I've created by myself or based on some others source code. There are also a few classes from other authors, that I am using in my applications without or with minor changes. Below I will list the links to their classes: Configuration: C#/.NET Command Line Arguments Parser(by the way, it was the first class in C#, that I included to VB solution) Custom app.config -load configuration settings from an external file(alternatively see Reading a config section from ......

Posted On Monday, September 3, 2007 6:35 PM

Generic function to removeDuplicates from Generic List
//created based on http://www.kirupa.com/net/r... //Why it is not in .Net Framework yet? Why HashSet<T> is only in Orcas(http://blogs.msdn.com... public static List<GenericType> removeDuplicates<Generic... inputList) { Dictionary<GenericType, int> uniqueStore = new Dictionary<GenericType, int>(); List<GenericType> finalList = new List<GenericType>(); ......

Posted On Tuesday, September 11, 2007 3:42 PM

"This SqlTransaction has completed; it is no longer usable." errors
Our system started to get intermittent errors like the foolowing in the code that was NOT changed recently: System.InvalidOperationExce... This SqlTransaction has completed; it is no longer usable. at System.Data.SqlClient.SqlTr... at System.Data.SqlClient.SqlTr... I was pointed to MS Kb http://support.microsoft.co... that I've installed, but it didn't change -errors still appeared. Unfortunately, the KB doesn't have a list of changed files and their ......

Posted On Monday, September 3, 2007 1:08 AM

Reading AppSettings to be Unit Test friendly.
My application uses a lot of AppSettings to enable/disable different function and I wanted to created unit tests for different combination. I found the simplest way is to create static class data field, that is set to null by default, and loaded from config file if it is null. This allows in unit test methods to explicitely assign values, and when you want return to reading from config file, just reset it to null. static private bool? st_bAPIEnabled; public static bool IsAPIEnabled() { st_bAPIDomesticEnabled ......

Posted On Wednesday, July 25, 2007 9:57 AM

Workaround "The incoming tabular data stream (TDS) remote procedure call (RPC) protocol stream is incorrect" error.
We have a .Net 1.1 application that worked with SQL server 2000. When we changed it to work with sql Server 2005, some calls to SPs returned errors like the following "The incoming tabular data stream (TDS) remote procedure call (RPC) protocol stream is incorrect. Parameter 8 ("@ParamName"): The supplied value is not a valid instance of data type numeric. Check the source data for invalid values. An example of an invalid value is data of numeric type with scale greater than precision." It was found, ......

Posted On Wednesday, June 20, 2007 12:45 AM

No Copy Constructor support in .Net framework.
I have a base class with a lot of data members and I wanted to create a constructor in derived class, that will take a base class as a parameter and assign all data members values from the parameter: class Derived: Base { Derived(Base baseClass) { //Assign all data } } The function is almost like Copy Constructor, so I tried to search Google for it. There is a discussion on MBR IT/.NET 247 : how to implement a C# copy constructor . where Jeffrey Tan from Microsoft Support suggested : public extendeddatagrid(MyDataGrid ......

Posted On Friday, May 25, 2007 12:46 PM

DataHelper.ExecuteDataset for different database providers
I have a small utility .Net that was used to transform data from one database to another. Initially it was written using SQLHelper DAAB class. Then it was extended to work with OledbHelper , that was created based on SqlHelper. Now it was requested to work with ODBC provider as well.I know, that I can use Enterprise library DAAB(e.g see here) , but I decided not involve additional DLLs and extra settings in config file for this simple application.The static finction to return dataset for specified ......

Posted On Monday, March 19, 2007 10:57 AM

Parser Error Message: Access to the path is denied. caused by SourceSafe merge.
I've used Visual SourceSafe Merge method to merge changes from different brunches of the ASP.NET site project. VSS created merged file, as well as renamed original file with .org extension. (By the way, it is not widely known, that VSS creates a backup copy of the original file filename.ext.ORG, that can be used to restore file, if merge unsucceded by some reason). However when I started to run the ASP.NET application in IIS, it caused "Access to the path" errors, e.g. Parser Error Message: Access ......

Posted On Thursday, January 4, 2007 11:24 AM

No way to specify namespace for Typed-Dataset

I am using typed datasets in my C# library and I desided to re-structure files -move .xsd file to sub-folder.
Should it effect my code? I expected, that it shouldn't. But  namespace of the generated typed-dataset has been changed and broke my code.

It seems there is no way to set it in the way I like - namespace is derived from folder and filename.
This is not good.

Posted On Friday, December 29, 2006 9:57 AM

Visual Studio 2005 SP1: Unable to detach from one or more processes
I've just updated VS 2005 to SP1. I am using WAP project with DevServer and enabled "Edit and Continue". My common procedure is to start debugging session, do the changes in the code if required, and if the code is blocked by VS(very annoying, but MS doesn't want to fix it) ,I detaching the debugger from the project. In SP1 it started to show error:Unable to detach from one or more processes. Operation not supported. Unknown error: 0x80131c32.It is not always reproducible, but happened a few times ......

Posted On Thursday, December 28, 2006 7:45 AM

Print UserAccountControl AD property programmatically.
Even there are a few standard AD Editors, including AD MMC, ADSIEdit, and LDM, I needed to read the UserAccountControl AD property from my application. UserAccountControl is a bit flags attribute, so I had to create C# enum similar to C++ ADS_USER_FLAG_ENUM enum from MSDN. Below is the code of functions GetUserAccountControl(Direc... anEntry) and UserAccountControlToString(... nUserAccountControl) : public static int? GetUserAccountControl(Direc... anEntry) { //MNF 10/8/2005 if Properties["userAccountCont... ......

Posted On Friday, December 8, 2006 9:01 AM

Update appSettings in App.Config for executable.
I wanted programmatically (for administrator) to update configuration settings for .Net 2.0 executable. The new in VS 2005 Properties.Settings class saves only user-scope settings, not application scope, which is inconvinient. I've decided to use The easiest way to read/write AppSettings from the very good article Read/Write App.config with .NET 2.0/Enterprise Library However I noticed two issues: config.AppSettings.Settings (KeyValueConfigurationColle... class) has Add and Remove methods, but ......

Posted On Tuesday, November 21, 2006 3:48 PM

Dataset.Merge should invoke virtual Table.Clone for copied tables.
In my previous post I described a problem when Typed Dataset merged into un-typed dataset.I've reviewed the code of Dataset.Merge using Reflector and found, that if table doesn't exist in the current dataset, Table.Clone is called(in internal private DataTable Merger.MergeSchema function) to add a new table to the dataset.Unfortunately,they do not call virtual Table.Clone() method, that is overridden by the derived typed dataset, but use internal DataTable Clone(DataSet cloneDS),which can't be overridden ......

Posted On Saturday, November 11, 2006 8:32 AM

After Merge of Typed Dataset access to row fields causes System.ArgumentException
I am using typed dataset(generated by VS 2005) that I merged to empty dataset (actually to class, derived from dataset). When I am accessed a particular row and tried to read value of the row field, I've got System.ArgumentException: Column <ColumnName> does not belong to table <TableName>. at System.Data.DataRow.CheckCo... column) After debugging and digging into Designer generated code, I found that the cause is that the generated typed-safe columns have property Table as ......

Posted On Friday, November 10, 2006 12:58 PM

Calling C unmanaged DLL with with output parameters char **result from C#
In C# library I wanted to call c function from YAZ library YAZ_EXPORT int yaz_marc_decode_buf(yaz_marc_t mt, const char *buf, int bsize, char **result, int *rsize); The problem was that I didn't know how to specify char **result in managed declaration. I didn't find similar samplers in Zoom.NET implementation.The article Call Unmanaged DLLs from C# recommended to use StringBuilder for LPSTR (char*) but it wasn't enough. After some experimentation I found that adding ref will do the trick(which makes ......

Posted On Tuesday, October 31, 2006 1:19 PM

Invoke Executable as custom action during Install.
I've used MS Installer class to provide custom actions during setup in a few projects(e.g.see Using VS 2005 Web Setup Project with custom actions).However if you have some complex logic to do as a part of setup, it is possible that some exception will occur. I don't like to hide exceptions, and they are shown to the user,causing installation to rollback. It is not good, becuse sometimes user wants to ignore exception and use installation even if some custom action failed.I found that moving code ......

Posted On Monday, October 23, 2006 11:14 PM

.Net SQL Parser
I had a requirement to parse SQL string, in particular with CONTAINS(column_list) and modify SELECT column list.I've found two most promising implementations General SQL Parser from http://www.sqlparser.com/ and SharpHSQL from http://www.c-sharpcorner.co... article. General SQL Parser has quite qood API, but it doesn't have open source and doesn't recognize contains with column_list. SharpHSQL is a early C# port of the HSQL Database Engine which has a source code, but also doesn't ......

Posted On Saturday, August 12, 2006 3:36 PM

Debug helper functions for Regex/Match classes
I've created debug functions PrintMatch, PrintMatchCollection and PrintRegexGroups that allowed to output information from Regular Expression classes, that not always easy to view in debugger. They are included in my Utility to Remove CodeBehind attribute From Ascx files that helps to use WAP User Control Libraries from Web Site Project. ......

Posted On Friday, August 4, 2006 4:53 PM

ImportRow to DataTable with reference to a new row
The MS .Net framework DataTable.ImportRow doesn't return reference to a new row. Also it is not documented how ImportRow will behave if record with primary keys already exist. So I've created a static "overload" of DataTable.LoadDataRow method. The common mistake that I had was that DataTable didn't have schema filled, and primary keys were empty. It caused that even existing records were considered as new, and duplicates were imported. So I've added a CheckPrimaryKey parameted, which is recommended ......

Posted On Wednesday, August 2, 2006 12:38 PM

VB.Net compiler error when compare with Nothing.
I've got a compiler error Compiler Error Message: BC30452: Operator '<>' is not defined for types 'BaseResultItemsListUsc' and 'BaseResultItemsListUsc'. If listResults <> Nothing ThenEnd If Of course, the correct code should be If listResults isNot Nothing ThenorIf Not (listResults is Nothing) ThenorIf Not IsNothing(listResults) Then I made a search that there are a few other places where the <> Nothing was used e.g. If Request.QueryString("Field") <> Nothing then dim r as ......

Posted On Monday, July 24, 2006 8:54 AM

use VS 2005 or VS 2003 due to VS 2005 slowness?
One reader of my post “How to fix "Visual Studio 2005 is very slow" problem -no solution so far“ asked me should he use VS 2005 or VS 2003: “We recently moved from VB6 environment to .net. We started our project in VS 2005 , asp.2.0 . But the issue is VS 2005 is VERY Slow on our computers. My Team members are getting frustrated. I increased the Ram to 1 GB... still no significant improvement! (yet to implement the hot fix).” I've posted his questions and my answers here: 1) ......

Posted On Wednesday, July 19, 2006 10:37 AM

my DebugHelper and TraceHelper classes
I've posted a few code snippets and some people noticed that there are references to unresolved methods. I am using a few helper classes. This post describes my DebugHelper and TraceHelper classes. namespace FSHelperLib { using Microsoft.VisualBasic; using Microsoft.VisualBasic.Compi... using System; using System.Collections; using System.Data; using System.Data.SqlClient; using System.Diagnostics; using System.Collections.Specialized ; using System.IO; using System.Net; using System.Runtime.CompilerServ... ......

Posted On Thursday, July 13, 2006 8:13 AM

Calling VS 2005 tests from Windows forms test harness
I like VS 2005 Team System ability to generate test cases. Using it with TestDriven.Net “Test with Debugger” allows quickly debug and test a new or existing code. However if you do a relatively long debugger session with multiple edit changes, the test session is often interrupted. I found that “Edit and Continue” for Windows form(or console) application is more stable. So my question was: can I call TestMethod from Windows form test harness? The answer is YES, no problem. You need to add reference ......

Posted On Thursday, July 6, 2006 3:57 PM

Ado.Net 2.0 How SqlCommandBuilder works.
I've debugged my code that uses SqlCommandBuilder: Dim daJoinTable As New SqlDataAdapter(sSQLSelect,c... Dim cbJoinTable As New SqlCommandBuilder(daJoinTable) daJoinTable.Update(dsJoinTa... and noticed that daJoinTable.UpdateCommand,I... and DeleteCommand are nulls, when I expected that they will be generated by SqlCommandBuilder. Even if code works fine, I was curious, how dataadapter knows which update SQL command should be used. I found a good article about SqlCommandBuilder, ......

Posted On Thursday, July 6, 2006 10:40 AM

Thread-safe MessageBox in Windows form
I've used TestEmailer.TestForm from A class for sending emails with attachments in C#. and got an InvalidOperationException that related to How to: Make Thread-Safe Calls to Windows Forms Controls. The following code is how to make event handler safe. private void OnMailSent() { SetStatusBar("Mail sent.");// statusBar.Text = "Mail sent."; //MessageBox.Show(this, "The mail has been sent.", "Mail Sent", MessageBoxButtons.OK, MessageBoxIcon.Information); ShowMessageBox("The mail has been sent.", "Mail ......

Posted On Tuesday, July 4, 2006 11:04 AM

Running Jscript demo functions from MSDN samples.
I’ve tried to port Query Parser written in JScript from Integrating User Search with ASP and Microsoft SQL Server Full-text Search to C#. The “Converting JScript.NET to C#” tool is quite useful, but doesn’t do all the job. I wanted to understand RegExp properties , but MSDN JScript help example doesn’t show output. So I’ve wrote simple exampleRun.js using WScript.Echo: WScript.Echo (matchDemo()); function matchDemo(){ var s; var re = new RegExp("d(b+)(d)","ig"); ......

Posted On Wednesday, June 21, 2006 7:53 AM

Set a property for ISSWebFile in subfolder.
Recently I posted class that I am using to Programmatically set IIS Authentication for a page. Later I found that initial implementation almost never worked because files in subfolders usually do not have explicit entries in the metabase, but inherit all properties from the parent. I've added code to create metabase entry (similar to this). But if the file is in subfolder, not in the virtual directory, adding the SchemaClassNames="IIsWebFile" doesn't work (see discussion Creating Virtual Directories ......

Posted On Friday, June 16, 2006 9:01 AM

Configuration.Save Method parameters combination
I've reported to MS that documentation of Configuration.Save Method (ConfigurationSaveMode, Boolean) is not detailed enough and they provided the clarification: The ConfigurationSaveMode parameter can have one of the following values: Full Causes all properties to be written to the configuration file. This is useful mostly for creating information configuration files or moving configuration values from one machine to another. Minimal Causes only properties that differ from inherited values to be ......

Posted On Friday, June 9, 2006 7:41 AM

Using Configuration.Section to access subsection
I have a section in Web.Config: <applicationSettings> <FSBsnsCsLib.Properties.... ... </FSBsnsCsLib.Properties... </applicationSettings> I've tried to access inner section using shortcut “Section/Subsection&#... string sSectionName="applicationSe... sectSettings = (ClientSettingsSection)conf... but it returned null. The correct way is the following: const ......

Posted On Friday, May 12, 2006 8:08 AM

Installing ASP.NET 2.0 Application -ensure that it runs ASP.Net 2.0
For my Web Setup (created by MS Visual Studio Setup Project) I wanted to ensure that a new web application runs ASP.Net 2.0. Pointed by this thread, I downloaded "IIS Chameleon". I've changed the assembly toDLL, excluded Non GUI classes, made ASPNetVersion,INETMGRHelper and CURRENT_RUNTIME_VERSION public and also changed definitions.xml to be embedded resource(may be not a good idea, because it will not allow to customize, but easier to distribute). I also changed GetAllASPNETVersions to read from ......

Posted On Thursday, April 27, 2006 1:09 PM

Parameters for WebConfigurationManager.OpenWebConfiguration(RootVDir, SiteNumber)
I needed to open web.config file from the external application(setup utility). I decided to use WebConfigurationManager.Ope... function. In the documentation it is not clear, that path should started with “\“ , e.g “\MyWebApp“.Passing “MyWebApp“ without leading “\” causes error. If I want to use metabase site path (e.g "/LM/W3SVC/1") instead of name of the application Web site, I can to pass “1“ as site parameter and it is fully acceptable(but not documented) ......

Posted On Tuesday, March 28, 2006 12:27 PM

MetaBuilders.ComboBox compile with Visual Studio 2005
I am using MetaBuilders.ComboBox[^] (see my previos posts here and here) and now compiled it with VS 2005.New compiler is more strict . It showed couple compiler errors “Cannot access protected member 'System.Web.UI.WebControls.... via a qualifier of type 'System.Web.UI.WebControls.... the qualifier must be of type 'MetaBuilders.WebControls.C... (or derived from it)“ for code linescontainer = new WebControl(); andbutton = new WebControl(); Fortunately ......

Posted On Friday, March 24, 2006 10:06 AM

Unexpected Changes in AxInterop.SHDocVw.dll
I had an existing .Net code that used WebBrowser Active-X control using AxInterop.SHDocVw.dll. I am not sure was it generated by VS or downloaded as primary interop. There were a few calls in the VB code with not specified optional third parameter like this: frmENQ.Web.ExecWB(SHDocVw.O... SHDocVw.OLECMDEXECOPT.OLECM... , z) Recently I tried to re-build the code and found the errors: Argument not specified for parameter 'pvaIn' of 'Public Overridable Sub ExecWB(cmdID ......

Posted On Wednesday, March 15, 2006 7:31 AM

Set defaultProxy configuration Element for Proxy Server
Some customers of our application have ISA Server that requires Proxy Authentication. When ASP.NET applcicationed called external web services (e.g. Google APIs) it caused the error: The request failed with HTTP status 407: Proxy Authentication Required ( The ISA Server requires authorization to fulfill the request. Access to the Web Proxy service is denied. ). In .Net 1/1.1. it was required to set in code myProxy.Credentials = CredentialCache.DefaultCred... . Now in .Net 2. there is a new defaultProxy ......

Posted On Wednesday, March 8, 2006 11:19 AM

Function to Clone DataView with new sort column(s)
I have a filtered DataView and I wanted to search it using different keys that was used for sorting. Ther is no function out-of-the-box, so I created a helper method public static DataView CloneDataView(DataView vwSource,string newSort) { return new DataView(vwSource.Table ,vwSource.RowFilter,newSort... ; } Another function to create new DataView with extra filter: public static DataView NewDataViewWithExtraFilter(... vwSource, string newFilter) { string sFilter = vwSource.RowFilter; ......

Posted On Thursday, March 2, 2006 1:20 PM

Change NullValue behavior for generated Typed Datasets in Visual Studio 2005.
Update: I found that the issue with similar solution is already discussed in “Setting NullValue property for typed dataset” blog In generated Typed Datasets attempt to access field with DBNull value by default throw an exception. It is usually not convinient, and I prefer to change nullValue annotation to _null, as it was suggested here However I didn't find a way to change the default(Anyone knows???). I have to open each column in desigher and change the nullValue to _null. Alternatively I have ......

Posted On Thursday, March 2, 2006 9:23 AM

Partial classes in .Net 2.0 do not allow to split property into different classes

I've started to use partial classes features and wanted to add set property to the read-only property (with get only) generated by VS.

But it is not allowed, which is fair enough.

So to add “set” functionality I have to create method or property with different name.

Posted On Thursday, March 2, 2006 7:15 AM

Different Web Setup Projects should have different output directories in Visual Studio 2005
I have 2 similar Setup Projects in Visual Studio 2005 solution. Actually second project was copied from the first one and some changes were done. The first project has ouput file set as “Release\Project1.msi... and the second ““Release\Proje... I expected that “build solution“ will create both .msi files in the output directory. However the second project cleans the output directory during build , and the Project1.msi was deleted. The solution was to ......

Posted On Friday, February 24, 2006 2:07 PM

Dynamic Web Services reference URL in Visual Studio 2005
I am using dynamic URLBehavior for some web services and during Setup change web services URLs to appropriate value (based on MSDN article). According to MSDN2: If you set the URL behavior of the Web reference to dynamic, the application obtains the URL at run time from the appSettings element of your application's configuration file. However I've noticed that app.config file has entries for the same URL in both appSettings and <applicationSettings>. After reading the generated code (Reference.vb/cs) ......

Posted On Friday, February 24, 2006 9:01 AM

"Visual Studio 2005 is very slow" -some tips for ASP.NET projects
I am very disappointed with performance of VS 2005, in particular when building ASP.NET web site projects. I've tried a lot of suggestions. 1.Workaround Description: Delete windows.prf & windowsidx.prf from C:\Documents and Settings\\Application Data\Microsoft\Visual Studio\8.0\ . Seems has no effect. 2 Uncheck Navigation bar. 3.Disable wordwrap at: Tools>Options>TextEditor >C#>General4. My project had referenced DLLs located on shared folder on remote computer. When I moved DLLs ......

Posted On Tuesday, February 21, 2006 8:14 AM

Visual Basic function IsDate depends on Current Culture.
I was puzzled when VB function IsDate(20/02/2006) returned false( in Australia date format is dd/mm/yyyy). After investigation using Reflector I found that it uses Thread.CurrentThread.Curren... and my ASP.NET application wasn't set to use AU culture by default. Using CurrentCulture does make sense, but it is not documented in MSDN. ......

Posted On Monday, February 20, 2006 11:29 AM

Backup source files using MSBuild project.

I wanted to create batch to backup source files from my Projects folder, but also exclude some folders that I do not use.

I was amased how quickly I was able to do it using MSBuild project without any previous experience with the tool.

I've posted details  here. 

Posted On Friday, February 17, 2006 2:09 PM

Parsing web.config with XmlDocument.SelectSingleNode
I have an utility that modified ASP.NET web.config using code like this: XmlDocument document = new XmlDocument();document.Load... nodeParent = document.SelectSingleNode("... I found that this code doesn't work with VS 2005 (SelectSingleNode returns null) because configuration element has xmlns <configuration xmlns="http://schemas.micro... . I was able to delete xmlns attribute without any visible side effects to make ......

Posted On Thursday, February 2, 2006 1:17 PM

Using VS 2005 Web Setup Project with custom actions
I've used VS 2003 Web Setup Project with custom actions and Installer class. that did some changes. After moving to VS 2005 I found that it is not possible to invoke custom action for DLL because only content output is available. The post suggested to use VS 2005 Web Deployment Project . However in my case compile failed with the very helpful Aspnet_merge.exe Exited With Code 1. Some posts explain that the error comes from duplicate class names in the project, even if the name comes from different ......

Posted On Thursday, February 2, 2006 12:02 PM

Namespace can't be shared between 2 assemblies in Visual Studio 2005
I have VB library that references C# library. C# library has a few classes with namespace FSWeb. And a few VB modules called this classes without any problem. When I've added to the VB Project a new class with the same namespace specified, the c# classes became invisible in all VB classes for both compiler and intellisence with the errors like: Error 231 'Search' is not a member of 'FSWeb'. Error 230 Type 'FSWeb.LoginHelper' is not defined. When I type “FSWeb.” intellisence shows only ......

Posted On Thursday, February 2, 2006 7:16 AM

Suggestions/bugs ranking on MS product feedback site
I've recently posted a few suggestings/bugs to MS Product Feedback site. They have Top Bugs/Suggestions (How we rank?) section, but I found that their way to use average vote is not appropriate. In the current approach bug with 3 users rated 5 has bigger rank, that the bug with 60 users voted with average 4.96( almost all rated as 5 and a few rated less).Also if I want to vote for the suggesting/bug, but consider it less than 5, I could reduce average rate and subsequently overall rank, even if I ......

Posted On Wednesday, January 18, 2006 9:52 AM

Quick Start of Debugger in VS 2005 Tip required manually handle Dependencies.
Because VS 2005 seems much slower compare with VS 2003, I was very excited when read a tip , that suggested to uncheck libraries from Configuration Manager. And it really improves the speed of start up.( I don't understand why dependency check became so slow in VS 2005) I have DotNetNuke web site project and a few library projects, both DotNetNuke and my own. The problem happened when I changed the code in one of the libraries. It was quite obvious that I had to re-build the library which I've changed.But ......

Posted On Tuesday, January 17, 2006 9:23 AM

GetTypeFromCLSID changes in .Net Framework 2.0
My application, written for .Net 1.1, used GuidAttribute of Type to uniquely identify classes and then load different classes, based on specified GUID passing to GetTypeFromCLSID. The classes were not COM classes. The functionality is broken in .NET 2.0 as documented here. Now GetTypeFromCLSID returns valid type only if the class is COM object (Type.IsComObject() returns true) and is registered as COM class. Managed class with matched GuidAttribute will not be returned by GetTypeFromCLSID(guid) . ......

Posted On Wednesday, January 11, 2006 8:54 AM

DirectorySearcher.FindAll() -should have PageSize=1000
When you are calling DirectorySearcher.FindAll() and there is a chance to have more than 1000 records back, you must set PageSize to non-zero value, preferably 1000. Otherwise only the first 1000 records will be returned and other entries will be missed without any warning. The names of DirectorySearcher members and documentation is quite messy. FindAll() method should return ALL records, not the first 1000. Setting PageSize doesn't mean that you get back only single page, but triggers returning ......

Posted On Tuesday, December 20, 2005 7:01 AM

COMException (0x80004005): Unspecified error] in DirectorySearcher.FindAll() means LDAP string is invalid.
I've got an error COMException (0x80004005) when called DirectorySearcher.FindAll() and had no idea, why it happened. Thanks to DirectorySearcher.FindAll() causes Unspecified Error in C# but not in VB.NET discussion I was pointed, that the error is shown if DirectorySearcher.SearchRoot path is not valid, e.g. it is “DomainName” instead of “LDAP://DomainName... I beleive MS could provide more clear error description ......

Posted On Monday, December 19, 2005 10:58 AM

Differences between Visual Basic Trim function and String.Trim() method
Today I recognized that Visual Basic Trim function removes spaces only, but String.Trim() method removes all white space characters(see Remarks here) including newline and carriage return. The following C# sample confirms this: public void VBTrim_Test() { string str="string" + '\r' + '\n'; Debug.WriteLine(String.Form... of {0} is {1}", str,Microsoft.VisualBasic.S... str=Microsoft.VisualBasic.S... Debug.WriteLine(String.Form... VB trim length of {0} is {1}", ......

Posted On Friday, November 11, 2005 1:11 PM

Copyright © Michael Freidgeim | Powered by: GeeksWithBlogs.net