Contents tagged with C#
-
A Quick Fix for the Validator SetFocusOnError Bug
The ASP.NET validators have this nice property called "SetFocusOnError" that is supposed to set the focus to the first control that failed validation. This all works great until your validator control is inside a naming container. I ran into this recently when using validators in a DetailsView. Take this simple example:<%@ Page Language="C#" %> <script runat="server"> protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) DataBind(); } </script> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <form id="_frm" runat="server"> <asp:DetailsView ID="dv1" DefaultMode="Edit" DataSource='<%# new object[1] %>' runat="server" > <Fields> <asp:TemplateField HeaderText="First Name:"> <EditItemTemplate> <asp:TextBox ID="FirstNameTextBox" runat="server" /> <asp:RequiredFieldValidator ID="FirstNameValidator1" ControlToValidate="FirstNameTextBox" ErrorMessage="First name is required." Display="Dynamic" EnableClientScript="false" SetFocusOnError="true" ValidationGroup="bug" Text="*" runat="server" /> </EditItemTemplate> </asp:TemplateField> </Fields> <FooterTemplate> <asp:ValidationSummary ID="vs1" DisplayMode="List" ValidationGroup="bug" runat="server" /> <asp:Button ID="Button1" Text="Post Back" ValidationGroup="bug" runat="server" /> </FooterTemplate> </asp:DetailsView> </form> </body> </html>
If you run this page and do a view source you'll see that the FirstNameTextBox gets rendered like this:<input name="dv1$FirstNameTextBox" type="text" id="dv1_FirstNameTextBox" />
If you just do a post back without entering a value to cause the validator to fail it will output this line of java script in an attempt to set the focus to the invalid element:WebForm_AutoFocus('FirstNameTextBox');
See anything wrong with this? It would seem that the validators just use the string value you typed in for the ControlToValidate property rather than doing a FindControl and using the UniqueID. This is exactly what happens and I verified it with reflector. The Validate method on BaseValidator does this:if ((!this.IsValid && (this.Page != null)) && this.SetFocusOnError) { this.Page.SetValidatorInvalidControlFocus(this.ControlToValidate); }
If you follow the call to SetValidatorInvalidControlFocus you'll see that it never resolves the full UniqueID of the control that its going to set focus to.Ok, so this sucks. How do I work around it. My solution was to simply ditch using the SetFocusOnError property and implement the focus logic myself which is actually pretty easy. I overrode Validate method on my Page like this:public override void Validate(string group) { base.Validate(group); // find the first validator that failed foreach (IValidator validator in GetValidators(group)) { if (validator is BaseValidator && !validator.IsValid) { BaseValidator bv = (BaseValidator)validator; // look up the control that failed validation Control target = bv.NamingContainer.FindControl(bv.ControlToValidate); // set the focus to it if (target != null) target.Focus(); break; } } }
If your using C# 3 this is even easier using LINQ:
public override void Validate(string group) { base.Validate(group); // get the first validator that failed var validator = GetValidators(group) .OfType<BaseValidator>() .FirstOrDefault(v => !v.IsValid); // set the focus to the control // that the validator targets if (validator != null) { Control target = validator .NamingContainer .FindControl(validator.ControlToValidate); if (target != null) target.Focus(); } }
I hope this saves someone the headache of tracking this down.
-
VS.NET Macro To Group and Sort Your Using Statements
I try to follow a coding standard for organizing my using statements. System.* goes at the top and then other namespaces grouped together like this:
-
Scott Guthrie presents at NDDNUG
Scott gave a whirlwind presentation to a standing room only crowd at the North Dallas Dot Net User Group tonight. A wide range of topics were covered from IDE tips and tricks to ASP.NET tips to MS AJAX to LINQ and DLINQ (I still like to call it DLINQ rather than LINQ to SQL). I'm still not sure how all this got packed into a little over 2 hours. :)
-
Using IronPython for Dynamic Expressions.
We recently had this question posted to our forums over at LVS:
-
Suggestions for distributing CTPs as VirtualPC images
I finally got around to trying the Sept. CTP of Orcas. I loaded up the VPC images on VPC7 Beta (which seems to perform much better than VPC2004). If this is going to be the way that MS is going to release CTPs in the future here are a few suggestions:
-
Problems with RewritePath and Search Engines.
We just recently launched the new version of LearnVisualStudio.NET. The implementation uses the RewritePath method to serve up dynamic pages based on templates. All of our pre deployment testing showed that this was all working without a hitch. Once we deployed to production however it became clear which test cases we had left out. We didn't test how the site responded when getting crawled by search engines.
-
New version of LearnVisualStudio.NET launched
-
A great article on functional programming...
http://www.defmacro.org/ramblings/fp.html
This article was a great overview of many of the aspects of functional programming. With what Micosoft is doing to the CLR and C# and VB it would seem that functional programming is making advances into the main stream. His article has imaginary Java samples and if you squint your eyes when he creates a class to hold a function you can see delegates.
I studied functional languages such as LISP and ML in college but quickly lost track of them after years of programming in corporate IT. To catch back up I've been spending the better part of a year studying functional programming concepts. While its been challenging at times, there have been alot of aha and oh yeah moments.
Since I have a great comfort level with C syntax I started my ride on the functional wagon with COmega. This is where I really began to "get" things like closures. I even found myself purposfully writing my own code to mimic a closure in good ol C# 1.0 for certain situations like Regex match evaluators. Once you see the "patterns" that higher order functions exhibit you can write them in plain imperative code. This will make you hunger for language constructs to do this work for you. Its like writing OO code in assembly language.
C# 2.0 Added true closures to the language with anonymous delegates. Woo hoo no more private nested classes to hold lexical context! (at least not that I write).
At PDC I got to see the preview of C# 3. This takes anonymous delegates a step further with "lambdas". There's lazy evaluation galore with LINQ. It would seem that MS has been bitten by the functional bug. Even the Atlas client APIs make good use of the functional elements of JavaScript.
I've also ventured out into IronPython and Ruby. These are great places to practice functional programming techniques.
The real challenge moving forward is finding the right balance. Theres no doubt in my mind that functional programming techniques are headed to the main stream. With the populatrity of Ruby and Rails and Microsoft adding functional capabilites into C# and VB the winds of change are blowing.
Link dump so I can keep track of what I'm researching:
COmega: http://research.microsoft.com/Comega/
LINQ: http://msdn.microsoft.com/data/ref/linq/
F#: http://research.microsoft.com/fsharp/fsharp.aspx
IronPython: http://www.codeplex.com/Wiki/View.aspx?ProjectName=IronPython
Ruby: http://www.ruby-lang.org/en/
Ruby.NET: http://www.plas.fit.qut.edu.au/rubynet/
IronRuby: http://wilcoding.xs4all.nl/Wilco/IronRuby.aspx
RubyCLR: http://www.iunknown.com/articles/2006/06/19/rubyclr-drop-4
Atlas: http://atlas.asp.net/Default.aspx?tabid=47
#Smalltalk: http://www.refactory.com/Software/SharpSmalltalk/index.html
brianbec's blog:
http://weblogs.asp.net/brianbec/default.aspx
http://weblogs.asp.net/brianbec/archive/2006/06/01/Lambdas_2C00_-Closures_2C00_-Currying_2C00_-and-All-That.aspx -
Migrating from System.Web.Mail to System.Net.Mail
I discovered how great the new System.Net.Mail namespace is this weekend.
-
What should a "Stream" operator look like in C#?
Streams were one of the core concepts that I latched onto with Cw. It elevated enumerable lists as a first class problem domain. The fact that int* really was IEnumerable
<int> melted away as an implementation detail and allowed me to begin to think in terms of lists ala (LISP/Scheme). This way of thinking seems to be extremely core to LINQ since the underpinnings are all based on IEnumerable<T>. This is why I feel very strongly that IEnumerable<T> deserves some special consideration by the language. If Nullable<T> can have its own operator where's the love for IEnumerable<T>?