Quote for the Week

"Learn to enjoy every moment of your life"

Tuesday, December 23, 2014

HTML Helpers in Asp.net MVC

HTML Helper is just a method that returns a HTML string. The string can represent any type of content that you want. For example, you can use HTML Helpers to render standard HTML tags like HTML <input>, <button> and <img> tags etc.
You can also create your own HTML Helpers to render more complex content such as a menu strip or an HTML table for displaying database data.

Different types of HTML Helpers


There are three types of HTML helpers as given below:

1. Inline Html Helpers


These are create in the same view by using the Razor @helper tag. These helpers can be reused only on the same view.

helper ListingItems(string[] items)
 {
 <ol>
 @foreach (string item in items)
 {
 <li>@item</li>
 }
 </ol>
 }

 <h3>Programming Languages:</h3>

 @ListingItems(new string[] { "C", "C++", "C#" })

 <h3>Book List:</h3>

 @ListingItems(new string[] { "How to C", "how to C++", "how to C#" })

2. Built-In Html Helpers


Built-In Html Helpers are extension methods on the HtmlHelper class. The Built-In Html helpers can be divided into three categories-

a. Standard Html Helpers


These helpers are used to render the most common types of HTML elements like as HTML text boxes, checkboxes etc. A list of most common standard html helpers is given below:


TextBox @Html.TextBox("Textbox1", "val") 
Output: <input id="Textbox1" name="Textbox1" type="text" value="val" />

TextArea @Html.TextArea("Textarea1", "val", 5, 15, null) 
Output: <textarea cols="15" id="Textarea1" name="Textarea1" rows="5">val</textarea>

Password @Html.Password("Password1", "val") 
Output: <input id="Password1" name="Password1" type="password" value="val" />

Hidden Field @Html.Hidden("Hidden1", "val") 
Output: <input id="Hidden1" name="Hidden1" type="hidden" value="val" />

CheckBox @Html.CheckBox("Checkbox1", false) 
Output: <input id="Checkbox1" name="Checkbox1" type="checkbox" value="true" /> <input name="myCheckbox" type="hidden" value="false" />

RadioButton @Html.RadioButton("Radiobutton1", "val", true) 
Output: <input checked="checked" id="Radiobutton1" name="Radiobutton1" type="radio" value="val" />

Drop-down list @Html.DropDownList (“DropDownList1”, new SelectList(new [] {"Male", "Female"})) 
Output: <select id="DropDownList1" name="DropDownList1"> <option>M</option> <option>F</option> </select>

Multiple-select  @Html.ListBox(“ListBox1”, new MultiSelectList(new [] {"Cricket", "Chess"})) 
Output: <select id="ListBox1" multiple="multiple" name="ListBox1"> <option>Cricket</option> <option>Chess</option> </select>

b. Strongly Typed HTML Helpers


These helpers are used to render the most common types of HTML elements in strongly typed view like as HTML text boxes, checkboxes etc. The HTML elements are created based on model properties.

The strongly typed HTML helpers work on lambda expression. The model object is passed as a value to lambda expression, and you can select the field or property from model object to be used to set the id, name and value attributes of the HTML helper. A list of most common strongly-typed html helpers is given below:

TextBox @Html.TextBoxFor(m=>m.Name) 
Output: <input id="Name" name="Name" type="text" value="Name-val" />

TextArea @Html.TextArea(m=>m.Address , 5, 15, new{})) 
Output: <textarea cols="15" id="Address" name=" Address " rows="5">Addressvalue</textarea>

Password @Html.PasswordFor(m=>m.Password) 
Output: <input id="Password" name="Password" type="password"/>

Hidden Field @Html.HiddenFor(m=>m.UserId) 
Output: <input id=" UserId" name=" UserId" type="hidden" value="UserId-val" />

CheckBox @Html.CheckBoxFor(m=>m.IsApproved) 
Output: <input id="Checkbox1" name="Checkbox1" type="checkbox" value="true" /> <input name="myCheckbox" type="hidden" value="false" />

RadioButton @Html.RadioButtonFor(m=>m.IsApproved, "val") 
Output: <input checked="checked" id="Radiobutton1" name="Radiobutton1" type="radio" value="val" />

