Pages

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.

Friday, July 5, 2013

TFS Build Error Solved: Set-AzureDeployment : Unable to write data to the transport connection: An existing connection was forcibly closed by the remote host

Hi guys,

Recently I faced a strange issue and figured out a solution as well so thought to share it because I didn't find much over the web about it.

We have created the TFS Build System built for on premise TFS server. We are using it for continuous deployment on Windows Azure Cloud Services and everything is working fine. There is an excellent documentation available here on MSDN so you can take a look at it.

What was the error?
The issue came in when build stopped working , prior builds were successful but we started facing issue with each new build.

Error Message was - Set-AzureDeployment : Unable to write data to the transport connection: An existing connection was forcibly closed by the remote host.

Actually in the background - build process has a workflow and it tries to execute an PowerShell command on build server for deployment of your cloud services in Windows Azure.

What is the solution?
The way build process workflow works is - it needs the .publishsetting file for doing deployments on your Azure Cloud Services.
All you need to do is , download the .publishsetting file for your Azure subscription (you can click here) and save it locally. Now go to the build server and replace your old .publishsetting file with this new one.
Now try queuing your builds - everything should work fine (If It would have worked before :) ).

If you are not using the build system but only using the PowerShell command i.e. Set-AzureDeployment to do the deployment then also you can opt the same solution , i.e. just download and replace your old .publishsetting file with new one.

Another solution
Now , even though the solution mentioned above worked for me fine - but I faced similar issue on another environment few days after I written this post and above solution didn't work so had to search for solution again and found a workaround.
So thought to edit the blog post and document this workaround so that it helps someone.

The changes needs to be done in the script - what this changes is - try to upload the cspkg file to blob storage and the create / updnate the deployment using blob url.

You can define the new variable $containerName at top of your file and initialize with some string value which will act as container name.

# If the target container does not already exist, create it. 
$containerState = Get-AzureStorageContainer -Name $containerName -ea 0
if ($containerState -eq $null)
{
    New-AzureStorageContainer -Name $containerName | out-null
}

Set-AzureStorageBlobContent -File $packageLocation -Container $containerName -Blob $blob -Force| Out-Null

$script:packageLocation = (Get-AzureStorageBlob -blob $blobName -Container $containerName).ICloudBlob.uri.AbsoluteUri

Hope this helps someone.

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.

Thursday, May 16, 2013

Error Solved : The specified module Azure was not loaded because no valid module file was found in any module directory

I was trying to configure the TFS build for continuous deployment on Azure Cloud Services by following the steps mentioned in the documentation http://www.windowsazure.com/en-us/develop/net/common-tasks/continuous-delivery/

After configuring everything, when I queued my build - I got this error message - The specified module Azure was not loaded because no valid module file was found in any module directory

As soon as I looked this error I knew that this was coming from the PowerShell file named as - PublishCloudService.ps1 which you can get from the link mentioned above.
After quick search - I got a link which actually resolved the issue.

What was the issue?

The build was trying to launch the process on build server - PowerShell.exe but somehow system was not able to find the AzurePowerShell module path.

Solution:

Open your PowerShell Script file and find the command Import-Module Azure and add the following line just above it
$env:PSModulePath=$env:PSModulePath+";"+"C:\Program Files (x86)\Microsoft SDKs\Windows Azure\PowerShell"

After this modification , save the file and try to queue the build again.

I hope this helps someone. 


Friday, May 3, 2013

Error creating the Web Proxy specified in the 'system.net/defaultProxy' configuration section - Azure Emulator

All right, again a quick post on a strange error I saw in Azure Emulator.

We had our ASP.NET MVC Site up and running when we used to run it in standalone mode.

So for Diagnostic purpose , we used Azure Diagnostic features and configured our web role with the settings which were needed to be done as described in article Here. and right after that we started facing the issue in our application which said

Error creating the Web Proxy specified in the 'system.net/defaultProxy' configuration section

After a long chase, reading few hundred posts on internet there was nothing logical which I could figure unless I came across this similar post.

Solution:

Open Web.config file of your application and check the trace listener's tag , In my case that was missing the filter type attribute.
So the correct tag should be like


<listeners>
 <add type="Microsoft.WindowsAzure.Diagnostics.DiagnosticMonitorTraceListener, Microsoft.WindowsAzure.Diagnostics, Version=1.8.0.0,
Culture=neutral, PublicKeyToken=31bf3856ad364e35" name="AzureDiagnostics">
   <filter type=""/>
 </add>
</listeners>

Hope this helps someone.



Server Error 500 Solved : Azure Emulator and ASP.NET MVC

Hi Guys,

A quick post on how we solved the strange issue in Azure Emulator.
We had our ASP.NET MVC site up and running , but when we used to run it in the Azure Emulator - we used to get an error with code 500.

After long research and reading various posts on it , nothing helpful was found.

What was the reason behind this error?

There is a class file named WebRole.cs for any web role project in Azure. This class is inherited from another class known as RoleEntryPoint.
So the WebRole.cs usually contains override of a method known as OnStart().
There are few more methods you can override in this class like OnStop() and OnRun()

In our case the OnRun() method was having empty implementation and was missing base.Run() statement which was causing the problem.

After adding simply one statement i.e. base.Run() in the OnRun() method everything started working fine.

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.