Pages

Showing posts with label MVC. Show all posts
Showing posts with label MVC. Show all posts

Wednesday, September 21, 2016

Solving Error 403 forbidden after deploying MVC web applications in Azure VM

As you have reached here and reading through this post, it makes me assume that you are facing the same issue which I did and are looking for solution after trying multiple workarounds for the error i.e. Error 403: Forbidden whenever any MVC application is deployed on Azure Virtual Machine.

Based on the error title, it appears that this must have to do something with permissions to some resource in IIS but that is not the thing here and I came to know this only after spending significant amount of efforts behind this. Lesson learnt– Error message could be misleading.

Initial investigation lead me to multiple solutions and looking at the answer’s help count on different sites it appeared that mentioned solutions were working for other people, but why not for me?

As mentioned, there are multiple links you will get describing resolutions which worked for number of people below are few such links


What worked for me?

After trying all the possible solutions mentioned in the links I was still getting same error. Here is the thing which worked for me

I was simply missing few IIS settings which I did not do while enabling IIS role on my Azure VM (Note that I am using Windows Server 2012 R2)

All I needed to do is,

Open Server Manager on VM hosting my MVC web application

Click on Add roles and feature



Reach to the screen for selecting the role on this server and make sure you have enabled below two features along with other required features to enable IIS role.


Note that, I managed to solve this by enabling below checkboxes (as shown above)
  • ASP.NET 4.5
  • .NET Extensibility 4.5
And after completing the installation, the 403 Forbidden error was gone.

Sunday, January 19, 2014

Inconvenient MVC Web Optimization Framework and High CPU Utilization

While I am writing this post I am bit relaxed and listening to 'bollywood' music so don't wonder if you find anything off topic or typos :), lazy weekend!!

What was the issue?

Last week, while working with the Window azure cloud services we tried to stress test it and guess what we found? CPU spikes!!
Initially we thought that this might be something related to load on the server as it was a small VM instance but at the same time the results were unbelievable as number of concurrent requests to the server were comparatively less. This gave us the kick start and we started to drill down to the real issue.

The approach:

It all started with several meetings with few brainy people around as I was clueless, some even directly said man your application got memory licks..but then
Thanks to the Visual Studio profiling framework which helped me a-lot to drill down into real issue about this CPU spikes. You can read about how to use this feature and how it helps in my blog post here Profiling windows azure cloud services - http://passionatetechie.blogspot.in/2014/01/profiling-for-windows-azure-cloud.html

When I tried to stress test the service and tried to collect the profiled logs , found that there were these two methods which were taking almost more than 80% of CPU, wowwwwww!!
1. Scripts.Render
2. Styles.Render

 Note - I was using ASP.NET MVC web optimization nuget version 1.0

Irony is, these methods are from the web optimization framework of ASP.NET MVC which is suppose to improve the performance of your web application by bundling the java-scripts and css files. More info about bundling here - http://www.asp.net/mvc/tutorials/mvc-4/bundling-and-minification

All right then of course the straight way to remove these calls from application and try to stress application again and check results. we did exact same thing and this time application performed pretty well!! no CPU spikes!! man bingooo!!!!!!

But then why in my application the optimization framework was doing something like this? why ? why why and why.......? this question even appeared in my dreams!!
I started search around it but didn't find something helpful, I even started doubting my decision about removing those calls from the application unless I hit this post here
http://stackoverflow.com/questions/14210721/mvc-4-on-azure-scripts-render-bundles-jquery-slow and
http://stackoverflow.com/questions/12230246/azure-cache-preview-outputcache-high-cpu-slow

Here is why and it is purely based on what I understood

When you use the bundling (Web optimization framework) - server uses the caching.
But now as you are mentioning the setting in your web.config file that you are not using default caching of server anymore instead you want to use the Windows azure distributed cache.
Like this


<caching>
  <outputCache defaultProvider="DistributedCache">
    <providers>
      <add name="DistributedCache" 
