Friday, May 25, 2012

Load partial page in jquery and ASP.Net MVC

http://miroprocessordev.blogspot.ca/2012/05/load-partial-page-in-jquery-and-aspnet.html


$('#usersdiv').load('/home?name=' + $(this).val() + ' #usersdiv');


public class HomeController
{
   public ActionResult Index(String name = "")
   {
      List<user> users = GetUsers()
                           .Where(u => u.Name.ToLower().StartWith(name.ToLower()) 
                                    || String.IsNullOrEmpty(search)).ToList();
      return view(users);
   }
}

Wednesday, May 23, 2012

Prevent Cross-Site Request Forgery (CSRF) using ASP.NET MVC’s AntiForgeryToken() helper

http://blog.stevensanderson.com/2008/09/01/prevent-cross-site-request-forgery-csrf-using-aspnet-mvcs-antiforgerytoken-helper/

Ways to stop CSRF

There are two main ways to block CSRF:
  • Check that incoming requests have a Referer header referencing your domain. This will stop requests unwittingly submitted from a third-party domain. However, some people disable their browser’s Refererheader for privacy reasons, and attackers can sometimes spoof that header if the victim has certain versions of Adobe Flash installed. This is a weak solution.
  • Put a user-specific token as a hidden field in legitimate forms, and check that the right value was submitted. If, for example, this token is the user’s password, then a third-party can’t forge a valid form post, because they don’t know each user’s password. However, don’t expose the user’s password this way: Instead, it’s better to use some random value (such as a GUID) which you’ve stored in the visitor’s Session collection or into a Cookie

Wednesday, May 9, 2012

How to deploy ASP.NET MVC 3 on IIS 6?

- Install AspNetMVC3Setup.exe
- Make sure web site and application pool are both set the ASP.NET version to 4.0.30319
- Add "Wildcard application maps"


Steps to add "Wildcard application maps":
In property for the website, click the Home Directory tab.
Click the "Configuration..." button. In the "Mappings" tab, click "Insert..."
Next to the "Wildcard application maps" label In the textbox, type in "c:\windows\microsoft.net\framework\v4.0.30319\aspnet_isapi.dll"
Uncheck the box labeled "Verify that file exists" Click OK

References:
This one is for earlier version of MVC, but idea is the same for Wildcard application maps
http://haacked.com/archive/2008/11/26/asp.net-mvc-on-iis-6-walkthrough.aspx

Monday, May 7, 2012

ASP.NET MVC Authentication - Customizing Authentication and Authorization The Right Way

http://weblogs.asp.net/jgalloway/archive/2012/05/04/asp-net-mvc-authentication-customizing-authentication-and-authorization-the-right-way.aspx

ASP.NET MVC: Adding aria-required attribute for required fields

http://blogs.msdn.com/b/stuartleeks/archive/2012/05/01/asp-net-mvc-adding-aria-required-attribute-for-required-fields.aspx

@{
     var attributes = new RouteValueDictionary
                          {
                             { "class", "text-box single-line"}
                          };
     if (ViewContext.ViewData.ModelMetadata.IsRequired)
     {
         attributes.Add("aria-required", "true");
     }
}
@Html.TextBox("", ViewContext.ViewData.TemplateInfo.FormattedModelValue, attributes)

What is aria-required?

It is a HTML property to indicate if user input field is required. This property is for Accessible Rich Internet Applications
<input name="ariaexample" id="example" aria-required="true" aria-label="Test"/>

Reference:
http://www.w3.org/WAI/GL/WCAG20-TECHS/ARIA2.html

Friday, May 4, 2012

Implementing [RequireHttps] with ASP.NET Web API

http://blogs.msdn.com/b/carlosfigueira/archive/2012/03/09/implementing-requirehttps-with-asp-net-web-api.aspx

public class RequireHttpsAttribute : AuthorizationFilterAttribute
{
    public override void OnAuthorization(HttpActionContext actionContext)
    {
        var request = actionContext.Request;
        if (request.RequestUri.Scheme != Uri.UriSchemeHttps)
        {
            HttpResponseMessage response;
            UriBuilder uri = new UriBuilder(request.RequestUri);
            uri.Scheme = Uri.UriSchemeHttps;
            uri.Port = 443;
            string body = string.Format("<p>The resource can be found at <a href=\"{0}\">{0}</a>.</p>",
                uri.Uri.AbsoluteUri);
            if (request.Method.Equals(HttpMethod.Get) || request.Method.Equals(HttpMethod.Head))
            {
                response = request.CreateResponse(HttpStatusCode.Found);
                response.Headers.Location = uri.Uri;
                if (request.Method.Equals(HttpMethod.Get))
                {
                    response.Content = new StringContent(body, Encoding.UTF8, "text/html");
                }
            }
            else
            {
                response = request.CreateResponse(HttpStatusCode.NotFound);
                response.Content = new StringContent(body, Encoding.UTF8, "text/html");
            }

            actionContext.Response = response;
        }
    }
}

Thursday, May 3, 2012

How to add custom error message into ValidationSummary on server side in ASP.NET webform?

On server side event handler, add following code:
                CustomValidator val = new CustomValidator();
                val.IsValid = false;
                val.ErrorMessage = "Error ";
                this.Page.Validators.Add(val);

http://blog.webmastersam.net/post/Adding-custom-error-message-to-ValidationSummary-without-validators.aspx

Wednesday, May 2, 2012

Security and the ASP.NET View State

http://radicaldevelopment.net/security-and-the-asp-net-view-state/
<pages enableViewState="true" enableViewStateMac="true" viewStateEncryptionMode="Auto"></pages>

Tuesday, May 1, 2012

How to valid email address by custom validation control and JavaScript regular expression in ASP.NET webform?

     <script type="text/javascript">
        function EmailValidation(sender, args) {
            var email = $("#TextBoxEmailAddress").val();
            var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
            args.IsValid = re.test(email);
        }
    </script>
    <asp:TextBox ID="TextBoxEmailAddress" runat="server" ClientIDMode="Static"></asp:TextBox>
    <asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="Invalid email"
        ClientValidationFunction="EmailValidation" ControlToValidate="TextBoxEmailAddress"></asp:CustomValidator>

Custom errors and error detail policy in ASP.NET Web API

http://lostechies.com/jimmybogard/2012/04/18/custom-errors-and-error-detail-policy-in-asp-net-web-api/