Tuesday, November 18, 2014

Email Availability Control using Microsoft AJAX and Json WCF

Hi Guys,

If you are a web developer, I am sure you would have encountered a scenario where you have to check the email/username availability. So I thought of making a control which will call a WCF service through Microsoft AJAX and let the user know whether the email/username is already taken or not. Hope you like it.
















Solution

1) Create a Solution like following,


- One is a web site
- Other is a Class Library





















2) Open AjaxEnabledControls -> EmailTextBox.cs and paste the following code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace AjaxEnabled
{
    public class EmailTextBox : TextBox,IScriptControl
    {
        private ScriptManager sMgr;
        public string ServiceUrl;
        

        protected virtual IEnumerable<ScriptDescriptor> GetScriptDescriptors()
        {
            ScriptControlDescriptor descriptor =
            new ScriptControlDescriptor("AjaxEnabled.EmailTextBox", this.ClientID);
            descriptor.AddProperty("serviceUrl", this.ServiceUrl);
            
            return new ScriptDescriptor[] { descriptor };
        }

        protected virtual IEnumerable<ScriptReference> GetScriptReferences()
        {
            ScriptReference reference = new ScriptReference();
            reference.Assembly = "AjaxEnabled";
            reference.Name = "AjaxEnabled.EmailTextBox.js";
            return new ScriptReference[] { reference };
        }

        protected override void OnPreRender(EventArgs e)
        {
            if (!this.DesignMode)
            {
                //test for the existence of a ScriptManager
                sMgr = ScriptManager.GetCurrent(Page);
                if (sMgr == null)
                    throw new HttpException(
                    "A ScriptManager control must exist on the page.");
                sMgr.RegisterScriptControl(this);
            }
            base.OnPreRender(e);
        }
        protected override void Render(HtmlTextWriter writer)
        {
            if (!this.DesignMode)
                sMgr.RegisterScriptDescriptors(this);
            base.Render(writer);
            writer.WriteLine(string.Format(@"<br /><div><input type=""hidden"" id=""{0}""/> 
                <div id=""{1}"" style=""float:left""></div><span class=""emailTextboxSpan"" id=""{2}""></span></div><br />",
                this.ClientID + "_Hidden",
                this.ClientID + "_Image", 
                this.ClientID + "_Status"));
        }
        IEnumerable<ScriptReference> IScriptControl.GetScriptReferences()
        {
            return GetScriptReferences();
        }
        IEnumerable<ScriptDescriptor> IScriptControl.GetScriptDescriptors()
        {
            return GetScriptDescriptors();
        }
    }

}


3) Open AjaxEnabledControls -> EmailTextBox.js and paste the following code

/// <reference name="MicrosoftAjax.js"/>
Type.registerNamespace("AjaxEnabled");

//create constructor
AjaxEnabled.EmailTextBox = function (element) {
    AjaxEnabled.EmailTextBox.initializeBase(this, [element]);
    this._serviceUrl = null;
    this._spanControlId = '';
    this._imageControlId = '';
    this._hiddenControlId = '';
    this._isEmailAvailable = true;
}

