Let me start by saying that Microsoft don't consider this issue as a problem, as you can see here this is a “by design” behavior.
The problem is well described in the referred Connect feedback and it contains a workaround.
Although simple, the workaround requires you to always register the GridView Sorting event and make the tweak according to the current GridView settings. Well, if are like me you will forget to do it half the times needed.
So, I made a not so simple workaround that will take care of the issue for me.
I override the OnSorting method from GridView so I can handle the GridViewEventArgs instance and override its SortDirection value.
To turn this into a general solution I partially reproduce the ParseSortString method from DataTable to find out if the current SortExpression contains either the ASC or DESC keywords.
Here is the code:
public class GridView : global::System.Web.UI.WebControls.GridView
{
protected override void OnSorting(GridViewSortEventArgs e)
{
if (!string.IsNullOrEmpty(this.SortExpression))
{
if (this.SortExpression.Equals(this.SortExpression))
{
bool isMultipleSortExpression;
SortDirection? sortDirection = GetSortDirection(this.SortExpression, out isMultipleSortExpression);
if (sortDirection.HasValue)
{
// To undo bug in GridView.HandleSort(string sortExpression) and then in GridView.CreateDataSourceSelectArguments()
e.SortDirection = SortDirection.Ascending;
}
}
}
base.OnSorting(e);
}
private SortDirection? GetSortDirection(string sortExpression, out bool isMultipleSortExpression)
{
SortDirection? sortDirection = null;
isMultipleSortExpression = false;
string[] strArray = sortExpression.Split(new char[] { ',' });
for (int i = 0; i < strArray.Length; i++)
{
string strA = strArray[i].Trim();
int length = strA.Length;
if ((length >= 5) && (string.Compare(strA, length - 4, " ASC", 0, 4, StringComparison.OrdinalIgnoreCase) == 0))
{
sortDirection = SortDirection.Ascending;
}
else if ((length >= 6) && (string.Compare(strA, length - 5, " DESC", 0, 5, StringComparison.OrdinalIgnoreCase) == 0))
{
sortDirection = SortDirection.Descending;
}
if (!sortDirection.HasValue)
{
break;
}
}
if (sortDirection.HasValue)
{
if (strArray.Length > 1)
{
isMultipleSortExpression = true;
}
}
return sortDirection;
}
}
Enjoy it.
Next October, 2 ReMIX 09 will be in Portugal.
I’ll be there.
If you are nearby, take the chance and came visit us.
Hope to see you there.
A very common mistake taken by junior ASP.NET developers is forgetting that any web application running in a IIS instance will most likely run in a multithread environment.
They forgot that, unlike the dev environment which usually runs in a single thread pool, production environment usually have a working thread pool with several dozen threads.
Common mechanism like the ASP.NET Cache or the ASP.NET Session have points of concurrency.
It’s common to create singletons in web apps. The most common scenario are provider pattern implementations. Many times, apps also need to have it’s own Cache mechanism or even Session mechanism. All this scenarios may leads us to multi thread racing for some resources.
Testing those code pieces were almost impossible … and multithread bugs and deadlocks were detected late in the application developing cycle:
- when running load tests
- or, in the worst scenario, only in a production environment.
Those days are gone … last May Typemock added a new tool to its toolkit, the Typemock Racer.
This new tool is intended to help finding and fixing possible deadlocks by enabling us to write threaded tests.
And if you think that this is a complex task to do, you are wrong. Doing race tests is as simple as writing a unit test and then decorate it with an attribute – [ParallelInspection].
That’s it .. you can then run the test and Racer will try to find and recreate deadlocks.
In future Racer will also check for race conditions.
Take a look at this Roy Osherove post for some snapshots and a little movie.
This toolkit is intended to improve web apps performance by decreasing total page size. This page size reduction is achieved by decreasing control ClientID size.
It’s been a year since I first made the code available at code.msdn.microsoft.com and now I decided to migrate it to CodePlex.
Try it !!!
In most common samples about faking static types, the type itself is public as the static methods are too.
Usually programmers tend to expose all members that going to be targeted by an Unit test. Well, that’s not how I see Unit tests.
I always try to produce code to keep the cyclomatic complexity lower, and If I succeeded I ended up with types that can be easily tested.
I won’t expose code simply to test it, code should always have the minimum visibility that it indeed requires.
Then I rely on tools to test all my type members, either private, internal or public.
Currently I use the Typemock Isolator and I must say that I’m completely satisfied.
So, here’s how I faked an internal static type and also override it’s GetString method to allow me test the first parameter value:
Type globalizationHelperType = Type.GetType("NG.Helper, NG", true);
Isolate.Fake.StaticMethods(globalizationHelperType);
Isolate.WhenCalled(() => globalizationHelperType.GetMethod("GetString", new Type[] { typeof(String) }).Invoke(null, new object[] { null })).DoInstead((callcontext) => { return callcontext.Parameters[0]; });
I’m not used to use Finalizers in my everyday job but I always thought that if I use it more frequently I could achieve some extra performance.
Well, I’m a natural lazy programmer and that prevents me from digging deeper and doing some tests to clarify this guess.
Thanks to community, there is always someone ready to share knowledge and help those lazy guys like me.
One of those guys were Andrew Hunter that posted an article named “Understanding Garbage Collection in .NET”.
In is article I found that:
- The Finalizer execution is non deterministic – it depends on GC and the way it’s operating: concurrent or synchronous.
- It requires two GC cycles to completely remove the object and memory footprint.
- Two many objects with Finalizers could slow down GC a lot
This don't mean that we shouldn’t use Finalizers, but we must take same care when we create Finalizers. The simplified way to Finalizer usage is:
- Implement System.IDisposable interface
- move Finalizer code to Dispose method
- Finish Dispose method execution with a GC.SupressFinalize() operation, this way the GC will know that this object wont need the Finalizer invocation and can be remove immediately.
- Invoke Dispose method in Finalizer – this way we ensure that external resources were always removed.
A deeper understand on this procedure, also known as the IDisposable Pattern, can be acquired by reading this article (kindly pointed by Luis Abreu).
Conclusion
Using finalizers don't bring any performance improvement but it’s wrong use can be a vector for severe memory management problems.
When we have a class that own external reference not managed automatically by Runtime then the IDisposable Pattern should be used to ensure the correct memory cleanup.
Finding out whether an assembly was compiled in Debug or Release mode is a task we must do from time to time.
I know two ways of accomplish this:
Either attributes are applied to Assemblies and can be found in the Assembly Manifest but there are a major difference between them:
- AssemblyConfigurationAttribute must be added by the programmer but is human readable.
- DebuggableAttribute is added automatically and is always present but is not human readable
You can easily get the Assembly Manifest by using the amazing ILDASM from your Visual Studio Studio Command Prompt:
And if you double click the MANIFEST item you will get all manifest data.
Looking carefully you will find the DebuggableAttribute:
And perhaps the AssemblyConfigurationAttribute:
AssemblyConfigurationAttribute
Locate the AssemblyConfigurationAttribute – this attribute can be easily interpreted: its value can either be Debug or Release
DebuggableAttribute
If AssemblyConfigurationAttribute is not present then we must use the DebuggableAttribute to get our goal.
Since we cannot understood the DebuggableAttribute value we have to open the assembly from another tool and read this attribute content. There’s no such tool available out-of-the-box but we can easily create a Command Line tool and use a method similar to:
private bool IsAssemblyDebugBuild(string filepath)
{
return IsAssemblyDebugBuild(Assembly.LoadFile(Path.GetFullPath(filepath)));
}
private bool IsAssemblyDebugBuild(Assembly assembly)
{
foreach (var attribute in assembly.GetCustomAttributes(false))
{
var debuggableAttribute = attribute as DebuggableAttribute;
if (debuggableAttribute != null)
{
return debuggableAttribute.IsJITTrackingEnabled;
}
}
return false;
}
or (if you prefer LINQ)
private bool IsAssemblyDebugBuild(Assembly assembly)
{
return assembly.GetCustomAttributes(false).Any(x => (x as DebuggableAttribute) != null ? (x as DebuggableAttribute).IsJITTrackingEnabled : false);
}
As you can see … it’s pretty simple.
Note:
Tipically I add a pre-build task to my build server so that the AssemblyConfigurationAttribute is added to the CommonAssemblyInfo file with the appropriated value: either “Debug” or “Release”. This way anyone can easily see, using only the ILDASM, which king of compilation was used to generate my assemblies.
Until 5 June the SmartBear is offering a five seat license of the new CodeReviewer 5.0, with full support and that never expires, for only 5 USD.
You must note that usually each user license is sell for 289 USD.
CodeReviewer is a web-based tool that simplifies and expedites peer code reviews and is specially oriented for small teams.
With such a price it’s a must have … even for our small pet projects.
Most web applications display messages to users. Displaying messages is the most effective way to inform user about errors and warnings or to simply display info or success status.
I also believe that most of those web applications renders user messages using HTML elements such as Div, Span or Label.
The others, mainly because their complex layout or business rules, have to render those messages using a different approach: they render each display message as a Javascript function call where the message itself is a function parameter. Such call could be simply like this:
string.Format("top.addMessage(\"{0}\");", message)
Those of you that already faced this problem won’t learn nothing new but I hope to alert the others and avoid them to face a problem that usually is only detected in advanced develop stage or even production environment.
Problem
The problem turns visible when the display message contains some special characters that prevent the function call to execute and trigger javascript errors.
Typically the characters are “ and ‘ but there are more.
Well, that is not completely correct, only the character “ is problematic, since he is the JSON string delimiter character, but, javascript engines also accept the character ‘ as a delimiter. The best way to avoid problems with ‘ is to ensure that the correct delimiter is used.
By now, you should be thinking that your applications are immune to this problem. Tell me, do you use string Resources? Most of us use, it’s a best practice and a smart choice. Also tell me, do you manage production string Resources? Most of us don’t. In fact, the application owner or sponsor can change it completely outside of your control scope.
String Resources are one of the major vectors of this problem but you can get this problem simply by trying to display an exception message:
string.Format("top.addMessage(\"{0}\");", exception.ToString())
Solution
What we are needing is an JScript.Encode method or similar that encode a C# string in such a way that it becomes a JSON encoded string.
Such method is not available on NetFX but, fortunately, Rick Strahl made a great post about this problem and made available a method that fits perfectly our needs.
Now that you know about it … use it.
This is subject to which I ended up returning from time to time, either for professional purposes, for some pet project or simply to help a friend.
For those of you that already played with Menu control knows that applying CSS styles to the standard ASP.NET Menu control can be a real frustrating task. For all the other I hope that this post avoid or at least reduce this pain.
Problem
The main question regarding styles is how the control renders. The Menu control renders HTML element TABLE, TR and TD and this approach bring us two main problems:
- Turns CSS style configuration more complex
- Increases the overall HTML size
I’m not sure why the control renders like this but I believe is related to multi browser CSS compatibility. We must not forget that even today we face several multi browser CSS problems (with IE8 the differences went minimal but we still have to deal with older browsers for many years) and by the time NetFX 2.0 saw the daylight the gap between browsers were larger and rendering HTML elements TABLE, TR and TD was the one that offered less compatibility issues.
Solution
Fortunately, ASP.NET 2.0 added the concept of ControlAdapter. This is a piece that can be associated to a control type and enable us to change the way that control renders.
As you can imagine, this opened a door to adjust controls without changing the control itself. But, there’s always a but, those kind of associations Adapter/Control are (out of the box) an application setting.
The mapping is made with a Browser Definition File Schema that should look similar to:
<browsers>
<browser refID="Default">
<controlAdapters>
<adapter controlType="System.Web.UI.WebControls.Menu"
adapterType="YourMenuAdapter" />
</controlAdapters>
</browser>
</browsers>
These files should be deployed to the App_Browsers folder.
Now that we know about the ControlAdapters is clear that we need one to the Menu control. Since I’m a lazy programmer, I won’t create from scratch a MenuAdapter. Instead I will use an existing one.
You can find in CodePlex a project that give us a set of Adapters very useful in most common scenarios: ASP.NET 2.0 CSS Friendly Control Adapters.
Between those adapters there’s a specific one for the Menu control. This adapter renders the Menu control as an unordered list using Div, Ul e Li HTML elements and this way allow us to easily apply CSS styles without loosing multi browser compatibility and with less Html signature. Here is an Html sample:
<div class="AspNet-Menu-Horizontal">
<ul class="AspNet-Menu">
<li class="AspNet-Menu-WithChildren AspNet-Menu-Selected"><a href="javascript:__doPostBack('ctl00$B$fvMenu','bTest 0')"
class="AspNet-Menu-Link AspNet-Menu-Selected">Test 0</a>
<ul>
<li class="AspNet-Menu-WithChildren AspNet-Menu-ParentSelected"><a href="javascript:__doPostBack('ctl00$B$fvMenu','bTest 0\\Test 1')"
class="AspNet-Menu-Link AspNet-Menu-ParentSelected">Test 1</a>
<ul>
<li class="AspNet-Menu-Leaf AspNet-Menu-ParentSelected"><a href="javascript:__doPostBack('ctl00$B$fvMenu','bTest 0\\Test 1\\Test 1a')"
class="AspNet-Menu-Link AspNet-Menu-ParentSelected">Test 1a</a> </li>
<li class="AspNet-Menu-Leaf AspNet-Menu-ParentSelected"><a href="javascript:__doPostBack('ctl00$B$fvMenu','bTest 0\\Test 1\\Test 1b')"
class="AspNet-Menu-Link AspNet-Menu-ParentSelected">Test 1b</a> </li>
<li class="AspNet-Menu-Leaf AspNet-Menu-ParentSelected"><a href="javascript:__doPostBack('ctl00$B$fvMenu','bTest 0\\Test 1\\Test 1c')"
class="AspNet-Menu-Link AspNet-Menu-ParentSelected">Test 1c</a> </li>
</ul>
</li>
<li class="AspNet-Menu-Leaf AspNet-Menu-ParentSelected"><a href="javascript:__doPostBack('ctl00$B$fvMenu','bTest 0\\Test 2')"
class="AspNet-Menu-Link AspNet-Menu-ParentSelected">Test 2</a> </li>
<li class="AspNet-Menu-Leaf AspNet-Menu-ParentSelected"><a href="javascript:__doPostBack('ctl00$B$fvMenu','bTest 0\\Test 3')"
class="AspNet-Menu-Link AspNet-Menu-ParentSelected">Test 3</a> </li>
<li class="AspNet-Menu-Leaf AspNet-Menu-ParentSelected"><a href="javascript:__doPostBack('ctl00$B$fvMenu','bTest 0\\Test 4')"
class="AspNet-Menu-Link AspNet-Menu-ParentSelected">Test 4</a> </li>
</ul>
</li>
</ul>
</div>
A great sample is available here and the source code can be downloaded here.
More Posts
Next page »