Add custom messages to Validation Summary in asp.net mvc form

Sometimes you might need to add messages to Validation summary. Here is a small javascript function that will help you do that. The method can be called onClick event of a button.

    function performValidation() {
        if ($("#notestext").val() == "") {
            var ul = $("#validationSummary ul");
            ul.html("");
            ul.append("<li>" + "Action Note must be entered." + "</li>");
            return false;
        }
        return true;
    }

Hope it helps

How to find all values that have changes in mvc object

‘Compare the original and new versions of any db model, return a string of changes
    Function GetChanges(ByRef database As YourCaretakerEntitiesByRef originalValues As ObjectByRef newValues As ObjectAs String
        Dim returnString As New StringBuilder()
        Dim comparer As ObjectStateEntry = database.ObjectStateManager.GetObjectStateEntry(originalValues)
        For Each changedField In comparer.GetModifiedProperties()
            returnString.Append(changedField)
            returnString.Append(” changed from “)
            returnString.Append(comparer.OriginalValues(changedField).ToString())
            returnString.Append(” to “)
            returnString.Append(comparer.CurrentValues(changedField).ToString())
            returnString.Append(“, “)
        Next
        If returnString.Length > 0 Then returnString = returnString.Replace(“, ““.”, returnString.Length – 2, 2)
        Return returnString.ToString()
    End Function

Handle Access Denied in asp.net MVC

Today I had to add security to the application. Essentially check if the logged in user has got permission to access a function and if not redirect to Unauthorised page. There may be a few ways this can be achieved. Some developers may prefer to add if else check in the view and depending if access needs to be granted they show selective part of the view. This will work, but I think there is a more elegant way to handle this. This is how I achieved this.

Create an attribute that will redirect unauthorised access to a SecurityController. In order to show custom unauthorised messages, it should allow specific messages which can be achieved by passing a reason string.

Here is the code for security attribute: (its in vb.net, but I am sure you can convert to C# easily)

<AttributeUsage(AttributeTargets.Method, AllowMultiple:=True, Inherited:=True)> _

Public NotInheritable Class ApplySecurityAttribute

    Inherits ActionFilterAttribute

    Private ReadOnly _permission As Integer

 

    Public Sub New(ByVal permission As Integer)

        Me.New(permission, String.Empty)

    End Sub

 

    Public Sub New(ByVal permission As Integer, ByVal reason_1 As String)

        _permission = permission

        Reason = reason_1

    End Sub

 

    Public Property Reason() As String

        Get

            Return m_Reason

        End Get

        Set(ByVal value As String)

            m_Reason = Value

        End Set

    End Property

    Private m_Reason As String

 

    Public Overrides Sub OnActionExecuting(ByVal filterContext As ActionExecutingContext)

        If Not PermissionsManager.HasPermission(_permission) Then

            ‘ Put security check here

            ‘ Security Controller

            ‘ Unauthorized Action

            ‘ Put the reason here

            Dim routeValueDictionary = New RouteValueDictionary() From { _

             {“controller”, “Security”}, _

             {“action”, “Unauthorized”}, _

             {“reason”, Reason} _

            }

 

            filterContext.Result = New RedirectToRouteResult(routeValueDictionary)

        End If

 

        MyBase.OnActionExecuting(filterContext)

    End Sub

End Class

Using the attribute is simple. Just declare it on a controller like this:

<ApplySecurity(Enums.Permissions.OfficeUserViewReports, "You are not authorised to view reports")>

Here is the Security Controller class.

Namespace YourCaretaker
    Public Class SecurityController
        Inherits System.Web.Mvc.Controller
        Function Unauthorized(ByVal reason As String) As ViewResult
           ViewBag.Reason = reason
            Return View()
        End Function
    End Class
End Namespace

And finally the permission manager

Public NotInheritable Class PermissionsManager
    Private Sub New()
    End Sub
    Public Shared Function HasPermission(ByVal permissionId As Integer) As Boolean
        'insert your implementation
        'if access allowed Return True else Return False
    End Function
End Class
Posted in .net, asp .net, mvc. Tags: . Leave a Comment »

How to get date 3 days before today

Its pretty simple really…

DateTime.Now.AddDays(-3)

Cheers

ASP MVC 3rd Party Controls

If you are looking for MVC Ajax controls to speed up application development, here are a few good ones,

I think the best are Telerik, not free

free http://mvccontrolstoolkit.codeplex.com/

about USD 1999 http://www.devexpress.com/Products/NET/Controls/ASP/

http://www.obout.com/inc/download.aspx#mvc

And ofcourse with lit bit of effort and fun you can integrate Jq* controls such as Grid, Date, Autocomplete, Modal box

JSON undefined

Here are some scripts that you can implement in your own javascript tag, class to implement json serialisation and parsing

var JSON = JSON || {};
// implement JSON.stringify serialization
JSON.stringify = JSON.stringify || function(obj) {
var t = typeof (obj);
if (t != "object" || obj === null) {
// simple data type
if (t == "string")
obj = '"' + obj + '"';
return String(obj);
} else {
// recurse array or object
var n, v, json = [], arr = (obj && obj.constructor == Array);
for (n in obj) {
v = obj[n];
t = typeof (v);
if (t == "string")
v = '"' + v + '"';
else if (t == "object" && v !== null)
v = JSON.stringify(v);
json.push((arr ? "" : '"' + n + '":') + String(v));
}
return (arr ? "[" : "{") + String(json) + (arr ? "]" : "}");
}
};
// implement JSON.parse de-serialization
JSON.parse = JSON.parse || function() {
var r = "(?:-?\\b(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?(?:[eE][+-]?[0-9]+)?\\b)", k = '(?:[^\-\\x08\\x0a-\\x1f"\\\\]|\\\\(?:["/\\\\bfnrt]|u[0-9A-Fa-f]{4}))';
k = '(?:"' + k + '*")';
var s = new RegExp(
"(?:false|true|null|[\\{\\}\\[\\]]|" + r + "|" + k + ")", "g"), t = new RegExp(
"\\\\(?:([^u])|u(.{4}))", "g"), u = {
'"' : '"',
"/" : "/",
"\\" : "\\",
b : "\u0008",
f : "\u000c",
n : "\n",
r : "\r",
t : "\t"
};
function v(h, j, e) {
return j ? u[j] : String.fromCharCode(parseInt(e, 16));
}
var w = new String(""), x = Object.hasOwnProperty;
return function(h, j) {
h = h.match(s);
var e, c = h[0], l = false;
if ("{" === c)
e = {};
else if ("[" === c)
e = [];
else {
e = [];
l = true;
}
for ( var b, d = [ e ], m = 1 - l, y = h.length; m = 0;)
delete f[i[g]];
}
return j.call(n, o, f);
};
e = p({
"" : e
}, "");
}
return e;
};
}();

 
You can refer to this link for more : https://github.com/douglascrockford/JSON-js

 

