Friday, 21 August 2015

runAllManagedModulesForAllRequests="true" when getting your MVC routing to work Don't use

It seems to be common advice to make your modules section of your web.config say <modules runAllManagedModulesForAllRequests="true">. In fact this is quite a drastic thing to do to solve the routing problem and has global effects that could CAUSE ERRORS.

You need a module that goes by the name of UrlRoutingModule-4.0 to be running through IIS. Now, since your MVC URLs are likely to end without .aspx these will not be picked up by IIS and run through the intergrated pipeline and therefore you will end up with 404 not found errors. I struggled with this when I was getting started until I found the <modules runAllManagedModulesForAllRequests="true"> workaround.

This highly recommended fix can cause other problems. These problems come in the form of making all your registered HTTP modules run on every request, not just managed requests (e.g. .aspx). This means modules will run on ever .jpg .gif .css .html .pdf etc.

This is:

  1. a waste of resources if this wasn't the intended use of your other modules
  2. a potential for errors from new unexpected behaviour.


Better solution

Fine, so the ranting about <modules runAllManagedModulesForAllRequests="true"> is over. What is a better solution?

In the modules section of your web.config, you can add the UrlRoutingModule-4.0 module in with a blank precondition meaning it will run on all requests. You will probably need to remove it first since it is most likely already registered at machine level. So make your web.config look like this:

?
1
2
3
4
5
<modules>
  <remove name="UrlRoutingModule-4.0" />
  <add name="UrlRoutingModule-4.0" type="System.Web.Routing.UrlRoutingModule" preCondition="" />
  <!-- any other modules you want to run in MVC e.g. FormsAuthentication, Roles etc. -->
</modules>

Note: the modules element does NOT contain the runAllManagedModulesForAllRequests="true" attribute because it is evil!

Wednesday, 29 April 2015

How to pass Microsoft Developing Microsoft Azure and Web Services 70-487 exam

Hi All,
I've recently certified Microsoft Azure with WCF Certification 70-487,
I've notice that Microsoft has changed From 30 April 2014, the questions on this exam include content covering Visual Studio 2013 and updates to Microsoft Azure.

I've have few good tips for exam, which I'm sharing with this blogs,

  • If you are afraid 70-487 exam, then do not need to hasitate, It's pretty easy exam you need to make sure with latest dump.
  1.  Microsoft has divided this exam into two section.
  •  Case  Study
  • General Question
    In my case almost 26 Case study Question and 33 general Question

1) General Question
2) Case Study
3) LAURA Third party Dump -2013 September
4) Sure Pass Dump

Above Link will navigate you to download.

Few of the website which was usually referred by me.

Let me know in case if you needed any further help.

Thanks,
Gauttam
     
 

Monday, 23 March 2015

List of Model Object Post to Controller in ASP.NET MVC

Introduction

Several times, we want to post list of model object from view to controller while HttpPost. Many developers try to get the list of data through an array. But I'll tell you without using array also, we can get those list of model objects in a simpler way. Let's go step by step. Create an ASP.NET MVC 4 application. First, create two model classes, for example, EmployeeModelClass.cs and DepartmentModelClass.cs inside Model folder in solution.

Model


public class EmployeeModelClass
    {
        public string Name { get; set; }

        public string Address { get; set; }

        public string Contact { get; set; }

        public IEnumerable<DepartmentModelClass> DeptList { get; set; }                 
    }

public class DepartmentModelClass
    {
        public string DepartmentCode { get; set; }
        public string DepartmentName { get; set; }
    }  

Controller
public class EmployeeController : Controller
    {
        //
        // GET: /Employee/

        public ActionResult Index()
        {
            return View(new EmployeeModelClass());
        }

        [HttpPost]
        public ActionResult Index(EmployeeModelClass emp, IEnumerable<DepartmentModelClass> dept)
        {
            emp.DeptList = dept;
            return View(emp);
        }
    }

