No ASP.NET MVC 5 Web Application Template on VS 2012?

[Origin]: http://stackoverflow.com/questions/20607648/no-asp-net-mvc-5-web-application-template-on-vs-2012

After creating a new project using ASP.NET MVC 5 Empty Project, you can right click on the project, then click Add.. > New Scaffolded Item..., select MVC on the left, then MVC 5 Dependencies and choose Full dependencies from the prompt.

This will add a default layout (Views\Shared\_Layout.cshtml), Content folder, Scripts folder with bootstrap, jquery, modernizr, etc, and other things the Web Application template creates.

If you get the error “CS0103: The name ‘Styles’ does not exist in the current context” just add <add namespace="System.Web.Optimization"/> under <namespaces> in Views/web.config

shareedit

Percentage Encoding of special characters before sending it in the URL

[Origin]: http://stackoverflow.com/questions/16186042/percentage-encoding-of-special-characters-before-sending-it-in-the-url

I need to pass special characters like #,! etc in URL to Facebook,Twitter and such social sites. For that I am replacing such characters with URL Escape Codes.

return valToEncode.Replace("!", "%21").Replace("#", "%23") .Replace("$", "%24").Replace("&amp;", "%26") .Replace("'", "%27").Replace("(", "%28") .Replace(")", "%29").Replace("*", "%2A");

It works for me, but I want to do it more efficiently.Is there any other way to escape such characters? I tried with Server.URLEncode() but Facebook doesn’t render it.

Thanks in advance,
Priya

shareedit

You should use the Uri.EscapeDataString method if you want to have compatibility with RFC3986 standard, where percent-encoding is defined.

For example spaces always will be encoded as %20 character:

var result = Uri.EscapeDataString("a q");
// result == "a%20q"

while for example usage of HttpUtility.UrlEncode (which is by the way internally used by HttpServerUtility.UrlEncode) returns + character:

var result = HttpUtility.UrlEncode("a q") 
// result == "a+q"

What’s more, the behavior of Uri.EscapeDataString is compatible with client side encodeURIComponent javascript method (except the case sensitivity, but RFC3986 says it is irrelevant).

shareedit

[Originally posted by]: http://stackoverflow.com/questions/13405130/mvc-razor-editable-dropdownlist

I am looking for a code to make the dropdown list editable in MVC razor. @Html.DropDownList provides the standard select list, but the values are not editable.

I tried an example from a tutorial, but it does not seem to work.

shareedit

First need to add the script reference to the page:

<script type="text/javascript" src="jquery.editable-select.pack.js></script>

This If you host this script on your server.

You only need to set the id on you razor definition of the dropdown and then do this:

$(‘#nameOfDropDown’).editableSelect({…});

After doing this and checking the documentation of this plugin you might be able to get a editable select list.

shareedit

ASP Request Queue (IIS 6.0)

[Originally posted by]: https://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/42706aba-107b-4d6b-84f5-b58b50a6df97.mspx?mfr=true

For requests to ASP pages, after the worker process picks up the request in the application pool queue, the request is sent to the Internet Server API (ISAPI) handler, which passes the request along to Asp.dll. If a thread is available, the ASP request is processed. If a thread is not available, the request waits in the ASP request queue. Requests are processed in the order in which they are received. If the ASP request queue fills to 3,000 requests (the default metabase value of AspRequestQueueMax) the server rejects the request, logs the error in the IIS log, and sends a 500 error (Server Too Busy) to the client.

If the number of queued requests is under 3,000, users with the last requests are forced to wait (called queue latency) as other requests are pulled from the queue and executed. This is an acceptable condition if the queue is cleared within a few seconds. After a few seconds, most users believe the server is not responding and click the Stop button on their Web browser. High queue latency results in poor performance for all ASP requests for the entire time the queue is saturated, because all ASP requests in a worker process share the same queue. Additionally, CPU utilization tends to spike when the queue is saturated, which results in slower response times.

You can improve ASP queuing by adjusting the default values for the AspProcessorThreadMax and AspRequestQueueMax metabase properties. AspProcessorThreadMax represents the maximum number of threads per processor, and AspRequestQueueMax represents the maximum size of the request queue. For more information about these metabase properties, see the AspProcessorThreadMax Metabase Property and AspRequestQueueMax Metabase Property.

Table 7.2 describes performance counters and their ideal values for ASP queuing. Monitor these counters in System Monitor by using a chart with one-second intervals before you change any metabase properties on your server. For more information about IIS 6.0 counters, seePerformance Counters Reference.

Table 7.2 Preferred Values for Active Server Pages Queuing Performance Counters
Object\Counter Preferred or Ideal Value

Active Server Pages\Request Wait Time

As low as possible. This counter determines how long clients connecting to your site must wait before the page starts executing. If this number is high, users connected to your site might be frustrated by slow response times.

Active Server Pages\Requests Queued

As low as possible. If large queues develop, or if this number fluctuates, you might need to adjust the metabase properties that affect ASP queuing, as described in Tuning AspRequestQueueMax. This counter is not as important as the Request Wait Time counter. Queues can clear quickly, but long wait times can frustrate users connected to your site.

Active Server Pages\Requests Rejected

As low as possible. If this number is high and Requests Queued is high, you might be reaching the ASP request queue default maximum of 3,000. You might need to adjust the metabase properties that affect ASP queuing, as described later in Tuning AspRequestQueueMax.

Active Server Pages\Requests/second

Application-specific. You want this number to be as high as possible. If Requests Queued is high, this number will typically be lower. Adjusting the metabase properties that affect ASP queuing can increase it.

Processor\% Processor Time (for each processor)

Application-specific. If Requests Queued never increases and % Processor Time is low, it is likely that ASP queuing is not affecting the performance of your site.

Everything you ever wanted to know about ASP.NET request queueing

[Originally posted by]: http://blog.leansentry.com/all-about-iis-asp-net-request-queues/

Did you know there are 5 places where ASP.NET requests can become queued on an IIS server?

Not all these queues are documented, and it can be very difficult to tell when and where requests are queued.

As part of LeanSentry’s automatic hang detection and troubleshooting, we had to figure out the IIS/ASP.NET request queueing behavior. So, we wanted to share the knowledge with everyone so you can properly track down queued requests.

Read on to learn all about these queues, how to tell when requests are queued, and how to identify the exact requests that are actually queued!

(UPDATE: Want to learn how to troubleshoot common ASP.NET issues like hangs, high CPU, etc?
Take our new LeanSentry Production Troubleshooting course. Its a free 5-7 email course that teaches the production troubleshooting techniques we’ve been using for years.)

The details on IIS and ASP.NET queues

When a request is received by your IIS server, here are all the queues it must clear in order to be processed:

1. HTTP.SYS: Application pool queue

Requests are always first queued here, for the IIS worker process to dequeue.

Behavior: Requests begin to accumulate when IIS falls behind in dequeueing requests. The limit is set by the application pool’s configured queueLength attribute, and defaults to 1000. When limit is reached, HTTP.SYS returns 503 Service Unavailable.

Monitor: “Http Service Request QueuesCurrentQueueSize” performance counter

2. IIS worker process: completion port

The dequeued requests queue up here, waiting for IIS i/o threads to pick them up.

Behavior: There is usually up to 20 possible requests queued here, and they are dispatched up to N at a time (where N = number of processor cores).

Monitor: This is an undocumented queue, with no available reporting.

3. ASP.NET: CLR threadpool queue

ASP.NET queues all incoming requests to the CLR threadpool.

Behavior: If all CLR threads are busy, requests can queue up here up to the configuredprocessModel/requestQueueLimit. When there are more than this many total requests (executing + queued), ASP.NET returns 503 Service Unavailable.

NOTE: Any async modules also re-post requests to the CLR threadpool, so requests can become “re-queued” again later in the request processing.

Monitor: “ASP.NET v4.0.30319Requests Queued” performance counter

NOTE: This counter is global for the entire server, there is no way to tell which website/apppool has queued requests. It also does not work correctly in Integrated mode for .NET 2.0/3.5.

4. ASP.NET: Integrated mode global queue

In Integrated mode, ASP.NET will queue all incoming requests after the configured concurrency limit is reached.

Behavior: Concurrency limit is set by the MaxConcurrentRequestsPerCPU registry key orapplicationPool/maxConcurrentRequestsPerCPU attribute (Defaults to 12 on .NET 2.0/3.5, and 5000 on .NET 4.0+) and MaxConcurrentThreadsPerCPU registry key or theapplicationPool/MaxConcurrentThreadsPerCPU attribute (defaults to 0, disabled).

Monitor: “ASP.NET v4.0.30319Requests Queued” performance counter

5. ASP.NET: Classic mode application queue

In Classic mode, ASP.NET will queue all incoming requests to the per-application queue when there are not enough threads.

Behavior: The threads available for request processing are determined by available threads in the CLR thread pool, minus the reserved threads set by the httpRuntime/minFreeThreads andhttpRuntime/minFreeLocalThreads attributes.

NOTE: This queue has poor performance, and does not guarantee FIFO in application pools with multiple applications (because threads are shared between multiple apps, so a single app can starve the other applications of available threads).

Monitor: “ASP.NET ApplicationsRequests in Application Queue” performance counter, with instances per application.

How to tell which requests are queued

Ok, so we can now tell whether requests are queued, but how we can tell which requests are queued vs. which requests are processing?

This helps us identify which requests are causing blocking in the system (and possibly causing a hang), vs. the requests that are simply queued as a result.

Well, we can’t tell which requests are queued in queues 1 & 2, because they have not yet been picked up by IIS. We also cant tell which requests are queued in the Classic mode per-application queue. Lucky for us, most queueing for ASP.NET apps in Integrated mode (default) happens in queue #3 and #4. And while we can’t always determine his 100%, there is a heuristic that can help us separated queued from processing requests 90% of the time. In my experience, that has been good enough!

Here is the trick:

1. Snapshot the currently executing requests

> %windir%system32inetsrvappcmd list requests /elapsed:1000

You’ll get a list like this:

// hanging!
REQUEST "7000000780000548" (url:GET /test.aspx, time:30465 msec, client:localhost, stage:ExecuteRequestHandler, module:ManagedPipelineHandler)
REQUEST "f200000280000777" (url:GET /test.aspx, time:29071 msec, client:localhost, stage:ExecuteRequestHandler, module:ManagedPipelineHandler)
…
// queued!
REQUEST "6f00000780000567" (url:GET /, time:1279 msec, client:localhost, stage:AuthenticateRequest, module:WindowsAuthentication)
REQUEST "7500020080000648" (url:GET /login, time:764 msec, client:localhost, stage:AuthenticateRequest, module:WindowsAuthentication)

2. Use this rule to identify the queued requests:

A group of requests to an Integrated pipeline ASP.NET app are queued if they are:

  1. Processing in an ASP.NET module
  2. There are no other requests to the same app in an ASP.NET module in an earlier pipeline stage
  3. There are no other requests to the same app in a different ASP.NET module/stage with higher avg. latency.

Basically, this takes advantage of the fact that the first ASP.NET module in the request processing pipeline will cause ASP.NET to queue the request, showing it as processing in that module in the executing request list. The request at the front of the list have been executing the longest, which means they are NOT queued (queueing is FIFO).

Practically, this just means that the last block of requests in the list the same ASP.NET module/stage are queued requests. Think about it. From experience, these usually show as blocks of:

REQUEST "6f00000780000567" (url:GET /, time:8076 msec, client:localhost, stage:AuthenticateRequest, module:WindowsAuthentication)
REQUEST "6f00000780000567" (url:GET /login, time:5601 msec, client:localhost, stage:AuthenticateRequest, module:WindowsAuthentication)
REQUEST "6f00000780000567" (url:GET /, time:5200 msec, client:localhost, stage:AuthenticateRequest, module:WindowsAuthentication)
REQUEST "6f00000780000567" (url:GET /test.aspx, time:3209 msec, client:localhost, stage:AuthenticateRequest, module:WindowsAuthentication)
REQUEST "6f00000780000567" (url:GET /test.aspx, time:1690 msec, client:localhost, stage:AuthenticateRequest, module:WindowsAuthentication)
REQUEST "6f00000780000567" (url:GET /, time:1279 msec, client:localhost, stage:AuthenticateRequest, module:WindowsAuthentication)

Simply because for most ASP.NET apps, WindowsAuthentication is the first ASP.NET module to process the request in the AuthenticateRequest stage. If you have a custom module or global.asax processing BeginRequest, expect to see that.

We hope this will help you make sense of queued requests when troubleshooting slow or hung ASP.NET requests.

To learn more about LeanSentry’s automatic hang detection and troubleshooting, check outThe holy grail: Automatically diagnose IIS & ASP.NET website hangs.

Best,
The LeanSentry Team

Integrating a persisted WF4.0 Workflow with MVC

[Originally posted on]: https://stevenwilliamalexander.wordpress.com/2010/11/16/integrating-a-persisted-wf40-workflow-with-mv/

Integrating a persisted WF4.0 Workflow with MVC

Introduction

Writing this as lately I’ve been interested in WF4.0 (it’s always pronounced “dub-F” in my head) and saw a post about using WF with MVC to handle a site registration wizard. Thetutorial it linked to used a state machine (WF only supports Sequential OOB) workflow without persistence, which made me think that you could easily use a normal workflow with persistence to do a lot of other things inside a web application. WF which is part of .NET4.0 allows you to easily create and call workflow processes, small or large, from anywhere inside .NET code and it’s been drastically improved since .NET3.5. That ease makes it practical to use workflow in places which it was previously too complicated to integrate, places where we normally manually code a process into business or web logic making it difficult to maintain and add standard features like tracing/auditing.

To run the sample or try this yourself you will need .NET4.0 and Visual Studio 2010, the instructions below are a simple overview and do not include all code or references.

1. Creating the WF SQL Persistence store

WF4.0 supports using a default SQL Persistence store, using a DB created using scripts in the .NET4.0 framework directory. Simply create a new DB (call it whatever you like) on your server and run the following scripts:

  1. C:WindowsMicrosoft.NETFrameworkv4.0.21006SQLenSqlWorkflowInstanceStoreSchema.sql
  2. C:WindowsMicrosoft.NETFrameworkv4.0.21006SQLenSqlWorkflowInstanceStoreLogic.sql

Multiple workflows can share the same DB or you can separate them out if you want.

2. Creating the MVC site and Workflow Activity Library

Solution

In Visual Studio, create a new MVC Web Application and add another project of type “Activity Library” (under templates Workflow) to hold your workflow. I also added a console application to test the workflow independently but this is not necessary.

3. Creating the Workflow

Workflow_logic
Wizardstep

Delete the existing workflow activity and create a new one with the name WizardActivity, in the activity drag and drop a Flowchart from the toolbox onto the workflow (using this instead of a state machine) and add a variable “Outcome” to the Flow chart scope (used to store the outcome Next/Back of the steps). In the Activtiy project add a new Class, WizardStep, which will be generic custom activity used for all the steps in the workflow. This activity contains the bookmark code which is used to halt and persist the workflow at the steps. Add the code and compile the project, this will update the workflow toolbox adding WizardStep and allowing you to drag and drop it onto the workflow. Add three Wizard steps to the workflow, setting the Name to “StepN“, Bookmark Name to “StepN” and Input to “Outcome” (this is an output parameter which will set Outcome to the value supplied when resuming the Bookmark in the custom activity). Add a custom Complete activity (which does nothing) and link up the workflow using Decision controls (set condition to “Outcome.Equals(“Next”)”) and arrows as per image. Lastly add a new Class WizardHostHelper (copy code from sample), which acts as the host for the workflow; creating the Workflow application object, setting instance store values, starting/resuming the workflow, actioning the bookmarks.

4. Update the MVC application to use the Workflow

Now to integrate the workflow into the website.

  1. Add a new class WizardModels, to hold the model logic for the wizard steps and workflow service (wrapper to WizardHostHelper).
  2. Add a new controller WizardController, for controller logic used in the wizard.
  3. Add four new views under Wizard, Step1-3 and final, for the views used in the Wizard.
  4. Update AccountModel, add a Guid parameter workflowKey to the MembershipService.CreateUser method, this will store the Workflow Instance key in the standard ASP user security providerUserKey. Also add a method GetUserWorkflowKey to return the key for a username.
  5. Update AccountController, changing Register method to start a workflow instance for the user using the WizardModels.WorkflowService and supply the workflow key into CreateUser. Update both Register and Logon to redirect action to the Wizard index.
  6. Update the web.config to set the instance store connection string.
Step1

And that should be it, registering a new user will now start the workflow process and redirect to the first step. Next/Back buttons on the step views cause the controller to action the steps, progressing the workflow. The workflow is persisted to the DB at each step, so even if the website goes down the current step of the user in the workflow is maintained. The workflow, rather than the controller, decides which step the website should display, separating the process logic from the controller logic.

There is very little code involved, just small service/host classes used to access the workflow and integrate with the website. To add persistence it only really took two lines of code in the host class (setting the workflow application instance store and telling it to persist when idle at the bookmarks), compared to the tutorial sample host. The workflow used could be much more complicated, branching to different steps depending on user response (e.g. redirecting to a different address screen if the user isn’t based in the UK) without adding complexity to the controller logic. As the workflow is separated from the website it can be tested independently (no website needed! automated testing!) and updated without large changes needed in the website. It’s also a very light weight (and cheap) way to add workflow, which is something we may need going forward. I’m currently looking at ways now to use WF with persistence in Azure cloud (without the upcoming Azure AppFabric) for simple workflow solutions, as right now we can’t use our current workflow applications like K2.

Attached sample inside word doc as Posterous won’t accept zips.

MVCWithWF_sample_attached.doc

How do I set the request timeout for one controller action in an asp.net mvc application

[From]: http://stackoverflow.com/questions/579523/how-do-i-set-the-request-timeout-for-one-controller-action-in-an-asp-net-mvc-app

I want to increase the request timeout for a specific controller action in my application. I know I can do it in the web.config for the entire application, but I’d rather change it on just this one action.

Web.config example:

<system.web>
  <httpRuntime executionTimeout="1000" />
</system.web>

How do I do it? Thanks,

Kyle

shareedit

You can set this programmatically in the controller:-

HttpContext.Server.ScriptTimeout = 300;

Sets the timeout to 5 minutes instead of the default 110 seconds (what an odd default?)

shareedit
<location path="ControllerName/ActionName">
  <system.web>
    <httpRuntime executionTimeout="1000"/>
  </system.web>
</location>

Probably it is better to set such values in web.config instead of controller. Hardcoding of configurable options is considered harmful.

shareedit