Parsing integer to enumerator with value out of the enumerator range

If you want to convert a integer value into the enumerator that contain this value you can explicit cast the value.

    public enum MyEnumType {
        KeyA = 1,
        KeyB = 2
    }

    class Program {
        static void Main(string[] args) {
            int myIntegerValue = 1;
            MyEnumType enu = (MyEnumType)myIntegerValue;
            Console.Read();
        }
    }

This will work if the value, in our example 1, is in the MyEnumType. It will also work if we use an integer over 2.

Since the .Net Framework 4, we can use the Parse and TryParse on enumerator. The TryParse let you parse the name of the enumerator or the value. This mean, you can parse “KeyA” and it will retrieve the enum for the value 1 or you can parse 1 and it will retrieve the enum for the value 1.

In real application, if the data is from outside, is always better to use TryParse because this one will indicate if it can parse without throwing an exception. Here is an example with Parse with wrong value followed by one with TryParse.

As you can see the Parse work with integer that is out of range but not for the named enumerator parsing, just for the value conversion.

What about the TryParse? Samething! It will return TRUE even if the value is out of range.

This can be problematic if you doesn’t have the control over the value. For example, the value is passed from Ajax call from the client side to your server as an Integer. You want to convert this one into an enumerator to continue to proceed as usual on the server. The way to ensure that the value is legit is to use Enum.IsDefined.

So, every time you want to Parse an enumerator from the external (as an integer from an Ajax request) you should check if the value is defined correctly because only using the parsing tool won’t tell you if you are out of range.

Dynamic function in Javascript

In some occasion, calling a dynamic function in Javascript can be useful. This is the case when you have a string that represent the name of the function that you want to execute. One way to do it it to use the EVAL keyword in Javascript. It’s not the best way to do it, but it’s the more known by developer. It let you evaluate Javascript in a string format. That mean that anything given to that function is executed on the client browser. This open a door to malicious code that could be executed if not well used. This is why, I’ll show you a second approach that will not use the EVAL key work to execute dynamic method in Javascript.

First of all, here is an example of code that execute a dynamic function with the EVAL keyword.

function myFunction
{
   alert('Test');
}

var functionName = "myFunction";							//Dynamic builded
var functionParameter = "firstParameter, secondParameter";	//Dynamic parameters
 
var functionToCall = functionName + "('" + functionParameter + "');";
var ret = eval(functionToCall);

As you can see, we could had some kind of logic to choose the functionName. This could have been generated by the server side or could have been loaded from the database or a Web Service. The dangerous part is that someone could change the functionName to direct Javascript statements that could harm the user.

Second, here is better approach that consist to use the window object to call the method. This, atleast, ensure that we are calling a function and not any Javascript statement. Howerver, it’s still possible to be hacked and to executed harmful code.

function myFunction
{
   alert('Test');
}

var functionName = "myFunction";							//Dynamic builded
var functionParameter = "firstParameter, secondParameter";	//Dynamic parameters
 
var functionToCall = window[functionName];
var ret = functionToCall(functionParameter);

In both case, the important thing is not to EVAL data that has been inputted by the user. The executed dynamic code in Javascript must be generated by the developper that has build the system only.

How to call anonymous function in Javascript?

You may have anonymous function that you want to call later in the same method (or to pass this one by parameter and call this one later). To be able to have a reference to this anonymous function, you need to use a variable that will keep a reference to this anonymous function. Later, when you want to use it, you simply need to call it by writing the variable name with parentheses.

var anonymous= function(){
    alert("Test123");
};
anonymous();

Pretty simple, isn’t?

From here you can have more complex prototype (Javascript class mechanism).

function MyClass(val1, val2){
    this.val1 = val1;
    this.val2 = val2;
    this.function1 = function()
    {
        alert(this.val1);
    }
}
//...
var x = new MyClass('Test','Hello');
x.function1();

This example show you that you can have an anonymous function that can be called later like the previous example.

Using onclick for Javascript function instead of href

Many people will use Javascript function call directly into the href attribute of the link tag when they want to execute Javascript. This let them execute Javascript without having to have the fallback of having the browser scrolling to the top. The problem with this method, other than having client script into an attribute which is been created for anchor link and external link is that it displays the Javascript code in the status bar of the browser.

<a href='javascript:MyFunction(1,2,3)'>Click me</a>

To avoid this kind of behavior, which is not very clean, is to simply use the onclick attribut which is dedicated to receive Javascript’s call.

<a href='#' onclick="MyFunction(1,2,3);return false;">Click me</a>

As you can see, the onclick contain also a second Javascript’s statement which indicate the to the browser to not execute the link in the href attribute (the hash tag). This will prevent the browser to scroll up. In fact, you could specify a page to go if something goes wrong with the Javascript or if the user doesn’t have Javascript enable.

<a href='fallbackpage.html' onclick="MyFunction(1,2,3);return false;">Click me</a>

In that case, if Javascript is disable, the user will be redirected to the “fallbackpage.html”.

You can also not systematic use the `return false` and simply use directly the return of your function.

<a href='nextpage.aspx' onclick="return MyFunction(1,2,3);">Click me</a>

In that case, this will call the MyFunction fonction and if the result is false will do nothing with the navigation and if true will move the user to “nextpage.aspx”. This can be interesting in a scenario where you need to have to confirm something with the user or if you need to validate data before moving to the next step.

