ASP.NET MVC 4 Redirects Incorrect Login URL /login.aspx

When working with ASP.NET MVC and WebMatrix.WebData.SimpleMembershipProvider, I faced an issue of ASP.NET redirecting to incorrect login page i.e. “/login.aspx” in case of unauthorized access. As a result, got server error something like below snapshot

Solution: 

The resolution is simple and somewhat intuitive. Somebody needs to tell ASP.NET my LoginUrl. There are two workaround for that which I have tried and worked for me.
  • Add a LoginUrl key in appSettings in web.config
<add key="LoginUrl" value="~/Account/Login"/>
  • OR Set the form loginUrl in   in web.config
<authentication mode="Forms">
<forms loginUrl="~/Account/Login" timeout="3000" />
authentication>
Another way around I found on stackoverflow is to set FormAuthenticationSettings but I didn’t give it a shot.
Finally, if you faced issue of redirect to ~/Account/Logon instead of ~/Account/Login in MVC 4 then make sure to check the PreserveLoginUrl is added and set true in your appSettings as mentioned in ASP.NET MVC 4 release notes
Hope it helps.

 

Android NetworkOnMainThread Exception

Hi folks,

Like me, if you are new to android platform and working with network requests such as using HttpRequest, HttpGet, or HttpPost etc. YOU may come across a “NetworkOnMainThread” exception or your application stopped responding. This really annoys in a way that your code complies nicely and smells like *it should work* but on runtime it throws an exception which result in application termination.

The other day I was working with RESTful services and was developing a sample code to send simple HttpPut request to my services and got this error.

Solution:

Most likely the root cause will be either you are calling some network activity on your main thread and it has restricted thread policy and/or your app does not have enough permission. It can be solved by taking following steps:

  1. In AndroidManifest, make sure your application has permission to access network/internet.

  2. Use AsyncTask to enable network request to run asynchronously on another thread. Following is the code snippet that demonstrates use of HttpPut request using AsyncTask

Disclaimer:The code below is not optimized to be used in production environment, it’s just a sample to give idea about the solution. All views expressed are mine only

This would solve the problem!

For further reading, I would suggest to go through an article on performance “Android Threads, Handlers, and AsyncTask – Tutorial

IIS 7 not loading CSS and Image

Yesterday, I faced a wired yet crazy issue. My machine has a bit freshly installed windows 7 and so while running web site hosted on local IIS, I was getting a pretty plain asp.net pages without CSS and Images being loaded properly.

After a little investigation, it appears to be a problem with Windows feature installation. All you have to do is run ‘optionalfeature’ command and make sure ‘Static Content’ option is checked.

Windows Features - Static Content

Hope this would help you, if you face similar kind of issue.





Client Additional Parameters using Custom Headers in WCF

When building Service communication applications using Windows Communication Foundation, we often come to a situation where we have multiple clients communicating with WCF Service and we need to pass additional parameters from client to service. This may be due to number of reasons such as sharing a unique customer ID to identify certain elements for that particular client. In such scenarios, for every communication between client and server, you need this unique ID to treat each client accordingly.

Client-Server-Customer-Id-Parameter-WCF

In a typical disconnected environment over the internet you need to pass such data on each call to service and of course passing in each Service Method or Operation Call is confusing and not appropriate.

A good Solution is to pass additional parameters in SOAP headers utilizing with the help of Custom headers in WCF. A SOAP envelope contains a header and a body. Method call and its parameters are transformed to SOAP body whereas SOAP header usually contains application-specific information (like authentication etc.)

 image

A simple way to achieve this in WCF is to add MessageHeader in your proxy class as in code snippet below:

public partial class TestServiceClient : ClientBase&lt;Client.ServiceProxy.ITestService&gt;, Client.ServiceProxy.ITestService
{
    public TestServiceClient()
    {
        var header = new MessageHeader&lt;string&gt;("Customer Unique Id: 12345");
        var untyped = header.GetUntypedHeader("Identity", "http://www.adilmughal.com");
        OperationContext.Current.OutgoingMessageHeaders.Add(untyped);
    }&nbsp;
    //Other constructors and Service Method Calls
}

