Draggable div

In this simple article I will demonstrate that how a div can be made draggable in ASP.Net. For this purpose we will use jQuery, jQuery-UI and jQuery Drggable

In order to make a div draggable all you need to do is to add the following files in your project. For this purpose I have added following two files in my project:-

  • jquery-1.8.3.js
  • jquery-ui-1.9.2.custom.min.js
  • jquery.ui.draggable.js

Then I will add these two files in header of my webpage. After adding these two scripts in web page, the head section of webpage will look something like this:-

<head runat="server">
<title></title>
<script src="js/jquery-1.8.3.js"></script>
<script src="js/jquery-ui-1.9.2.custom.min.js">
<script src="js/jquery.ui.draggable.js"></script>
</script>
</head>
Now we need to add a DIV control on our web page. I have placed a div with ID “MyMovableDiv”.  Code is given below:-
<div id="MyMovableDiv">
     <span>Following is the Image of Google</span><br />
<img src="http://www.google.com.pk/images/srpr/logo3w.png" />
</div>
Now we need to make this DIV “i.e. MyMovableDiv” draggable by using the following code in head section:-
 1: <script>
 2:            $(document).ready(function ()
 3:            {
 4:                $("#MyMovableDiv").draggable({ scroll: true });
 5:            });
 6:        </script>
 
After performing all these steps, our div is not draggable. Complete code of web page is given below:-
 
 1: <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="DraggableDiv.aspx.cs" Inherits="jQueryDemo.DraggableDiv" %>
 2:  
 3: <!DOCTYPE html>
 4:  
 5: <html xmlns="http://www.w3.org/1999/xhtml">
 6: <head runat="server">
 7:     <title></title>
 8:        <script src="js/jquery-1.8.3.js"></script>
 1:  
 2:        <script src="js/jquery-ui-1.9.2.custom.min.js">
 1: </script>
 2:         <script src="js/jquery.ui.draggable.js">
 1: </script>
 2:         <script>
 3:             $(document).ready(function ()
 4:             {
 5:                 $("#MyMovableDiv").draggable({ scroll: true });
 6:             });
 7:         
</script>
 9: </head>
 10: <body>
 11:     <form id="form1" runat="server">
 12:         <div id="MyMovableDiv">
 13:             <span>Following is the Image of Google</span><br />
 14:             <img src="http://www.google.com.pk/images/srpr/logo3w.png" />
 15:         </div>
 16:     </form>
 17: </body>
 18: </html>
 
Now if you run the code, you will be able to drag this DIV.
 

Stay Blessed and remember me in your prayers.

Ragards,

Shahid Riaz Bhatti

Draggable Div

In this simple article I will demonstrate that how a div can be made draggable in ASP.Net. For this purpose we will use jQuery, jQuery-UI and jQuery Drggable

In order to make a div draggable all you need to do is to add the following files in your project. For this purpose I have added following two files in my project:-

  • jquery-1.8.3.js
  • jquery-ui-1.9.2.custom.min.js
  • jquery.ui.draggable.js

Then I will add these two files in header of my webpage. After adding these two scripts in web page, the head section of webpage will look something like this:-

<head runat="server">
<title></title>
<script src="js/jquery-1.8.3.js"></script>
<script src="js/jquery-ui-1.9.2.custom.min.js">
<script src="js/jquery.ui.draggable.js"></script>
</script>
</head>
Now we need to add a DIV control on our web page. I have placed a div with ID “MyMovableDiv”.  Code is given below:-
<div id="MyMovableDiv">
     <span>Following is the Image of Google</span><br />
<img src="http://www.google.com.pk/images/srpr/logo3w.png" />
</div>
Now we need to make this DIV “i.e. MyMovableDiv” draggable by using the following code in head section:-
 1: <script>
 2:            $(document).ready(function ()
 3:            {
 4:                $("#MyMovableDiv").draggable({ scroll: true });
 5:            });
 6:        </script>
 
After performing all these steps, our div is not draggable. Complete code of web page is given below:-
 
 1: <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="DraggableDiv.aspx.cs" Inherits="jQueryDemo.DraggableDiv" %>
 2:  
 3: <!DOCTYPE html>
 4:  
 5: <html xmlns="http://www.w3.org/1999/xhtml">
 6: <head runat="server">
 7:     <title></title>
 8:        <script src="js/jquery-1.8.3.js"></script>
 1:  
 2:        <script src="js/jquery-ui-1.9.2.custom.min.js">
 1: </script>
 2:         <script src="js/jquery.ui.draggable.js">
 1: </script>
 2:         <script>
 3:             $(document).ready(function ()
 4:             {
 5:                 $("#MyMovableDiv").draggable({ scroll: true });
 6:             });
 7:         
