Contents:
ERROR: Resource name XXX cannot be used more than once
A couple weeks ago I had a client call me up with a perplexing build error. He had an ASP.NET 4 Web Application project open in Visual Studio 2010 that he was working on when, suddenly, the following error cropped up when building:
Resource name xxx.resources cannot be used more than once.
There was no line number, just this error message. According to my client, the project built fine minutes before the error started appearing and, in the interim, he had not made any changes that he was aware of: he had not changed any code; had not created any new web pages; had not deleted anything; had not changed the projects settings.
Unfortunately, we were unable to find much help online. While there are a lot of messageboard posts and blog entries noting this error, most of them were in the context of duplicate key names in resource files my clients project was not using resource files.
Anyway, we banged our heads on it for a good hour before we finally chose the nuclear option: start excluding files one by one, building after each one, and see if the error goes away. A ham-fisted approach for sure, but one that would likely identify the culprit.
Eventually we got to the obj folder why was that part of the project? The obj folder As we started working through the files, I noticed in Solution Explorer that the obj folder holds temporary build files, including .resource files. I presume that when building the project Visual Studio was attempting to create the same files that were already part of the project, and hence the error. In any event, excluding the obj folder from the project did the trick. Once it was omitted the project built without error.
So how did this happen? My client likes having the Show all files option turned on in the Solution Explorer. My guess is that he inadvertently right-clicked on the excluded obj folder and clicked the Include in project option. Or something, because he said he did not intentionally add the folder to his project. Regardless, its presence caused the build to choke and removing it fixed everything.
Thought I would share this experience here so others would have another possible avenue to check in the event that they receive this build error.
Happy Programming!

Using Log Parser to List All Blocked IP Requests
In a recent project we needed to block a series of IP addresses from accessing our website. IIS makes this easy with its IPv4 Address and Domain Restrictions feature, which lets the webmaster specify specific or ranges of IP addresses that are either allowed or denied access to the website. See Configure IPv4 Address and Domain Name Rules for more information.
After blocking the IP addresses of interest we wondered, how often are those blocked addresses attempting to access the website? Whenever IIS blocks an IP address it returns a particular HTTP status code - 403.6. Therefore, if we could search the IIS log files for all requests that returned a 403.6 status code we would know what banned IP addresses were attempting to access what pages and when.
Of course we werent at all interested in manually pouring through the log files. Fortunately, there is Log Parser. Log Parser is a free command-line tool from Microsoft for searching through IIS log files using a SQL-like syntax. We ended up using the following command, which provides the IP address, the requested URL, and the local date/time of the blocked request ordered from the most recent blocked request to the oldest. The results are outputted as a CSV file. (Note: the extra spaces and carriage returns in the below command are for readability only; remove this whitespace before attempting to run the command from the command line.)
LogParser.exe -i:W3C
"SELECT c-ip as IP,
cs-uri-stem as URL,
TO_LOCALTIME(TO_TIMESTAMP(date, time)) AS DateTime
FROM c:inetpublogsLogFilesW3SVC1*
WHERE TO_STRING(sc-status) = '403'
AND TO_STRING(sc-substatus) = '6'
ORDER BY TO_LOCALTIME(TO_TIMESTAMP(date, time)) DESC"
-o:CSV
Note the SQL-like syntax very easy to read and understand for a DBA or developer who works regularly with SQL. Log Parser supports the standard SQL clauses, including GROUP BY clauses. Log Parser also supports a variety of output types. Above I request the data to be outputted as a CSV (see the o:CSV switch) but I could have chosen the output as an XML file, a grid even a chart!
For more on Log Parser, along with some common queries, check out the following resources:
There is also a Samples folder that is included when you install Log Parser with dozens of sample queries.
Happy Programming!