//define class
AjaxEnabled.EmailTextBox.prototype = {
    //initialize the UI control
    initialize: function () {
        AjaxEnabled.EmailTextBox.callBaseMethod(this, 'initialize');
        this._onKeyupHandler = Function.createDelegate(this, this._onKeyup);
        this._onTextChangeHandler = Function.createDelegate(this, this._onTextChange);
        $addHandlers(this.get_element(), { 'keyup': this._onKeyup, 'change': this._onTextChange }, this);
    },
    dispose: function () {
        $clearHandlers(this.get_element());
        AjaxEnabled.EmailTextBox.callBaseMethod(this, 'dispose');
    },
    //define keystroke event
    _onKeyup: function (e) {
        this.validateEmail(e);
    },
    _onTextChange: function (e) {
        this.validateEmail(e);
    },
    validateEmail: function (e) {
        //get email text

        var emailValid = true;

        var x = this.get_element().value;
        var email = x;
        var atpos = x.indexOf("@");
        var dotpos = x.lastIndexOf(".");
        if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= x.length) {
            emailValid = false;
        }
        this._spanControlId = this.get_element().id + '_Status';
        this._imageControlId = this.get_element().id + '_Image';
        this._hiddenControlId = this.get_element().id + '_Hidden';
        var spanEmail = $get(this._spanControlId);
        var imageElement = $get(this._imageControlId);
        if (emailValid) {

            this.returnEmailAvailable(email);

        }
        else {
            this.get_element().className = '';
            imageElement.className = '';
            spanEmail.innerHTML = '';
            this._isEmailAvailable = false;
        }

    },
    //define properties
    get_serviceUrl: function () {
        return this._serviceUrl;
    },
    set_serviceUrl: function (value) {
        this._serviceUrl = value;
    },

    get_isEmailAvailable: function () {
        return this._isEmailAvailable;
    },
    OnWebRequestCompleted: function onWebRequestCompleted(executor, eventArgs) {
        if (executor.get_responseAvailable()) {

            var userContext = executor.get_webRequest().get_userContext();
            userContext.DisplayWebRequestBody(executor);
        }
        else {
            if (executor.get_timedOut())
                alert("Timed Out");
            else
                if (executor.get_aborted())
                    alert("Aborted");
        }
    },
    DisplayWebRequestBody: function displayWebRequestBody(executor) {

        var userContext = executor.get_webRequest().get_userContext();
        var displayElement = $get(userContext._spanControlId);

        displayElement.innerHTML =
        "Email Address is ";

        var isAvailable = executor.get_responseData() == "true" ? true : false
        var content = (isAvailable) ? "Available" : "Taken";
        if (document.all)
            displayElement.innerText += content;
        else
        // Firefox
            displayElement.textContent += content;

        userContext.get_element().className = content + "CssClass";
        userContext._isEmailAvailable = isAvailable;
        var imageElement = $get(userContext._imageControlId);
        var hiddenElement = $get(userContext._hiddenControlId);
        imageElement.className = content + "ImageCssClass";
        hiddenElement.value = isAvailable.toString();

    },

    returnEmailAvailable: function (email) {

        // Instantiate the WebRequest object.
        var wRequest = new Sys.Net.WebRequest();

        // Set the request Url.  
        wRequest.set_url(this._serviceUrl + email);

        // Set the request verb.
        wRequest.set_httpVerb("GET");

        // Set user's context
        wRequest.set_userContext(this);

        // Set the web request completed event handler,
        // for processing return data.
        wRequest.add_completed(this.OnWebRequestCompleted);

        // Execute the request.
        wRequest.invoke();


    }

}

//register class as a Sys.Control
AjaxEnabled.EmailTextBox.registerClass('AjaxEnabled.EmailTextBox',
Sys.UI.Control);
//notify loaded
if (typeof (Sys) !== 'undefined') Sys.Application.notifyScriptLoaded();

4) Open AjaxEnabled WebSite -> App_Code -> IEmailService.cs and paste the following code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.ServiceModel.Web;

// NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IEmailService" in both code and config file together.
[ServiceContract]
public interface IEmailService
{
[OperationContract]
    [WebGet(UriTemplate = "/CheckEmail?email={email}",
            ResponseFormat = WebMessageFormat.Json)]
bool CheckEmail(string email);
}

5) Open AjaxEnabled WebSite -> App_Code -> EmailService.cs and paste the following code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

// NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "EmailService" in code, svc and config file together.
public class EmailService : IEmailService
{
    public bool CheckEmail(string email)
{
        if (email.Trim().ToLower() == "shahim@dummy.com")
            return false;
        else
            return true;
}
}

6) Open AjaxEnabled WebSite -> Styles -> Site.css and paste the following styles

.weak
{
border: medium solid #008000;
}
.medium
{
border: thin solid #FFFF00;
}
.strong
{
border: medium solid #FF0000;
}
.emailTextboxSpan
{
    font-style : oblique;
}
.TakenCssClass
{
     border : 1px solid red;
}
.AvailableCssClass
{
    border : 1px solid green;
}

.TakenImageCssClass
{
    background-image : url('../Images/Taken.png');
    background-repeat : no-repeat;
    padding-top : 2px;
    width:24px;
    height:24px;
}
.AvailableImageCssClass
{
    background-image : url('../Images/Available.png');
    background-repeat : no-repeat;
    padding-top : 2px;
     width:24px;
    height:24px;
}

7) Finally add the following mark up in AjaxEnabled WebSite -> Default.aspx

<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
    CodeFile="Default.aspx.cs" Inherits="_Default" %>
    <%@ Register Assembly="AjaxEnabled" Namespace="AjaxEnabled"
TagPrefix="ajaxEnabled" %>
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">

<script type="text/javascript">
    function ClientValidate(source, arguments) {

        var available = document.getElementById("MainContent_emailTextBox1_Hidden").value;
        if (available != '')
            arguments.IsValid = (available == "true") ? true : false;
        else
            arguments.IsValid = true;

    }
</script>

<asp:ScriptManager ID="ScriptManager1" runat="server">

