IEnumerable,IList,ICollection in C#

. Friday, January 20, 2012
4 comments

Hello Friends, I am writing blog after really a long time due to my busy work schedule, anyway Today I am going to tell you about these interfaces with their uses.
IEnumerable
Its a core interface which is used to iterate over collection of specified type.Mainly it Implements two methods:
MoveNext: which is of boolean type which tells whether there are more records to move on or not.
GetCurrent: which returns the current record from the collection.
ICollection :Implements IEnumerable
Its a Interface used to Manipulate generic Collections,as it is Implements IEnumerable interface so its obvious that this will also Implements methods MoveNext and GetCurrent,so with this interface you can iterate through collection.
Apart from this its also having its own methods like
Add:Which adds record at the end of collection.
Remove:Removes Specified Item from collection.
Contains:Its a boolean type method which tells whether collection contains the specified item or Not.
I will post code later to explain something tricky thing in this hierarchy.

class Collection
{
static void Main(string[] args)
{
//declare array
string[] arystr = new string[] { "Ajay", "Anil", "Ravi", "Vishal", "Ram" };
//Check for IEnumerable
IEnumerable enumstr = from record in arystr select record;
Console.WriteLine("Start for Enumerable");
foreach (string name in enumstr)
{
Console.WriteLine("Names are {0}", name);
}
Console.WriteLine("Ends for Enumerable");

//Check for IList
IList Liststr = (from record in arystr select record).ToList();
Console.WriteLine("Start for List");
Liststr.Add("Rakesh");
foreach (string name in Liststr)
{
Console.WriteLine("Names are {0}", name);

}
Console.WriteLine("Ends for List");

//Check for ICollection
ICollection Collectionstr = (from record in arystr select record).ToList();
Console.WriteLine("Start for Collection");

Console.Write(Collectionstr.Contains("Ram"));
foreach (string name in Collectionstr)
{
Console.WriteLine("Names are {0}", name);

}
Console.WriteLine("Ends for Collection");
Console.Read();
}
}


IList


Interface which is collection of Non-generic type objects and can be accessed by index. Its the Interface which Implements two interfaces ICollection and IEnumerable.so its obvious that this will Implements the methods of the both the interfaces.Its own methods are like


Insert: Insert the given item at specified Index.


RemoveAt:Removes the Item from Specified Index.


IndexOf : retrieves the item from specified Index.


Now Lets take and Example


When I use IL to see the compilation of above Code I get the following:


 image


image




image


image





This was for IEnumerable Which Implements two basic methods MoveNext and GetCurrent.


image


image


image


 image


 image


From IL its very clear that IList also Implements Interface IEnumerable so when I receive array of string inside IList it internally uses movenext and GetCurrent these two methods to iterate over records,and one more is the method Add,which is because its also Implements ICollection.


image


  image


image


ICollection also Implements IEnumerable but I didn’t added IL code for this, only you can see for ICollection is Contains method which is a boolean type as you can see from IL Output.


So among IList,ICollection,IEnumerable the hierarchy is like


IList Implements ICollection Implements IEnumerable.


hope you enjoyed this article. Thanks

uses of success and complete events in Jquery Ajax

. Wednesday, December 14, 2011
0 comments

Hello Friends,after a long time I'm writing this post.well everyone of us uses Ajax and there are two Events in this

Success : this event is called when your request get succeed. else this does not call.

Complete: doesn't matter whether your request get succeed or not, this event always called,and you can   check various http status code like 200 for OK,501 for Internal Server Error, 400 bad ,404
page not found etc.inside this event for the response for xmlhttprequest.


Which event fires first.?

between success and complete event success event fires before complete event. for details about the sequence of these event check on the official site of jquery ajax here

here is a simple code snippet







the ajax is called when GetQoute form is submitted and receives the httpxmlresponse which later displayed inside the various div's in success event. and if status code received is 200 then success alert message shown in complete event.

What the trick inside this ?

well, as success is fired before complete event we can get response data only in success event and not in complete event because this is useful only for check response status. in the above code,data corresponding to openingPrice,Ratings are displayed but not displayed for closingPrice because its inside complete event.

Hope you enjoyed this.Thanks

Really a Great book by Mr steve sanderson for Asp.net MVC

. Tuesday, December 13, 2011
0 comments

Download this Ebook from Here.
also follow steve sanderson for asp.net mvc updates here

Json Post and Get in Asp.net MVC

. Thursday, October 13, 2011
0 comments



What is Json ?


Json stands for javascript object notation which is used to interchange data between various languages a typical example is any server side language like c#,vb.net with Javascript.


How to use Json in MVC ?

well,whenever you make an Ajax Call to retrieve some sort of data then the best format to retrieve data is Json which is string:value pair.
get more about json here

Now lets create a Html to Make an Ajax call and retrieve Json.

What time is it?

<% using (Ajax.BeginForm("GetTime", new AjaxOptions { UpdateTargetId = "myResults" })) { %> Show me the time in: <% } %>
Results will appear here
This page was generated at <%= DateTime.UtcNow.ToString("h:MM:ss tt") %> (UTC)
Confirmation Dialog..

which looks like as follows :






















