April 29, 2011

Class Properties example in C#

Create a reference type called Person.  Populate the Person class with the following properties to store the following information:

  1. First name
  2. Last name
  3. Email address
  4. Date of birth
Add constructors that accept the following parameter lists:

  1. All four parameters
  2. First, Last, Email
  3. First, Last, Date of birth
Add read-only properties that return the following computed information:

  1. Adult - whether or not the person is over 18
  2. Sun sign - the traditional western sun sign of this person
  3. Birthday - whether or not today is the person's birthday





using System;
using System.Collections.Generic;
using System.Text;


namespace TestProperties
{
    class Person
    {


        private String FirstName;
        private string LastName;
        private string Email;
        private DateTime Dob;




        public string SetfirstName
        {
            get
            {
                return FirstName;
            }
            set
            {
                FirstName = value;


            }


        }


        public string SetLastName
        {
            get
            {
                return LastName;
            }
            set
            {
                LastName = value;


            }


        }


        public string SetEmail
        {


            set
            {
                Email = value;


            }


        }


        public DateTime SetDob
        {


            set
            {
                Dob = value;


            }


        }


        /////////////////////////////
        public Person(String First, String Last, String email, DateTime DOfB)
        {
            FirstName = First;
            LastName = Last;
            Email = email;
            Dob = DOfB;
        }


        public Person(String First, String Last, String email)
        {
            FirstName = First;
            LastName = Last;
            Email = email;


        }
        public Person(String First, String Last, DateTime DOfB)
        {
            FirstName = First;
            LastName = Last;
            Dob = DOfB;
        }


        public int age(DateTime dtDOB)
        {
            // DateTime dtDOB = new DateTime(1984, 10, 6);
            TimeSpan ts = DateTime.Now.Subtract(dtDOB);
            int years = ts.Days / 365;
            return years;


        }


        public string ZodiacSign(DateTime DateOfBirth)
        {
            string returnString = string.Empty;
            string[] dateAndMonth = DateOfBirth.ToLongDateString().Split(new char[] { ',' });
            string[] ckhString = dateAndMonth[1].ToString().Split(new char[] { ' ' });
            if (ckhString[1].ToString() == "March")
            {
                if (Convert.ToInt32(ckhString[2]) <= 20) { returnString = "Pisces"; } else { returnString = "Aries"; }
            }
            else if (ckhString[1].ToString() == "April") { if (Convert.ToInt32(ckhString[2]) <= 19) { returnString = "Aries"; } else { returnString = "Taurus"; } } else if (ckhString[1].ToString() == "May") { if (Convert.ToInt32(ckhString[2]) <= 20) { returnString = "Taurus"; } else { returnString = "Gemini"; } } else if (ckhString[1].ToString() == "June") { if (Convert.ToInt32(ckhString[2]) <= 20) { returnString = "Gemini"; } else { returnString = "Cancer"; } } else if (ckhString[1].ToString() == "July") { if (Convert.ToInt32(ckhString[2]) <= 22) { returnString = "Cancer"; } else { returnString = "Leo"; } } else if (ckhString[1].ToString() == "August") { if (Convert.ToInt32(ckhString[2]) <= 22) { returnString = "Leo"; } else { returnString = "Virgo"; } } else if (ckhString[1].ToString() == "September") { if (Convert.ToInt32(ckhString[2]) <= 22) { returnString = "Virgo"; } else { returnString = "Libra"; } } else if (ckhString[1].ToString() == "October") { if (Convert.ToInt32(ckhString[2]) <= 22) { returnString = "Libra"; } else { returnString = "Scorpio"; } } else if (ckhString[1].ToString() == "November") { if (Convert.ToInt32(ckhString[2]) <= 21) { returnString = "Scorpio"; } else { returnString = "Sagittarius"; } } else if (ckhString[1].ToString() == "December") { if (Convert.ToInt32(ckhString[2]) <= 21) { returnString = "Sagittarius"; } else { returnString = "Capricorn"; } } else if (ckhString[1].ToString() == "January") { if (Convert.ToInt32(ckhString[2]) <= 19) { returnString = "Capricorn"; } else { returnString = "Aquarius"; } } else if (ckhString[1].ToString() == "February") { if (Convert.ToInt32(ckhString[2]) <= 18) { returnString = "Aquarius"; } else { returnString = "Pisces"; } } return returnString;
        }


