DotNetSlackers: ASP.NET News for lazy Developers

Showing posts with label dot net. Show all posts
Showing posts with label dot net. Show all posts

Friday, October 16, 2015

Form validation in Asp.Net MVC with AngularJs


In this tutorial, we will form validation in angularJs.

In most of Web Application, We require user to register on our application.

In this way, We need do some action like Form validation , so that user can’t submit a Invalid form.

There are too many way to validate a form in Client side.

Here We are using AngularJs for the form validation.

AngularJs Provide many form Validation Directives, We will use then to validate our form.

Let’s create a mvc application.

Add a Employee class.

01
02
03
04
05
06
07
08
09
10
11
namespace FormValidationInAj.Models
{
    public class Employee
    {
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Email { get; set; }
        public int Age { get; set; }
    }
}
Add a Empty Home Controller .
?
01
02
03
04
05
06
07
08
09
10
11
12
using System.Web.Mvc;
 
namespace FormValidationInAj.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
    }
}
 
 
Add Index view corresponding to Index action.

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
@model FormValidationInAj.Models.Employee
<div ng-controller="myCntrl" class="divForm">
    <form name="registerForm" novalidate ng-submit="Save(registerForm.$valid)">
        @Html.AntiForgeryToken()
 
        <fieldset>
            <legend>Employee</legend>
 
            <div class="editor-label">
                @Html.LabelFor(model => model.FirstName)
            </div>
            <div class="editor-field form-group">
                <input type="text" ng-model="firstName" name="firstName" ng-required="true" />
                <p ng-show="registerForm.firstName.$error.required && !registerForm.firstName.$pristine" class=" error">First Name Required</p>
 
            </div>
 
            <div class="editor-label">
                @Html.LabelFor(model => model.LastName)
            </div>
            <div class="editor-field form-group">
                <input type="text" ng-model="lastName" name="lastName" />
 
            </div>
 
            <div class="editor-label">
                @Html.LabelFor(model => model.Email)
            </div>
            <div class="editor-field form-group">
                <input type="email" ng-model="Email" name="Email" ng-required="true" />
                <p ng-show="registerForm.Email.$error.required && !registerForm.Email.$pristine" class="error">Email Required</p>
                <p ng-show="registerForm.Email.$error.email && !registerForm.Email.$pristine" class="error">Invalid Email</p>
            </div>
 
            <div class="editor-label">
                @Html.LabelFor(model => model.Age)
            </div>
            <div class="editor-field form-group">
                <input type="number" ng-model="Age" name="Age" ng-required="true" />
                <p ng-show="registerForm.Age.$error.required && !registerForm.Age.$pristine" class="error">Age Required</p>
                <p ng-show="registerForm.Age.$error.number && !registerForm.Age.$pristine" class="error">Invalid Age </p>
            </div>
 
            <p>
                <input type="submit" value="Create" class="btn btn-primary" />
            </p>
        </fieldset>
    </form>
</div>
Above I have used AngularJs directives for form validation .
  • Required :using ng-required="true", Validated a input field that is required.
  • Email : using Type="email" property of input field, validate Email address.
  • Number : using Type="number" property of input field, validate number field.
There are many form validation directives in AngularJs.

To show the error message, I have used Error Name of AngularJs.

To show error message only when used has been interacted with form, unless Error message will be hidden, I have used $pristine .

$pristine : It will be true If user has not interacted with form yet.

Add two new Js file .

module.js

1
var app = angular.module("myApp", []);
 
Controller.js

01
02
03
04
05
06
07
08
09
10
app.controller("myCntrl", function ($scope, $http) {
    $scope.Save = function (Valid) {
        if (!Valid) {
            alert("Invalid form");
            return;
        } else {
            alert("It's Great. Form Submitted");
        }
    }
});
 
 
Modilfy your _Layout.cshtml file.

I have included required Js file for angularJs.

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<!DOCTYPE html>
<html ng-app="myApp">
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width" />
    <title>@ViewBag.Title</title>
    @Styles.Render("~/Content/css")
 
    <link href="~/Content/bootstrap.min.css" rel="stylesheet" />
    <script src="~/Scripts/angular.min.js"></script>
    <script src="~/Scripts/Angular/Module.js"></script>
    <script src="~/Scripts/Angular/Controller.js"></script>
    <style>
        .divForm{
           margin: 15px 50px;
           padding: 0;
           width: 30%;
         }
    </style>