Now my Javascript with making ajax call is as follows :



The Main thing for this post is $.Ajax with Get and Post xmlHttpRequests.
on successful response its get displayed else response received with an Error like internal server error (500) etc.

following action receives the submit for this page with an Ajax Call.

public JsonResult GetTime(string zone)
        {
            Person person = new Person();
            person.Name = "Vishal";
            person.Address = "Indore";
            return Json(person);
        }

Which returns the data in Json Format.


When I use xmlhttprequest Post in $.Ajax function of Jquery I receive the following Response.






and When I use xmlhttprequest type Get in $.Ajax function nothing is updated in Red dotted area and I receive internal server Error (500) with following Error Message as Response.

This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request. To allow GET requests, set JsonRequestBehavior to AllowGet.

Its because Json only allow Json Post(as its more secure) Request but deny Get request because confidential information can not be retrieve using get request.

but if you aware its risk and want to allow Get request for Json you can do this as follows :
return Json(person,JsonRequestBehavior.AllowGet);

in this way you can retrieve data from Get Request but its won't be secure anymore as anyone can now access this infromation by simply sending request using url.

client side validation in Asp.net mvc 2 and mvc 3

. Monday, October 3, 2011
0 comments

Hello Guys,

we all are aware about how do we validate user input for model in asp.net mvc using server side validation.
but this feature is also applicable for client side as well. its a pretty thing to hear..
So what will do the client side validation if Server side validation already over there?
well this give you very much facility as you don't need to make the whole page refresh just put some javascript libraries and they will do their job by making partial page refresh and without posting your page back.
So with this technique of validation we can validate user input without making page to post back every time and displaying the validation after the complete page Call.

Lets have a look for this pretty thing.

a)First I create a model which will need to validate for user input in our View.
 public class Person
    {
        public int Id { get; set; }

        [Required(ErrorMessage = "First Name is required")]
        [StringLength(10, ErrorMessage = "First Name max length is 10")]
        public string FirstName { get; set; }
    
        [Required(ErrorMessage = "Last Name is required")]
        [StringLength(10, ErrorMessage = "Last Name max length is 10")]
        public string LastName { get; set; }
    
        [Required(ErrorMessage = "Email is required")]
        [RegularExpression(@"^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$", ErrorMessage = "Email Format is wrong")]
        public string Email { get; set; }
    }

b) create an action method in controller which will used to render View later for this model.
       
        public ActionResult Person()
          {
                return View();
          }

c)Now just need to reference some of the js libraries for client side validation to work,so for this 
  reference following js which are already in script folder into your Master Page.
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>


    Person


    

Person

<%Html.EnableClientValidation(); %> <% using (Html.BeginForm()) { %>

<%=Html.ValidationSummary(true) %>

Id:

<%=Html.TextBoxFor(x=>x.Id) %>
<%=Html.ValidationMessageFor(x=>x.Id)%>

FirstName;

<%=Html.TextBoxFor(x=>x.FirstName) %>
<%=Html.ValidationMessageFor(x=>x.FirstName)%>

LastName:

<%=Html.TextBoxFor(x=>x.LastName) %>
<%=Html.ValidationMessageFor(x=>x.LastName)%>

Email:

<%=Html.TextBoxFor(x=>x.Email) %>
<%=Html.ValidationMessageFor(x=>x.Email)%>


<%} %>


Here thing to notice is that everything is same as Server Side Validation Except one new thing is added which is
<%Html.EnableClientValidation(); %>

Which Causes the Client Side Validation.
The above scenario will look like as follows :
When someone enter the wrong value for field the validation is displayed.

          
           
 



















Now when someone enters the correct value for specified field the validation removes without causing the whole page refresh.



























Client Side Validation in Asp.net MVC 3 :

All the things are same as done with mvc 2 except the following :
a)Add the appropriate references in the master page as follows :



 

Here a New thing to note is Unobrustive Javascript library which is generally writing Html and Javascript separately.

you also need to set Unobrustive js and clientside validation in Web.config file
as follows :


 
        
     
 

both the options need to set true if you want client side validation in your application.

Hope you Enjoyed this article.

In vs Exists in Sql Server

. Monday, September 19, 2011
0 comments

Hi Guys you've used lots of time In and Exists in Sql and they look almost same
but there is difference between both of these.

Suppose you have two tables as follows :

a)tbl_employee(id,emp_name,comp_id)
b)tbl_company(id,comp_name)

Now if you fire following query

select * from tbl_employee where comp_id in (select id from tbl_company)

by the way this query is executes in the following way :

select * from tbl_employee,(select distinct(id) from tbl_company) tbl_company
where tbl_employee.comp_id=tbl_company.id

What's the scenario Here:
a)the indexed result from tbl_employee,which is fast in terms of time.
b)a full scan through tbl_company for and selecting distinct of id from this,
for matching records in where condition.

Where's the IN is suitable:
well, in a scenario where your subquery having less record then IN suitable in that
case,because you main query have indexed and only need to have matched with subquery
while subquery need to have a full scan for each matching id with where condition.

Now if you fire following query

select * from tbl_employee where exists(select null from tbl_company where id=tbl_employee.comp_id)