</script>
 9: </head>
 10: <body>
 11:     <form id="form1" runat="server">
 12:         <div id="MyMovableDiv">
 13:             <span>Following is the Image of Google</span><br />
 14:             <img src="http://www.google.com.pk/images/srpr/logo3w.png" />
 15:         </div>
 16:     </form>
 17: </body>
 18: </html>
 
Now if you run the code, you will be able to drag this DIV.
 

Stay Blessed and remember me in your prayers.

Ragards,

Shahid Riaz Bhatti

jQuery UI Selectable

jQuery UI selectable enables a DOM element/s to be selectable. It can also be used to select multiple items of a given element (such as multiple selection or single selection in order or un order list). I will be using VS 2012, jQuery 1.8.3 and jQuery-ui-1.9.2.

I am writing this, because last day one of my student asked me that he is facing some problem in incorporating jQuery UI in his project.

So please follow the given steps which are mentioned in this tutorials.

Create a New ASP.Net Empty Web Application as shown in the following diagram:-

1

Add a New folder in your project called “js”. Add following two files in this folder.

  • jquery-1.8.3.js
  • jquery-ui-1.9.2.custom.min

Above two files can be downloaded from internet by googling jQuery UI.

After adding these two files, our solution explorer will look like as follow:-

2

Now add a new web form in your project. I have added a web form called jQuerySelectable.aspx. Now add following code in header section of your new web form.

<script src="js/jquery-1.8.3.js"></script>
  
 <script src="js/jquery-ui-1.9.2.custom.min.js">
</script>

IN the above code , we have included the required jQuery and jQuery UI files in our project. As we are implementing jQuery selectable, so we need to write the following code in our header section which will be used to style our element when some item is selected or not selected. So please copy the following code just beneath the lines where you have included the required jQuery files.

<style>
    #selectabledemo .ui-selecting
    {
        background: blue;
    }
 
    #selectabledemo .ui-selected
    {
        background: #F39814;
        color: black;
    }
</style>

In above CSS we have set some basic attributes, which is stating background color and fore color when some item is about to select or selected in a container having ID of selectabledemo.

Now we need to bind the selectable function of jQueryUI to this container which is selectabledemo. We will write this code in the document.ready. Its code is given below:-

<script>
 
    $(document).ready(function()
    {
        $("#selectabledemo").selectable();
    });
</script>

After this, our head section of page will look like this:-

<head runat="server">
    <title></title>
    <script src="js/jquery-1.8.3.js"></script>
  
     <script src="js/jquery-ui-1.9.2.custom.min.js">
</script>
    <style>
        #selectabledemo .ui-selecting
        {
            background: blue;
        }
 
        #selectabledemo .ui-selected
        {
            background: #F39814;
            color: black;
        }
    </style>
</head>

Now we have done the important part. Now we will add an unordered lists in our HTML page. Its code is given below:-

<ul id="selectabledemo">
          <li class="ui-widget-content">This is Item 1</li>
          <li class="ui-widget-content">This is Item 2</li>
          <li class="ui-widget-content">This is Item 3</li>
          <li class="ui-widget-content">This is Item 4</li>
          <li class="ui-widget-content">This is Item 5</li>
          <li class="ui-widget-content">This is Item 6</li>
          <li class="ui-widget-content">This is Item 7</li>
      </ul>

Now all things are set. Now its time to run our page. View this page and you will see an un ordered list. You can select a single or multiple items from this list. Out put is given below:-

Selectable

In this article, we have used the jQuery selectable in our web form. If you want to use other jQuery UI control, then the steps which are mentioned in this tutorial in green color will remain unchanged.

Complete source code is attached.

Download Code

 

Stay blessed and remember me in your prayers.

Regards,

Shahid Riaz Bhatti

How to Pass data from Controller to View & Vice Versa

Hi all,

In this tutorial I will go through a some simple steps which will guide you that how you can pass data from Controller to a View and how to pass data from View to a controller so that this data can be pushed back into the database.

In this tutorial I will not use Entity Framework and scaffolding (which does all the magic and all you need to do is to change the code as per your requirements).