View

Here, I want to get Employee details with list of department names which belong to that employee. The business logic is multiple departments should assign to a single employee.
I hope you understood what I am trying to do here. See the controller. In HttpPost Action, I am not using any array to get the Department list from view page while HttpPost. Simply, I am passing two parameters inHttpPost like below:
[HttpPost]
        public ActionResult Index(EmployeeModelClass emp, IEnumerable<DepartmentModelClass> dept)
        {
            emp.DeptList = dept;
            return View(emp);
        }
See those parameters, EmployeeModelClass emp and IEnumerable<DepartmentModelClass> dept. We can get the employee data from emp object and list of department data from dept object very easily here.
See the view section inside for loop I am putting DepartmentCode and Departmentname four times. This property name should be the same as the property in Model object.
To see the result in output, append the following lines in view page:
@{
                    if (Model.Name != null)
                    {
                        <div>
                    
                            Employee Name : @Model.Name <br/>
                            Address : @Model.Address <br/>
                            Contact : @Model.Contact <br/>
                            
                            @{
                                if (Model.DeptList != null)
                                {
                                  <table>
                                        <tr>
                                            <th>Dept code</th>
                                            <th>Dept Name</th>
                                        </tr>
                                    
                                    @{
                                        foreach (var dept in Model.DeptList)
                                        {
                                            <tr>
                                                <td>@dept.DepartmentCode</td>
                                                <td>@dept.DepartmentName</td>
                                            </tr>
                                        }
                                    }
                                </table>
                            }
                            }

                        </div>
                    }
                }



Attached Code Link to Download Source


Wednesday, 10 December 2014

Understanding ASP.NET MVC Filters and Attributes

ASP.NET MVC provides a simple way to inject your piece of code or logic either before or after an action is executed. This is achieved by decorating the controllers or actions with ASP.NET MVC attributes or custom attributes. An attribute or custom attribute implements the ASP.NET MVC filters(filter interface) and can contain your piece of code or logic. You can make your own custom filters or attributes either by implementing ASP.NET MVC filter interface or by inheriting and overriding methods of ASP.NET MVC filter attribute class if available.
Typically, Filters are used to perform the following common functionalities in your ASP.NET MVC application.
  1. Custom Authentication
  2. Custom Authorization(User based or Role based)
  3. Error handling or logging
  4. User Activity Logging
  5. Data Caching
  6. Data Compression

Types of Filters

The ASP.NET MVC framework provides five types of filters.
  1. Authentication filters (New in ASP.NET MVC5)
  2. Authorization filters
  3. Action filters
  4. Result filters
  5. Exception filters

Authentication Filters

This filter is introduced with ASP.NET MVC5. The IAuthenticationFilter interface is used to create CustomAuthentication filter. The definition of this interface is given below-
  1. public interface IAuthenticationFilter
  2. {
  3. void OnAuthentication(AuthenticationContext filterContext);
  4.  
  5. void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext);
  6. }
You can create your CustomAuthentication filter attribute by implementing IAuthenticationFilter as shown below-
  1. public class CustomAuthenticationAttribute : ActionFilterAttribute, IAuthenticationFilter
  2. {
  3. public void OnAuthentication(AuthenticationContext filterContext)
  4. {
  5. //Logic for authenticating a user
  6. }
  7. //Runs after the OnAuthentication method
  8. public void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext)
  9. {
  10. //TODO: Additional tasks on the request
  11. }
  12. }

Authorization Filters

The ASP.NET MVC Authorize filter attribute implements the IAuthorizationFilter interface. The definition of this interface is given below-
  1. public interface IAuthorizationFilter
  2. {
  3. void OnAuthorization(AuthorizationContext filterContext);
  4. }