</asp:ScriptManager>
   
        Email Validator TextBox using Microsoft AJAX
       <br />
       <br />

  <ajaxEnabled:EmailTextBox ID="emailTextBox1" serviceUrl="./EmailService.svc/CheckEmail?email="  
   runat="server" width="200" ></ajaxEnabled:EmailTextBox>
   <br />
   <br />

   <asp:Button ID="btnSubmit" runat="server" Text="Submit" ValidationGroup="vgSubmit"/>
   <br />
   <br />
   <asp:CustomValidator 
       ID="cvEmail" runat="server" ErrorMessage="Email Address is already Taken. Please change to Proceed!"
       ClientValidationFunction="ClientValidate" ValidationGroup="vgSubmit"></asp:CustomValidator>

    
</asp:Content>


Thursday, November 13, 2014

Bootstrap and Web API

Hi Guys,

This time I made a small webpage which consumes a JSON Web API Restfully. Hope you like it.














Solution

1) Create a Solution like following 


Add New Project -> ASP.NET MVC 4 Web Application





 Select Web API as the Project Template

The Solution will look as following





















Right Click on Controllers -> Add -> Controller as follows name it as the TimeLogController. Remember you have to call it as Timelog if you name it TimeLog[Controller].















Then Open App_Start -> WebApiConfig.cs and add the following line to enable JSON format (default is XML format)

//Add this to allow Json format through 
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));

Then Create a LINQ-SQL Classes for your database objects and add the following code to the TimeLogController.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace MyWebAPI.Controllers
{
    public class TimeLogController : ApiController
    {
        /// <summary>
        /// GET api/timelog
        /// </summary>
        /// <returns></returns>
        public List<EP_TimeLog> Get()
        {
            using (TimeLogDataContext context = new TimeLogDataContext())
            {
                var timeLogs = from r in context.EP_TimeLogs
                               select r;

                return timeLogs.ToList();
            }
            
        }

        /// <summary>
        /// GET api/timelog/id
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public List<EP_TimeLog> Get(long id)
        {
            using (TimeLogDataContext context = new TimeLogDataContext())
            {
                var timeLogs = from r in context.EP_TimeLogs
                               where r.ID == id
                               select r;

                return timeLogs.ToList();
            }
        }


    }
}

Finally add the TimeLogs.html file and call the API using jquery.

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Time Logs </title>
</head>
<body>
   

    <div class="panel panel-primary">
           <div class="panel-heading">
             <h1 >My Time Logs</h1>   
       
            </div>
    <div class="panel-body">
             
                   <div class="table-responsive">
                       <table class="table table-striped table-hover" id="timelogs"  width="100%"  >
<thead>
            <tr>


                
</tr>
<tr>
            <th>
                    Name
                </th>
                <th>
                    Description
                </th>
                <th>
                    Start Time
                </th>
                 <th>
                    End Time
                </th>
                <th>
                    Duration (Mins)
                </th>
           
                
</tr>

</thead>
<tbody>


</tbody>

</table>
                   </div>
            
             
            </div>
         </div>



    <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.min.js"></script>
    <script src="Content/js/bootstrap.js"></script>
    <script src="Content/js/bootstrap.min.js"></script>
    <link href="Content/css/bootstrap.css" rel="stylesheet" />
    <link href="Content/css/bootstrap.min.css" rel="stylesheet" />
  <script>
      var uri = 'api/timelog';

      $(document).ready(function () {
          // Send an AJAX request
          $.getJSON(uri)
              .done(function (data) {
                  // On success, 'data' contains a list of timelogs.
                  $.each(data, function (key, item) {
                      // Add a list item for the timelog.
                      var row = '<td>' + item.Name + '</td><td>' + item.Description + '</td>'
                      + "<td>" + item.StartTime.replace("T", " ") + "</td><td>" + item.EndTime.replace("T", " ") + "<td>" + item.Duration + "</td>";
                      $('<tr>', { html: row })  
                          .appendTo($('#timelogs'));
                  });
              });
      });

      
     
  </script>

</body>

</html>




Saturday, November 1, 2014

nHibernate, SQL Server and WCF

Hi Guys,

This time I made a small program to illustrate the power and maturity of nHibernate ORM and integration of WCF with it. Hope you like it.


Solution


1) Create a Solution like following 






















2) Download the nHibernate from http://nhforge.org/ and add it to your solution

3) Create Domain -> EP_TimeLog.cs and paste the following code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;

