Best asp.net questions in September 2011

Is there an implementation somewhere of the yellow screen of death?

13 votes

In ASP.NET when you are in DEBUG mode and something fails you get a the famous yellow screen of death.

It shows that there was a Server Error in <Location> Application, provides a description, exception details, source file and stack trace.

I would like to extend this error page to include some extra information.

  • Is there an "open source" implementation of the yellow screen of death?
  • Is there a way to extend the built-in yellow screen of death?

The error page formatting is done by System.Web.ErrorFormatter and its subclasses, which unfortunately are internal. You can grab the HTML and modify it if you like using HttpException.GetHtmlErrorMessage(). But I'd be inclined to do as other commenters have suggested and use Server.GetLastError and format it myself.

If so - please ensure you HtmlEncode the error message output to mitigate XSS and ensure your production sites don't display any information about the error (as this was the attack vector for the ASP.NET padding oracle decryption attack in 2010).

How to send the browser to an error page if part of the response has been sent (chunked)

9 votes

This is typical scenario: a page is evaluated, and there's a buffer - once the buffer is full, the part of the page that is evaluated is sent to the browser. This uses the HTTP 1.1 chunked encoding.

However, an error can occur in one of the chunks (after the first one is already sent). In that case:

  • you can't redirect (send a Location header), because the headers and the response status were already sent
  • you can't do server-side redirect (forward), because the new page will have to be rendered after the part that is already sent - it will look ugly for sure.

So what should you do in this case? I asked a question whether you can send a Location header in the chunked trailer, but this is low-level http and the abstraction of languages may not allow it, even if it is possible (and it is likely not to be supported across browsers)

Another option is to send a <script>window.href.location="errorPage"</script> and thus force the client to redirect, but that's ugly. Plus you have to put </script> to close any potential unclosed <script> tag in the partial page.