query is executes in the following way :

for emp in ( select * from tbl_employee )
loop
if ( exists ( select null from tbl_company where id = emp.comp_id )
then
output the record
end if
end loop

What's the scenario Here:
a)indexed on tbl_employee which gives emp rowset.
b)for each emp rowset we need to check weather if exists is true or false if so output the record.


Where's the Exists is suitable:
well, in a scenario where your subquery having Huge records then Exists suitable ,because you only need to check with subquery that if the above record id exist or not and a full scan is made with main query for each rowset.









Display jquery dialog when Ajax calls in Asp.net MVC

. Wednesday, September 14, 2011
0 comments

If you want to display jquery dialog box when you post using Ajax there are various Jquery dialog available you can check them here.
For Now I am going to tell you how can you use jquery confirmation dialog when click on button which post to action in asp.net mvc using Ajax.

First We need to include neccessary libraries.
<pre name="code" class="js">
<script src="../../Scripts/jquery-1.6.2.js" type="text/javascript"></script>
<script src="../../Scripts/jquery.bgiframe-2.1.2.js" type="text/javascript"></script>
<script src="../../Scripts/jquery.ui.core.js" type="text/javascript"></script>
<script src="../../Scripts/jquery.ui.widget.js" type="text/javascript"></script>
<script src="../../Scripts/jquery.ui.mouse.js" type="text/javascript"></script>
<script src="../../Scripts/jquery.ui.button.js" type="text/javascript"></script>
<script src="../../Scripts/jquery.ui.draggable.js" type="text/javascript"></script>
<script src="../../Scripts/jquery.ui.position.js" type="text/javascript"></script>
<script src="../../Scripts/jquery.ui.resizable.js" type="text/javascript"></script>
<script src="../../Scripts/jquery.ui.dialog.js" type="text/javascript"></script>
<script src="../../Scripts/jquery.effects.core.js" type="text/javascript"></script>
</pre>
these are the necessary script need to include for calling jquery confirmation dialog.
in addition to this I added two css files to look dialog pretty.

<link rel="stylesheet" href="../../Content/demos.css">
<link rel="stylesheet" href="../../Content/jquery.ui.all.css">

after this we need to set Ajax in Asp.net MVC.

as we know Ajax is used for partial page refresh,which uses javascript.microsoft provides two beautiful js for ajax just include them in your page as follows:

<script src="../../Scripts/MicrosoftAjax.js" type="text/javascript"></script>
<script src="../../Scripts/MicrosoftMvcAjax.js" type="text/javascript"></script>

and for calling ajax using the following ajax extension methods with a dropdown and submit button to post to action using Ajax.
<% using(Ajax.BeginForm("GetTime",
new AjaxOptions { UpdateTargetId = "myResults" })) { %>
<p>
Show me the time in:
<select name="zone" id="zone">
<option value="utc">UTC</option>
<option value="bst">BST</option>
<option value="mdt">MDT</option>
</select>
<input type="submit" value="Go"  id="create-user"/>
</p>
<% } %>

<div id="myResults" style="border: 2px dotted red; padding: .5em;">
Results will appear here
</div>

in the above code when the submit is clicked an ajax call is made for the associated action which returns the response as string which will update the text inside div myResult.

for this my action is as follows:

 public ActionResult GetTime(string zone)
{
DateTime time = DateTime.UtcNow.AddHours(1);
if (Request.IsAjaxRequest())
{
// Produce a fragment of HTML
string fragment = string.Format(
"
The time in {0} is {1:h:MM:ss tt}
", zone.ToUpper(),time); return Content(fragment); } else { // Produce a complete HTML page return View(time); } }
well we need to write a little bit of script so that we can detect when submit button is clicked then we can call jquery to display confirmation dialog.  <script type="text/javascript">     var zone;     $(function() {         // a workaround for a flaw in the demo system (http://dev.jqueryui.com/ticket/4375), ignore!         $("#dialog:ui-dialog").dialog("destroy");  //display the dialog-form div as confirmation dialog.         $("#dialog-form").dialog({             autoOpen: false,             height: 300,             width: 350,             resizable: false,             modal: true,             closeOnEscape: true,             draggable: false,             show: 'slide',             stack: true,             buttons: { //the confirmation dialog will contain two button one is submit and other is cancel,if someone clicks on submit then will we post the data to specified url(in this case our action) and then receive the response and update the text inside myResult div.                 Submit: function() {                     var url = "/Home/GetTime/" + zone;                     $.post(url, function(data) {                         $('#myResults').html(data);                                            });                     $(this).dialog("close");                 },                 Cancel: function() {                     $(this).dialog("close");                 }             },             close: function() {             }         }); //this will use to detect wether "create-user" button has been clicked if so we need to display the div with Id "dialog-form"         $("#create-user")             .button()             .click(function() {                 zone = $("#zone").val();                 $("#dialog-form").dialog("open");                 return false;             });     });     </script> Here is the final screenshot which will appear when you click on submit button
















so when you click on Go button the confirmation dialog opens and when click on submit the content inside myresult div is updated with response given by the action using Ajax. Hope guys you enjoyed this article.