The AuthorizeAttribute class provides the following methods to override in the CustomAuthorize attribute class.
  1. public class AuthorizeAttribute : FilterAttribute, IAuthorizationFilter
  2. {
  3. protected virtual bool AuthorizeCore(HttpContextBase httpContext);
  4. protected virtual void HandleUnauthorizedRequest(AuthorizationContext filterContext);
  5. public virtual void OnAuthorization(AuthorizationContext filterContext);
  6. protected virtual HttpValidationStatus OnCacheAuthorization(HttpContextBase httpContext);
  7. }
In this way you can make your CustomAuthorize filter attribute either by implementing IAuthorizationFilter interface or by inheriting and overriding above methods of AuthorizeAttribute class.

Action Filters

Action filters are executed before or after an action is executed. The IActionFilter interface is used to create an Action Filter which provides two methods OnActionExecuting and OnActionExecuted which will be executed before or after an action is executed respectively.
  1. public interface IActionFilter
  2. {
  3. void OnActionExecuting(ActionExecutingContext filterContext);
  4. void OnActionExecuted(ActionExecutedContext filterContext);
  5. }

Result Filters

Result filters are executed before or after generating the result for an action. The Action Result type can be ViewResult, PartialViewResult, RedirectToRouteResult, RedirectResult, ContentResult, JsonResult, FileResult and EmptyResult which derives from the ActionResult class. Result filters are called after the Action filters. The IResultFilter interface is used to create an Result Filter which provides two methods OnResultExecuting and OnResultExecuted which will be executed before or after generating the result for an action respectively.
  1. public interface IResultFilter
  2. {
  3. void OnResultExecuted(ResultExecutedContext filterContext);
  4. void OnResultExecuting(ResultExecutingContext filterContext);
  5. }

Exception Filters

Exception filters are executed when exception occurs during the actions execution or filters execution. The IExceptionFilter interface is used to create an Exception Filter which provides OnException method which will be executed when exception occurs during the actions execution or filters execution.
  1. public interface IExceptionFilter
  2. {
  3. void OnException(ExceptionContext filterContext);
  4. }
ASP.NET MVC HandleErrorAttribute filter is an Exception filter which implements IExceptionFilter. When HandleErrorAttribute filter receives the exception it returns an Error view located in the Views/Shared folder of your ASP.NET MVC application.

Order of Filter Execution

All ASP.NET MVC filter are executed in an order. The correct order of execution is given below:
  1. Authentication filters
  2. Authorization filters
  3. Action filters
  4. Result filters

Configuring Filters

You can configure your own custom filter into your application at following three levels:
  1. Global level

    By registering your filter into Application_Start event of Global.asax.cs file with the help of FilterConfig class.
    1. protected void Application_Start()
    2. {
    3. FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    4. }
  2. Controller level

    By putting your filter on the top of the controller name as shown below-
    1. [Authorize(Roles="Admin")]
    2. public class AdminController : Controller
    3. {
    4. //
    5. }
  3. Action level

    By putting your filter on the top of the action name as shown below-
    1. public class UserController : Controller
    2. {
    3. [Authorize(Users="User1,User2")]
    4. public ActionResult LinkLogin(string provider)
    5. {
    6. // TODO:
    7. return View();
    8. }
    9. }
What do you think?
I hope you will enjoy the ASP.NET MVC filter while extending ASP.NET MVC framework. I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome.

Tuesday, 18 November 2014

Twitter Auth login using dot .Net C#

Hello all,

Twitter Login using Auth in c#;

Step 1 : Create OAuthHelper.cs File use this below code :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.IO;
using System.Text;
public class OAuthHelper
{
    public OAuthHelper()
    {
    }

    private static string oauth_consumer_key = "YOUR CONSUMER KEY";
    private static string oauth_consumer_secret = "YOUR CONSUMER SECRET";
    private static string callbackUrl = "YOUR CALL BACK URL";

    #region (Changable) Do Not Change It

    private static string REQUEST_TOKEN = "YOUR REQUEST TOKEN URL";
    private static string AUTHORIZE = "YOUR AUTHORIZE URL";
    private static string ACCESS_TOKEN = "YOUR ACCESS TOKEN URL";