However this is really NOT a suitable approach as if you would be generating proxy using svcutil.exe or using Visual Studio then it will replace your proxy code.

A Better Solution to solve this problem is to utilize custom behavior extension in WCF to pass additional parameters in SOAP Message header. Following are the steps required on client:

1) Implement IClientMessageInspector to create custom message inspector

public class MyMessageInspector : IClientMessageInspector
{
    public void AfterReceiveReply(ref Message reply,object correlationState)
    {
       Console.WriteLine("SOAP Response: {0}", reply.ToString());
    }
        
    public object BeforeSendRequest(ref Message request,IClientChannel channel)
    {
       var header = new MessageHeader&lt;string&gt;("Customer Unique Id: 12345");
       var untyped = header.GetUntypedHeader("Identity", "http://www.adilmughal.com");
       request.Headers.Add(untyped);Console.WriteLine("SOAP Request: {0}", request.ToString());
       return null;
    }&nbsp;
}

2) Create a custom behavior class implementing IEndPointBehavior and BehaviorExtensionElement. Then add the custom message inspector in runtime in ApplyClientBehavior method as shown in code snippet below:

public class CustomBehavior : BehaviorExtensionElement, IEndpointBehavior
{
    public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
    {
    }

    public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
    {
        clientRuntime.MessageInspectors.Add(new MyMessageInspector());
    }

    public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
    {
    }

    public void Validate(ServiceEndpoint endpoint)
    {
    }

    public override Type BehaviorType
    {
        get {   return typeof(CustomBehavior);  }
    }   

    protected override object CreateBehavior()
    {
        return new CustomBehavior();
    }
}

3) Finally, register behavior in .config under

<behaviors>
 <endpointBehaviors>
 <behavior>
 <customInspector />
 </behavior>
 </endpointBehaviors>
</behaviors>
<extensions>
 <behaviorExtensions>
 <add name="customInspector" type="Client.CustomBehavior, Client, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"/>
 </behaviorExtensions>
</extensions>

That is all you have to do on client end to pass additional parameter in SOAP header using Custom Behavior in WCF.

To retrieve parameter passed in header on server side, you need to use OperationContext object

MessageHeaders headers = OperationContext.Current.IncomingMessageHeaders;
string customParameter = headers.GetHeader&lt;string&gt;("Identity", "http://www.adilmughal.com");
return string.Format("You entered: {0}", customParameter);

This would achieve the objective. Following is the detail of SOAP Envelope:

SOAP Request:
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
<s:Header>
<Action s:mustUnderstand="1" xmlns="http://schemas.microsoft.com/ws/2005/05/addressing/none">http://tempuri.org/ITestService/GetDataAction>
<Identity xmlns="http://www.adilmughal.com">Customer Unique Id: 12345Identity>
s:Header>
<s:Body>
<GetData xmlns="http://tempuri.org/">
<value>123value>
GetData>
s:Body>
SOAP Response:
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
<s:Header />
<s:Body>
<GetDataResponse xmlns="http://tempuri.org/">
<GetDataResult>You entered: Customer Unique Id: 12345GetDataResult>
GetDataResponse>
s:Body>
s:Envelope>

In this post we saw how to create custom SOAP header in WCF to pass parameter from client to server using WCF behavior extension. Hope this helps.




ValidateRequest=”false” in ASP.NET 4

If you are someone like me who have recently upgrade to ASP.NET 4.0, you may have come across Yellow Screen of Death with Http Request Validation Exception, something like:

“A potentially dangerous Request.Form value was detected from the client”