Drop-down list @Html.DropDownListFor(m => m.Gender, new SelectList(new [] {"Male", "Female"})) 
Output: <select id="Gender" name="Gender"> <option>Male</option> <option>Female</option> </select>

Multiple-select Html.ListBoxFor(m => m.Hobbies, new MultiSelectList(new [] {"Cricket", "Chess"})) 
Output: <select id="Hobbies" multiple="multiple" name="Hobbies"> <option>Cricket</option> <option>Chess</option> </select>

c. Templated HTML Helpers


These helpers figure out what HTML elements are required to render based on properties of your model class. This is a very flexible approach for displaying data to the user, although it requires some initial care and attention to set up. To setup proper HTML element with Templated HTML Helper, make use of DataType attribute of DataAnnitation class.
For example, when you use DataType as Password, A templated helper automatically render Password type HTML input element.


Display Renders a read-only view of the specified model property and selects an appropriate HTML element based on property’s data type and metadata. 

@Html.Display("Name")
@DisplayFor Strongly typed version of the previous helper 
@Html.DisplayFor(m => m. Name)

Editor Renders an editor for the specified model property and selects an appropriate HTML element based on property’s data type and metadata. 
Html.Editor("Name")
EditorFor Strongly typed version of the previous helper 
Html.EditorFor(m => m. Name)

3. Custom Html Helpers


You can also create your own custom helper methods by creating an extension method on the HtmlHelper class or by creating static methods with in a utility class.

public static class CustomHelpers
{
 //Submit Button Helper
 public static MvcHtmlString SubmitButton(this HtmlHelper helper, string 
 buttonText)
 {
 string str = "<input type=\"submit\" value=\"" + buttonText + "\" />";
 return new MvcHtmlString(str);
 }
 //Readonly Strongly-Typed TextBox Helper
 public static MvcHtmlString TextBoxFor<TModel, TValue>(this 
 HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TValue>>
 expression, bool isReadonly)
 {
 MvcHtmlString html = default(MvcHtmlString);

 if (isReadonly)
 {
 html = System.Web.Mvc.Html.InputExtensions.TextBoxFor(htmlHelper,
 expression, new { @class = "readOnly",
 @readonly = "read-only" });
 }
 else
 {
 html = System.Web.Mvc.Html.InputExtensions.TextBoxFor(htmlHelper,
 expression);
 }
 return html;
 }
}

Tuesday, December 16, 2014

HashSet in C#.net

A HashSet holds a set of objects, but in a way that it allows you to easily and quickly determine whether an object is already in the set or not. It does so by internally managing an array and storing the object using an index which is calculated from the hashcode of the object.

For more information on hashing, check out the HashMap category.

Things to remember:
– A HashSet is not synchronized, so not thread-safe.
– Its elements are not ordered
– Add an element to the HashSet with the method add(Object o)
– Remove an element with the method remove(Object o)
– Remove all elements with the method clear()
– Get the number of elements with the method size()


Note:

This internally calls the UnionWith method to eliminate the duplications. ToArray transforms the HashSet into a new array.

Creation of Hashset<>

The following line of code describes how to create the hashset in C#:

HashSet<int> firstset = new HashSet<int>();
HashSet<int> secondset = new HashSet<int>();



Add elements in the Hashset<>

To add an element to the Hashset we use the add() method like:

for (int i = 1; i < 10; i++)
{
   firstset.Add(5 * i);
}
for (int j = 1; j < 10; j++)
{
   secondset.Add(10 * j);
}

Prints the elements of hashset using foreach loop

Write the following code to print the elements of the hashset:

namespace ConsoleApplication14
{
    class Program
    {
        static void Main(string[] args)
        {
            HashSet<int> firstset = new HashSet<int>();
            HashSet<int> secondset = new HashSet<int>();
            for (int i = 1; i <= 10; i++)
            {
                firstset.Add(5 * i);
            }
            for (int j = 1; j <=10; j++)
            {
                secondset.Add(10 * j);
            }
            Console.WriteLine("The table of five(5) is:");
            foreach (int a in firstset)
            {
                Console.WriteLine(a);
            }
            Console.WriteLine("The table of Ten(10) is:");
            foreach (int b in secondset)
            {
                Console.WriteLine(b);
            }
        }
    }
}

Thursday, December 11, 2014