    public enum httpMethod
    {
        POST, GET
    }
    public string oauth_request_token
    {
        get;
        set;
    }
    public string oauth_access_token
    {
        get;
        set;
    }
    public string oauth_access_token_secret
    {
        get;
        set;
    }
    public string user_id
    {
        get;
        set;
    }
    public string screen_name
    {
        get;
        set;
    }
    public string oauth_error
    {
        get;
        set;
    }

    public string GetRequestToken()
    {
        HttpWebRequest request = FetchRequestToken(httpMethod.POST, oauth_consumer_key, oauth_consumer_secret);
        string result = getResponce(request);
        Dictionary<string, string> resultData = OAuthUtility.GetQueryParameters(result);
        if (resultData.Keys.Contains("oauth_token"))
            return resultData["oauth_token"];
        else
        {
            this.oauth_error = result;
            return "";
        }
    }
    public string GetAuthorizeUrl(string requestToken)
    {
        return string.Format("{0}?oauth_token={1}", AUTHORIZE, requestToken);
    }
    public void GetUserTwAccessToken(string oauth_token, string oauth_verifier)
    {
        HttpWebRequest request = FetchAccessToken(httpMethod.POST, oauth_consumer_key, oauth_consumer_secret, oauth_token, oauth_verifier);
        string result = getResponce(request);

        Dictionary<string, string> resultData = OAuthUtility.GetQueryParameters(result);
        if (resultData.Keys.Contains("oauth_token"))
        {
            this.oauth_access_token = resultData["oauth_token"];
            this.oauth_access_token_secret = resultData["oauth_token_secret"];
            this.user_id = resultData["user_id"];
            this.screen_name = resultData["screen_name"];
        }
        else
            this.oauth_error = result;
    }
    public void TweetOnBehalfOf(string oauth_access_token, string oauth_token_secret, string postData)
    {
        HttpWebRequest request = PostTwits(oauth_consumer_key, oauth_consumer_secret, oauth_access_token, oauth_token_secret, postData);
        string result = OAuthHelper.getResponce(request);
        Dictionary<string, string> dcResult = OAuthUtility.GetQueryParameters(result);
        if (dcResult["status"] != "200")
        {
            this.oauth_error = result;
        }

    }