</head>
<body>
    @RenderBody()
 
    @Scripts.Render("~/bundles/jquery")
    @RenderSection("scripts", required: false)
</body>
</html>
 
 
We have Done the form validation in AngularJs .

Demo
Form validation in Asp.Net MVC with AngularJs.
DOWNLOAD

Learn MongoDb with Asp.Net MVC


In this tutorial, I’ll show you how to use MongoDB with Asp.Net MVC.

Before start, Let’s know about MongoDB.

What is MongoDB ?

MongoDB is document oriented database, Where Records are stored as documents.
Is it also called as NOSQL database.
MongoDb stores the data in the form of document which is similar to JSON , Known as BSON.

BSON : BSON is a binary representation of JSON with additional type information.
Terms related to MongoDB.
  • Collection : A collection is a group of related documents that have a set of shared common indexes. Collections are analogous to a table in relational databases.
  • Documents : Document is set of Key-value pair. here is Document Sample
    ?
    1
    2
    3
    4
    {
    Name  : "Amit",
    Email : "amitverma0511@gmail.com"
    }
Advantage of using MongoDB.
  • A document-based data model. The basic unit of storage is analogous to JSON.
    This is a rich data structure capable of holding arrays and other documents.
  • No schema migrations. Since MongoDB is schema-free, your code defines your schema.
  • Replication is very easy.
  • You can perform rich queries.
  • More on MongoDB
Let’s get started
First of all Download the MongoDB.
How to Install MongoDB.
After installing MongoDb in your system .

Create Database in MongoDb.

Here I’m creating Database name as “School“.
Execute the following command in Mongo Shell.

1
use School
Learn MongoDb with Asp.Net MVC

Insert records in School Database .

Create an array which contains list of name of student.
using for loop we will insert records.

1
2
3
4
var Name=["Amit","Rohit","Ajay","Sumit","Rahul"];
 for(i=0 ;i<5;i++){
    db.Students.insert({Name : Name[i]});
}
Learn MongoDb with Asp.Net MVC
Now you see the inserted records by using following query.

1
db.Students.find()
Learn MongoDb with Asp.Net MVC
So far we have created Database and Inserted records in it.
Now let’s learn how to connect MongoDb with C#.

Download C# Driver for MongoDB

Extract the Zip file (if you have downloaded the .Zip file)

In Extracted folder, you will get two .dll file
  • MongoDB.Bson.dll
  • MongoDB.Driver.dll
Now create an Asp.Net MVC project.
Add the the reference of those two dll file.
Right click on Reference => Add Reference => Browse
Learn MongoDb with Asp.Net MVC
Add a Model Class Students.
?
01
02
03
04
05
06
07
08
09
10
11
using MongoDB.Bson;
 
namespace MvcWithMongoDb.Models
{
    public class Students
    {
 
        public ObjectId Id { get; set; }
        public string Name { get; set; }
    }
}
Add Home Controller .
Create constructor of HomeController.

01
02
03
04
05
06
07
08
09
10
11
12
13
private MongoDatabase mongoDatabase;
public HomeController()
{
    // create connectionstring
    var connect = "mongodb://localhost";
    var Client = new MongoClient(connect);
 
    // get Reference of server
    var Server = Client.GetServer();
 
    // get Reference of Database
    mongoDatabase = Server.GetDatabase("School");
}
In Constructor, I have created Mongo Client which need the connection string.
Mongo Client will interact with the server, so using MongoClient instance , call the GetServer method.
Now to Access the database of MongoDb, I have used this instance of Server.
Now Create Method which will return Json Type result.
?
01
02
03
04
05
06
07
08
09
10
11
public JsonResult GetAll()
{
    var collections = mongoDatabase.GetCollection<Students>("Students");
    IList<Students> students = new List<Students>();
    var getStudents = collections.FindAs(typeof(Students), Query.NE("Name", "null"));
    foreach (Students student in getStudents)
    {
          students.Add(student);
    }
    return Json(students, JsonRequestBehavior.AllowGet);
}
Complete code for controller.

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
using System.Collections.Generic;
using System.Web.Mvc;
using MongoDB.Driver;
using MongoDB.Driver.Builders;
using MvcWithMongoDb.Models;
namespace MvcWithMongoDb.Controllers
{
    public class HomeController : Controller
    {
        private MongoDatabase mongoDatabase;
        public HomeController()
        {
            // create connectionstring
            var connect = "mongodb://localhost";
            var Client = new MongoClient(connect);
 
            // get Reference of server
            var Server = Client.GetServer();
 
            // get Reference of Database
            mongoDatabase = Server.GetDatabase("School");
        }
 