        public bool IsAdult
        {
            get
            {
                if (age(this.Dob) >= 18)
                {


                    return true;


                }
                else
                {


                    return false;
                }


            }
        }


        public bool isBirthdayToday
        {
            get
            {
                if ((this.Dob.Day == DateTime.Now.Day) && (this.Dob.Month == DateTime.Now.Month))
                {


                    return true;


                }
                else
                {


                    return false;
                }
            }
        }




        public string GetSunSign
        {
            get
            {
                return (ZodiacSign(this.Dob));


            }
        }
    }
    class Program
    {
        private String getAdultString(Person obj)
        {
            if (obj.IsAdult)
            {


                return obj.SetfirstName +"  Is Adult";
            }


            else
            {
                return obj.SetfirstName+"  Is not Adult";


            }


        }




        private String getBdayString(Person obj)
        {
            if (obj.isBirthdayToday )
            {


                return "Today Is   "+obj.SetfirstName +"'s B'day";
            }


            else
            {
                return "Today Is not " + obj.SetfirstName +"'s B'day";


            }


        }


        private String getSunSignString(Person obj)
        {
            return obj.SetfirstName + "'s Sun sign is " + obj.GetSunSign;


        }
        static void Main(string[] args)
        {
            Person p = new Person("Test1", "Test1", new DateTime(1984, 10, 30));
            Person p1 = new Person("Test2", "Test2", new DateTime(2010, 4, 30));


            Program objProgram = new Program();


            Console.WriteLine( objProgram.getAdultString(p));
            Console.WriteLine(objProgram.getBdayString(p));
            Console.WriteLine(objProgram.getSunSignString(p));
            Console.WriteLine();
            Console.WriteLine( objProgram.getAdultString(p1));
            Console.WriteLine( objProgram.getBdayString(p1));
            Console.WriteLine( objProgram.getSunSignString(p1));


        }
    }
}


below is the o/p



April 7, 2011

Code Example Creating a Custom Validation Attribute in ASP.NET MVC 2.0


The System.ComponentModel.DataAnnotations namespace includes a number of built-in validation attributes .
So far(In Previous Example) We have used  [Required], [StringLength], and [RegularExpression].
We can also create  own custom validation attributes by deriving from the ValidationAttribute base class within the System.ComponentModel.DataAnnotations namespace.  
Or We can  derive from any of the existing validation attributes just to modify the  functionality. 
So We Will Include One  more class in Previous StudentModel.cs


Now this Custom Validator can be used Like this


Before I was using Regular Expression Validation Attribute to validate the email.
Now I am using Email Attribute which is Custom Validation Attribute
Now To test it enter Wrong Email and see the Custom Validation Attribute in action.

April 5, 2011

Code Example for ASP.NET MVC2.0

This is my first step towards learning ASP.NET MVC Architecture
Here I ll create a Student Form and Will save the form Data in Sqlserver database using ASP.NET MVC2.0

1.) Install ASP.NET MVC 2.0 for Visual Studio 2008 from the below link
http://www.microsoft.com/downloads/en/details.aspx?familyid=C9BA1FE1-3BA8-439A-9E21-DEF90A8615A9&displaylang=en

2.)First Create a New Project by selecting ASP.NET MVC2 Web Application Template

3.)Click Ok It will add sample application with two Views Home and Account
4.) We will Add Our Form Student within the same App
5.)Right click on Models Add new class StudentModel.cs
6.)Code On StudentModel.cs Create property corresponding to each Form Field + Write the Validation

Models/StudentModel.cs


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Data.SqlClient;
using System.Data;
using System.Web.Mvc;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;


namespace TestMVCapplication.Models
{
    public class StudentModel
    {


        [Required(ErrorMessage = "* Required")]
        [StringLength (10,ErrorMessage="must be under 10")] 
        [RegularExpression ("^([a-zA-z\\s]{4,32})$",ErrorMessage ="Only Alphabets are allowed")]
        [DisplayName("Name")]
         public string Name { get; set; }


        [Required(ErrorMessage = "* Required")]
        [DataType(DataType.EmailAddress, ErrorMessage = "Your email address contains some errors")]
        [DisplayName("Email address")]
        [RegularExpression("^[\\w-\\.]+@([\\w-]+\\.)+[\\w-]{2,4}$",ErrorMessage="Enter a Valid Email")]
        public string Email { get; set; }