    HttpWebRequest FetchRequestToken(httpMethod method, string oauth_consumer_key, string oauth_consumer_secret)
    {
        string OutUrl = "";
        string OAuthHeader = OAuthUtility.GetAuthorizationHeaderForPost_OR_QueryParameterForGET(new Uri(REQUEST_TOKEN), callbackUrl, method.ToString(), oauth_consumer_key, oauth_consumer_secret, "", "", out OutUrl);

        if (method == httpMethod.GET)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(OutUrl + "?" + OAuthHeader);
            request.Method = method.ToString();
            return request;
        }
        else if (method == httpMethod.POST)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(OutUrl);
            request.Method = method.ToString();
            request.Headers["Authorization"] = OAuthHeader;
            return request;
        }
        else
            return null;


    }
    HttpWebRequest FetchAccessToken(httpMethod method, string oauth_consumer_key, string oauth_consumer_secret, string oauth_token, string oauth_verifier)
    {
        string postData = "oauth_verifier=" + oauth_verifier;
        string AccessTokenURL = string.Format("{0}?{1}", ACCESS_TOKEN, postData);
        string OAuthHeader = OAuthUtility.GetAuthorizationHeaderForPost_OR_QueryParameterForGET(new Uri(AccessTokenURL), callbackUrl, method.ToString(), oauth_consumer_key, oauth_consumer_secret, oauth_token, "", out AccessTokenURL);

        if (method == httpMethod.GET)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(AccessTokenURL + "?" + OAuthHeader);
            request.Method = method.ToString();
            return request;
        }
        else if (method == httpMethod.POST)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(AccessTokenURL);
            request.Method = method.ToString();
            request.Headers["Authorization"] = OAuthHeader;

            byte[] array = Encoding.ASCII.GetBytes(postData);
            request.GetRequestStream().Write(array, 0, array.Length);
            return request;
        }
        else
            return null;

    }
    HttpWebRequest PostTwits(string oauth_consumer_key, string oauth_consumer_secret, string oauth_access_token, string oauth_token_secret, string postData)
    {
        postData = "trim_user=true&include_entities=true&status=" + postData;
        string updateStatusURL = "https://api.twitter.com/1/statuses/update.json?" + postData;

        string outUrl;
        string OAuthHeaderPOST = OAuthUtility.GetAuthorizationHeaderForPost_OR_QueryParameterForGET(new Uri(updateStatusURL), callbackUrl, httpMethod.POST.ToString(), oauth_consumer_key, oauth_consumer_secret, oauth_access_token, oauth_token_secret, out outUrl);

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(outUrl);
        request.Method = httpMethod.POST.ToString();
        request.Headers["Authorization"] = OAuthHeaderPOST;

        byte[] array = Encoding.ASCII.GetBytes(postData);
        request.GetRequestStream().Write(array, 0, array.Length);
        return request;

    }

    public static string getResponce(HttpWebRequest request)
    {
        try
        {
            HttpWebResponse resp = (HttpWebResponse)request.GetResponse();
            StreamReader reader = new StreamReader(resp.GetResponseStream());
            string result = reader.ReadToEnd();
            reader.Close();
            return result + "&status=200";
        }
        catch (Exception ex)
        {
            string statusCode = "";
            if (ex.Message.Contains("403"))
                statusCode = "403";
            else if (ex.Message.Contains("401"))
                statusCode = "401";
            return string.Format("status={0}&error={1}", statusCode, ex.Message);
        }
    }


    #endregion
}

Step 2 : CreateOAuthUtility.cs File use this below code :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;

public class OAuthUtility
{
    public OAuthUtility()
    {
        //
        // TODO: Add constructor logic here
        //
    }
    #region *******Common Methods**********
    protected static string unreservedChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.~";
    public static string UrlEncode(string value)
    {
        StringBuilder result = new StringBuilder();

        foreach (char symbol in value)
        {
            if (unreservedChars.IndexOf(symbol) != -1)
            {
                result.Append(symbol);
            }
            else
            {
                result.Append('%' + String.Format("{0:X2}", (int)symbol));
            }
        }

        return result.ToString();
    }

    public static string GenerateTimeStamp()
    {
        TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
        return Convert.ToInt64(ts.TotalSeconds).ToString();
    }
    public static string GenerateNonce()
    {
        // Just a simple implementation of a random number between 123400 and 9999999
        Random random = new Random();
        return random.Next(123400, 9999999).ToString();
    }
    public static Dictionary<string, string> GetQueryParameters(string dataWithQuery)
    {
        Dictionary<string, string> result = new Dictionary<string, string>();
        string[] parts = dataWithQuery.Split('?');
        if (parts.Length > 0)
        {
            string QueryParameter = parts.Length > 1 ? parts[1] : parts[0];
            if (!string.IsNullOrEmpty(QueryParameter))
            {
                string[] p = QueryParameter.Split('&');
                foreach (string s in p)
                {
                    if (s.IndexOf('=') > -1)
                    {
                        string[] temp = s.Split('=');
                        result.Add(temp[0], temp[1]);
                    }
                    else
                    {
                        result.Add(s, string.Empty);
                    }
                }
            }
        }
        return result;
    }
    #endregion Common Methods