Exception Details: System.Web.HttpRequestValidationException: A potentially dangerous Request.Form value was detected from the client
Surprisingly, you will still see this exception even if you have set ValidateRequest to false in either the Page Tag or Web.Config.
ValidateRequest="false" or  <pages validateRequest="false" />
This may end you being freak out identifying the problem.
The solution is perhaps very simple. I would recommend to go and read ASP.NET 4 Breaking Changes.
“In ASP.NET 4, by default, request validation is enabled for all requests, because it is enabled before the BeginRequest phase of an HTTP request. As a result, request validation applies to requests for all ASP.NET resources, not just .aspx page requests. This includes requests such as Web service calls and custom HTTP handlers. Request validation is also active when custom HTTP modules are reading the contents of an HTTP request.and therefore request validation errors might now occur for requests that previously did not trigger errors.”
In order to revert to the behavior we had previously, you need to add the following setting in Web.config file:
<httpRuntime requestValidationMode="2.0"/>
And this should work!
Hope this helps!

Debug Class in .NET

One of the alternative yet under utilized way to debug code in .NET is using Debug class found in System.Diagnostics Namespaces. This class really gives bunch of functionalities to developer that are very useful for debugging and I wonder why but I have observed that fewer percentage of developers use it. So I thought to share the usage of Debug class with developers out there as I found it very useful.

I will directly jump to code snippet demonstrating the functionality of Debug class:

using System.Collections.Generic;
using System.Diagnostics;
 
namespace DemoDebugClass
{
    public class Customer
    {
        public int    Id   { get; set; }
        public string Name { get; set; }
        public int    Age  { get; set; }
    }
 
    public static class CustomerExtensions
    {
        public static void PrintCustomersBelowAge25(this IEnumerable customersList)
        {
            foreach (var customer in customersList)
            {
                Debug.WriteLine(string.Format("Customer Name: {0}", customer.Name));
                Debug.WriteLineIf(customer.Age < 25, "Required Customer Found!");
            }
        }
    }  
 
    class Program
    {
        static void Main(string[] args)
        {
            List customersList = new List();
            customersList.Add(new Customer { Id = 1, Age = 30, Name = "Customer A" });
            customersList.Add(new Customer { Id = 2, Age = 15, Name = "Customer B" });
            customersList.Add(new Customer { Id = 3, Age = 20, Name = "Customer C" });
            customersList.PrintCustomersBelowAge25();
        }
    }
}

In the above code snippet, we have a customer class and assume that we are interested in finding customers below age 25 as shown in code snippet above. With the Debug.WriteLine you can print data to Output Window in Visual Studio (View –> Output Window) and even conditional data as well, as depicts in image below.

Output Window

Now this is really interesting because it gives liberty to developers to debug the program and data without using breakpoints as most of us used to do. Further these lines are only executed when the program is executed in Debug mode. Besides, this also allows you to easily share the output log with your colleagues.

So go ahead and give it a try! If you don’t use it for some reason then please share your remarks in comments below. Happy Coding!

Beauty of jQuery

Since last year when we discussed jQuery in one of our User Group Meeting, I have been amazed by the power of jQuery. A month ago, I also tweet a picture “Say No to JavaScript without jQuery” and that is because with CSS and jQuery we can exploit the power of JavaScript/CSS, by writing just few lines of code, plus it allow you to make your HTML markup clean and independent of script/event logic. If you take a look at the twitpic below, you will observe that markup does not register any event rather the binding on click event has been taken care inside script tag using jQuery selectors.

twitpic

And that is not the all. To further decouple it, we can use CSS class instead of button Id “btnTest” and then move the JavaScript in .js file. I hope this make sense to you! (if not than don’t worry, just continue reading…)

But today what I am going to share is a real world scenario of how jQuery helped me in observing change in any input element of page.

Usually, we have requirement on web form that when users presses a cancel button after entering any information on page then we have to prompt a cancel confirmation dialog like:

Cancel Dialog

And I really don’t know what is the best way to do this but what I have observed is that developers have done this by registering onchange JavaScript event on every single input element that needs to be tracked down. Something like snippet below:

Observing Change without jQuery

along with some script:

JavaScript without jQuery Library

So what it does is that whenever users enters any text in text input element or change the value of dropdown then it will fire the method SetChangeVariable() which will set value of isChanged to true, which means we need to show cancel confirmation dialog.

Now imagine if I have a page with more than 20-30 fields then I have to go and manually wire the onchange method. Let’s see what jQuery and CSS together offers to us.