Uploading a Variable Number of Files from an ASP.NET Web Page
ASP.NET has long offered the FileUpload control, which simplifies uploading a file from the clients computer to the web servers file system. This control provides a very simple, straight-forward user experience the browser renders a Browse or Select File button that, when clicked, brings up a dialog box from which the user can select a file from her computer. Behind the scenes, the FileUpload control renders as an <input type=file /> HTML element and sets the WebForms encoding type to multipart/form-data. The <input type=file /> HTML element is what instructs the browser to render the file upload interface and the multipart/form-data encoding type instructs the browser to send the forms contents (including the binary contents of the selected file) to the server as a multipart MIME message, which allows for transmission of binary data.
Recently, I was working on a web page where users needed the ability to upload a variable number of files. While most users would only upload a single file, some would need to upload two, while others three, four, or possibly more. Since a single FileUpload control can upload only a single file, one option was to add four (or five or six) FileUpload controls on the page, but that would crowd the page and be overkill for the majority of users who only needed to upload a single file. We considered using a third-party file upload control (such as SlickUpload) that would supports richer upload scenarios, including multifile uploads, but ended up with a simpler solution that involved a bit of HTML and jQuery.
In particular, we had the page initially contain a single <input type=file /> HTML element. Next, we added an Upload another file link that, when clicked, executed JavaScript that dynamically added another <input type=file /> HTML element to the DOM. Additionally, we added a Remove link next to each <input type=file /> HTML element that, when clicked, removed the associated file upload user interface from the DOM.
Show Me!
Here is a demo of this concept. First the HTML. Note that there is a form whose enctype attribute is explicitly set to multipart/form-data. Inside the form is a paragraph with an id of uploadUI and an Upload another file link with the id of addFileUpload. Theres also a Button Web control (btnUpload) that, when clicked, will postback the form, submitting the file contents to the server. Well see how to access the uploaded files from server-side code shortly.
<form id="form1" runat="server" enctype="multipart/form-data">
<p id="uploadUI">
</p>
<p>
[<a href="#" id="addFileUpload">Upload another file...</a>]
</p>
<p>
<asp:Button ID="btnUpload" runat="server" Text="Upload Files"
onclick="btnUpload_Click" />
</p>
</form>
The bulk of the content in this page is the JavaScript that creates and removes the <input type=file /> HTML elements in response to the user clicking the Upload another file and Remove links. Each file upload user interface is comprised of:
- A <div> element with an id of fileContainerCount, where Count is a variable that starts at 0 and is incremented each time a new file upload interface is added to the DOM. This <div> element contains the following:
- An <input type=file /> HTML element
- A Remove link that has a class attribute value of removeUpload
The file upload user interface is added by the createFileUpload function. The <div> element (and its containing elements) are added to the end of the uploadUI paragraph.
var uploadControlCounter = 0;
function createFileUpload() {
$("#uploadUI")
.append(
$("<div />")
.attr("id", "fileContainer" + uploadControlCounter)
.append(
$("<input />")
.attr("type", "file")
.attr("name", "file" + uploadControlCounter)
)
.append(" ")
.append(
$("<a />")
.attr("href", "#")
.attr("class", "removeUpload")
.text("Remove")
)
);
uploadControlCounter++;
}
In the $(document).ready event handler I wire up the click event handlers for the Upload another file and Remove links, as well as add the initial file upload user interface. Note that for the Remove links I use the delegate behavior for jQuerys on function because I want this event handler to fire for not just the current Remove links (which there are none), but for all Remove links that may be added to the DOM at a later point in time.
$(document).ready(function () {
$("#addFileUpload").click(function (e) {
e.preventDefault();
createFileUpload();
});
$("#uploadUI").on("click", "a.removeUpload", function (e) {
e.preventDefault();
$(this).parent().remove();
});
// Start by creating one file upload
createFileUpload();
});
Onto the Server-Side
When the user clicks the Upload Files button their browser will make a request back to the page sending the selected files contents. We can inspect the set of uploaded files on the server-side by looping through the Request objects Files collection. The Request.Files property is a collection of HttpPostedFile objects, which have properties that provide the file name, content type, content length, and a stream to the raw binary data. In my demo I loop through the Request.Files collection and for each file save it to the ~/Uploads folder, but since you have access to the raw uploaded binary data via the HttpPostedFile objects InputStream property you could do whatever it is you needed to do, such as save the contents to a database, inspect the contents in memory, and so on.
// Save each upload and redirect user to thank you page
for (int i = 0; i < Request.Files.Count; i++)
{
HttpPostedFile file = Request.Files
;
string filePath = Server.MapPath("~/Uploads/" + Path.GetFileName(file.FileName));
using (FileStream streamToDisk = File.Create(filePath))
{
file.InputStream.CopyTo(streamToDisk);
streamToDisk.Close();
}
}
Thats all there is to it! You can download the complete demo from http://scottonwriting.net/demos/MultiFileUpload.zip
Happy Programming!