        public ActionResult Index()
        {
            return View();
        }
        public JsonResult GetAll()
        {
            var collections = mongoDatabase.GetCollection<Students>("Students");
            IList<Students> students = new List<Students>();
            var getStudents = collections.FindAs(typeof(Students), Query.NE("Name", "null"));
            foreach (Students student in getStudents)
            {
                  students.Add(student);
            }
            return Json(students, JsonRequestBehavior.AllowGet);
        }
    }
}
Add the Index view .
write the following code.

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
<link href="~/Content/bootstrap.css" rel="stylesheet" />
<script src="~/Script/jquery-2.1.1.min.js"></script>
<script src="~/Script/School.js"></script>
<div id="divList">
    <p>
        <img src="~/Content/images/images.jpg" />
    </p>
    <table class="table table-bordered" id="tblList">
        <tr>
            <th colspan="2" style="text-align:center;">Student List</th>
        </tr>
        <tr>
            <th> SNo.</th>
            <th>Name</th>
        </tr>
    </table>
</div>
You can see, I have added Js file named “School.js”.
write the following code in School.js.
?
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
$(document).ready(function () {
    GetAll();
});
 
function GetAll()
{
    $.ajax({
        type: 'GET',
        contentType: 'application/json; charset=utf-8',
        url: 'Home/GetAll',
        success: function (data) {
            var genHtml = "";
            $.each(data, function (index, value) {
                genHtml += "<tr><td>"+(index+1)+"</td><td>" + value.Name +"</td></tr>";
            });
            $('#tblList').append(genHtml);
        },
        error: function (data) {
            alert('Error in getting result');
        }
    });
}
See the Result.
Demo
Learn MongoDb with Asp.Net MVC
DOWNLOAD

Thursday, October 15, 2015

AJAXHoverMenuExtender with ASP.NET



Today i am going to discuss, how to use AJAXHoverMenuExtender with ASP.NET. There are javascript available for onmouseover function which shows some text or something like menus. Today I am going to implement the same on serverside by using ajax functionality. There are number of tools available with ajax for our requirement I am going to use AjaxHoverMenuExtender - it show the menus or some text onmouseover of control or image or text.

First Create AjaxEnabled Website - so it automatically include AJAX Controls on your toolbox.

Place the ScriptManager on your page.
 <ajax:ScriptManager ID="ScriptManager1" runat="server">
        </ajax:ScriptManager>

Then Drag the Hyperlink and AjaxHoverMenuExtender on the Design page.
<asp:HyperLink ID="Hyperlink1" runat="server" Text="Session Mode"               NavigateUrl="~/Description.aspx"></asp:HyperLink>

 <ajaxToolkit:HoverMenuExtender ID="hme2" runat="Server" TargetControlID="Hyperlink1"
            PopupControlID="Panel1" PopupPosition="Center" OffsetX="-25" OffsetY="15"
/>

Main Properties of AjaxHoverMenuExtender

TargetControlID - Specify the server ControlID where you going to show the popup text.

PopupControlId -  Specify the ControlD which shows the popup while onmouseover of the

text of link.

PopupPosition - Center , Left , Right .

OffSetX , OffSetY - specify the X and Y position on that page according to the parent
Control.

Now i have to define the PopUp so this will be shown while mouseover.So here I used the panel which contains Datalist inside Where I bind the data from DB.

