Common Asp.Net Tips and Tricks 3

Introduction

This is a series articles on ASP.NET Tips and Tricks. Under my previous article Common ASP.Net Tips and Tricks, we learned configuration tips and tricks. The article explained common exceptions we encounter while development and best practices for code implementation.

Tips and Tricks



LINQ to Entities does not recognize ToString


Sometimes LINQ to Entities does not recognize the method "System.String ToString()" and this method cannot be translated into a store expression.

Solution

This type of exception frequently occurs when we are working with LINQ or Entity Framework.

For example:

  1. var result=dc.Tests.Where(i=>i.status==status.ToString()).FirstOrDefault();  

According to the preceding syntax, when we convert “status.ToString()”, in the where condition the exception "Expression not found such method in SQL" occurs where the condition returns an IQueryable result. So if we convert the result to IEnumerable, then the preceding type of exception never occurs.

For example:

  1. var result=dc.Tests. AsEnumerable().Where(i=>i.status==status.ToString()).FirstOrDefault();

ToString() vs Convert.ToString()

Which is best, ToString() or Convert.ToString()?

Solution

Always use Convert.ToString() conversion for strings since it handles null values also, whereas ToString() leads to an exception when we convert a string from null.

string or StringBuilder

What to use, string or StringBuilder, for string manipulation?

Solution

Always use StringBuilder that stores a string for manipulation or appends a string to it. Whereas each string concatenation leads to copying a string to another string variable instead of preserving one memory allocation.

If(isBool==true) vs if(isBool)


What to use, If(isBool==true) or if(isBool)?

Solution

Always use if(isBool) like if condition since it is comfortable to read easily.

If(strValue==”some Value”) vs If(strValue.ToLower()==”some value”)

What to use, If(strValue==”some Value”) or If(strValue.ToLower()==”some value”)?

Solution

Whereas we filter records with search parameter always, first convert to lower case or upper case, then compare the result, since some search results do not work as expected with case sensitive words.

“” or string.Empty

What to use, “” or string.Empty, when initializing or reinitializing a string variable?

Solution
Best practices are to use string.Empty since no new instance is created, setting a “” value creates a new memory location to store the value into it.

Detecting which control is responsible for a postback event

How to detect which control is responsible for a postback event in an ASP.Net web form?

Solution
ASP.NET internally uses a “__EVENTTARGET” hidden field that stores the ID of the control that caused the postback and acts accordingly. So we can easily detect a Checkbox change, Radio button change, Dropdownlist change and so on.

Resource Files not being compiled into DLLs


What to do when resource files are not being compiled into DLLs?

Solution
This type of error or problem occurs when we are using a resource file and a proper build action is not set.

Step 1


Right-click on the resource file that you have added or just selected and press F4 that displays the Properties window.

Step 2


Change the Build Action to Embedded Resource.

Then when we publish the website with a third-party DLL or tools on Go Daddy or another hosting platform sometimes a System.Security.Security Exception occurs due to trust level.

For example, Exception Details: System.Security.SecurityException: Request for the permission of type 'System.Security.Permissions.SecurityPermission, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.

Solution

To allow third-party tools or DLL to run without website we need to put the following configuration on the web.config :

<configuration> 
<system.web> 
<trust level="Full" /> 
</system.web> 
</configuration>

Conclusion

I hope you found my previous article on ASP.NET Tips and Tricks Part 1 useful. In this article, we learned common exceptions and their solutions with some best practices when developing to build a better product. I will provide other useful tips in my next series of articles. Thanks!

Validate CKEditor using jQuery validate

Introduction

In this article we learn about how to validate CKEditor control using jquery validate
Prerequisite. Below JavaScript library are used to validate CKEditor control.
  1. Jquery-1.11.1.js
  2. Jquery.Vaidate.js

Description

When we configure CKEditor control in our html page it render in Iframe so jquery validate library fails to check weather this control is empty or not and we face issue while validating this control. Let’s see example:
HTML:
<form>
    <textarea id="txtDemo1" name="txtDemo1"></textarea>
        <textarea id="txtDemo2" name="txtDemo2"></textarea>
    <input type="submit" value="submit">
</form>

Let’s assume we have configured CKEditor for both text area control and both fields are required in system. For validation we have implemented following validation for both control as shown below:


SCRIPT:

$("form").validate({
ignore: [],
rules: {
txtDemo1: {
ckrequired: true //Custom required field 
}
, txtDemo2: {
 required: true  //Default required field fails
}
}});

Extention method for check CKEditor Control

jQuery.validator.addMethod("customfunctionanme",validationfunction,validationmessage);


jQuery.validator.addMethod("ckrequired", function (value, element) {
var idname = $(element).attr('id');
var editor = CKEDITOR.instances[idname];
var ckValue = GetTextFromHtml(editor.getData())
    .replace(/<[^>]*>/gi, '').trim();
    if (ckValue.length === 0) {
//if empty or trimmed value then remove extra spacing to current control
      $(element).val(ckValue);
      } else {
       //If not empty then leave the value as it is
       $(element).val(editor.getData());
       }
        return $(element).val().length > 0;
 }, "This field is required");

function GetTextFromHtml(html) {
            var dv = document.createElement("DIV");
            dv.innerHTML = html;
            return dv.textContent || dv.innerText || "";
        }


From above code we have used both default required validation and ckrequired custom required method by extending jquery validate library. Along with custom method we have use one JavaScript utility function to extract text from html value after that we have trimmed value to validate trim value with extra space.

Hope this article is useful for validate CKEditor control as well as create custom validation method using jquery validate.

Conclusion

In this article we learn about validating CKEditor using custom jquery validation method.

Dynamic Query in LINQ using Predicate Builder

Introduction This tutorial explains how to create a dynamic query using LINQ, Using Predicate Builder  LINQ to SQL dynamic query an...

Learn More