Now lets start coding without wasting any time. In this simple step by step tutorial, I will Create a controller and two Views and a simple class which will act as our model. I hope you will be familiar with the terms of controller, Views and Models.

In ASP.Net MVC controllers are your special classes which deals with the incoming requests from the users and fulfill the request by sending back a View or doing some magic such as inserting/updating or deleting a record.

Views are the HTML which gets renders on the browsers. How to use razor in these views are out of scope of this tutorials. Razor is not a new language. It’s a new way to write HTML in ASP.Net MVC but a keyword “@” is used to refer that the immediate code following the @ sign is a razor code which can be used to access data from the server.

Model in MVC is used to write the entities i.e. our Business objects. Example of such Business objects includes Customer , Products etc.

I have written a very simple class in Models. This class is given below:-

public class TestCls
   {
       public int ID
       {
           get;
           set;
       }
       public string Name
       {
           get;
           set;
       }
       public string Description
       {
           get;
           set;
       }
   }

Above class is very simple and contains three simple properties. This class does not relate to any real world object because its just for demonstration.

Next, I have create a New Controller called TestContoller.  As I have mentioned that Controller are special classes which are used to handle the incoming request. These are special classes because they are inherited from a class called “Controller”.

I have created three ActionResult. ActionResult are method inside the controller and they are also called Action Method. Action Methods return models to views, file streams, redirect to other controllers, or whatever is necessary for the task at hand. Code of this controller class is given below:-

public class TestController : Controller
    {
        //
        // GET: /Test/
 
        public ActionResult Index()
        {
            List<TestCls> AllData = new List<TestCls>();
            for (int i = 0; i < 10; i++) 
            {
                TestCls cls = new TestCls();
                cls.ID = i;
                cls.Name = "Name : " + i.ToString();
                cls.Description = "Description" + i.ToString();
                AllData.Add(cls);
            }
            return View(AllData);
        }
        public ActionResult Create()
        {
            return View();
        }
        [HttpPost]
        public ActionResult Create(TestCls obj)
        {
            // Insert Data into Database
            int ID = obj.ID;
            string Name = obj.Name;
            string Description = obj.Description;
 
            return RedirectToAction("Index");
        }
 
    }

Above controller class contains following three ActionResults

  • Index
  • Create (Two versions i.e. Overloaded)

In Index Action result, I have filled a List of TestCls class with some dummy data. This data needs to be passed to the View. I am following the default Convention and Configuration. So I have also created a Folder with the name of “Test” and Created a View called “Index”. Whenever ActionResult is invoked it will redirect to the View called Index and the this dummy data will also be passed to this Index View, because we have passed the data in the View. The line which is doing the magic is given below:-

return View(AllData);

Complete Code of Index View is also shown below:-