type="Microsoft.Web.DistributedCache.DistributedCacheOutputCacheProvider, 
Microsoft.Web.DistributedCache" cacheName="default" dataCacheClientName="default" />
    </providers>
  </outputCache>
</caching>

So seems this web optimization framework doesn't understand this distributed cache and it simply ignores the caching part.
Due to this it tries to recompile your bundles every time with each request which causes higher CPU utilization.


I also had the distributed cache related settings in my application's web.config , so I decided to remove both from my application i.e. Bundling as well as distributed caching - it worked and CPU utilization never touched the boundary.


Takeaways:

In case you are facing the same issue of high CPU consumption on the web server in your ASP.NET MVC application or cloud service then
1. Run the VS Profiler locally and see whats the root cause of it
2. If you find the Optimization framework APIs are taking most of the CPU then try removing it and stress your application again to see the results.

Next step:

According to this link http://aspnetoptimization.codeplex.com/workitem/46 , its the discussion on codeplex on very same issue but If you go to the comments section then someone said that they have fixed it in the next version of nuget. (i.e. post version 1.0)
I havent tried using next version of this nuget but when I will do it I will update this post.

Hope this helps and stops wondering someone about why my CPU percentage is higher when using web optimization framework of MVC.







Thursday, December 5, 2013

Working with boolean values and hidden fields in MVC 4



Hi guys,

This is quite simple but I learned something new in MVC today, so thought to share with you all.

I was trying to assign a Boolean field to a hidden field using ViewBag in MVC

<input type="hidden" id="somehiddenfield" value="@ViewBag.MyBooleanValue" />

And now when I was trying to read the value using jQuery it was always returning me hidden field’s value as “value” which was quite strange to me as I was expecting true or false.

var hiddenVal = $("#somehiddenfield").val();

After a quick search, came to know that this has been changed a little in MVC 4 , now it follows the checkbox behavior.
i.e. you will get the hidden field’s value as “value” when the Boolean value will be true and nothing when Boolean value will be false.

So you might need to change the implementation a little if you explicitly want to read the true and false as hidden field values from jQuery.

<input type="hidden" id="somehiddenfield " value="@(ViewBag.MyBooleanValue.ToString())" />

 
Hope this helps someone.

Tuesday, August 27, 2013

Error Solved : http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name was not present on the provided ClaimsIdentity.

While working with MVC application , I came across an interesting thing and got something to learn from it so thought to share.

Scenario :
Typically when you implement any MVC web application , you want to implement some security features in it and hence use of anti-forgery token is one of the approach I was trying to implement in one of my MVC web application.

How it works?
Internally how it works is , in traditional web application which are not claims aware – it simply uses User.Identity.Name as anti-forgery token to validate form submitted.  
But when we try the same with claims aware applications– it throws an error. 
Why? 
Because now it tries to use the claims of type NameIdentifier and IdentityProvider (by default).

Error:
‘http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name' was not present on the provided ClaimsIdentity.

Solution:
Either your claims provider should send you the claims of type NameIdentifier as well as IdentityProvider , but in my case I was not having both claims with me.
So I had to use the following workaround to resolve this issue -

Add the following line in the App_Start method of the application.

AntiForgeryConfig.UniqueClaimTypeIdentifier = "http://your-sts.net/user/EmailAddress";

As the name suggest - it makes application aware that the unique claim type provider is EmailAddress and not the default one.


After this change , you can see the __RequestVerificationToken on the details page source information.

Conclusion:
This Error can be solved by letting application know that which is the claim type you want to use as unique identifier. In my case I am using EmailAddress because I had this type of claim available with me so you can also use any other claim type which your sts is providing you.

Thursday, May 23, 2013

Passing String Collection or Array from Controller to View Script in MVC 4

Hi Guys,

This is going to be a short post but thought to just keep this for the record, as I had to search on this for some time.