        [Required(ErrorMessage = "* Required")]


        public string Comment { get; set; }




    }
}


7.)We’ll then add a “StudentController.cs” controller class to our project's Controllers folder that exposes two “GetStudent” action methods.  
The first action method is called when an HTTP-GET request comes for the /Student/Create URL.  It will display a blank form for entering Student data. 
 The second action method is called when an HTTP-POST request comes for the /Student/Create URL.  It maps the posted form input to a Student object, verifies that no binding errors occurred, and if it is valid will eventually save it to a database(Business Logic)


Controllers/StudentController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TestMVCapplication.Models;
using System.Data;
using System.Data.SqlClient;

namespace TestMVCapplication.Controllers
{
    public class StudentController : Controller
    {
       


        SqlConnection connObj = new SqlConnection();
        DataSet ds;
        SqlCommand objCommand;
        SqlDataAdapter objAdapter;


        
        // GET: /Student/
        public ActionResult GetStudent()
        {
            return View();
        }

        
        [HttpPost]

        public ActionResult GetStudent(StudentModel model)
        {
            Response.Write(model.Name + model.Comment + model.Email);
            //code to insert data in DB using ADO.NET
            connObj.ConnectionString = "Data Source=.\\sqlexpress;Initial Catalog=TestMVC;Integrated Security=True";
         connObj.Open();
        SqlCommand comm = new SqlCommand("insert into student(name,email,comment) values(@name,@email,@comment)", connObj);
        
            comm.Parameters.Add("@name", SqlDbType.VarChar , 50).Value =model .Name ;
            comm.Parameters.Add("@email", SqlDbType.VarChar, 50).Value = model.Comment;
            comm.Parameters.Add("@comment", SqlDbType.VarChar, 50).Value = model.Email;

        int result = comm.ExecuteNonQuery();
        if (result != 0)
            Response.Write(" added");
        else
            Response.Write("Error");

            return View();
        }

    }
}

8.)After we’ve implemented our controller, we can right-click within one of its action methods and choose the “Add View” command within Visual Studio – which will bring up the “Add View” dialog.  


Visual Studio will then generate a Getstudent.aspx view file for us under the \Views\student\ directory of our project.  See How we can use  new strongly-typed HTML helpers in ASP.NET MVC 2 (enabling better intellisense and compile time checking support):


9.) Design the form on Getstudent.aspx using HTMlHelper Class
Views/Student/GetStudent.aspx

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<TestMVCapplication.Models.StudentModel>" %>


<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
GetStudent
</asp:Content>


<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">


    <h2>GetStudent</h2>




 <% Html.EnableClientValidation(); %> 
    <% using (Html .BeginForm() ){%>
        <%= Html.ValidationSummary(true, "A few fields are still empty") %>
        <fieldset>
             <legend>Student Detail</legend>
            <div class="editor-label">
                <%= Html.LabelFor(m => m.Name) %>
            </div>
            <div class="editor-field">
                <%= Html.TextBoxFor(m => m.Name) %>
                <%= Html.ValidationMessageFor(m => m.Name) %>
            </div>
            <div class="editor-label">
                <%= Html.LabelFor(m => m.Email) %>
            </div>
            <div class="editor-field">
                <%= Html.TextBoxFor(m => m.Email) %>
                <%=Html.ValidationMessageFor(m => m.Email) %>
            </div>
            <div class="editor-label">
                <%= Html.LabelFor(m => m.Comment) %>
            </div>
            <div class="editor-field">
                <%= Html.TextAreaFor(m => m.Comment, 10, 25, null) %>
                <%= Html.ValidationMessageFor(m => m.Comment) %>
            </div>
            <p>
                <input type="submit" value="Submit" />
            </p>
        </fieldset>
        <p id="result"><%=TempData["Message"] %></p>
    <% } %>
</asp:Content>

10)Add The link for Student in Site.Master

11.) Run The app



12) Click On Student


13) As  we’ve added the validation attributes to our studentModel.cs , let’s re-run our application and see what happens when we enter invalid values and post them back to the server:
The Html.ValidationMessageFor() helper will output the appropriate error message for any invalid model property passed to the view