(I'm tagging major web languages/frameworks, because this is an universal issue)

You cannot redirect from the server in a chunked encoding because the headers have already been sent. The only way to perform a redirect is to send a <script> tag from the server and perform a client side redirect. Just out of curiosity are you trying to implement a COMET server? If this is the case HTML5 WebSockets seem better way (if the browsers you are targeting support them of course) compared to the hidden iframe technique.

Only count a download once it's served

9 votes

We have this code which serves a download:

public class downloadRelease : IHttpHandler {

    public void ProcessRequest (HttpContext context) {

        -- snip --

        context.Response.Clear();
        context.Response.ContentType = "application/octet-stream";
        context.Response.AddHeader("Content-Disposition", "attachment; filename=" + OriginalFileName);
        context.Response.WriteFile(Settings.ReleaseFileLocation + ActualFileName);

        // Log download
        Constructor.VersionReleaseDownload.NewReleaseDownload(ActualFileName);

It works fine, except that the log download code runs as soon as the download starts seemingly, not when the download has fully completed as we expect.

Can someone explain why this is, and how to change it so it only logs when it's completed? We don't want to count partial downloads.

This blog post has exactly same issue as yours and a solution too.

Response.Buffer = false;
Response.TransmitFile("Tree.jpg");
Response.Close();
// logging here

How to post an array of files in ASP.NET MVC 3?

9 votes

I would like to be able to post multiple files in one form. I would like to pass these files as an array of files. For example I would like to do this.

<input type="file" name="files[0]" />
<input type="file" name="files[1]" />
<input type="file" name="files[2]" />

Then I would like to be able to receive these files as an array in the Controller. I've tried this.

public ActionResult AddPart(HttpPostedFileBase[] files)

But that doesn't work. I've googled it but all I can find is examples on uploading one file. Does anyone know how to do this using MVC3 C#.

If you want to upload not only one file, you need to use enctype="multipart/form-data" in your form.

@using (Html.BeginForm("", "Client", FormMethod.Post, new {enctype="multipart/form-data"}))

And controller:

[HttpPost]
public ActionResult AddPart(IEnumerable<HttpPostedFileBase> files) 

All other parts is ok.

Query problem - rows are returned when query is run in sql navigator , but not in my c# program

7 votes

enter image description here

Update:

This is the query from the debugger, which was retrieved from a string builder:

{SELECT * FROM FCR.V_REPORT WHERE DATE BETWEEN to_date('14/09/2001' , 'dd/mm/yyyy') AND to_date('30/09/2011' , 'dd/mm/yyyy')}

If you remove the curly brackets and post it in Navigator, it works.

Original:

I have a problem when running my program. The query in sql navigator returns 192 rows but when I run the query on c#(visual studio 2010) the query returns 0 rows. Below is my c# code:

public static DataTable GetReport(string date1, string date2)
{
  DatabaseAdapter dba = DatabaseAdapter.GetInstance();
  string SqlQuery =
    string.Format(@"SELECT * 
                  FROM FCR.V_REPORT 
                  WHERE DATE BETWEEN to_date('{0}' , 'dd/mm/yyyy')
                    AND to_date('{1}' , 'dd/mm/yyyy')", date1, date2);
  OracleDataReader reader = dba.QueryDatabase(SqlQuery);
  DataTable dt = new DataTable();
  dt.Load(reader);
  int temp = dt.Rows.Count;
  return dt;
}

This is the query I am using in sql navigator(which returns 192 rows):

SELECT * 
FROM FCR.V_REPORT
WHERE DATE BETWEEN to_date('01/01/2001' , 'dd/mm/yyyy')
AND to_date('30/09/2011' , 'dd/mm/yyyy')

Try dropping the view and create again. Make sure you got the aliases correct too.

ASP.net mobile application development

6 votes

I have an existing website for schools and colleges management which is developed in ASP.NET,C# and SQL Server.

Now I am planning to support for the mobile applications (like basic models from Nokia/Samsung and for opera mobiles). I know the normal site we can access through some of the devices without any change, but needs to be optimized.

I am preparing another version which will be only few required fields and easy navigation for mobile. For that which method I need to use.

  1. Normal ASPX files with optimized HTML code.
  2. Or using WAP controls
  3. Should I use HTML 5

Please help me to decide.

I recommend using HTML5 with ASP.NET MVC 3 and the jQuery Mobile framework. Let the jQuery Mobile framework do all the multi-device heavy lifting for you.

jQuery Mobile Supported Devices

When jGrowl is called, the thickbox stops working properly (using UpdatePanel)

5 votes

I am calling a thickbox when a link is clicked:

<a href="createContact.aspx?placeValuesBeforeTB_=savedValues&TB_iframe=true&height=400&width=550&modal=true"
                            title="Add a new Contact" class="thickbox">Add a new Contact</a>

And, when a server button is clicked I call this javascript function to show a jGrowl notification:

ScriptManager.RegisterClientScriptBlock(this, typeof(Page), Guid.NewGuid().ToString(), "$(function(){$.jGrowl('No Contact found: " + searchContactText.Text + "');});", true);

Both works as expected except when the jGrowl is shown first than the thickbox. This will cause the thickbox not to work and the page will be shown as a normal web (as if the thickbox had been gone).

Does anyone know what is happening?

UPDATE: This is the a test page without Master Page:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm2.aspx.cs" Inherits="RoutingPortal.Presentation.WebForm2" %>

<!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>
<script src="../Scripts/jquery-1.6.2.js" type="text/javascript"></script>
<script src="../Scripts/jquery-ui-1.8.16.custom.min.js" type="text/javascript"></script>
<script src="../Scripts/thickbox.js" type="text/javascript"></script>
<script src="../Scripts/jquery.jgrowl.js" type="text/javascript"></script>
<link href="../Scripts/css/jquery.jgrowl.css" rel="stylesheet" type="text/css" />
<link rel="stylesheet" href="~/CSS/thickbox.css" type="text/css" media="screen" />
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<div>
    <a href="createContact.aspx?placeValuesBeforeTB_=savedValues&TB_iframe=true&height=400&width=550&modal=true"
            title="Add a new Contact" class="thickbox">Add a new Contact</a>
        <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
</div>
</ContentTemplate>
</asp:UpdatePanel>
</form>
</body>
</html>

This is the codebehind:

namespace RoutingPortal.Presentation
{
public partial class WebForm2 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        ScriptManager.RegisterClientScriptBlock(this.Page, typeof(Page), Guid.NewGuid().ToString(),
                "$(function(){$.jGrowl('My Message');});", true);
    }
}
}

I have just tested it without the UpdatePanel and it worked perfectly. So, it is definitely a problem with the UpdatePanel or the way that it is interacting with the jGrowl called from the codebehind.

I would massively appreciate your help guys.

UPDATE: I have even created a demo project where this problem can be easily identified. Wouldn't mind to send it to anyone willing to help me out with this. Thanks in advance guys!

UPDATE: I have also tried the solution given by @Rick, changing the way the jGrowl script is executed from codebehind:

ScriptManager.RegisterStartupScript(this.Page, typeof(Page), Guid.NewGuid().ToString(),
        "$.jGrowl('My Message');", true);

However, the problem persist since the outcome is exactly the same. Any other ideas? I'd massively appreciate your help.

UPDATE: I have also tried this in IE8 and Chrome, facing the same problem. So, this is nothing to do with the browser. Just in case.

I believe your problem has nothing to do with jGrowl, and all to do with your use of an UpdatePanel.

When you use an UpdatePanel, it refreshes all the elements in the DOM that are contained in it. What this means is that the original <a> tag that was created in the page and that had its click event set to use thickbox no longer exists. After the UpdatePanel refreshes, you now have a NEW <a> tag that has the thickbox class, but has not been "initialized" (since thickbox sets the click handler during page load, which doesn't happen like normal during a partial postback). Hence, when you click on the link, it acts like a normal link.

There are several ways to fix this, depending on your situation.

Option 1: Based on your code pasted above, it does not look like anything actually changes related to the link during your postback handling. So maybe you could move your <div><a ...></a> </div> outside of the UpdatePanel, and leave only the button inside. This will keep your link as part of the page and it will still have its thickbox handler attached.

Option 2: If there's some reason you can't go with Option 1, then you can set some javascript to run during the load of your UpdatePanel to re-attach the click handler for your link. In the function that calls jGrowl, try adding tb_init('a.thickbox'); to your code.

Option 3: You could modify the thickbox.js file to use jQuery's live handler instead of the normal click handler. In the tb_init function, you would change it to be $(domChunk).live('click', function(){..}). I think this would work, though it's possible the update panel process might still foil it.

Hope this helps.

Fastest Way to Count Distinct Values in a Column, Including NULL Values

5 votes

The Transact-Sql Count Distinct operation counts all non-null values in a column. I need to count the number of distinct values per column in a set of tables, including null values (so if there is a null in the column, the result should be (Select Count(Distinct COLNAME) From TABLE) + 1.

This is going to be repeated over every column in every table in the DB. Includes hundreds of tables, some of which have over 1M rows. Because this needs to be done over every single column, adding Indexes for every column is not a good option.

This will be done as part of an ASP.net site, so integration with code logic is also ok (i.e.: this doesn't have to be completed as part of one query, though if that can be done with good performance, then even better).

What is the most efficient way to do this?


Update After Testing

I tested the different methods from the answers given on a good representative table. The table has 3.2 million records, dozens of columns (a few with indexes, most without). One column has 3.2 million unique values. Other columns range from all Null (one value) to a max of 40K unique values. For each method I performed four tests (with multiple attempts at each, averaging the results): 20 columns at one time, 5 columns at one time, 1 column with many values (3.2M) and 1 column with a small number of values (167). Here are the results, in order of fastest to slowest

  1. Count/GroupBy (Cheran)
  2. CountDistinct+SubQuery (Ellis)
  3. dense_rank (Eriksson)
  4. Count+Max (Andriy)

Testing Results (in seconds):

   Method          20_Columns   5_Columns   1_Column (Large)   1_Column (Small)
1) Count/GroupBy      10.8          4.8            2.8               0.14       
2) CountDistinct      12.4          4.8            3                 0.7         
3) dense_rank        226           30              6                 4.33 
4) Count+Max          98.5         44             16                12.5        

Notes:

  • Interestingly enough, the two methods that were fastest (by far, with only a small difference in between then) were both methods that submitted separate queries for each column (and in the case of result #2, the query included a subquery, so there were really two queries submitted per column). Perhaps because the gains that would be achieved by limiting the number of table scans is small in comparison to the performance hit taken in terms of memory requirements (just a guess).
  • Though the dense_rank method is definitely the most elegant, it seems that it doesn't scale well (see the result for 20 columns, which is by far the worst of the four methods), and even on a small scale just cannot compete with the performance of Count.

Thanks for the help and suggestions!

SELECT COUNT(*)
FROM (SELECT ColumnName
      FROM TableName
      GROUP BY ColumnName) AS s;

GROUP BY selects distinct values including NULL. COUNT(*) will include NULLs, as opposed to COUNT(ColumnName), which ignores NULLs.

ASP.net MVC get current viewengine

5 votes

Is it possible to get the currently used viewengine from lets say the ControllerContext or the viewengine collection? I would like to be able to do say the following Viewengines.GetCurrent. I know that i can make an extensions for that method but i have no idea on how to implement this.

You can use ViewEngineCollection to look up the ViewEngine associated with a particular view.

ViewEngineResult result = ViewEngines.Engines.FindView(controllerContext,
                                                       "myView","myMaster");
IViewEngine viewEngine = result.ViewEngine;

See here for more info.

ASP.Net - Handling session data in a load balanced environment?

5 votes

How does ASP.Net deal with session data in a load balanced environment? Let's say a user makes multiple requests while navigating through a couple of pages? Do all requests go to the same server in the load balancer?

What can I do if they don't all point to the same server? how do I deal with my session data?

You need to ensure that your NLB has the ability to enable "Sticky" sessions.

If this isn't an option, then you need to look at using the ASP.Net Session Modes to configure either a Session Server, or some backing store like SQL Server.

Rows showing up multiple times in GridView

5 votes

I have a GridView control on my web page which makes use of paging. I am seeing apparently duplicate rows appearing, but I know they are not in the data, and they seem to disappear whenever I sort on a different column from the default one I'm using. However, they reappear when sorting on this original column again.

Here's a snippet of the ascx;

<asp:GridView
    ID="gvResults"
    AllowPaging="True"
    CssClass="DataTable"
    runat="server"
    AutoGenerateColumns="False"
    OnRowDataBound="gvResults_RowDataBound"
    AllowSorting="True"
    Width="750px"
    OnSorting="gvResults_Sorting"
    PagerSettings-Mode="NumericFirstLast"
    PagerSettings-FirstPageText="<<"
    PagerSettings-LastPageText=">>"
    PagerSettings-PageButtonCount="5"
    PagerSettings-Position="Bottom"
    PagerStyle-CssClass="paginationContainer"
    PagerStyle-HorizontalAlign="Left"
    OnPageIndexChanging="gvResults_PageIndexChanging">

<PagerSettings 
    FirstPageText="&lt;&lt;" 
    LastPageText="&gt;&gt;" 
    Mode="NumericFirstLast"
    PageButtonCount="5" />

<PagerStyle CssClass="paginationContainer" HorizontalAlign="Left" />

That might be irrelevant to my issue, but I'm including it just in case.

Now, I believe that the issue is possibly being caused because there is a particular scenario in which the column on which the grid is sorted by default, will be populated with an identical value for many rows. That might sound strange, but the column is a proximity, and the grid is displaying proximity search results, so it is possible that some searches are going to return many results with the same proximity.

The issue of the duplicate results only happens once the number of rows with an identical proximity exceeds the number of results displayed per page (in my case, 10).

Whenever this happens, I see a row appear on, e.g. the 2nd page, and also on the 3rd page (never on the same page however). Sorting on a different column and paging through the results seems to eradicate the issue.

Now, after much head / wall interfacing, I have arrived at a speculative explanation;

That this is totally expected behaviour because there is no specified way to sort the rows when the fields are identical. Some other mechanism must be deciding how to sort the rows, and whatever this mechanism is causes the duplicate issue whenever paging through results.

Am I on the right track here? And if so, how can I address this issue? Is there some way to sort on a secondary column in addition to the user specified one?

I don't know whether you are on the right track or not because w/o looking at the data it's difficult to tell, but to your question regarding sorting by a secondary column, you definitely can do this easily:

  1. If you are using a DataTable to bind your data, you can order by two columns with something like this on your gvResults_Sorting event:

    Expression<Func<DataRow,object>> expCol1 = row => row["SortExpressionFirstColumn"];
    Expression<Func<DataRow,object>> expCol2 = row => row["SortExpressionSecondColumn"];
    
    OrderedEnumerableRowCollection<DataRow> result = yourTabale.AsEnumerable().OrderBy(expCol1.Compile()).ThenBy(expCol2.Compile());
    
    DataTable sortedTable = new DataTable();
    foreach (var item in result)
    {
            sortedTable.ImportRow(item);
    }
    gvResults.DataSource=sortedTable;
    gvResults.DataBind();
    
  2. Or you don't get so fancy and use a DataView to sort the datatable:

    DataTable t ....
    t.DefaultView.Sort="SortExpressionColumn1 ASC/DESC , SortExpressionColumn2 ASC/DESC";
    gvResults.DataSource=t.DefaultView.ToTable();
    gvResults.DataSource=t.DataBind();
    
  3. If you are using custom business objects, much easier:

    List<CutomObject> co = ....
    
    co=co.OrderBy(x => x.FirstProperty).ThenBy(x => x.SecondProperty);
    gvResults.DataSource=co;
    gvResults.DataBind();
    

Javascript error: 'window.top.document.getElementById(...)' is null or not an object

4 votes

I am getting a javascript error when I attempt to click on my calendar control.

The html code is:

        <td align="left" style="width:50%;"><asp:Label runat="server" CssClass="TextFontBold" ID="lblStartDate" Text="Start Date:"></asp:Label>
            <input type="text" class="TextBox" id="FromDate" runat="server"/><a href="javascript:ShowCalendar('FromDate1')"><img src="images/Calendar.png" border="0" /></a>
            <iframe src="Calendar.aspx?DateTextID=FromDate" style="display:none; top: 0px; left: 0px; width:245px; height:164px" frameborder="0" scrolling="no" name="FromDate1" id="FromDate1"></iframe>&nbsp;&nbsp;&nbsp;&nbsp;
            &nbsp;&nbsp;&nbsp;&nbsp;<asp:Label runat="server" CssClass="TextFontBold" ID="lblPromoStartTime" Text="Start Time:"></asp:Label>
        </td>  

When I click on a date in the calendar control, this code is executed on the code-behind:

Protected Sub Calendar1_SelectionChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles Calendar1.SelectionChanged
    Dim strjscript As String = "<script language=""javascript"" type=""text/javascript"">"
    strjscript &= "window.top.document.getElementById('" & HttpContext.Current.Request.QueryString("DateTextID") & "').value = '" & Calendar1.SelectedDate & "';"
    strjscript &= "window.top.document.getElementById('" & HttpContext.Current.Request.QueryString("DateTextID") & "1').style.display = 'none';"
    strjscript = strjscript & "</script" & ">"
    Literal1.Text = strjscript
End Sub  

The error I am getting is 'window.top.document.getElementById(...)' is null or not an object

I do have an object called FromDate.
What else could be causing this error?

Try window.parent.document.getElementById() instead of window.top.document.getElementById()

Infinite URL Parameters for ASP.NET MVC Route

4 votes

I need an implementation where I can get infinite parameters on my ASP.NET Controller. It will be better if I give you an example :

Let's assume that I will have following urls :

example.com/tag/poo/bar/poobar
example.com/tag/poo/bar/poobar/poo2/poo4
example.com/tag/poo/bar/poobar/poo89

As you can see, it will get infinite number of tags after example.com/tag/ and slash will be a delimiter here.

On the controller I would like to do this :

foreach(string item in paramaters) { 

    //this is one of the url paramaters
    string poo = item;

}

Is there any known way to achieve this? How can I get reach the values from controller? With Dictionary<string, string> or List<string>?

NOTE :

The question is not well explained IMO but I tried my best to fit it. in. Feel free to tweak it

Like this:

routes.MapRoute("Name", "tag/{*tags}", new { controller = ..., action = ... });

ActionResult MyAction(string tags) {
    foreach(string tag in tags.Split("/")) {
        ...
    }
}

Update ASP.NET Page after GridView DataBind

4 votes

EDIT:
Apparently, part of the problem is that while an ASP:GridView has an OnDataBound() event (which you can use in the code-behind), the corresponding HTML table that is produced does NOT, so you can attach that event to JavaScript. (Did I get that right?) So, that's why I'm having trouble with that bit of the issue. Back to the drawing board.


I'm a desktop developer (WinForms with VB.NET) transitioning into ASP.NET development. My mind is really bending around the DOM and JavaScript and Session State and all of the stuff that goes along with web development. I'm not stupid, and I've done research (including hours of video watching and hundreds of pages of "Intro to ASP.NET" reading), but I keep hitting the wall with what seem to be fairly straightforward problems.

Basically, my current situation can be summed up as follows:

  1. I have a page that runs a very long process initiated by the user.
  2. The long process can take up to a few minutes , so I want to indicate to the user that SOMETHING is happening.
  3. When the process has completed, I either have:
    a. Results to show in a GridView
    b. No results to show
  4. If I have results to show, I want to display them.
  5. If I have no results to show, I want to show a label to the user that says "No results to show."

What's working:

  1. I have a basic page where the user selects start and end dates and kicks off the check process.
  2. The check process works fine (using LINQ-to-SQL logic developed for a desktop version of this program).
  3. I've got an UpdatePanel on my page which shows a label and an animated gif to indicate that something's happening.
  4. If I get results, they display appropriately in my GridView.

What's not working:

  1. I'd love to give the user some sort of progress bar to indicate actual progress made toward completion rather than some endlessly-animating gif that doesn't indicate much at all. I could calculate this value quickly and easily, but can't figure out how to transfer said value from server to web page.

  2. I can't figure out how to trigger an "unhide" event for the label. The long-running process is in a button's click event handler, where I run my custom code and generate a DataTable, which I then save as a session variable, assign it as the GridView's DataSource and call GridView.DataBind(). When I try to determine the contents of the DataTable and hide/reveal the label there, nothing seems to happen.

Problem #2 is really what I need to figure out in order to publish this web site. I'm assuming it involves a JavaScript solution, and I've tried some stuff, but I find that I'm truly guessing and don't have a good grasp on what the solution should resemble.

Here's the label I'd like to selectively reveal/make visible:

<tr>
    <td colspan="2" align="center">
        <h2><asp:Label runat="server" ID="lblNoMissing" Text="No Missing Documentation Found" Visible="false"></asp:Label></h2>
    </td>
</tr>

Here's a JavaScript function I'm trying to test:

<script type="text/javascript">
    function databound() {
        var gridViewID = '<%=_gridView1.ClientID%>';
        var labelID = '<%=lblNoMissing.ClientID%>';
        var gridView = document.getElementById(gridViewID);
        if (gridView.rows.length > 0) {
            $get(labelID).style.visibility = "false";
        } else {
            $get(labelID).style.visibility = "true";
        }
    }
</script>

Problem: This fails (databound not a member of Default.aspx):

<asp:GridView ID="_gridView1" runat="server"
    AllowSorting="True" AutoGenerateColumns="False" CellPadding="4" 
    ForeColor="#333333" GridLines="Horizontal" PageSize="20" OnDataBound="databound();">
// Rest of GridView definition removed
</asp:GridView>

What am I missing?

Thanks!!!!

For problem #1, there are a whole bunch of free Javascript progress bars out there. As for your value that you can't retrieve, try this:

<asp:Label ID="ProgressValue" runat="server" visible="false" /> 

And in your code behind.

ProgressValue.Text = //Your value from your database. 

And just reference it from your Javascript there.

For your second problem, can't you just do in your code behind (written in C#)

//Process here
if(IDofGridView.Rows != null) 
{
    lblNoMissing.Visible = true; 
}

Or am I missing something?

How do I use my HTTP handlers for selected paths and MVC handler for the rest?

4 votes

I have an MVC2 application. I also have a set of ready HTTP handlers that derive from System.Web.IHttpHandler. How do I use them together?

I tried the following in web.config:

<system.webServer>
    <!--other stuff-->
        <handlers>
            <add name="MyCustomHandler" verb="GET" path="MySpecificPath*" type="CustomHandling.CustomHttpHandlerBase, CustomHAndlingAssembly"/>
            <add name="MvcHttpHandler" preCondition="integratedMode" verb="*" path="*.mvc" type="System.Web.Mvc.MvcHttpHandler, System.Web.Mvc, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL"/>
        </handlers>
</system.webServer>

yet control never reaches my handler and MVC handler is used for all requests.

How do I use my handler for one specific path and MVC handler for all other paths?

I believe that you need to ignore those specific paths from routes collection in application start. For example,

routes.IgnoreRoute("MySpecificPath/{*pathInfo}");

Otherwise UrlRoutingModule will match with the route and then http handler will be located via IRouteHandler for that route.

See this article for more info about mixing ASP.NET WebForms with ASP.NET MVC .