namespace nHibernateDL.Domain
{
    /// <summary>
    /// Time Log Class 
    /// </summary>
    [Serializable]    
    [DataContract]
    public class EP_TimeLog
    {
        [DataMember]
        public virtual long Id { get; set; }
        [DataMember]
        public virtual string Name { get; set; }
        [DataMember]
        public virtual string Description { get; set; }
        [DataMember]
        public virtual DateTime StartTime { get; set; }
        [DataMember]
        public virtual DateTime EndTime { get; set; }
        [DataMember]
        public virtual decimal Duration { get; set; }
        [DataMember]
        public virtual string CreatedBy { get; set; }
        [DataMember]
        public virtual DateTime CreatedOn { get; set; }
        [DataMember]
        public virtual string EditedBy { get; set; }
        [DataMember]
        public virtual DateTime? EditedOn { get; set; }
        [DataMember]
        public virtual byte[] RowVer { get; set; }
    }
}

4) Create nHibernateDL -> Domain -> EP_TimeLogRepository.cs and paste the following code

using NHibernate;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace nHibernateDL.Domain
{
    /// <summary>
    /// Interface for Repository
    /// </summary>
    public interface IEP_TimeLogRepository
    {
        EP_TimeLog GetById(long id);
        bool Add(EP_TimeLog log);
        bool Update(EP_TimeLog log);
    }

    /// <summary>
    /// Class for the Repository
    /// </summary>
    public class EP_TimeLogRepository : IEP_TimeLogRepository
    {
        /// <summary>
        /// Method to get data by ID
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public EP_TimeLog GetById(long id)
        {
            using (ISession session = nHibernateHelper.OpenSession())
            {
                var timeLog = session.Get<EP_TimeLog>(id);
                return timeLog;
            }
        }

        /// <summary>
        /// Method to Add new entity
        /// </summary>
        /// <param name="log"></param>
        /// <returns></returns>
        public bool Add(EP_TimeLog log)
        {
            bool isSaved = false;
            using (ISession session = nHibernateHelper.OpenSession())
            {
                
                    session.Save(log);                    
                    isSaved = true;           
                
            }

            return isSaved;
        }

        /// <summary>
        /// Method to update entity
        /// </summary>
        /// <param name="log"></param>
        /// <returns></returns>
        public bool Update(EP_TimeLog log)
        {
            bool isSaved = false;
            using (ISession session = nHibernateHelper.OpenSession())
            {
                using (ITransaction transaction = session.BeginTransaction())
                {
                    session.SaveOrUpdate(log);
                    transaction.Commit();
                    isSaved = true;
                }

            }

            return isSaved;
        }
    }

}

5) Create nHibernateDL-> Mappings -> EP_TimeLog.hbm.xml and paste the following xml

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
                   assembly="nHibernateDL"
                   namespace="nHibernateDL.Domain">

  <class name="EP_TimeLog">
    <id name="Id" type="long">
      <generator class="identity"/>
    </id>
    
    <property name="Name" />
    <property name="Description" />
    <property name="StartTime" />
    <property name="EndTime" />
    <property name="Duration" />
   
    <property name="CreatedOn" />
    <property name="CreatedBy" />
    <property name="EditedBy" />
    <property name="EditedOn" />
   
  </class>

</hibernate-mapping>

6) Create nHibernateDL-> hibernate.cfg.xml and paste the following xml

<?xml version="1.0" encoding="utf-8" ?>


<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
  <session-factory>
    <property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
    <property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property>
    <property name="connection.connection_string">Data Source=.\SQLEXPRESS;Initial Catalog=KPICatalog;Integrated Security=true</property>
    <property name="dialect">NHibernate.Dialect.MsSql2008Dialect</property>
    
   
  </session-factory>
</hibernate-configuration>

7) Create nHibernateDL-> nHibernateHelper.cs and paste the following code

using NHibernate;
using NHibernate.Cfg;
using nHibernateDL.Domain;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace nHibernateDL
{
    /// <summary>
    /// Helper Class to Create an nHibernate Session
    /// </summary>
    public class nHibernateHelper
    {
        private static ISessionFactory _sessionFactory;
 
        private static ISessionFactory SessionFactory
        {
            get
            {
                if(_sessionFactory == null)
                {
                    var configuration = new Configuration();
                    configuration.Configure();
                    configuration.AddAssembly(typeof(EP_TimeLog).Assembly);
                    _sessionFactory = configuration.BuildSessionFactory();
                }
                return _sessionFactory;
            }
        }
 
        public static ISession OpenSession()
        {
            return SessionFactory.OpenSession();
        }
    
    }
}

8) Create nHibernateWcfServiceLibrary -> HibernateService.cs and paste the following code

using nHibernateDL.Domain;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using nHibernateDL;