    public static string GetAuthorizationHeaderForPost_OR_QueryParameterForGET(Uri url, string callbackUrl, string httpMethod, string consumerKey, string consumerSecret, string token, string tokenSecret, out string normalizedUrl)
    {
        string normalizedParameters = "";

        Dictionary<string, string> parameters = new Dictionary<string, string>();
        parameters.Add("oauth_version", "1.0");
        if (token != "")
            parameters.Add("oauth_token", token);
        parameters.Add("oauth_nonce", GenerateNonce()); //Random String
        parameters.Add("oauth_timestamp", GenerateTimeStamp()); // Current Time Span
        parameters.Add("oauth_consumer_key", consumerKey); //Customer Consumer Key
        parameters.Add("oauth_signature_method", "HMAC-SHA1"); //Singnatur Encription Method
        parameters.Add("oauth_callback", UrlEncode(callbackUrl)); //return url

        Dictionary<string, string> drQuery = GetQueryParameters(url.Query);
        foreach (string key in drQuery.Keys)
            parameters.Add(key, drQuery[key]);

        if (url.Query != "")
            normalizedUrl = url.AbsoluteUri.Replace(url.Query, "");
        else
            normalizedUrl = url.AbsoluteUri;

        List<string> li = parameters.Keys.ToList();
        li.Sort();

        StringBuilder sbOAuthHeader = new StringBuilder("OAuth ");
        StringBuilder sbSignatureBase = new StringBuilder();
        foreach (string k in li)
        {
            sbSignatureBase.AppendFormat("{0}={1}&", k, parameters[k]); // For Signature and Get Date (QueryString)
            sbOAuthHeader.AppendFormat("{0}=\"{1}\", ", k, parameters[k]); // For Post Request (Post Data)
        }

        string signature = GenerateSignatureBySignatureBase(httpMethod, consumerSecret, tokenSecret, normalizedUrl, sbSignatureBase);

        if (httpMethod == "POST")
        {
            string OAuthHeader = sbOAuthHeader.Append("oauth_signature=\"" + UrlEncode(signature) + "\"").ToString();
            normalizedParameters = OAuthHeader;
        }
        else if (httpMethod == "GET")
        {
            normalizedParameters = sbSignatureBase.AppendFormat("{0}={1}", "oauth_signature", signature).ToString(); ;
        }
        return normalizedParameters;
    }
    private static string GenerateSignatureBySignatureBase(string httpMethod, string consumerSecret, string tokenSecret, string normalizedUrl, StringBuilder sbSignatureBase)
    {
        string normalizedRequestParameters = sbSignatureBase.ToString().TrimEnd('&');
        StringBuilder signatureBase = new StringBuilder();
        signatureBase.AppendFormat("{0}&", httpMethod.ToString());
        signatureBase.AppendFormat("{0}&", UrlEncode(normalizedUrl));
        signatureBase.AppendFormat("{0}", UrlEncode(normalizedRequestParameters));

        HMACSHA1 hmacsha1 = new HMACSHA1();
        hmacsha1.Key = Encoding.ASCII.GetBytes(string.Format("{0}&{1}", UrlEncode(consumerSecret), UrlEncode(tokenSecret)));
        byte[] hashBytes = hmacsha1.ComputeHash(System.Text.Encoding.ASCII.GetBytes(signatureBase.ToString()));
        return Convert.ToBase64String(hashBytes);
    }
}


Step 3 : Create login.aspx page use this code:
  var oauthhelper = new OAuthHelper();
            string requestToken = oauthhelper.GetRequestToken();

            if (string.IsNullOrEmpty(oauthhelper.oauth_error))
                Response.Redirect(oauthhelper.GetAuthorizeUrl(requestToken));
            else
                Response.Write(oauthhelper.oauth_error);



Step 4 : Create Response.aspx page to handle response use this code:
                   if (Request.QueryString["oauth_token"] != null && Request.QueryString["oauth_verifier"] != null)
                {
                    string oauth_token = Request.QueryString["oauth_token"];
                    string oauth_verifier = Request.QueryString["oauth_verifier"];
}


 Do you still need any help? Feel free to comment