<asp:Panel ID="Panel1" runat="server" Width="600px">
            <asp:DataList ID="Dtl_Unit" CellPadding="1" CellSpacing="1"
ShowHeader="False" BorderWidth="0px"
                runat="server" DataKeyField="ServicesSubId" DataSourceID="Sqd_Unit" 

RepeatColumns="5">
                <ItemTemplate>
                    <table border="0">
                        <tr>
                            <td>
                                     <asp:HyperLink ID="Hyperlink2"  runat="server" 

NavigateUrl='<%#"Description.aspx?SId="+Eval("sessionmodeID") %>'
Text='<%#Eval("sessionmodeName")%>'></asp:HyperLink>
                            </td>

                        </tr>
                    </table>
                </ItemTemplate>
                <ItemStyle BorderWidth="0px"  />
            </asp:DataList>
            <asp:SqlDataSource ID="Sqd_Unit" runat="server" ConnectionString="<%$ 

ConnectionStrings:ConnectionString %>"
                SelectCommand="SELECT [sessionmodeID], [sessionmodeName] FROM 

[SessionTable]">
            </asp:SqlDataSource>
        </asp:Panel>

Output:

Javascript PAN Number validation in Asp.net Textbox onkeypress event

Explanation

Permanent Account Number is simply called as (PAN) in India who are all paying the TAX using this identification card.PAN is ten digit alphanumeric characters.All characters should be in upper case.The first five characters should be Alphabets and followed by four digit numbers and the last one should be Alphabet.The first character is the type of the PAN and the fifth character is the name of the person.

  For example an individual person Bharat having a PAN card and his PAN number is

        CAMCB3456K

First Letter C-Individual
Fifth Letter B-His name starts with Bharat.

You may find N number of approaches for validating the PAN using javascript but in this post i have tried to validate the PAN number in textbox onkeypress event.

Design
 

<table cellpadding="2" cellspacing="3" border="1" align="center" width="420px">            
            <tr>
                <td>
                    Pan Number
                </td>
                <td>
                    <asp:TextBox ID="txtPanNumber" runat="server" Width="268px" onkeypress="return ValidatePAN(this.id);"></asp:TextBox>
                </td>
            </tr> 
        </table>

Javascript
 

<script type="text/javascript">
        /*Pan Card Number First 5 Letter should be Character and following next 4 letter should be numbers and last 1 should be Character and it should not exceed 10*/

        function ValidatePAN(ObjID) {
            var PANNumber = document.getElementById(ObjID).value;
            var count = PANNumber.length;
            var keyCode = (window.event.which) ? parseInt(window.event.which) : parseInt(window.event.keyCode);

            if (count <= 4) {
                if ((keyCode <= 90 && keyCode >= 65)) {
                    return true;
                }
                else {
                    return false;
                }
            }
            if (count <= 8 && count >= 5) {
                if (keyCode <= 57 && keyCode >= 48) {
                    return true;
                }
                else {
                    return false;
                }
            }

            if (count == 9) {
                if ((keyCode <= 90 && keyCode >= 65)) {
                    return true;
                }
                else {
                    return false;
                }
            }
            else {
                return false;
            }
        }

    </script>


Output
 
In this post i tried to validate the PAN number validation using javascript Asp.net textbox onkeypress event.

Send email to multiple receipent in asp.net

Sending email using Asp.net is simple thing but I cannot forget my first task.Because am a fresher without knowing about dotnet I started my carrer, the first task is email sending using asp.net I have searched in google for more than 15 days and finally found the solution.Ok let me come to the point, here am trying to explain how to send the same email details to multiple receipents, One way this code will helpful for monthly news letters sending and checking.Also we may easily check the email configuration setting through this.First we may design the screen as mentioned below.

Design

 
 