Using Templates to Display Boolean Values as Yes/No Options
One of ASP.NET MVCs most useful features is its powerful templating system. Templates were introduced with ASP.NET MVC 2 as a way to have the view render either a display- or editing-related user interface for the entire model or for a property of the model. The Html.DisplayFor and Html.EditorFor methods provide a strongly-typed mechanism for rendering the appropriate template for a particular model property:
@Html.DisplayFor(model => model.PropertyName)
@Html.EditorFor(model => model.PropertyName)
For an in-depth overview of templates in ASP.NET MVC, see Brad Wilsons multi-part article series, ASP.NET MVC 2 Templates. (The content in Brads articles apply the same to ASP.NET MVC 3.)
How Html.DisplayFor and Html.EditorFor Determine Which Template to Use
ASP.NET MVC includes a number of built-in display and editor templates. For instance, when rendering a display or editing template for a Boolean value ASP.NET MVC will render either a disabled or enabled checkbox. When rendering a display template for an email address, ASP.NET MVC will render an actual mailto: anchor tag so that the email address is clickable. The editor template for a password property renders an <input type=password /> textbox so that the users input is masked. Additionally, you can create your own custom display and editor templates.
The Html.DisplayFor and Html.EditorFor methods, when called, need to determine which template to render for the given property. To make this determination these methods examine the specified propertys metadata, which includes information like the propertys data type (bool, string, int, etc.) along with attributes decorating the model properties. For instance, in your model you can decorate a property with a DataType attribute to inform the view and the templating system the type of data this property expresses. In the following model, the property Password is decorated as a password data type, while the Bio property is decorated as a multiline text input (which will render a multiline textbox for this propertys editor template).
public class MyModel
{
...
[DataType(DataType.Password)]
public string Password { get; set; }
[DataType(DataType.MultilineText)]
public string Bio { get; set; }
...
}
Specifically, the Html.DisplayFor and Html.EditorFor methods consult the following metadata in this order:
- The UIHint attribute - specifies the name of the template to use.
- The DataType attribute
- The data type
Creating a custom template in ASP.NET MVC is a breeze. Simply add DisplayTemplates and EditorTemplates subfolders to the ViewsShared folder. Then add a view file (e.g., .cshtml) to the subfolder with the name of the template. You can override the default templates by naming the template with the same name as the data type to override such as String.cshtml or DateTime.cshtml or you can give it a unique name such as YesNo.cshtml in which case you specify the template to use via the UIHint attribute. The custom template is a view that defines the incoming model via the @model directive and emits the desired output.
Building a Yes/No Template for Boolean Values
ASP.NET MVCs default display template for Boolean values renders a disabled checkbox, but replacing it with the text Yes or No is quite simple to do when using templates. Start by adding a new template to the ViewsSharedDisplayTemplates folder named YesNo.cshtml with the following content:
@model bool
@if (Model)
{
<text>Yes</text>
}
else
{
<text>No</text>
}
The display template starts by defining the incoming models type (bool) via the @model directive. Next, it emits the literal string Yes if the incoming value (Model) is true, No otherwise. Thats all there is to it!
At this point we have the display template defined, but no view will use it unless we specifically instruct it to do so. (In other words, ASP.NET MVC will continue to use its default display template for Boolean values, which is the disabled checkbox.) To instruct a particular model property to use our display template rather than the default, use the UIHint attribute like so:
public class MyModel
{
...
[UIHint("YesNo")]
public bool ReceiveNewsletter { get; set; }
...
}
With those two pieces of the puzzle in place the template itself and the UIHint attribute a view will render the text Yes or No when using the following code:
@Html.DisplayFor(model => model.ReceiveNewsletter)
What about editing? Here we need to create a new template file with the same name (YesNo.cshtml) in the ViewsSharedEditorTemplates folder and then add the following content:
@model bool
@Html.DropDownList("", new SelectListItem[] { new SelectListItem() { Text = "Yes", Value = "true", Selected = Model }, new SelectListItem() { Text = "No", Value = "false", Selected = !Model }})
As with the display template, we start by defining the incoming models type (bool) via the @model directive. Then we render a drop-down using the Html.DropDownList method. This drop-down is composed of two select options Yes and No with the values true and false, respectively. The first item is selected if the incoming value (Model) is true, while the second option is selected if the incoming value is false.
And were done! The screen shot below shows the output of a Boolean value when decorated with the [UIHint("YesNo")] attribute and displayed using the Html.EditorFor method.

Happy Programming!

Searching SQL Server Stored Procedure and Trigger Text
While I like to consider myself a web developer, every now and then I have to put on my DBA hat to address some SQL related issue. This little script has saved my butt more than once. It searches the text of triggers, UDFs, stored procedures and views for a particular substring, returning the name and type of those database objects that match.
DECLARE @Search varchar(255)
SET @Search='text_to_search'
SELECT DISTINCT
o.name AS Object_Name,o.type_desc
FROM sys.sql_modules m
INNER JOIN sys.objects o ON m.object_id=o.object_id
WHERE m.definition Like '%'+@Search+'%'
ORDER BY 2,1
The above script is one of many in my bag of scripts Ive collected over the years. This particular gem was snagged from Stackoverflow: How to find a text inside SQL Server procedures / triggers?

ASP.NET Training in San Diego on Saturday, September 24th
On Saturday September 24th Ill be doing two four-hour ASP.NET MVC 3 and Razor training events in San Diego:
- Getting Started with ASP.NET MVC 3 and Razor (8 AM to Noon) - This four hour morning class introduces ASP.NET MVC 3 and the new Razor view syntax, explores how to build ASP.NET MVC applications, covers key differences between Web Forms and ASP.NET MVC, and highlights the benefits of ASP.NET MVC. It is intended for developers who are interested in getting started with or learning more about ASP.NET MVC 3 and what it has to offer, as well as for developers using ASP.NET MVC 2 who want to see what's new with ASP.NET MVC 3.
- Building Real-World Web Applications with ASP.NET MVC 3 (1 to 5 PM) - This four hour afternoon class examines building real-world web applications using ASP.NET MVC 3. Learn how to craft lean controllers that comprise only a few lines of code. See how to use display and editor templates to decouple the user interface from your views. And practice creating rich and expressive view-specific models. Best practices on mapping domain models to view models, on input validation, and other topics will be explored. (This class is intended for students who attended the mornings
Home