namespace nHibernateWcfServiceLibrary
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in both code and config file together.
    public class HibernateService : IHibernateService
    {
        /// <summary>
        /// Get Data Method
        /// </summary>
        /// <param name="value">Id of the Log</param>
        /// <returns>Return Message of Time Log</returns>
        public ReturnMsg<EP_TimeLog> GetData(long value)
        {
            ReturnMsg<EP_TimeLog> objReturn = new ReturnMsg<EP_TimeLog>();

            try
            {
                nHibernateHelper.OpenSession();
                IEP_TimeLogRepository repo = new EP_TimeLogRepository();

                objReturn.Data = repo.GetById(value);

                objReturn.Status = Status.Success;  
            }
            catch (Exception ex)
            {
                objReturn.Message = ex.Message + Environment.NewLine + ex.StackTrace;
                objReturn.Status = Status.Failed;               
            }

            return objReturn;
        }

        /// <summary>
        /// Save Method
        /// </summary>
        /// <param name="log">Log to Save</param>
        /// <returns>Return whether saved</returns>
        public ReturnMsg<bool> Save(EP_TimeLog log)
        {
            ReturnMsg<bool> objReturn = new ReturnMsg<bool>();

            try
            {
                nHibernateHelper.OpenSession();
                IEP_TimeLogRepository repo = new EP_TimeLogRepository();

                if (log.Id > 0)
                {
                    objReturn.Data = repo.Update(log);
                }
                else
                {
                    objReturn.Data = repo.Add(log);
                }               

                objReturn.Status = Status.Success;
            }
            catch (Exception ex)
            {
                objReturn.Message = ex.Message + Environment.NewLine + ex.StackTrace;
                objReturn.Status = Status.Failed;
            }

            return objReturn;
        }

        
    }
}

9) Create nHibernateWcfServiceLibrary -> IHibernateService.cs and paste the following code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using nHibernateDL.Domain;

namespace nHibernateWcfServiceLibrary
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService1" in both code and config file together.
    [ServiceContract]
    public interface IHibernateService
    {
        [OperationContract]
        ReturnMsg<EP_TimeLog> GetData(long value);   
     
        [OperationContract]
        ReturnMsg<bool> Save(EP_TimeLog log); 
    }

   
}

10) Create ReturnMsg.cs and paste the following code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;

namespace nHibernateWcfServiceLibrary
{
    public enum Status : byte
    {
        Success = 1,
        Failed = 2
    }

    [DataContract]
    public class ReturnMsg<T>
    {
        [DataMember]
        public T Data { get; set; }
        [DataMember]
        public string Message { get; set; }
        [DataMember]
        public Status Status { get; set; }
    }
}

11) Add the nHibernateWcfServiceLibrary as a Service reference to the nHibernateTest

12) Open nHibernateTest -> Program.cs and paste the following code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using nHibernateTest.HibernateService;

namespace nHibernateTest
{
    class Program
    {
        static void Main(string[] args)
        {
            using (HibernateServiceClient objService = new HibernateServiceClient())
            {

                EP_TimeLog objToAdd = new EP_TimeLog()
                {
                    Name = "Test Task through WCF",
                    Description = "Test Task through WCF",
                    StartTime = DateTime.Parse("11/01/2014 16:00"),
                    EndTime = DateTime.Parse("11/01/2014 16:30"),
                    Duration = 30,
                    CreatedBy = "sshahim",
                    CreatedOn = DateTime.Now,
                    EditedBy = "sshahim",
                    EditedOn = DateTime.Now
                };

                ReturnMsgOfboolean objSaveReturn = objService.Save(objToAdd);

                if (objSaveReturn.Status == Status.Success && objSaveReturn.Data)
                    Console.WriteLine("Data Saved Successfully!");
                
                ReturnMsgOfEP_TimeLog6f00b6nb objReturnMsg = objService.GetData(15);
                if (objReturnMsg.Status == HibernateService.Status.Success)
                {
                    EP_TimeLog objToUpdate = objReturnMsg.Data as EP_TimeLog;

                    Console.Write(string.Format("Id : {0}\nName : {1}\n", objToUpdate.Id, objToUpdate.Name));

                    objToUpdate.Name = objToUpdate.Name + " Modified";

                    ReturnMsgOfboolean objUpdateReturn = objService.Save(objToUpdate);

                    if (objUpdateReturn.Status == Status.Success && objUpdateReturn.Data)
                    Console.WriteLine("Data Modified Successfully!");

                }
            }

            Console.Read();
        }
    }
}

Before Adding New Record












After adding New Record














After Modifying