This posting is provided “AS IS” with no warranties, and confers no rights.

ASP .Net MVC – Yes or No

Finally got a chance to work on a MVC 3.0 project. Still not convinced if MVC is best choice for asp application development. I found this on net which explains how to decide to go for MVC or not when starting your application development using ASP .Net. Its a simple analyser that can be a great help when in doubt.

Hope it helps.

MVC or Web form

MVC or Web form

How to put comments in .skin files

Skin files, introduced in ASP.NET 2.0, make it easier to specify an application’s look and feel. Commercial developers will want to add a comment with their copyright notice, but Microsoft does not explain how to put a comment in a skin file. In his book “Programming ASP.NET 2.0 Core Reference,” Dino Esposito shows skin file content with an HTML comment, but that will cause a build failure in the release version of Visual Studio 2005.

Although a skin file looks like .aspx markup, it is highly restricted. However, it does recognize ASP code blocks and will accept code block comments, such as this example:

< % – - Copyright 2006 XYZ Corp. All rights reserved. – - % >

[Note: because of display limitations, characters "" here are shown with a space after or before them.]

– copied from http://aspnet2holes.blogspot.com/2006/06/comments-in-skin-file.

TFS Build Agent Unreachable

Today when I kicked off a TFS build I got an error:

TF215085: An error occurred while connecting to agent \#####\##BuildAgent: TF215076: Team Foundation Build on computer wd201a013v (port 9191) is not responding. (Detail Message: Unable to connect to the remote server).

The steps I took to resolve it.

1. Check if 9191 is added in the windows firewall exception list on the build machine. Control Panel > Windows Firewall. If not add an explicit rule to allow the port (9191 is default)

2. Check if Visual Studio Team Foundation Build service is running. Run > Services.msc > locate service if it running. If not start it. Visual Studio Team Foundation Build is the build service for Visual Studio Team Foundation 2008. If the service doesn’t start check the logon credentials. Make sure it is a valid Domain account or Workgroup account.

Problem Solved.

Pragma no-cache

I had a requirement where an aspx page should not be cached in the Temporary Internet Files, simply because we want to reload the page from the server each time. This sort of scenario may present when login or authenticating. Some research and I found this article http://support.microsoft.com/kb/222064.

I was writing code in .Net and luckily its even simpler. Simply add this to the Page_Load

Response.Cache.SetCacheability(HttpCacheability.NoCache);
 Response.AddHeader(“Pragma”, “no-cache”);

Follow

Get every new post delivered to your Inbox.