Quote for the Week

"Learn to enjoy every moment of your life"

Thursday, October 30, 2014

Remove special characters using Regular expression

This post will help you to remove the special characters in the given string. Using Regular expression we can achieve this. Here i'm replacing the special characters with empty character.

For using Regular Expression class, you have to import System.Text.RegularExpressions.
Here i have made a string which contains all the special characters. This is the input.
And the output will be the string, free of special characters.

using System.Text.RegularExpressions;

public void RemoveSpecialCharacter()
{
  string inputStr = "'he*s .anf{# & 54= Sp'a(bfda+.%fgf},gh_gh&? XT R;SD<kb<$)-fd!z*>~`5+7fdR\\^ed";
  Regex re = new Regex("[;\\\\/:*?\"<>|{}~`().,_!+=&%^@#$'-]");
  string outputStr = re.Replace(inputStr, " ");
  Response.Write("<b>Origional String:</b>"+inputStr + "<br/><br/>");
  Response.Write("<b>After Removed Special characters:</b>" + outputStr);
}


Output :

Monday, October 27, 2014

Output Caching in MVC

Introduction


The main purpose of using Output Caching is to dramatically improve the performance of an ASP.NET MVC Application. It enables us to cache the content returned by any controller method so that the same content does not need to be generated each time the same controller method is invoked. Output Caching has huge advantages, such as it reduces server round trips, reduces database server round trips, reduces network traffic etc.

Keep the following in mind:-


  • Avoid caching contents that are unique per user.
  • Avoid caching contents that are accessed rarely.
  • Use caching for contents that are accessed frequently.
  • Let's take an example. My MVC application displays a list of database records on the view page so by default each time the user invokes the controller method to see records, the application loops through the entire process and executes the database query. And this can actually decrease the application performance. So, we can advantage of the "Output Caching" that avoids executing database queries each time the user invokes the controller method. Here the view page is retrieved from the cache instead of invoking the controller method and doing redundant work.


Cached Content Locations


In the above paragraph I said, in Output Caching the view page is retrieved from the cache, so where is the content cached/stored?

Please note, there is no guarantee that content will be cached for the amount of time that we specify. When memory resources become low, the cache starts evicting content automatically.

OutputCache label has a "Location" attribute and it is fully controllable. Its default value is "Any", however there are the following locations available; as of now, we can use any one.

1. Any   2. Client   3. Downstream   4. Server   5. None   6. ServerAndClient

With "Any", the output cache is stored on the server where the request was processed. The recommended store cache is always on the server very carefully. You will learn about some security related tips in the following "Don't use Output Cache".


Output Cache Filter

The OutputCache filter allow you to cache the data that is output of an action method. By default, this attribute filter cache the data till 60 seconds. After 60 sec, Asp.Net MVC will execute the action method again and cache the output again.
Enabling Output Caching
You can enable the output caching for an action method or controller by adding an [OutputCache] attribute as shown below:

[OutputCache(Duration=20, VaryByParam="none")]
public ActionResult Index()
{
 ViewBag.Message = DateTime.Now.ToString();
 return View();
}

The output of the Index() action method will be cached for 20 seconds. If you will not defined the duration, it will cached it for by default cache duration 60 sec. You can see the cache effect by applying the break point on index method as shown below.



Output Caching Location


By default, content is cached in three locations: the web server, any proxy servers, and the user's browser. You can control the content's cached location by changing the location parameter of the OutputCache attribute to any of the following values: Any, Client,Downstream, Server, None, or ServerAndClient.
By default, the location parameter has the value Any which is appropriate for most the scenarios. But some times there are scenarios when you required more control over the cached data.
Suppose you want to cache the logged in use information then you should cached the data on client browser since this data is specific to a user. If you will cached this data on the server, all the user will see the same information that is wrong.
You should cache the data on the server which is common to all the users and is sensitive.
Configure Cache Location
For configuring the cache location, you need to add the System.Web.UI namespace on your controller. You can cached the user's personal information in his browser like as below.

[OutputCache(Duration = 7200, Location = OutputCacheLocation.Client, VaryByParam = "none", NoStore = true)]
public ActionResult Index()
{
 ViewBag.Message = "Welcome : " + User.Identity.Name;
 return View();
}



Thursday, October 9, 2014

New Features Added to C# 5.0

C# mosst recent version 5.0 was released on August 15, 2012 with .NET Framework 4.5 and Visual Studio 2012. There are two main features in C# 5.0 - Async Programming and Caller Information. Let's understand both these features in details as given below.

1. Async Feature (Asynchronous Methods)


C# 5.0 Async feature introduces two keywords async and await which allows you to write asynchronous code more easily and intuitively like as synchronous code. Before C# 5.0, for writing an asynchronous code, you need to define callbacks (also known as continuations) to capture what happens after an asynchronous process finishes. This makes your code and other routine task such exception handling complicated.
Both the keywords are used in a combination of each other. Hence, an await operator is applied to a one or more than one expressions of an async method. An async method returns a Task or Task<TResult> that represents the ongoing work of the method. The task contains information that the caller of the asynchronous method can use, such as the status of the task, its unique ID, and the method's result.
public async Task<IEnumerable<Product>> GetProductList()
{
 HttpClient client = new HttpClient();
 Uri address = new Uri("http://dotnet-tricks.com/");
 client.BaseAddress = address;
HttpResponseMessage response = await client.GetAsync("myservice/product/ProductList");

 if (response.IsSuccessStatusCode)
 {
 var list = await response.Content.ReadAsAsync<IEnumerable<Product>>();
 return list;
 }
 else
 {
 return null;
 }
}