Suppose that we have a CSS class element

CSS Element

Then we will assign each element class “TrackChange” that needs to be taken care of as in code snippet below:

Observing Change with CSS

along with some JavaScript that uses jQuery library:

JavaScript with jQuery

What above code does is that when document is ready, that’s what $(document).ready does, its going to select all elements with class assigned “TrackChanged” through one of its selector $(“.TrackChange”) and wired up event of change and set global variable isChanged to true. That’s it!

By using CSS class you can now move the JavaScript in .js file and make your HTML markup clean…

If you don’t like assigning CSS class, another great thing you can do with jQuery is to wire change event on all input elements using input selector:

jQuery Input Selectors

and no need to assign any CSS class! Isn’t that amazing?

That is all for today. Happy Coding!

Final Year Project (FYP) Suggestions and Ideas

From time to time, I receive emails and concerns of students regarding Final Year Project (FYP). And we even get request for organizing events on FYP. At the start of the year, it’s mostly NEDians that ping us and in summer, students from FAST-NUCES, University of Karachi, Bahria University send us their queries.

And mostly these queries are related to

  • What we should do in the FYP
  • Can you give us any idea?
  • What if we want to participate in Imagine Cup?
  • We want to do something good in FYP.
  • Tell us the technology on which we develop Final Year Project

So I thought maybe its good time to write a detail post on blog about what I feel about FYP and answer to some of the common concerns student raise.

Why Final Year Project Matters?

I always emphasize on the importance of Final Year Project (FYP) and we can say it’s one of the most important aspects of your degree. It is the point where you can apply knowledge or what you have been learning in the past few years. It is the point that creates an ordinary graduate vs. an entrepreneur. It is the point that creates meaning of your degree and your existence as an engineer. It is the way of getting exposure and experience of what real world problems are, if done properly. It will inevitably be used as a gateway to industry and to discriminate YOU among your peers.

What you can do in FYP?

Final year project usually span across 6 months to 1 year. I recommend you to take it seriously and do something hard, so don’t do just simple websites or simple ABC management system. Do something which you are passionate about and that makes you exciting, don’t get afraid, and accept big challenges. Utilize technology and go beyond what was not achievable before time.

Make a meaning: Try to solve real life issues, it might be big or small, but at the end of the project it must contribute in some manner to the society. Also, don’t delay it till the end of semester/year to work on FYP because in that case it will be nearly a piece of garbage not creating any meaning.

From my experience, I have observed that mostly highly praised projects are somewhat

  • An implementation of research paper (after all computer scientist/engineer)
  • A combination of hardware + software to solve a real world problem
  • Project following Imagine cup theme and level
  • Newest trend/buzz word/paradigm in the industry
  • Working with organization to solve a problem, more than just an ordinary ABC Management System (Make sure you deliver them your project at the end)
  • Integrate with online platform such as LinkedIn, Facebook, Google Code, Live etc to solve a great problem
  • Unleash computing/storage power by utilizing cloud platform and achieve something that was not possible before Cloud/Grid

Also make sure the material and guide related to your project in available online, you may also refer to IEEE or ACM libraries and digital content.

Which Technology/Platform you should use?

Now this is very famous question. Computer Science/Engineering students keep asking about what technology/platform we should use such as Sun Java, Microsoft .NET or C++ etc. and it is pretty interesting question.

The answer to this question is that it depends on what you want to do in future. Perhaps at many occasion, I have instructed students to taste several platforms before graduation and let final year project be on platform which you like most. For example, Starting from a procedural language in first semester such as C, move to learn OOP in C++ and then in third year make a project such as networking and database using .NET and Java.

So what I mean from “It depends on what you want to do in future” is basically number of factors that you want to

  • Continue your career in particular platform (probably because you like it or there are more job opportunities in it)
  • Participate in any Software competition that might have some requirement. For example, if you want to participate in Imagine Cup you probably should go for .NET platform

Whatever reason be it for selecting platform, it’s always better to have your interest in it 🙂

