Common Asp.Net Tips and Tricks 3
IntroductionThis 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
This type of exception frequently occurs when we are working with LINQ or Entity Framework.
- var result=dc.Tests.Where(i=>i.status==status.ToString()).FirstOrDefault();
- var result=dc.Tests. AsEnumerable().Where(i=>i.status==status.ToString()).FirstOrDefault();
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
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)
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”)?
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
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
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?
This type of error or problem occurs when we are using a resource file and a proper build action is not set.
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=18.104.22.168, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.
To allow third-party tools or DLL to run without website we need to put the following configuration on the web.config :
<trust level="Full" />