My Blog has been MOVED to https://mfreidge.wordpress.com
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... ......
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 ......
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... ......
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], ......
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... ......
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 ......
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... ......
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... ......
.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 ......
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 ......
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 ......
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 ......
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, ......
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... ......
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 ......
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 ......
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, ......
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... ";"); ......
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 ......
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... ......
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... ......
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... ......
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. } ......
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 ......
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 ......
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... ......
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 ......
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... ......
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; } ......
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... ......
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 ......
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 ......
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 ......
// <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; } } ......
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... ......
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... } } ......
/// <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(); ......
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() ......
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"- ......
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 ......
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 ......
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); } ......
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 ......
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 ......
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 ......
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 ......
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, ......
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); } } ......
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 ......
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 ......
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 ......
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; ......
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 ......
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 ......
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 ......
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, ......
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 - ......
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, ......
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; ......
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> ......
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 ......
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... ......
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 ......
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]; } ......
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. ......
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 ......
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; } ......
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 ......
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 ......
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; } ......
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 ......
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 ......
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 ......
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 ......
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 ......
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' ......
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 ......
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 ......
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 ......
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... ......
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). ......
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 ......
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... ......
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 ......
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, ......
//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>(); ......
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 ......
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 ......
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 ......
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 ......
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 ......
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 ......
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 ......
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 ......
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.
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 ......
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... ......
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 ......
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); } } ......
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 ......
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") ......
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. ......
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 ......
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 ......
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 ......
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 ......
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 ......
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 ......
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. ......
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 ......
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 ......
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) ......
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... ......
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 ......
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, ......
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 ......
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"); ......
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 ......
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 ......
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 ......
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 ......
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) ......
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 ......
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 ......
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 ......
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; ......
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 ......
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.
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 ......
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) ......
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 ......
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. ......
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.
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 ......
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 ......
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 ......
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 ......
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 ......
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) . ......
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 ......
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 ......
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}", ......