Wednesday, December 4, 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.

Saturday, September 7, 2013

Unable to open TFS Build Process Templates in Visual Studio 2012

Hi guys,

Yet another development issue and solution

Issue:

After installing Visual Studio 2012 , I was not able to open the build process templates on my environment. Strange this was - they were getting opened correctly in other environments or on other machines.

What was the error - 

System.IO.FileNotFoundException: Could not load file or assembly 'Microsoft.VisualStudio.SharePoint.WorkflowExtensions, Version=11.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified.
File name: 'Microsoft.VisualStudio.SharePoint.WorkflowExtensions, Version=11.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'

What was the issue and solution?

Well, not quite sure about the exact issue but only solution which I could find to resolve this error is to install the workflow manager on your environment.
Here is how you can do it

Launch you command prompt (as administrator) and run this command

C:\Program Files\Microsoft\Web Platform Installer>WebpiCmd.exe /Install /Products:WorkflowManagerTools /AcceptEula

After doing this I was able to open build process templates on my environment.
Hope this helps you.

Reference - Here

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.



Thursday, May 2, 2013

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.



Saturday, February 23, 2013

Passing Parameters to Events - C#

All right , again one post away from my favorite SharePoint world but this is kind of generic which can be used anywhere in C#.

Today we will see how we can pass some custom parameters to any event in C#.

Consider a scenario where you are calling some method asynchronously and execution is happening in loops.
In General, we register an event with the method which gets called after method call is completed. but as the asynchronous execution is happening in the loop , so in the on completed event you never know which for which call the execution has been completed.

Check out this sample scenario where I have a simple windows forms application with two buttons and label, both buttons are registered to a same on click event. Now say, on click of each button I want to perform some independent actions and also want to pass some parameters to the on click event. I know there can be many approaches to do this but I have just taken this example to prove the actual point of this blog post.


public Form1()
{
   InitializeComponent();

   button1.Click += new EventHandler(button_Click);
   button2.Click += new EventHandler(button_Click);
}

void button_Click(object sender, EventArgs e)
{
   label1.Text = "Hi ";
}

Now on both button clicks - the text of a label is printed as 'Hi' as the event is common between both buttons.

Now what I want is to pass some extra information to the on click event from both buttons , you can pass on any number and type of  objects as you want. for the example I will send a string and Enum to click events.

I will also need to modify the button click event , as I am going to send some parameters to event so I need to catch those in the event.

public Form1()
{
  InitializeComponent();

  button1.Click += delegate(object sender, EventArgs e) { button_Click(sender, e, "This is   From Button1", MessageType.B1); };

  button2.Click += delegate(object sender, EventArgs e) { button_Click(sender, e, "This is From Button2", MessageType.B2); };

}

void button_Click(object sender, EventArgs e, string message, MessageType type)
{
   if (type.Equals(MessageType.B1))
   {
      label1.Text = message;
   }
   else if (type.Equals(MessageType.B2))
   {
      label1.Text = message;
   }
}

enum MessageType
{
   B1,
   B2
}


Thursday, February 21, 2013

Creating Custom Workflow Activity - Windows Workflow Foundation 4.0


It’s been long since I written new blog post , but today got some time to write one on which I was working recently.
This time it’s little away from SharePoint world, just to stroll Windows Workflow Foundation 4.0. The time I am writing this post, Bollywood music is running over my ears so I am really in mood of writing J

Workflow Foundation

Microsoft has provided us a very strong foundation since release of .NET Framework 3.5 known as Windows Workflow Foundation (WF), and it is getting much better with every release. The latest one is WF 4.0 and is really useful in mapping your business processes to workflows. The basic idea behind any workflow creation is to automate the business processes and do it more declarative way.

Need of Custom Activities