What is the HandleError attribute goal?

In Asp.Net Mvc, you can add an attribute to your controller or to some actions of your controller to tell Asp that you will take care of errors if they occur. You simply need to add the attribute HandleError.

[HandleError]
public class MyController : Controller
{
}

You can take care of specific error by specifying one or many type of exception that you want to handle. To do, simply add the property ExceptionType at your HandleError level.

[HandleError(ExceptionType = typeof(SqlException))]
public class MyController : Controller
{
}

If you need to handle multiple exception, you will need to use multiple attributes.

[HandleError(ExceptionType = typeof(SqlException))]
[HandleError(ExceptionType = typeof(NullReferenceException))]
public class MyController : Controller
{
}

You can also in HandleError attribute specify what view to display.

[HandleError(ExceptionType = typeof(SqlException), View="SqlView")]
public class MyController : Controller
{
}

If you do not specify any view, the exception will be viewed in the default error page. At first, it will check for Error.aspx in the Views folder associated with the Controller and then go see in the Shared folder.

Now you have the control to display specific exception to a specific view, others errors to the generic error page or to do not use anything and use the default ASP error page (yellow page of death) by setting the customErrors to off in the web.config file.

How to get from an ASP.MVC Controller the absolute path for an action?

You may need to have the full url of an action in the case you desire to do some Javascript redirection. You may want to pass which url to redirect via Json. Using not a fully constructed url will fail the redirection. The trick is to pass a full url. Asp.Net MVC give you the possibility to generate a fully formed url with the URL helper. The class that will help you to get the url is called “UrlHelper“.

The class contains many Action method that are overloaded with many parameters. The one that interest us has 4 parameters.

public string Action(string actionName, string controllerName, object routeValues, string protocol) 
{
//...
}

The first parameter is the action name to which you want to have the url. The second one is the controller name. This one can be NULL if you use it inside a controller and want to have the url with the same url. If you are inside the action X or the controller Y and you put NULL, you will get a url for the controller Y. The route values doesn’t interest us in this case. You can pass NULL. The last parameter is the protocol. When you provide a procotol, the url returned by the Action method will contain a full absolute url. A trick is to use Request.Url.Scheme which will use the current protocol used by the method that has been called by the controller. That mean that if you are using HTTP that the url formed will have the same protocol, HTTP. Samething if the request would have been done by a HTTPS request, the formed url would contain HTTPS.

We can take a look inside Asp.Net MVC source code and see that the Action method with 4 parameters call GenerateURL with a lot of parameters.

        public string Action(string actionName, string controllerName, object routeValues, string protocol) {
            return GenerateUrl(null /* routeName */, actionName, controllerName, protocol, null /* hostName */, null /* fragment */, new RouteValueDictionary(routeValues), RouteCollection, RequestContext, true /* includeImplicitMvcValues */); 
        }

The GenerateUrl method check the protocol and if not NULL will build the absolute URL.

public static string GenerateUrl(string routeName, string actionName, string controllerName, string protocol, string hostName, string fragment, RouteValueDictionary routeValues, RouteCollection routeCollection, RequestContext requestContext, bool includeImplicitMvcValues) { 
            string url = GenerateUrl(routeName, actionName, controllerName, routeValues, routeCollection, requestContext, includeImplicitMvcValues);

            if (url != null) {
                if (!String.IsNullOrEmpty(fragment)) { 
                    url = url + "#" + fragment;
                } 
 
                if (!String.IsNullOrEmpty(protocol) || !String.IsNullOrEmpty(hostName)) {
                    Uri requestUrl = requestContext.HttpContext.Request.Url; 
                    protocol = (!String.IsNullOrEmpty(protocol)) ? protocol : Uri.UriSchemeHttp;
                    hostName = (!String.IsNullOrEmpty(hostName)) ? hostName : requestUrl.Host;

                    string port = String.Empty; 
                    string requestProtocol = requestUrl.Scheme;
 
                    if (String.Equals(protocol, requestProtocol, StringComparison.OrdinalIgnoreCase)) { 
                        port = requestUrl.IsDefaultPort ? String.Empty : (":" + Convert.ToString(requestUrl.Port, CultureInfo.InvariantCulture));
                    } 

                    url = protocol + Uri.SchemeDelimiter + hostName + port + url;
                }
            } 

            return url; 
        } 

So, that mean that if you want to have your action method to get an absolute URL you would need to call:

return Json(new JsonResponse { url = Url.Action("MyActionOfThisController", null, null, Request.Url.Scheme)});

Telerik MVC grid can insert new rows at the bottom of the grid since 2012 sp1

It’s rare that I am writing about third party control but Telerik grid has a new feature that is kinda hard to find any way to implement. If you want to insert a new row to a Telerik ASP.Net MVC grid that you need to add a call to the method InsertRowPosition. This can be done inside the method Editable of the grid.

  @Html.Telerik().Grid<YourObjectType>().Editable(e=>e.InsertRowPosition(GridInsertRowPosition.Bottom))

This is a short snippet of code to demonstrate how to add a row at the bottom of a grid with Telerik Grid.

Of course, to the button to add a new row you need to use the ToolBar method to add a command to insert. This is done by adding ToolBar method to the Telerik().Grid().

.ToolBar(c=> c.Insert().ButtonType(GridButtonType.Text))