<table cellpadding="2" cellspacing="2" border="2" align="center" width="500px">
    <tr>
    <td colspan="2"><asp:Label ID="lblMessage" runat="server" ForeColor="Red"></asp:Label></td>
    </tr>
    <tr>
    <td>SMTP(HOST) :</td>
    <td><asp:TextBox ID="txtsmtp" runat="server" Width="268px"></asp:TextBox></td>
    </tr>
    <tr>
    <td>UserName eMailID :</td>
    <td><asp:TextBox ID="txtFromUID" runat="server" Width="270px"></asp:TextBox></td>
    </tr>
    <tr>
    <td>Password :</td>
    <td><asp:TextBox ID="txtPwd" runat="server" Width="133px" TextMode="Password"></asp:TextBox></td>
    </tr>
    <tr>
    <td>Port :</td>
    <td><asp:TextBox ID="txtPort" runat="server" Width="270px"></asp:TextBox></td>
    </tr>
    <tr>
    <td>Enable SSL :</td>
    <td><asp:CheckBox ID="chkSSL" runat="server" /> </td>
    </tr>
    <tr>
    <td>FromID :</td>
    <td><asp:TextBox ID="txtFromID" runat="server" Width="270px"></asp:TextBox></td>
    </tr>
    <tr>
    <td>To :</td>
    <td><asp:TextBox ID="txtTo" runat="server" Width="272px" Height="60px" 
            TextMode="MultiLine"></asp:TextBox><br />(use comma for multiple mailid)</td>
    </tr>
    <tr>
    <td>Subject :</td>
    <td><asp:TextBox ID="txtSubject" runat="server" Width="267px"></asp:TextBox></td>
    </tr>
    <tr>
    <td>Body :</td>
    <td><asp:TextBox ID="txtBody" runat="server" Width="279px" Height="52px" 
            TextMode="MultiLine"></asp:TextBox></td>
    </tr>

    <tr align="center">
    <td colspan="2"><asp:Button ID="btnSubmit" runat="server" Text="Send" 
            onclick="btnSubmit_Click" />&nbsp;<asp:Button ID="btnClear" runat="server" Text="Clear" 
            onclick="btnClear_Click" /></td>
    </tr>
    </table>



Coding
 

using System.Net.Mail;



    public void Clear()
        {
            txtTo.Text = "";
            txtSubject.Text = "";
            txtsmtp.Text = "";
            txtPwd.Text = "";
            txtPort.Text = "";
            txtFromID.Text = "";
            txtBody.Text = "";
        }
    
    protected void btnClear_Click(object sender, EventArgs e)
        {
       Clear();

    }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            lblMessage.Text = string.Empty;
            SmtpClient smtpClient = new SmtpClient();
            MailMessage message = new MailMessage();

            try
            {
                MailAddress fromAddress = new MailAddress(txtFromID.Text, "");                
                //Provide smtp Host name
                smtpClient.Host = txtsmtp.Text;
                //made default credential as false
                smtpClient.UseDefaultCredentials = false;
                //Here pass the login from emailID and Password
                smtpClient.Credentials = new System.Net.NetworkCredential(txtFromUID.Text, txtPwd.Text);
                //Port is important, default port is 25.
                smtpClient.Port = (txtPort.Text.Trim() == string.Empty) ? 25 : Convert.ToInt32(txtPort.Text.Trim());
                
                //From email Id
                message.From = fromAddress;
                //Subject which we are going to send
                message.Subject = txtSubject.Text.Trim().Replace("'","");
                //Whether we are going to send body content as plain text/HTML format here i am going to use plain text so i kept html false
                message.IsBodyHtml = false;

                if ((txtTo.Text != null) && (txtTo.Text != string.Empty))
                {
                    //Here we are splitting the email ID by comma separated
                    string[] emailTo = txtTo.Text.Split(',');

                    foreach (string emails in emailTo)
                    {

                        if (emails.Trim().Length > 0)
                        {
                            //Add the To email id in Mail to List
                            message.To.Add(new MailAddress(emails));

                        }
                    }
                }

                // Message body content
                message.Body = txtBody.Text.Trim().Replace("'", "");

                //If SSL is enabled we have check the enable SSL true
                if (chkSSL.Checked)
                {
                    smtpClient.EnableSsl = true;
                }
                // Send SMTP mail
                smtpClient.Send(message);

                Clear();
                lblMessage.Text = "Email successfully sent.";               

            }
            //Here am using smtp exception original mail exception able to catch
            catch (SmtpException ex)
            {
                lblMessage.Text = "Email sending Failed." + ex;
            }
            catch (Exception ex)
            {
                lblMessage.Text = "Email sending Failed." + ex;
            }
        }


