Thursday, September 4, 2014

How to get name of the member (property name, etc) of a .NET class without using hard-coded/ magic strings

Consider following sample class:

public class City()
{
public int CityId { get; set; }
public string CityName { get; set; }
}

For various reasons, we need name of the properties/ field of the class in a string variable in our code. (For example, while binding ID and Text fields in DropDown controls, etc).

One option which is quite easy is to use the hard-coded strings directly.
For exmaple,
string idField = "CityId";

But the biggest disadvantage with the above approach is that whenever a field name or property name is changed, you will need to manually search and edit such string values. If you forget, it will not give you any compile error and you will only come to know when some exception will be thrown from your code.

In order to get rid of such issues, we should avoid using hard-coded values.

.NET 3.5 or higher provides support of encapsulating methods using Func helper which we can use to find a name of the property/ field.

using System;
using System.Linq.Expressions;

string idField =
                ((MemberExpression)((Expression<Func<City, int>>)(c => c.CityId)).Body).Member.Name;

string textField =
                ((MemberExpression)((Expression<Func<City, string>>)(c => c.CityName)).Body).Member.Name;

That means, now whenever some changes property "CityId" to "City_Id" or whatever, s/he must will need to change the above code otherwise it will always give a compile error.

Hope this helps

Monday, July 28, 2014

Exploring Abstract class (OOP concepts) in .NET - My Observations

Following are my observations with Abstract classes in .NET.
Feel free to write in comments if you think of more points to be added in this list, or if you want know more details about one or more points :)

  1. A class must be declared with "abstract" keyword
  2. It can contain complete implantation of methods
  3. Methods declared with "abstract" keyword can contain only declarations in Abstract class
  4. We cannot create an instance of abstract class
  5. Abstract class must be inherited
  6. A class derived from an abstract class must contain complete implementation of all abstract methods
  7. An abstract class can be derived from another abstract class
  8. Abstract class can be used as a parameter in methods
  9. If a class contains an abstract method, then that class must be marked as "abstract"
  10. An abstract class can have a constructor
  11. An abstract class can be inherited from a non-abstract class
  12. Constructor rules are also applied in case of abstract classes inheritance

P.S. - Please note all keyword and code snippets (if demonstrated above) are in C#.NET 

Thursday, July 24, 2014

HTML/ CSS: FIX >> Contents do not appear on new line after floated DIVs.

When we use "float:left", or "float:right" styles in DIVs, we come across an issue due to which the contents after those floated DIVs is not appearing in new line, rather they start appearing immediately besides the completion of last floated DIV.

In order to make further contents appearing in new line, add following DIV after floated DIVs:

<div style="clear: both;"></div>

How constructors are called while the classes are inherited: Exploring Object Oriented Programming and Concepts

Constructor Calls in Inheritance

Case study 1:

ClassA is a base class of ClassB.
Both classes have default constructor.

Observations:
While creating a new instance of ClassB (without parameters):
- it will first call default constructor of ClassB which will call constructor of ClassA.
- it will complete executing code of default constructor of ClassA.
- after that, it will complete executing code of default constructor of ClassB.

Case study 2:

ClassA is a base class of ClassB.
ClassA has no default constructor, but only parameterized constructor.
ClassB has a default constructor.


Observations: 
- it will not allow creating ClassA without a default constructor 
- if you want to do so, you need to call a base class constructor from ClassB's constructor: 
For example, following is the constructor of class A 
public ClassA(string someVariable) ..... some code .... }  
To allow ClassA without a default constructor, its all child classes should call base class constructor as below: 
public ClassB(): base("some value") 
or
public ClassB(string fullName): base(fullName)

Thursday, July 17, 2014

MVC Attribute to restrict users to enter any kind of HTML tags in the input fields

By default, if a user tries to enter any HTML tags in any of the input boxes in an MVC website, it will throw an error saying "Potentially dangerous request".
This is OK, as it doesn't allow user to enter HTML tags and prevents the site from security threat.

However, the error page is not user friendly, and it is not giving a clue to the user as what was wrong there. So you may need to avoid default error page of browser, and instead your custom validation message should be displayed.

Also, there may be circumstances when you want to allow some fields to accept HTML tags (such as rich text boxes), and rest of the input fields shouldn't allow HTML. In that case, this approach will help.

In order to achieve this we need to create an attribute in MVC and then can decorate Model properties with that attribute.

Step 1
- Decorate HttpPost method with [ValidateInput(false)] 
Validate input is true by default, and that is why it prevents execution of any code in case if there is any HTML input values are detected in posted data.
Here, we need to set it to false" as we would like to execute code of our custom attribute       

[HttpPost]
[ValidateAntiForgeryToken]
[ValidateInput(false)]
public virtual ActionResult CreateCustomer(Customer viewModel)
{
......
}


Step 2
- Create custom attribute as below:

using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
using System.Text.RegularExpressions;
public class DenyHtmlInputAttribute: ValidationAttribute
{


protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (value == null)
return ValidationResult.Success;


var tagWithoutClosingRegex = new Regex(@"<[^>]+>");


var hasTags = tagWithoutClosingRegex.IsMatch(value.ToString());


if (!hasTags)
return ValidationResult.Success;

return new ValidationResult(String.Format("{0} cannot contain html tags", validationContext.DisplayName));
}


}
Step 3 
- Decorate all input fields of your Model with the attribute created above:
[DenyHtmlInput]
public string Comments { get; set; }
That's it.

This is how you can restrict Html inputs on specific fields of your MVC view.

Tuesday, July 15, 2014

FIX: CKEditor not showing up when site is deployed on IIS server (ckeditor-full version 4.4.2)

Scenario:

Recently, I came across an issue due to which CKEditor was not showing up after deploying website in IIS. It was showing an empty placeholder instead. It was showing up completely fine in development environment, and while running site through Visual Studio.

I had "ckeditor-full" (Version 4.4.2)" package added in my MVC project, and also bundles to load "\ckeditor\adapters\jquery.js" and "ckeditor\ckeditor.js" javascript files in the project.

I checked in the code but it all looked fine.

As a resolution, it turned out that, I had to include following line in my view before loading the bundles -

<script type="text/javascript">
    CKEDITOR_BASEPATH = "@Url.Content("~/Scripts/ckeditor/")";
</script>

Hope this will help someone.

Friday, April 18, 2014

How to disable generating .PDB files while compiling .NET assembly/ website in Release mode

While compiling your .NET assembly or publishing ASP.NET or MVC project in Release mode, you may observe .pdb file also gets generated along with necessary .dll or supporting files.
PDB file contains debugging information and symbol which does not make any sense during deployment or release of a product.
In order to get rid of generating PDB files during publish/ build -
1. Open the project properties of a project in Visual Studio
2. Click on "Build" tab
3. Make sure the configuration selected is "Release"
4. Click on "Advanced" button
5. Select "none" in "Debug Info" selection box.
6. Click OK, and save the project
Try building the project, and you will not see PDB files.

Screenshots:



Tuesday, April 1, 2014

Function Evaluation Timed out error in Entity Framework

While running a time-consuming queries in Entity Framework, you may face the error saying "Function evaluation timed out".
In order to fix this error, you will need to increase the timeout of underlying DbContext.

Steps


  • Open "EntityName.Context.cs" file.
  • This file must be having an Entity class inherited from "DbContext"
  • Copy following code in the default constructor of this class:
            var adapter = (IObjectContextAdapter)this;
            var objectContext = adapter.ObjectContext;
            objectContext.CommandTimeout = 120; //2 minutes

Please note that CommandTimeout is in seconds.

Monday, March 31, 2014

Error 403, 403.14, 404 - After deploying ASP.NET MVC website on IIS 7, IIS 7.5

After deploying your ASP.NET MVC website on IIS 7 or IIS 7.5, you might face following errors while browsing your website:

  • 403.14 - Forbidden (The Web server is configured to not list the contents of this directory.)
  • 404 - Not Found (The resource you are looking for has been removed, had its name changed, or is temporarily unavailable)

Following are the possible causes/ fixes for this -
  • Make sure the Application pool targets correct version of .NET framework (i.e .NET Framework v4.0.30319 for .NET 4 and 4.5)
  • Make sure the Pipeline mode of IIS Application pool is "Integrated"
  • Check UrlRoutingModule-4.0 is added in the modules of that website.
  • (To do that, open list of added modules by clicking "Modules" against your website, and see if the module "UrlRoutingModule-4.0" is added or not). If not, then add a module by clicking "Add Managed Module" button, where select System.Web.Routing.UrlRoutingModule as a Module type, and give "UrlRoutingModule-4.0" as its name)
  • Make sure you have following element added in system.webServer section of website's web.config
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"></modules> 
</system.webServer>

In most cases of 403.14, or 404 error, above are the possible causes and fixes. 

Tuesday, March 25, 2014

FIX: 'Model' conflicts with the declaration 'System.Web.Mvc.WebViewPage.Model'

I suddenly started receiving this error in one of my razor view. The error message was -
'Model' conflicts with the declaration 'System.Web.Mvc.WebViewPage<TModel>.Model'

This error is caused if you use "Model" instead of "model" in one or more lambda expressions (predicates) in your view.

Perform a case-sensitive search for "Model =>", and its very much possible that you may notice this in one or more lambda expressions,
For example,
@Html.EditorFor(Model => Model.BirthDate)
This should be actually, @Html.EditorFor(model => model.BirthDate)
Correcting this should fix the Model conflict error for you in your view.

Thursday, January 2, 2014

Accessing Model property in MVC View from Javascript

For example, you have following model in your MVC application:

public class Employee
{
public string EmployeeName
public int EmployeeNumber
}

You have bound this model to your MVC view (Razor/ Html), and there may be a case when you need to access "EmployeeName" in the Javascript from that view.

You can access value of "EmployeeName" property of your model by following way:

<script type="text/javascript">
function showEmployeeName()
{
alert('@(Model.EmployeeName)');
}

</script>