About New Asp.net vNext and MVC 6

Microsoft has announced the next generation of ASP.NET at TechEd North America on 12 May 2014, which is called ASP.NET vNext. ASP.NET vNext includes new cloud optimized versions of MVC6, Web API3, Web Pages4, SignalR3 and Entity Framework7.

Features of ASP.NET vNext

  • ASP.NET vNext includes new cloud-optimized versions of MVC, Web API, Web Pages, SignalR, and Entity Framework.
  • MVC, Web API and Web Pages have been merged into one framework, called MVC 6. This will follow common programming approach between all these three i.e. a single programming model for Web sites and services.
  • For example, there is unified controller, routing concepts, action selection, filters, model binding, and so on. In this way, You will have a single controller that returns both MVC views and formatted Web API responses, on the same HTTP verb.
  • MVC 6 has no dependency on System.Web since it was quite expensive. A typical HttpContext object graph can consume 30K of memory per request and working with small JSON-style requests this is very costly. With MVC 6 it is reduced to roughly 2K. The result is a leaner framework, with faster startup time and lower memory consumption.
  • ASP.NET vNext has new project extension project.json to list all the dependencies for the application and a startup class in place of Global.asax.
  • ASP.NET vNext apps are cloud ready by design. Services such as session state and caching will adjust their behavior depending on hosting environment either it is cloud or a traditional hosting environment. It uses dependency injection behind the scenes to provide your app with the correct implementation for these services for cloud or a traditional hosting environment. In this way, it will easy to move your app from on-premises to the cloud, since you need not to change your code.
  • .NET next version, .NET vNext is host agnostic. Hence you can host your ASP.NET vNEXT app in IIS, or self-host in a custom process.
  • .NET vNext support true side-by-side deployment. If your app is using cloud-optimized subset of .NET vNext, you can deploy all of your dependencies including the .NET vNext (cloud optimized) by uploading bin to hosting environment. In this way you can update your app without affecting other applications on the same server.
  • Dependency injection is built into the framework. Now, you can use your preferred IoC container to register dependencies.
  • .NET vNext use the Roslyn compiler to compile code dynamically. Hence you will be able to edit a code file and can see the changes by refreshing the browser; without stopping or rebuilding the project.
  • .NET vNext is open source and cross platform. It can run on Mono, on Mac and Linux.

Tuesday, December 2, 2014

A Four questions Survey about this blog..!!

Dear Subscribers and Followers..!!


Please specify your opinion about this blog on below link for future posts and services. It very important to know about your feedback for our service.

https://www.surveymonkey.com/s/F6DMQ3N

Thank you.

Monday, December 1, 2014

.NET is going to Open source and Cross-Platform

The next release of .NET will enable .NET cloud applications on multiple platforms, with future support of the core .NET server runtime and libraries for Linux and Mac. This implementation will be part of the .NET Foundation, home of the increasing number of .NET components being open sourced. Join and participate by visiting the .NET Foundation and the related GitHub repositories.


Download Visual Studio 2015 Preview and .NET 2015 Preview

These previews provide a first glimpse of Microsoft’s investment in an innovative set of technologies to help you efficiently build powerful, versatile applications across the platform spectrum – from Windows to web to iOS and Android. A few highlights include:

Cross-platform ASP.NET 5 websites

Multi-device app support, with Visual Studio Tools for Apache Cordova and the new Visual C++ tools for cross-platform library development.

Connected Services, enabling easier integration of services into apps including Office 365, SalesForce, and Azure Platform Services,
Smart Unit Testing (formerly PEX) technology from Microsoft Research.

For more info:

Thursday, November 27, 2014

Showing Message Box in Asp.net

We don't have predefined function for message box or alert in asp.net web application. It's available only in windows application. But we can create our own method that gives alert functionality. Here the ClientScript used to add the script to the page. so we can get the javascript alert in page.


Page.ClientScript.RegisterStartupScript(this.GetType(), "MessageBox", <your javascript>);

or

ScriptManager.RegisterClientScriptBlock(Me, Me.GetType(), "Confirm", "Confirm('Text U want to display');", True);

You can define your own script as per your requirement.

Wednesday, November 19, 2014

Data Caching in Asp.net

Data Caching:

Data caching stores the required data in cache. So the web server did not send request to DB server every time for each and every request which increase the web site performance. Hence, caching of data can dramatically improve the performance by reducing database hits and round-trips.

We can do the caching like this,


HttpContext.Current.Cache.Insert("strCacheName","data you want to cache", null, DateTime.Now.AddMinutes(expTime), TimeSpan.Zero);

Parameters used:

key:
The cache key used to reference the object.

value:
The object to be inserted in the cache.

dependencies:
The file or cache key dependencies for the inserted object. When any dependency changes, the object becomes invalid and is removed from the cache. If there are no dependencies, this parameter contains null.

absoluteExpiration:
The time at which the inserted object expires and is removed from the cache. To avoid possible issues with local time such as changes from standard time to daylight saving time, use System.DateTime.Utc. Now rather than System.DateTime.Now for this parameter value. If you are using absolute expiration,the slidingExpirationparameter must be System.Web.Caching.Cache.NoSlidingExpiration.

slidingExpiration:
The interval between the time the inserted object is last accessed and the
time at which that object expires. If this value is the equivalent of 20
minutes, the object will expire and be removed from the cache 20 minutes
after it was last accessed. If you are using sliding expiration, the absoluteExpiration
parameter must be System.Web.Caching.Cache.NoAbsoluteExpiration.

Friday, November 14, 2014

How to disable copy , paste in text box using jQuery


  • Some times in validation point of view we need to disabled copy, paste, cut , like password or mobile number etc..,
  • We can achieve this using jQuery - 


$(document).ready(function(){
      $('#txtInput').bind("cut copy paste",function(e) {
          e.preventDefault();
      });
 });


That's it! It is very simple.

Have a Good Day.

Thursday, November 13, 2014

Simple validation technique using jQuery without any plug-ins


  • This Article subjected to How we do validation , As we have many validations with different plugins or jQuery validation.
  • Today I am going to show you how we can do validation using our own customize script at client-side.
  • Initially, we will add class called 'validation' to all text boxes which are required for ex: Name, Mobile, Email



First name: <input  type='text' id='txtName'  class='validation'/>

Phone : <input  type='text' id='txtPhone'  class='validation'/>

-----------------------
-----------------------

<input type='button' value='submit' id='btnSubmit' />

Now in script write as
<script>
$(document).ready(function(){
$("#btnSubmit").click(function(){

  $('.validation').each(function () {
            if ($(this).val() == "" || $(this).val()==0) {
                isValid = false;
                $(this).css({
                    "border": "1px solid red",
                    "background": "#FFCECE"
                });
            }
            else {
                $(this).css({
                    "border": "",
                    "background": ""
                });
            }
        });
});
});

</script>

That's simple, validation is Done. Do you want to try it, you can.


If any queries mail to dotnetcircle@gmail.com.

HAVE A GOOD DAY.


Monday, November 3, 2014

Difference between Response.Redirect and Server.Transfer


       In ASP.Net Technology both "Server" and "Response" are objects of ASP.Net. Server.Transfer and Response.Redirect both are used to transfer a user from one page to another. But there is some remarkable differences between both the objects which are as follow.


Response.Redirect

  1. Response.Redirect() will send you to a new page, update the address bar and add it to the Browser History. On your browser you can click back.
  2. It redirects the request to some plain HTML pages on our server or to some other web server.
  3. It causes additional roundtrips to the server on each request.
  4. It doesn’t preserve Query String and Form Variables from the original request.
  5. It enables to see the new redirected URL where it is redirected in the browser (and be able to bookmark it if it’s necessary).
  6. Response. Redirect simply sends a message down to the (HTTP 302) browser.



Server.Transfer


  1. Server.Transfer() does not change the address bar, we cannot hit back.One should use Server.Transfer() when he/she doesn’t want the user to see where he is going. Sometime on a "loading" type page.
  2. It transfers current page request to another .aspx page on the same server.
  3. It preserves server resources and avoids the unnecessary roundtrips to the server.
  4. It preserves Query String and Form Variables (optionally).
  5. It doesn’t show the real URL where it redirects the request in the users Web Browser.
  6. Server.Transfer happens without the browser knowing anything, the browser request a page, but the server returns the content of another.

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.

Tuesday, September 30, 2014