Output

Here I mentioned the gmail smtp configuration for sending the email for multiple users, you may give your email id and password and try the same.

 

 
In this post I tried to explain how to Send email to multiple recipient in Asp.net.

Wednesday, October 14, 2015

Classes & Objects in OOPS



Doing things in an object-oriented manner is a way of thinking. And C# is an object-oriented language.

So, while I will illustrate with code examples, my focus will be on the following core concepts:

1) classes
2) objects
3) inheritance
4) polymorphism.

CLasses and objectS GenerallY

The terms class and object are sometimes used interchangeably. But classes describe the type of objects. And objects are usable instances of classes.
Think of classes like cookie cutters. Objects are like the cookies we cut out with those cookie cutters.
Or think of classes like blueprints. Objects are like the buildings we build from those blueprints.
Takeaway: classes are the templates from which we create objects.

CLasseS

Each class can have different class members that include properties that describe class data, methods that define class behavior, and events that provide communication between different classes and objects.

Fields and properties represent information that an object contains. Fields are like variables because they can be read or set directly. A method is an action that an object can perform. A class can have several implementations, or overloads, of the same method that differ in the number of parameters or parameter types. Note: in most cases you declare a method within a class definition. But C# also allows you to add methods to an existing class outside the actual definition of the class.
To create an object, you need to instantiate a class – or create a class instance. After instantiating a class, you can assign values to the instance’s properties and fields and you can invoke class methods. Inheritance describes the ability to create new classes based on an existing class. Inheritance enables you to create a new class that reuses, extends, and modifies the behavior that is defined in another class. The class whose members are inherited is called the base class, and the class that inherits those members is called the derived class. Notably, all classes in C# implicitly inherit from the Object class, which supports .NET class hierarchy and provides a lot of built-in functionality for all classes.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
// instantiates a class called DrawingObject
public class DrawingObject
{
    // implements DrawingObject, with a single method
    // note: the modifier "virtual" indicates to derived
        // classes that they can override this method       
    public virtual void Draw()
    {
        Console.WriteLine("I'm a generic drawing object.");
    }
}
// instantiates a derived class, Line, which inherits
    // from the base class, DrawingObject
public class Line : DrawingObject
{
    // note: the modifier "override" allows a method to
        // override the virtual method of its base class
    public override void Draw()
    {
        Console.WriteLine("I'm a Line.");
    }
}
// instantiates a derived class, Circle, which inherits
    // from the base class, DrawingObject
public class Circle : DrawingObject
{
    public override void Draw()
    {
        Console.WriteLine("I'm a Circle.");
    }
}
// instantiates a derived class, Square, which inherits
    // from the base class, DrawingObject
public class Square : DrawingObject
{
    public override void Draw()
    {
        Console.WriteLine("I'm a Square.");
    }
}

Polymorphism – from Greek πολύς, polys, “many, much” and μορφή, morphē, “form, shape” – means many shapes. More specifically, it means that you can have multiple classes that can be used interchangeably, even though each class implements the same properties or methods in different ways.

Continuing with our example, we see polymorphism illustrated by each derived class – Line, Circle, and Square – responding differently to the same “Draw()” method even though each inherits from the same base class, DrawObject.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
public class DrawDemo
{
    static void Main(string[] args)
    {
        //creates an array to hold four objects of type
            // DrawingObject.
        DrawingObject[] dObj = new DrawingObject[4];
        // initializes objects in array
        dObj[0] = new Line();
        dObj[1] = new Circle();
        dObj[2] = new Square();
        dObj[3] = new DrawingObject();
        // enumerate through each element in the array,
            // invoking the Draw() method
        foreach (DrawingObject drawObj in dObj)
        {
            drawObj.Draw();
        }
        // Output:
        // I'm a Line.
        // I'm a Circle.
        // I'm a Square.
        // I'm a generic drawing object.
        Console.ReadLine();
    }
}

Thanks for reading. I’m grateful for your feedback. And if we haven’t yet, let’s connect!
Now to make some real and metaphorical cookies.