Scenario:
All I was trying to do was to initialize collection of strings in the controller and wanted to pass this collection to the view.
View was having the JavaScript function which required to have this collection in the form of array.

After searching around this I found a solution which is a single liner :).

Here is my controller where I have simply initialized the string collection and passing through the ViewBag on the view

Controller:


public ActionResult Index()
{
   List<string> entites = new List<string>();
   entites.Add("User 1");
   entites.Add("User 2");
   entites.Add("User 3");
   entites.Add("User 4");

   ViewBag.Users = entites;
   return View();

}


View / JavaScript:

<script>
    $(document).ready(function ()
    {
        var usersArray = @Html.Raw(Json.Encode(ViewBag.Users))
           
        //Some Code..


    });
</script>

Output:

var usersArray = ["User 1","User 2","User 3","User 4"]




Hope this helps someone.

Sunday, March 24, 2013

Creating Custom HTML Helpers - ASP.NET MVC 4

What are HTML Helpers in ASP.NET MVC?

HTML Helpers are nothing but the way of rendering HTML on the view page in ASP.NET MVC. Typically what we have in traditional ASP.NET web forms is Web Controls to achieve same functionality but with the evolution of MVC pattern , you don't have any web controls to add on to the view pages.
In simple words - it is just a method which returns you a string , and string is HTML.

Example of HTML Helpers:

ASP.NET MVC framework ships with various inbuilt HTML helpers such as ActionLink , Label.
Lets take a look at how a HTML helper is added to the view page. I am considering Razor view engine for this example.


@Html.ActionLink("Display Name of Link", "MethodName", "ControllerName");

Example above shows how OOB Action Link is used to render the HTML hyperlink on the view page.

Another example is shown as below where it is used to render the Html label tag to render Store Name property of model class. 

@Html.LabelFor(model => model.StoreName)

 Why to use Html Helpers?

Question might have poped up in your mind by now that Html helpers are just going to render the string of html then why do I need to use them ? If I know the Html syntax then why not add the Html directly on to the view page? 
Answer is simple, it depends how clean and consistent you want to make your application. of course you can do the direct addition of html tags on your view pages but if you observe second example - you can see that it is simply rendering the label tag on view page for a property in model at run time. so it just for making developer's life more easy and to have the cleaner html for your view page.

Need of Custom Html Helpers?

Well, there is always need to do some custom stuff on top of what framework offers, and reason for doing this is either business requirement or to get things done in smarter way.

Writing a custom Html helper is nothing but writing an extension method. you are actually writing an extension method for HtmlHelper class.
Being a SharePoint developer I always find this task similar to creation of a web control where you override the render method of base class and do the custom Html rendering. 

Creating Custom Html Helper

All right , for demo purpose I will keep the example simple - I will simply write an Html helper which will render the header of any content on view page.
This is done simply by using the <header> tag of Html 5.

Step 1: Define your custom static class for creation of your custom Html helpers

public static class DemoCustomHtmlHelpers
{

}

Step 2: Add static method to the class and make sure that return type is MvcHtmlString. Write an input paramter of method as HtmlHelper and also a string for which the header tag needs to be generated.
You might need to add System.Web.Mvc namespace to your class.

public static MvcHtmlString Header(this HtmlHelper helper, string content)
{

          
}

Step 3 : Add the rendering logic in the method , you can take help from TagBuilder class to generate Html tags to be rendered.

public static MvcHtmlString Header(this HtmlHelper helper, string content)
{
   var tagBuilder = new TagBuilder("header");
   tagBuilder.InnerHtml = content;
   return new MvcHtmlString(tagBuilder.ToString());
}


Step 4: Build the project and open any of the view page. Now you can use your custom Html helper to render the header. Make sure that your view page has correct using namespace for using your custom Html helper extension.


@Html.Header("Create")


When you observe the view page's Html , you will be finding the generated Html tag by our Custom Html helper extension

<header>Create</header>


So this is all guys , have fun and try to create these Html Helper extensions in your scenarios.