@model IEnumerable<MVC1.Models.TestCls>
@{
    Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <div>
        <table>
            <tr>
                <th>ID</th>
                <th>Name</th>
                <th>Description</th>
            </tr>
            @foreach (var i in Model)
            {
                <tr>
                    <td>@i.ID</td>
                    <td>@i.Name</td>
                    <td>@i.Description</td>
                </tr> 
            }    
        </table>
        <br />
        @Html.ActionLink("Create", "Create")
    </div>
</body>
</html>

In Index View, we can see @model directive on top. This is actually referencing a strongly typed model. Then using razor we have iterated through all the items which were passed to this view from the controller and showed that data in an HTML table. At the end we have created a New Action Link called “Create”. Clicking on this Link button will redirect the user to another View which will be used to Create a New Item. This Action Link will invoke Create Action result (without the HttpPost attribute version). This Create version redirect the user to Create Page. Screenshot of this Index Page is given below:-

MVC1_thumb

You can see all the data in the browser which was sent to this View from the Controller. Clicking on the Create Link button will redirect the user to the Create Page. Code of Create View is given below:-

@model MVC1.Models.TestCls
@{
    Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Create</title>
</head>
<body>
    <div>
        @using (@Html.BeginForm()) 
        {
            <table>
                <tr>
                    <td>
                        @Html.LabelFor(model => model.ID)
                    </td>
                    <td>
                        @Html.EditorFor(model => model.ID)
                    </td>
                </tr>
                 <tr>
                    <td>
                        @Html.LabelFor(model => model.Name)
                    </td>
                    <td>
                        @Html.EditorFor(model => model.Name)
                    </td>
                </tr>
                 <tr>
                    <td>
                        @Html.LabelFor(model => model.Description)
                    </td>
                    <td>
                        @Html.EditorFor(model => model.Description)
                    </td>
                </tr>
                <tr>
                    <td>
                        <input type="submit" value="Create" />
                    </td>
                </tr>
            </table>
        }
    </div>
</body>
</html>

In the Create View , we have again used the @model directive to reference this view to TestCls. In this View, we have used razor to create a simple HTML form which can be used to fill the object of TestCls. In this View, we have created a submit button. You might know that Submit button is used to post the data to some processing page. In this case this submit button will post the data to Create Action results (second version i.e. with HttpPost attribute). This posted data can be retrieved in this ActionResult. Create Page with some dummy data which will be filled by the user and data which was posted by the user by hitting the Create Link button on Create Page to the Create Action results is shown below respectively:-

MVC2_thumb

Clicking on Create button will cause the Create Action result (HttpPost attribute version) to be invoked. In this Action result we can see that we can access the data which was filled by the user on Create Page. Screenshot is given below:-

MVC3_thumb1

So in this tutorial we explored that how data can be passed from Controller to View and vise versa. So by using this method you can develop application in MVC without using Entity Framework. For example, I can use Index Action result to fill TestCls from the database using ADO.Net or Linq To Sql. And similarly I can modify the Create Action result to Save the records into the database.

You can also explore ViewBag which can be used to send data from Controller to View and vice versa Smile

Stay Blessed and Happy Coding.

Regards,

Shahid Riaz Bhatti

How to Use FormView to Insert/Update and Delete Records

In ASP.Net there are several controls which can be used to Insert/Update/Delete records from the database. In this tutorial I will use FormView control for the Listing of database records. I will also use FormView control to Insert/Update and delete the records.

Validation control can also be added to FormView control but in this tutorial I will skip this validation part. Because Validation control works on FormView control in the similar way as they work on a Page. FormView control displays one record per page. So If you have lot of data then you can use pagination feature of FormView control also.

FormView control is a template driven control. Some of the template are given below:-

  • ItemTemplate (Ideally used to display records in Read only mode)
  • EditItemTemplate( Ideally used to display records with editable control so that records can be edited)
  • InsertItemTemplate ( Used to Insert New records)

If you configure your formview control using the wizard of .Net , then you have very little coding to do. Because once you configure the formview control using the wizrad, then insert,update, delete and cancel events are handled by the datasource itself. You can use different data source controls such as SqlDataSource, Object Data source etc. But in this tutorial I will not use this approach and will write code for insertion/updation and for listing of records. So in this case I will be handling different events of FormView controls which are ItemUpdating, ItemInserting, ItemDeleting etc. To save the time, I will use LINQ 2 SQL, so that I have to spent little time on writing the code for the database connectivity etc. More...

State Server Mode

In this article I will explain how to store the Session in State server mode. Session are server side variables and its contains the data in key value pair. So if a user store some data in session, then that stored data will be available to only that particular user who stored the data in session. This stored data will be available to user until the session is expired. Data which is stored in session can be of any type. When you store data in Session, the .Net framework box that data. So whenever you need to pull the data from the session, you need to do the un-boxing. If you do not perform the un-boxing then data will be in the form of object.

By default, the data which you store in the Session is stored in the memory of the webserver. This is the default behavior of .Net, but this default behavior can be changed as per the requirement. Different session state mode are given below:-

  • InProc (this is the default)
  • StateServer
  • SQL Server
  • Custom
  • Off

More...

LINQ

LINQ stands for language integrated queries. It’s a technique developed by Microsoft which enables you to write queries directly into the language such as C#, VB.Net etc. LINQ targets to a wide range of targets which includes but not limited to LINQ to entities, LINQ to XML, LINQ to SQL etc..

LINQ can also use lambda expression.

I will present different implementation of LINQ in my coming articles such as LINQ to objects, LINQ to entities, LINQ to XML, LINQ to SQL, but in this article I will jump start with a basic example of LINQ which will show the power of LINQ.

This article will be very easy to understand if you have experience of programming or if you are familiar with SQL, because its syntax is very similar to SQL. So lets start with a very basic example. Please look the following code:-

 
int[] Numbers = new int[]{1,2,3,4,5,6,7,8,9};
IEnumerable<int> FilteredNumber = from n in Numbers
                                   where n > 3
                                   select n;
IEnumerator en = FilteredNumber.GetEnumerator();
while (en.MoveNext())
{
    Console.WriteLine(en.Current);
}

In the above example, I have declared an array of type int. This array has 9 elements. Then we have used the LINQ to fetch our desired record from the int array. See how simple it is to use LINQ.

Look how simple and user friendly is the syntax of LINQ. We have used to keyword “from” and then we wrote any arbitrary variable number (which is ‘n’ in the example) and then we used the keyword “in” and gave the source name (which is Numbers i.e. an int array). Then we have restricted our resultant by using the keyword of “where” and we set the criteria using the keyword “where” which in this case is all numbers in the array which are greater than 3, and the we selected our desired output using the keyword “select”.

Please note that this can be implemented on any object which is implementing the IEnumerable interface. So this can be applied to all arrays, List etc of any type.

Lets look another example in which we will be using LINQ on a List.

List<Person> pCollection = new List<Person>();
Person p = new Person();
p.FirstName = "Shahid Riaz Bhatti";
pCollection.Add(p);
p = new Person();
p.FirstName = "Asif Kamran";
pCollection.Add(p);
p = new Person();
p.FirstName = "Ilyas";
pCollection.Add(p);
p = new Person();
p.FirstName = "Ryan";
pCollection.Add(p);
p = new Person();
p.FirstName = "Nawaz Sharif";
pCollection.Add(p);
p = new Person();
p.FirstName = "Abdul Qadeer";
pCollection.Add(p);
p = new Person();
p.FirstName = "Imran Khan";
pCollection.Add(p);
var FindPerson = from _p in pCollection
                 where _p.FirstName.Contains("s")
                 select new { _p };
foreach (var i in FindPerson)
{
    Console.WriteLine(i._p.FirstName);
}

 

In the above example, we have added instance of a class Person in List with different FirstName. Then we have used LINQ to find all those person whose name contains characters “s”. In this example instead of returning IEnumerable<Person> we stored the result into anonymous type. For detail of anonymous type you can go through my article of Anonymous Type.

LINQ using Lambda Expression:-

As I mentioned in start of this article that LINQ also uses Lambda expression, but in the above example we did not used Lambda expression in LINQ. So lets try it now.

Lets modify our last example with the following:-

var testData = pCollection
                .Where(pTemp => pTemp.FirstName.Contains("s"))
                .Select(pTemp => new { pTemp.FirstName });
 
            foreach (var tem in testData)
            {
                Console.WriteLine(tem.FirstName);
            }

In this example, we have just mentioned the name of the data source or target from on which we are going to write LINQ. pCollection will return all the Persons, but we have used the where clause to restrict the result and used the lambda expression.

Best Regards,

Shahid Riaz Bhatti

Lambda Expression

Lambda expressions are anonymous function which can be used to create delegate. It can also be used to create anonymous method that can return value of some function call or that can be used to pass as an argument.

Lambda expression are useful in writing the LINQ queries. Lambda expression is represented as sign “=>”.

Follow the following steps in order to create a lambda expression ,

  • specify input parameters (if any) on the left side of the lambda operator =>
  • put the expression or statement block on the other side.

Please look closely the following example:-

(a, b) => { string res1 = a + b; return res1; };

In the above example we can see that there are two input parameters which are ‘a’ and ‘b’

Then on the right side of the Lambda operator i.e. (=>), is the expression or statement block. In the example we are adding the two input parameters and returning the result. In this way, we have basically done , which I have mentioned in the start i.e. “Lambda expressions are anonymous function ”.

This expression can be assigned to a delegate type. But before doing that, I would like to recommend you to go through the article Delegate in C#.

Delegate points to a function and it can be used to invoke any function which have the same signature. But in the Lambda expression we did not created any function, instead we have created an anonymous function. Then any delegate with the compatible signature can be used to invoke this anonymous function.

Here is the complete simple example:-

class Program
    {
        public delegate int Test(int a);
        public delegate string TestString(string a, string b);
        public delegate string TestString1(string a, string b, string c);
        static void Main(string[] args)
        {
            Test t = x => x * x;
            int res = t.Invoke(5);
            Console.WriteLine(res);
 
 
            TestString ts = (a, b) => { string res1 = a + b; return res1; };
            Console.WriteLine(ts.Invoke("Shahid", "Riaz"));
 
            TestString1 ts1 = new TestString1(delegate(string a, string b, string c) { return a+b+c; });
            Console.WriteLine(ts1.Invoke("Shahid", "Riaz", "Bhatti"));
}
}

In the above example, we have created three simple delegate. Then we have used Lambda expression and assigned the resultant of these lambda expression to the delegate type. Then we have printed the out put by invoking the delegates.

That’s all

Regards,

Shahid Riaz Bhatti

jQuery Visual Cheat Sheet

Please download the attached pdf file.

Its a Visual Cheat Sheet. Its very handy if some one wants to learn jQuery in a quick way.

Please try to implement the things, selectors etc which are mentioned i this cheat sheet. You can google to get the help for the functions and selectors which are mentioned in this cheet sheet.

Thanks

jQuery-17-Visual-Cheat-Sheet.pdf (558.83 kb)

Anonymous Type

What is Anonymous Type?


There are times in programming when you would like to define a class that holds data temporarily and which is not required to be reused anywhere else in the application. This is where anonymous type helps which provides you massive shortcut for creating types on the fly by using extended syntax of the new operator. When you define anonymous type you also use object initialization syntax along with the new var keyword.
For the purpose of this tutorial, I have created a simple C# Console Application in Visual Studio 2008. Inside the main Program I am creating the following anonymous type to illustrate its syntax.

   1:  var studentInfo = new { ID = 1, Name = "Shahid Riaz", Fee = 3000.00 };

   2:  Or 

   3:  var studentInfo = new { 

   4:     ID = 1, 

   5:     Name = "Shahid Riaz", 

   6:     Fee = 3000.00 

   7:  };


The above anonymous type is representing a Student object that has few properties such as ID, Name and Fee. The first thing you should note that anonymous types are types with no name and as a programmer you don’t have any control on the name of anonymous type. That’s why you need to implicitly typed it by using var keyword. At compile time, the C# compiler will generate a uniquely named class automatically and because you don’t have information about the name of the type so the use of var keyword is mandatory.
The second thing to notice in the above syntax is the use of new keyword without the type name and the use of object initializer syntax to define and set the type properties and their values. When you create anonymous type the compiler automatically build a type inherited from System.Object and then called its default constructor behind the scene. Once you have defined the properties of your anonymous type you can access them by using normal C# syntax as shown below:

   1:  Console.WriteLine("Student ID: " + studentInfo.ID); 
   2:  Console.WriteLine("Student Name: " + studentInfo.Name); 
   3:  Console.WriteLine("Student Fee: " + studentInfo.Fee); 

Keep in mind here is that all the properties you define inside your Anonymous Type are read only so following line will never compiler.
studentInfo.ID = 4;
As I mentioned that all Anonymous Types inherit from System.Object by default so they have access to the methods such as ToString(), GetType() etc. In the case of anonymous type the ToString() method returns a string that has all the properties and their values inside. For example if you will call the ToString() method of our studentInfo object you will get the output shown below. Notice how curly braces are attached automatically with name/value pairs.
{ ID = 1, Name = Shahid Riaz, Fee = 3000 }
It is also possible to compose one anonymous type inside another anonymous type. Check the following example:
var emp = new {
   ID = 1,
   Name = "Ali",
Address = new {
      Street = "Baker Street",
      City = "London",
      Country = "UK"
   }

};
In the example above I have created an anonymous type holding employee ID and Name and another anonymous type to store the employee Address information. You can access both anonymous types as you access normal classes and their composed objects.
Console.WriteLine(emp.ID);
Console.WriteLine(emp.Name);
Console.WriteLine(emp.Address.Street);
Console.WriteLine(emp.Address.City);
Console.WriteLine(emp.Address.Country);
Although anonymous types provides you very quick and short syntax to create types in your applications but you would never stop defining strongly typed classes because of the following limitations.

  1. You don’t have control on the name of the anonymous type
  2. Anonymous Type always inherit from System.Object
  3. The properties of an anonymous type are read only
  4. You cannot create events, operators or methods inside anonymous type
  5. You cannot override any method of System.Object in anonymous type
  6. Anonymous types are sealed types so you cannot inherit from anonymous type
  7. Anonymous types are always created using default constructor.


With all the above limitations in mind, you may be thinking why you would ever need to use anonymous types. The answer is that you need to use them when you will start using LINQ queries because you will find the anonymous type syntax very quick and useful in many cases.