2. Caller Information (Caller info attributes)


Caller Information can help you in tracing, debugging and creating diagnose tools. It will help you to avoid duplicate codes which are generally invoked in many methods for same purpose, such as logging and tracing.
You could get the following information of caller method:
CallerFilePathAttribute
Full path of the source file that contains the caller. This is the file path at compile time.
CallerLineNumberAttribute
Line number in the source file at which the method is called.
CallerMemberNameAttribute
Method or property name of the caller.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

class Example
{
 static void Main(string[] args)
 {
 Console.WriteLine("Main method Start");
 InsertLog("Main");
 MyMethodB();
 MyMethodA();
 Console.WriteLine("Main method End!");
 Console.ReadLine(); // hold on result
 }

 static void MyMethodA()
 {
 InsertLog("MyMethodA");
 MyMethodB();
 }

 static void MyMethodB()
 {
 // some code here.
 }

 static void InsertLog(string method)
 {
 Console.WriteLine("{0} called MyMethodB at {1}", method,
 DateTime.Now);
 }
}
/* Output:
 Main method Start
 Main called MyMethodB at 11/17/2013 11:12:24 PM
 MyMethodA called MyMethodB at 11/17/2013 11:12:24 PM
 Main method End!
*/

In both Main and MyMethodA, method InsertLog is invoked for logging. Now we can change the above code as follows.
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;

class Example
{
 static void Main(string[] args)
 {
 Console.WriteLine("Main method Start");
 MyMethodB();
 MyMethodA();
 Console.WriteLine("Main method End!");
 Console.ReadLine();
 }

 static void MyMethodA()
 {
 MyMethodB();
 }

 static void MyMethodB([CallerMemberName] string memberName = "", [CallerFilePath] string sourceFilePath = "", [CallerLineNumber] int sourceLineNumber = 0)
 {
 InsertLog(memberName);
 }

 static void InsertLog(string method)
 {
 Console.WriteLine("{0} called MyMethodB at {1}", method, DateTime.Now);
 }
}

/*Output:
 Main method Start
 Main called MyMethodB at 11/17/2013 10:30:11 PM
 MyMethodA called MyMethodB at 11/17/2013 10:30:11 PM
 Main method End!
 */


 3. C# Evolution Matrix


Microsoft just published a new version of C# : 5.0 beta with CLR version 4.5 (Visual Studio 11 beta).
In order to get a big picture of the whole evolution of C# language, I summarized all the key features
into a C# Evolution Matrix for your reference as below diagram shows:



In C# version 5.0, there are two key features: Async Programming and Caller Information.

Thursday, October 2, 2014

LINQ Vs Stored Procedure

LINQ provide you common query syntax to query various data sources like SQL Server, Oracle, DB2, WebServices, XML and Collection etc. LINQ also has full type checking at compile-time and IntelliSense support in Visual Studio, since it used the .NET framework languages like C# and VB.NET.

On the other hand a stored procedure is a pre-compiled set of one or more SQL statements that is stored on RDBMS (SQL Server, Oracle, DB2 and MySQL etc.). The main advantage of stored procedures is that they are executed on the server side and perform a set of actions, before returning the results to the client side. This allows a set of actions to be executed with minimum time and also reduce the network traffic.

A brief comparison of LINQ and Stored Procedure

  1. Stored procedures are faster as compared to LINQ query since they have a predictable execution plan and can take the full advantage of SQL features. Hence, when a stored procedure is being executed next time, the database used the cached execution plan to execute that stored procedure.
  2. LINQ has full type checking at compile-time and Intellisense support in Visual Studio as compared to stored procedure. This powerful feature helps you to avoid run-time errors.
  3. LINQ allows debugging through .NET debugger as compared to stored procedure.
  4. LINQ also supports various .NET framework features like multi –threading as compared to stored procedures.
  5. LINQ provides the uniform programming model (means common query syntax) to query the multiple databases while you need to re-write the stored procedure for different databases.
  6. Stored procedure is a best way for writing complex queries as compared to LINQ.
  7. Deploying LINQ based application is much easy and simple as compared to stored procedures based. Since in case of stored procedures, you need to provide a SQL script for deployment but in case of LINQ everything gets complied into the DLLs. Hence you need to deploy only DLLs.


Limitation of LINQ over Stored Procedures

  1. LINQ query is compiled each and every time while stored procedures re-used the cached execution plan to execute. Hence, LINQ query takes more time in execution as compared to stored procedures.
  2. LINQ is not the good for writing complex queries as compared to stored procedures.
  3. LINQ is not a good way for bulk insert and update operations.
  4. Performance is degraded if you don't write the LINQ query correctly.
  5. If you have done some changes in your query, you have to recompile it and redeploy its DLLs to the server.