Difference Between ADO.Net & LINQ to SQL

Introduction


Even though on a low level, LINQ may itself use subsets of ADO - this article focuses more on the programming aspect as a comparison between the two. I am also aware of the slight difference in "run-time" speed, in terms of data access times. However, again - we focus on differences during the development or "design-time" aspect thereof.

About ADO.Net

ADO.Net is an acronym for Advanced Data Objects. It is a subset of the .Net framework. The first versions which were "non .Net", were separate libraries for accessing data. However, as the of .Net Framework it has been incorporated as part thereof.

Accessing SQL based databases using ADO.Net is fast and efficient. However, data is often returned as different types or custom types, and have to be cast or formatted into usable or .Net or native types.

However, when working with web services, like WCF Services and Silverlight, it's a breeze to query data, compile the objects and send them across the service.

I will not go into a too detailed discussion regarding ADO.Net as it's been used for a long time and that is how most of the .Net developers access data.

About LINQ

LINQ is an acronym for Language INtegrated Query. For the purpose of this article, which focuses on C#, .Net and MS-SQL based data mainly, you may understand LINQ as the following: C# Syntax like SQL.

You must understand that any possible collection of objects can be queries with LINQ, where SQL is mostly related to data and querying databases. For example, you may query the Windows file system (like your C drive) as if it were a database or a collection of data - however, we will not look at that during this article.