I guess that’s all for this post. I will write few more posts on FYP such as participating in Imagine Cup, about FYP Presentation and some other FYP ideas you can work on. If you have any specific questions, please feel free to ask I will include them in upcoming post.

Till then, have a great time!




Real World Scenario: Month Based Selection using AJAX Calendar Extender

Often we get requirement of enabling only month based selection in calendar control in which a calendar should display only month instead of dates or you can say a calendar that allow users to pick month only. This can be achieved by manipulating functionality of AJAX Calendar extender using JavaScript.

First, you need to set the behaviorID property of Calendar extender control and add two event handler “OnClientHidden” and “OnClientShown”. For instance,

<asp:TextBox ID="txtDate" runat="server" ReadOnly="false" onfocus="AjaxDateOnFocus(this);" Width="60px" onblur="AjaxDateOnBlur(this);" />
<
cc1:CalendarExtender ID="ctxtDate" runat="server" TargetControlID="txtDate" Format="MMM-yyyy" OnClientHidden="onCalendarHidden" OnClientShown="onCalendarShown" BehaviorID="calendar1" />

Now use the following JavaScript with respective BehaviorID

function onCalendarShown() {
var cal = $find("calendar1"); //Setting the default mode to month
cal._switchMode("months", true); //Iterate every month Item and attach click event to it
if (cal._monthsBody) {
for (var i = 0; i < cal._monthsBody.rows.length; i++) {
var row = cal._monthsBody.rows[i];
for (var j = 0; j < row.cells.length; j++) {
Sys.UI.DomEvent.addHandler(row.cells[j].firstChild, "click", call);
}
}
}
}

function onCalendarHidden() {
var cal = $find("calendar1");
//Iterate every month Item and remove click event from it
if (cal._monthsBody) {
for (var i = 0; i < cal._monthsBody.rows.length; i++) {
var row = cal._monthsBody.rows[i];
for (var j = 0; j < row.cells.length; j++) {
Sys.UI.DomEvent.removeHandler(row.cells[j].firstChild, "click", call);
}
}
}
}

function call(eventElement) {
var target = eventElement.target;
switch (target.mode) {
case "month":
var cal = $find("calendar1");
cal._visibleDate = target.date;
cal.set_selectedDate(target.date);
cal._switchMonth(target.date);
cal._blur.post(true);
cal.raiseDateSelectionChanged();
break;
}
}

That’s all 🙂 and your calendar extender will now look like

image

Enjoy!

Please note that the script is partially taken from AghaUsman.net

Real World Scenario: MCTS 70-562

Yet another post on Real World Scenario. The query I received this time was related to MCTS 70-562. Truth is the highest number of queries I received are related to Microsoft Certifications 🙂 As mentioned earlier, the purpose of blogging about these issues is to share solution with others facing similar problem.

Scenario/Query (Copied from email):

Sir ,

My Self, Rahul Singh I have read your blog.It was a very good blog, that helped me a lot. Can you provide me some additional information about MCTS 70- 562 . Information which i required are:

  1. Good book that could help me in preparing for paper MCTS  70-562.
  2. whether paper 70-562 in made in C# or VB (Visual Basic) or their in option between two.
  3. some sample paper for paper70- 562

Thank you Rahul for asking and appreciation. Here is what I think:

  1. It really depends on how much experience you have in ASP.NET 3.5. Well in most of the cases MCTS Self Paced Training Kit for 70-562 is good enough for the exam’s preparation. However, if you don’t have much experience with ASP.NET 3.5 or some new features of ..NET 3.5 like LINQ, Entity Framework etc then I don’t think only Training Kit is enough for you. So if that is the case, you need to have some hands on stuff you are weak and go for some books other than training kit such as Professional ASP.NET 3.5 SP1 – Wrox or Programming ASP.NET 3.5 -Microsoft Press.
  2. You will always have the option to select C# or VB in every .NET exam.
  3. There are sample exams, a kind of Past Papers, available such as Brain Dumps or Test Kings but they are costly. I would recommend you to have some firm working knowledge of ASP.NET and you will clear the exam hopefully.

Good Luck.