14.)So far we saw  server-side validation – which means that our end users will need to perform a form submit to the server before they’ll see any validation error messages.
One of the feature of  ASP.NET MVC 2’s validation architecture is that it supports both server-side and client-side validation.  
To enable Client Side Validation
 we need to do is to add two JavaScript references to our view, and write one line of code:
  1. Add Reference of JS files in site.master


      2)Write Code in View to Enable client Side Validation


To see the client-side JavaScript support in action   Notice how we’ll get an immediate error message for our missing value without having to hit the server:

15.) Insert Valid Form Values Click on submit it will call the Post GetStudent Action Method and will insert the    record in DB






See the Record Updated in the DB
                         

April 3, 2011

Variable Parameter passing in C#

How We can write  a method that accepts a variable number of parameters?


Answer :The params keyword can be used for  a method parameter that is an array.  When the method is invoked, the elements of the array can be passed as a comma separated list.


Below is the sample code




using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;


namespace ConsoleApplication1
{
    class Program
    {


        static void TestVarArg(params int[] args)
        {
            foreach (int arg in args)
            {
                Console.WriteLine(arg);
            }
        }




        static void TestVarArgString(params string [] args)
        {
            foreach (string  arg in args)
            {
                Console.WriteLine(arg);
            }
        }




        static void Main(string[] args)
        {
            TestVarArg(1, 2, 3);
            Console.WriteLine();


            TestVarArg(3, 4, 5,6,7);


            Console.WriteLine();


            string[] names = new string[3] { "Test1", "Test2", "Test3" };
            TestVarArgString(names);


            Console.WriteLine();


            TestVarArgString("Test4", "Test5");


        }
    }
}


See the o/p 


WebUserControl Example

Below is the example for creating a web user control for selecting date from a calendar and display in the textbox.

1.) Add .ascx file by choosing WebUserControl template

DateSelectControl.ascx

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="DateSelectControl.ascx.cs" Inherits="DateSelectControl" %>


<asp:TextBox ID="txtDate" runat="server" 
    style="margin-top:0px; z-index: 1; left: 45px; top: 40px; position: absolute;"></asp:TextBox>
<asp:ImageButton ID="ImageButton1" runat="server" 
    ImageUrl="~/Images/Calendar Icon.jpg" 
    style="margin-left: 10px;margin-top:50px; z-index: 1; left: 201px; top: -30px; position: absolute; height: 50px; width: 50px;" 
    onclick="ImageButton1_Click" /><br />
<asp:Calendar ID="Calendar1" runat="server" 
    onselectionchanged="Calendar1_SelectionChanged" 
    
    style="z-index: 1; left: 185px; top: 87px; position: absolute; height: 188px; width: 259px" 
    onvisiblemonthchanged="Calendar1_VisibleMonthChanged"></asp:Calendar>



DateSelectControl.ascx.cs

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


public partial class DateSelectControl : System.Web.UI.UserControl
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Calendar1.Visible = false;
    }
    protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
    {
        Calendar1.Visible = true;
    }
    protected void Calendar1_SelectionChanged(object sender, EventArgs e)
    {


        txtDate.Text = Calendar1.SelectedDate.ToString("dd MMM yyyy");




    }
    protected void Calendar1_VisibleMonthChanged(object sender, MonthChangedEventArgs e)
    {
        Calendar1.Visible = true;
    }


    //Create value Property


    public String Value
    {
        get
        {
            return Calendar1.SelectedDate.ToString();


        }




    }
}

2.) Built it
3.) Add .aspx page to use the above control



UseDateselectcontrol.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="UseDateselectcontrol.aspx.cs" Inherits="UseDateselectcontrol" %>


<%@ Register src="DateSelectControl.ascx" tagname="DateSelectControl" tagprefix="uc1" %>


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
      <asp:Label ID="lbl1" runat ="server" Text ="Date Of Birth :" ></asp:Label>
      
       <asp:Label ID="lbl2" runat ="server" Text ="" ></asp:Label>
        
    </div>
        <uc1:DateSelectControl ID="DateSelectControl1"    runat="server"   style="margin-left: 250px" />
    
    </form>
</body>
</html>


UseDateselectcontrol.aspx.cs

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


public partial class UseDateselectcontrol : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {


       


    }
}




4.) Run UseDateselectcontrol.aspx you should see below interface


5.) Click On the Button Calendar will be displayed



6.) Select the date from calendar , date will be displayed in text box and calendar will disappear