The reason why LINQ is (or can be) so popular with developers, and me at least, is that it allows you to stay in your native programming language (C# in this instance) and query data, or any other collection of objects for that matter. Another nice feature, is the comparable native types it uses to build and return these objects.

Another problem I have with LINQ, is that it basically creates "it's own" version of the objects returned. This is not really a problem - and actually, it's one of the best features. It does a lot of the work for you. Let me explain. If you go through the process of creating a new database, it's data structures, communication layers, business rules, data entry and exist points, and start working with larger projects where such data libraries are shared between teams, you can imagine how complicated the SQL, Stored Procedures, etc. can get. As well as where things (like business rules) are located, in the database, or in the libraries. (But that is another can of worms for another article)

But let's get back to that problem I started the previous paragraph with - the issue I have, if you query (lets say) the user table, it will build user objects based on the data structure. If you then want to send this across a WCF service for instance, it creates a very hairy and difficult scenario to overcome. You have to either work some black magic with inheritance or even darker magic with WCF data contracts and really get your hands dirty in the WCF frameworks. However, it's so cumbersome you may actually completely get side-tracked and forget you are actually working with data, fetching it and returning it - and not communication layers and protocols. Another way, is to recreate each class or object entity, and write interfaces, or perhaps try and only work with native types in the methods. Other ways may exist, but this entire situation is a bit of a sticky one - I'm working on better ways to handle them every year. I will publish an article on my best solution in the near future.

However, if your application is less widely scoped, lets say, you have a typical .Net Windows App (WPF or Win-Forms) over a fast company network, linked to a database server - you will regret not using LINQ. It's only problematic when you start combining WCF or web services and LINQ.

Summary:

 Have Any Questions, Most welcome, just mail to  dotnetcircle@gmail.com

Monday, September 29, 2014

Garbage Collection - C#

What is garbage?


“Garbage” consists of objects created during a program’s execution on the managed heap that are no longer accessible by the program. Their memory can be reclaimed and reused with no averse effects.


What is the garbage collector?


The garbage collector is a mechanism which identifies garbage on the managed heap and makes its memory available for reuse. This eliminates the need for the programmer to manually delete objects which are no longer required for program execution. This reuse of memory helps reduce the amount of total memory that a program needs to run. In technical terms, we say that it keeps the program’s “working set” small.

How does the garbage collector identify garbage?


In Microsoft’s implementation of the .NET framework the garbage collector determines if an object is garbage by examining the reference type variables pointing to it. In the context of the garbage collector, reference type variables are known as “roots”. Examples of roots include:




  1. A reference on the stack
  2. A reference in a static variable
  3. A reference in another object on the managed heap that is not eligible for garbage collection
  4. A reference in the form of a local variable in a method
  5. Take the following method.


void CreateList()
{
var myList = new List<object>();
myList.Add(new object());
myList.Add(new object());
myList.Add(new object());
Console.WriteLine("Objects added!");
}

When the method starts to execute, a List<object> is instantiated on the managed heap along with several objects. The List contains a root to each of the objects, and the stack contains a root to the List. While the method is executing, all of these roots are accessible from within the program and are considered to be “active”. When the method finishes executing, the stack is cleaned up, removing the root pointing to the List. The List is now no longer accessible within the program. All of the roots contained by the List (those pointing to the objects) are now considered to be “inactive”.

The garbage collector identifies garbage by examining an application’s roots. Objects which have no active roots pointing to them are considered to be garbage.


How does the garbage collector manage to collect garbage without impacting application performance?


The truth is that the garbage collector does impact application performance. However, Microsoft has done a very good job at ensuring that it runs as quickly and efficiently as possible, and its impact is virtually unnoticeable from a user standpoint. It manages to do this by employing a wide variety of strategies and optimisations, a few of which we’ll talk about here.

Reference tracking optimisations


When the garbage collector begins a collection, it starts by setting a bit on every object which could potentially be garbage to 0. This marks these objects for collection. It then traverses the active roots in the application and sets that bit to 1 on every object which is not in fact garbage.

Remember from our previous example that when an object is considered not to be garbage, all objects that it references are also considered not to be garbage. This means that marking a single object as not garbage (such as a List) can result in hundreds or thousands of others also being marked. The garbage collector makes this process more efficient by examining the garbage collection bit before marking a given object. If the bit is already set to 1, it simply moves on, knowing that the object and its roots and their roots and so on and so forth have already been traversed. This makes the marking process significantly more efficient.


Generations in Managed Heap

1. Generation 0

This is the youngest generation and contains the newly created objects. Generation 0 has short-lived objects and collected frequently. The objects that survive the Generation 0 are promoted to Generation 1.
Example : A temporary object.

2. Generation 1

This generation contains the longer lived objects that are promoted from generation 0. The objects that survive the Generation 1 are promoted to Generation 2. Basically this generation serves as a buffer between short-lived objects and longest-lived objects.

3. Generation 2

This generation contains the longest lived objects that are promoted from generation 1 and collected infrequently.
Example : An object at application level that contains static data which is available for the duration of the process.

Compacting


When the runtime allocates heap memory, it attempts to do so in a linear fashion. Objects are created one after another on the heap, and the runtime makes use of what is called the “next object pointer” to know where to place the next object. As you can imagine, however, once a garbage collection has taken place, the once smooth, contiguous block of memory that made up the heap is left full of holes. However, the garbage collector doesn’t leave the heap in this state*. Instead, it embarks on a compacting phase, whereby it moves objects back towards the beginning of the heap, filling the reclaimed memory spaces in the process.

As you can imagine, moving objects around is no trivial matter. When an object is moved in memory, existing references to it need to be updated. This understandably requires that program execution be suspended, as to ensure that all references to a given object are valid at all times during program execution. The CLR attempts to make this suspension as painless as possible by fine-tuning how and when garbage collection executes. Details of these techniques go beyond the scope of this article, but can be found here on the MSDN website.

Smart invocation


The garbage collector ensures that it only collects garbage when it really needs to by setting out a memory budget for each of its three generations. These budgets can be modified by the CLR throughout program execution in order to be as well-adapted as possible to the execution conditions of a given program. When generation 0 of the managed heap surpasses its budget, the garbage collection process begins. The garbage collector checks to see if any other generations have surpassed their budgets, and then decides which generations to actually collect. This often means that garbage collection is only performed on a portion of the objects living on the managed heap, which makes the process significantly more efficient.

It is important to note that while the majority of garbage collections in an average program are invoked when generation 0 exceeds its memory budget, garbage collections can also be triggered by other events. These include the system reporting low memory conditions, the unloading of an AppDomain, the shutting down of the CLR, or a manual call to the GC.Collect method**.

Final word


Hopefully this article will have given you a broad idea of how the garbage collector works in Microsoft’s implementation of the .NET Framework. The garbage collector is a very, very complex mechanism which could merit its own book, and this article by no means constitutes a deep dive into its inner workings. Instead, I’ve attempted to provide a simple and concise explanation of the key talking points, with hopes that it will give you a basic understanding of what goes on behind the scenes in your .NET programs.