Though the framework provides you lots of inbuilt activities so that you can grab them and directly use in your workflow application as it is, but again in most of the cases business scenarios are complex and requirement cannot be solved directly using out of the box activities. So in such cases what needs to be done? Nothing worry, similar to SharePoint workflows – windows workflow foundation also supports creating custom activities. (Awkward to say but WF seems much much stronger when compared to SharePoint workflow engine). You can also provide input parameters to your activity and activity can return you output which can be later used in the workflow.

Example

Ok enough of theory and let’s get in to the action.
Intentionally I have taken very simple example for demo, it simply uses a custom activity and workflow simply adds a new product in the products database and finishes. Nothing much but just to understand the creation and execution of custom activity.
I will start by creating a project in Visual Studio 2012
Open up visual studio and click on create new project. From left side of new project window – click on workflow category and select Workflow Console Application project.
You will see a Workflow.xaml opened up in the editor. This is basically playground for you where you can start designing you workflow.
If you take a look at left side of the window , you will see something familiar as Toolbox (remember ASP.NET web applications? ) and here is the place where you will find all out of the box activities provided by WF 4.0
I have designed a very simple workflow which prints a line to the windows when workflow starts and do some execution of activities and then again prints line to window when workflow finishes.



Now wait a minute, did you observe something called as AddProduct there in the editor as well as in the toolbox? From where on the earth that came?
Nothing suspicious going on here so don’t worry, this is the custom activity which I created which simply adds a new product in the products inventory. I won’t go in much details of the how I have created the database and used it using the entity framework but we will concentrate more on creating that custom activity and passing parameters to it.

Implementation

Custom activities in the windows workflow foundation are nothing but the class which is derived from a class known as ‘CodeActivity’.
Once you create your own class and derive it from CodeActivity , you will need to override the execute method of the parent class. This method gives you the workflow execution context so that you can play around input and output parameters.
Following code is just for understanding purpose on how we can create custom activity, you can add any complex logic in the execute method.
So here is the AddProduct activity code



public class AddProduct : CodeActivity
{
  public InArgument<int> ProductId { get; set; }
  public InArgument<string> ProductName { get; set; }
  public InArgument<string> ProductDescription { get; set; }
  public InArgument<int> ProductPrice { get; set; }
  public InArgument<int> ProductDiscount { get; set; }
  public OutArgument<string> Result { get; set; }

  protected override void Execute(CodeActivityContext context)
  {
    try
    {
      using (var productEntities = new ProductsEntities())
      {
        productEntities.ProductInfoes.Add(new ProductInfo
        {
           ProductId = ProductId.Get(context),
           ProductName = ProductName.Get(context),
           ProductDescription = ProductDescription.Get(context),
           ProductPrice = ProductPrice.Get(context),
           ProductDiscount = ProductDiscount.Get(context)
         });
         productEntities.SaveChanges();
        }
              
    context.SetValue(Result, "Product with Id : " + context.GetValue(ProductId) + " Added Successfully!!");
     }
     catch (Exception ex)
     {
       context.SetValue(Result, "Error While Adding Product : " + ex.Message);
     }

   }
  }

As you can see that this activity is having 5 input parameters and one output parameter which is later consumed by workflow write line activity (at end of workflow) to display the message to users.
Once you are creating the class and done with implementation of execute method, then just rebuild your solution and observe the toolbox. Framework automatically adds the custom activity for you in the toolbox.
Now question is how to pass parameters to the activity?
Once the activity is available in the toolbox, simply drag and drop to the workflow. Right click on activity and go to the properties window.
Here you will need to provide the input parameters and also if you are returning something from your custom activity then you will need to catch that output to some workflow variable.



I am passing some hardcoded values as parameters to the activity but this can be made dynamic by passing in workflow arguments.
Result is nothing but the output message which our activity is producing from execute method. I have simply assigned that result to the workflow variable called as varResult , so that I will be able to use it in workflow context.
That’s all guys, I hope now you know how to create custom activities in Windows Workflow Foundation and use them to make your life easier. Hope this helps someone.