Hello.cshtml



@{
    var strName = "";
    if(IsPost)
    {
        strName = "Hello welcome to Razor";
    }
}
<form method="post">
<p>
@strName
</p>

<input type="submit" value="Submit" id="submit1"/>
</form>


TextBoxVal.cshtml





@{
    var strName = "";
    if(IsPost)
    {
        strName = "Hello " + Request["txtName"];
    }
}
<form method="post">
<p>
@strName
</p>
Name
<input name="txtName" type="text" />
<br />
<br />
<input type="submit" value="Submit" id="submit1"/>
</form>

sum.cshtml





@{
    var sum = 0;
    if(IsPost)
    {
        sum = Request["txtValue1"].AsInt() + Request["txtValue2"].AsInt();
       
    }
 
}

<form method ="post">
<p>
@sum
</p>
Value 1<input name= "txtValue1" type="text" />
<br />
Value 2<input name= "txtValue2" type="text" />
<br />
<input id="Submit1" type="submit" value="submit" />
</form>


Session.cshtml



@{
    Session["name"] = "dear";
}
<form method="post">
<a href = "@Href("Welcome")">Welcome</a>
</form>


Welcome.cshtml



@{
var strName = "Hello " + Session["Name"];
}
<form>
<p>
@strName
</p>
</form>
Application information
Properties
References
Application folders
                                                                        App_Data Folder
                                                                        Content Folder
                                                                        Controllers Folder
                                                                         Models Folder
                                                                        Scripts Folder
                                                                         Views Folder
Configuration files
Global.asax
packages.config
Web.config
Architecture is an important feature and the very first step in the development of an application. n-Tier the term is used for multiple tier or multiple layers. n-Tier Architecture splits the solution process into different projects based on the business requirements. The main advantage of using n-Tier is that the complexity associated with the business and the process is reduced and it is easy to work with. The elements of performance, scalability and future development issues need to be considered when deciding on the architecture of the application depending on the priorities required.

The n-Tier application has three tiers or layers, they are called the presentation tier, the business tier and the data tier. Each layer interacts with the layer directly below, and has specific function to perform. Presentation Layer is responsible for displaying user interface to either programmer or end user. Programmer uses this layer for designing purpose and to get the data back and forth. In ASP.NET it includes ASPX pages, user controls, server controls and sometimes security related classes and objects.

The Business layer works as a mediator to transfer the data from presentation layer. In the three tier architecture the data access layer is not made to interact with the presentation layer. The architecture in ASP.NET includes using SqlClient or OleDb objects to retrieve, update and delete data from SQL Server or Access databases and passing the data retrieved to the presentation layer in a DataReader or DataSet object, or a custom collection object. The Data layer gets the data from the business layer and sends it to the database or vice versa. This layer is further divided into two sub layers Business Logic Layer (BLL) and Data Access Layer (DAL). DAL is responsible for accessing data and forwarding it to BLL. In ASP.NET it uses SqlClient or OleDb to retrieve the data and send it to BLL in the form of a DataSet or DataReader. BLL (Business Logic Layer) is responsible for preparing or processing the data retrieved and sends it to the presentation layer.

The Data layer gets the data from the business layer and sends it to the database or gets the data from the database and sends it to the business layer. In ASP .NET it is an SQL Server or Access database. It can also be Oracle, mySQL or even XML.
In an ASP.NET n-tiered architecture web pages do not make direct calls to the database. A given layer only communicates with its neighboring layers. ASP.NET Web pages should reference custom objects defined in the business object layer. These objects provide database information in a class structure.

All the programming languages supporting Object oriented Programming will be supporting these three main concepts:
1. Encapsulation
2. Inheritance
3. Polymorphism

Encapsulation in C#:

Encapsulation is process of keeping data and methods together inside objects. In this way developer must define some methods of object?s interaction. In C# , encapsulation is realized through the classes. A Class can contain data structures and methods. Consider the following class.

public class Aperture
{
public Aperture()
{

}

protected double height;
protected double width;
protected double thickness;

public double GetVolume()
{
double volume = height*width*thickness;
if(volume<0)
return 0;
return volume;
}
}

In this example we encapsulate some data such as height, width, thickness and method GetVolume. Other methods or objects can interact with this object through methods that have public access modifier. It must be done using ?.? operator.


Inheritance in C#:

In a few words, Inheritance is the process of creation new classes from already existing classes. The inheritance feature allows us to reuse some parts of code. So, now we have some derived class that inherits base class?s members. Consider the following code snippet:

public class Door : Aperture
{
public Door() : base()
{

}

public bool isOutside = true;
}

As you see to inherit one class from another, we need to write base class name after ?:? symbol. Next thing that was done in code Door () ? constructor also inherits base class constructor. And at last we add new private field. All members of Aperture class are also in Door class. We can inherit all the members that has access modifier higher than protected.

Polymorphism in C#:

Polymorphism is possibility to change behavior with objects depending of object?s data type. In C# polymorphism realizes through the using of keyword virtual and override. Let look on the example of code:

public virtual void Out()
{
Console.WriteLine("Aperture virtual method called");
}
//This method is defined in Aperture class.
public override void Out()
{
Console.WriteLine("Door virtual method called");
}


Now we need to re-define it in our derived Door class. The usage of virtual methods can be clarified when we creating an instance of derived class from the base class:
Aperture ap = new Door();
ap.Out();

UI:
Login Page
public partial class login : System.Web.UI.Page
{
businessLogic obj = new businessLogic();

protected void button_Click(object sender, EventArgs e)
{
obj.Username = username.Text;
obj.Password = password.Text;
obj.loginbll();
Response.Redirect("HOme.aspx");
}
}

BLL:

using databaselogic;
public class businessLogic
{

public businessLogic ()
{
databaselogic obj_Bl = new databaselogic();

}
public string _username, _password;

public string Username
{
get { return _username; }
set { _username = value; }
}

public string Password
{
get { return _password; }
set { _password = value; }
}

public void loginbll()
{

obj_Bl.login(Username,Password);

}


DAL:

namespace databaselogic
{

public class databaselogic
{
public databaselogic()
{
}
public void login(string username, string password)
{
//code related to Queries goes on here
}
}
}
"PostBack is the name given to the process of submitting an ASP.NET page to the server for processing ."



protected void Page_Load(object sender, EventArgs e)
{
   if (IsPostBack)
   {
        ClientScript.RegisterHiddenField("hdnPostBack", "1");
   }
 }




$(document).ready(function () {

    var isPostBackOccured = document.getElementById('hdnPostBack');
    if (isPostBackOccured== null) alert('Page is called first Time');
    else alert('Page is called after Postback');
});
@{
    Layout = null;
}

<!DOCTYPE html>
<html>
<head>
<title>Main Page</title>
<link href="@Href("../../Content/styles/Style.css")" rel="stylesheet" type="text/css" />
</head><body>
<div class="header">This is header text.</div>
<h1>Index Page Content</h1>
@Html.ActionLink("Content", "Content1", "Helper")
@Html.ActionLink("MultiSection Content", "Content2", "Helper")
@Html.ActionLink("Passing Data", "Content3", "Helper")
<p>This is the content of the main page.</p>
<div class="footer">&copy; 2010 Contoso Pharmaceuticals. All rights reserved.</div>
</body></html>


h1
{
    border-bottom: 3px solid #cc9900;
    font: 2.75em/1.75em Georgia, serif;
    color: #996600;
}
ul
{
    list-style-type: none;
}
body
{
    margin: 0;
    padding: 1em;
    background-color: #ffffff;
    font: 75%/1.75em "Trebuchet MS", Verdana, sans-serif;
    color: #006600;
}
#list
{
    margin: 1em 0 7em -3em;
    padding: 1em 0 0 0;
    background-color: #ffffff;
    color: #996600;
    width: 25%;
    float: left;
}
#header, #footer
{
    margin: 0;
    padding: 0;
    color: #996600;
}

@{var dataFilePath = "~/dataFile.txt";
 
 var fileContents = "";
 var physicalPath = Server.MapPath(dataFilePath);
 var userMessage = "Hello world, the time is " + DateTime.Now;
 var userErrMsg = "";
 var errMsg = "";
 if(IsPost)
 {
 // When the user clicks the "Open File" button and posts
 // the page, try to open the created file for reading.
 try {
    // This code fails because of faulty path to the file.
    fileContents = File.ReadAllText(@"K:\batafile.txt");
    // This code works. To eliminate error on page,
    // comment the above line of code and uncomment this one.
    fileContents = File.ReadAllText(physicalPath);
 }
 catch (FileNotFoundException ex)
  {
     // You can use the exception object for debugging, logging, etc.errMsg = ex.Message;
    // Create a friendly error message for users.
    userErrMsg = "A file could not be opened, please contact "+ "your system administrator.";
    }
    catch (DirectoryNotFoundException ex)
    {
    // Similar to previous exception.
    errMsg = ex.Message;
    userErrMsg = "A directory was not found, please contact "+ "your system administrator.";
    }
 }
 else
 {
     // The first time the page is requested, create the text file.
     File.WriteAllText(physicalPath, userMessage);
 }
 }

 <!DOCTYPE html>
 <html lang="en">
 <head><meta charset="utf-8" />
 <title>Try-Catch Statements</title>
 </head><body>
 <form method="post" action="" >
 <input type="submit" name="Submit" value="Open File"/>
 </form>
 <p>@fileContents</p>
 <p>@userErrMsg</p>
 </body>
 </html>
Objects and Collections
Page Objects
The most basic object in ASP.NET is the page. You can access properties of the page object directlywithout any qualifying object. The following code gets the page's file path, using the Request object of the page:

        @{var path = Request.FilePath;}
        @path
        @{
        var pageUrl = this.Request.Url;
        }
        <br />
        <a href="@pageUrl">My page</a>
 
/Helper/Objects
My page
Collection Objects (Arrays and Dictionaries)
        @{
        <h3>Team Members</h3>
            string[] teamMembers = {"Matt", "Joanne", "Robert", "Nancy"};
            foreach (var person in teamMembers)
            {
                <p>@person</p>
            }
          }
@{
             <p>The number of names in the teamMembers array: @teamMembers.Length </p>
             <p>Robert is now in position: @Array.IndexOf(teamMembers, "Robert")</p>
             <p>The array item at position 2 (zero-based) is @teamMembers[2]</p>
             <h3>Current order of team members in the list</h3>
              foreach (var name in teamMembers){<p>@name</p>}
            <h3>Reversed order of team members in the list</h3>
              Array.Reverse(teamMembers);
              foreach (var reversedItem in teamMembers){<p>@reversedItem</p>}
            }

Team Members
Matt
Joanne
Robert
Nancy
The number of names in the teamMembers array: 4
Robert is now in position: 2
The array item at position 2 (zero-based) is Robert
Current order of team members in the list
Matt
Joanne
Robert
Nancy
Reversed order of team members in the list
Nancy
Robert
Joanne
Matt
Dictionary

            @{var myScores = new Dictionary<string, int>();
              myScores.Add("test1", 71);
              myScores.Add("test2", 82);
              myScores.Add("test3", 100);
              myScores.Add("test4", 59);}
              <p>My score on test 3 is: @myScores["test3"]%</p>
              @(myScores["test4"] = 79)
              <p>My corrected score on test 4 is: @myScores["test4"]%</p>          


My score on test 3 is: 100%
79 My corrected score on test 4 is: 79%
Conditional Logic and Loops
ASP.NET server code lets you perform tasks based on conditions and write code that repeats statementsa specific number of times (loops).
Testing Conditions
To test a simple condition you use the if statement, which returns true or false based on a test youspecify:


 @{var showToday = true;if(showToday){@DateTime.Today;}}

        @{
            showToday = false;
            if(showToday)
            {
                @DateTime.Today;
            }
            else
            {
                <br />
                <text>Sorry!</text>
            }}



9/13/2012 12:00:00 AM
Sorry!
If else Code
You can add multiple conditions using an else if block:


@{
            var theBalance = 4.99;
           if(theBalance == 0)
           {
                      <p>You have a zero balance.</p>        
           }
            else if (theBalance > 0 && theBalance <= 5)
            {
            <p>Your balance of $@theBalance is very low.</p>
            }
            else
            {
            <p>Your balance is: $@theBalance</p>
            }
            }



Your balance of $4.99 is very low.
Switch case Code
To test a large number of conditions, use a switch block:


 @{
                var weekday = "Wednesday";
                var greeting = "";
                switch (weekday)
                {
                    case "Monday":
                        greeting = "Ok, it's a marvelous Monday";
                        break;
                    case "Tuesday":
                        greeting = "It's a tremendous Tuesday";
                        break;
                    case "Wednesday":
                        greeting = "Wild Wednesday is here!";
                        break;
                    default:
                        greeting = "It's some other day, oh well.";
                        break;
                }
                <p>Since it is @weekday, the message for today is: @greeting</p>
                }



Since it is Wednesday, the message for today is: Wild Wednesday is here!
For Looping Code
 @for(var i = 10; i < 21; i++){<p style="font-size: @(i + "pt")">My font size is now: @i</p>}

My font size is now: 10
My font size is now: 11
My font size is now: 12
My font size is now: 13
My font size is now: 14
My font size is now: 15
My font size is now: 16
My font size is now: 17
My font size is now: 18
My font size is now: 19
My font size is now: 20
For each Looping Code
<ul>@foreach (var myItem in Request.ServerVariables){<li>@myItem</li>}</ul>
ALL_HTTP
ALL_RAW
APPL_MD_PATH
APPL_PHYSICAL_PATH
AUTH_TYPE
AUTH_USER
AUTH_PASSWORD
LOGON_USER
REMOTE_USER
CERT_COOKIE
CERT_FLAGS
CERT_ISSUER
CERT_KEYSIZE
CERT_SECRETKEYSIZE
CERT_SERIALNUMBER
CERT_SERVER_ISSUER
CERT_SERVER_SUBJECT
CERT_SUBJECT
CONTENT_LENGTH
CONTENT_TYPE
GATEWAY_INTERFACE
HTTPS
HTTPS_KEYSIZE
HTTPS_SECRETKEYSIZE
HTTPS_SERVER_ISSUER
HTTPS_SERVER_SUBJECT
INSTANCE_ID
INSTANCE_META_PATH
LOCAL_ADDR
PATH_INFO
PATH_TRANSLATED
QUERY_STRING
REMOTE_ADDR
REMOTE_HOST
REMOTE_PORT
REQUEST_METHOD
SCRIPT_NAME
SERVER_NAME
SERVER_PORT
SERVER_PORT_SECURE
SERVER_PROTOCOL
SERVER_SOFTWARE
URL
HTTP_CONNECTION
HTTP_ACCEPT
HTTP_ACCEPT_ENCODING
HTTP_ACCEPT_LANGUAGE
HTTP_COOKIE
HTTP_HOST
HTTP_REFERER
HTTP_USER_AGENT
HTTP_DNT
While Looping Code
@{var countNum = 0;while (countNum < 50){countNum += 1;<p>Line #@countNum: </p>}}

Line #1:
Line #2:
Line #3:
Line #4:
Line #5:
Line #6:
Line #7:
Line #8:
Line #9:
Line #10:
Line #11:
Line #12:
Line #13:
Line #14:
Line #15:
Line #16:
Line #17:
Line #18:
Line #19:
Line #20:
Line #21:
Line #22:
Line #23:
Line #24:
Line #25:
Line #26:
Line #27:
Line #28:
Line #29:
Line #30:
Line #31:
Line #32:
Line #33:
Line #34:
Line #35:
Line #36:
Line #37:
Line #38:
Line #39:
Line #40:
Line #41:
Line #42:
Line #43:
Line #44:
Line #45:
Line #46:
Line #47:
Line #48:
Line #49:
Line #50:

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <title>Files</title>
</head>
<body>
    <div>
        <h1>The ~ operator: Getting the virtual root</h1>
        @{
            var myImagesFolder = "../../Content/images";
            var myStyleSheet = "../../Content/Site.css";
            }

            <h1>The Server.MapPath method: Converting virtual to physical paths</h1>
            @{var dataFilePath = "~/dataFile.txt";}
            <!-- Displays a physical path C:\Websites\MyWebSite\datafile.txt -->
            <p>@Server.MapPath(dataFilePath)</p>


            <h1>The Href method: Creating paths to site resources</h1>
            <!--This code creates the path "../images/Logo.jpg" in the src attribute. -->
         
            <img src="@Href(myImagesFolder)/Chrysanthemum.jpg" alt="Image" width="100px" height="100px" />
            <br /><br />
            <!-- This produces the same result, using a path with ~ -->
            <img src="@Href("../../Content/images")/Chrysanthemum.jpg" alt="Image" width="100px" height="100px" />
            <!-- This creates a link to the CSS file. -->
            <link rel="stylesheet" type="text/css" href="@Href(myStyleSheet)" />

    </div>
</body>
</html>

Output:

D:\MyProjects\Registrationmvc3PArt2\CabAutomationSystem\CabAutomationSystem\dataFile.txt
@{
    Layout = null;
}

 <!DOCTYPE html>
 <html lang="en">
 <head>
 <title>My Title</title>
 <meta charset="utf-8" />
 <style type="text/css">
     body
     {
         background-color: beige; font-family: Verdana, Arial;margin: 50px;
          }
          form
          {padding: 10px; border-style: solid; width: 250px;}
          </style>
          </head>
          <body>
          <p>
          Enter two whole numbers and then click
          <strong>Add</strong>.</p>
          <form action="" method="post">
          @{
            var total = 0;
            var totalMessage = "";
            if(IsPost)
             {
             @*Retrieve the numbers that the user entered.*@
             var num1 = Request["text1"];
             var num2 = Request["text2"];
             @*Convert the entered strings into integers numbers and add.*@
             total = num1.AsInt() + num2.AsInt();
             totalMessage = "Total = " + total;
             }
             }
          <p>
          <label for="text1">First Number:</label>
          <input type="text" name="text1" />
          </p><p>
          <label for="text2">Second Number:</label>
          <input type="text" name="text2" />
          </p><p>
          <input type="submit" value="Add" />
          </p>
          </form>
          <p>@totalMessage</p>
          </body>
          </html>

1.You add code to a page using @ Character

The @ character starts inline expressions, single statement blocks, and multi-statement blocks:


<!-- Single statement blocks -->
       @{ var total = 7; }
       @{ var myMessage = "Hello World"; }
       <!-- Inline expressions --><p>
       The value of your account is: @total </p>
       <p>The value of myMessage is: @myMessage</p>
       <!-- Multi-statement block -->
       @{
         var greeting = "Welcome to our site!";
         var weekDay = DateTime.Now.DayOfWeek;
         var greetingMessage = greeting + " Today is: " + weekDay;

        }
        <p>The greeting is: @greetingMessage</p>


The value of your account is: 7
The value of myMessage is: Hello World
The greeting is: Welcome to our site! Today is: Thursday
2. You enclose code blocks in braces
A code block includes one or more code statements and is enclosed in braces.:


<!-- Single statement block. -->
        @{ var theMonth = DateTime.Now.Month; }
        <p>The numeric value of the current month: @theMonth</p>
        <!-- Multi-statement block. -->
        @{
            var outsideTemp = 79;
             var weatherMessage = "Hello, it is " + outsideTemp + " degrees.";
          }
                                                                                                                                                                     
        <p>Today's weather: @weatherMessage</p>

The numeric value of the current month: 9
Today's weather: Hello, it is 79 degrees.
3. Inside a block, you end each code statement with a semicolon
Inside a code block, each complete code statement must end with a semicolon. Inline expressions donot end with a semicolon.:
4. You use variables to store values
You can store values in a variable , including strings, numbers, and dates, etc. You create a new variableusing the var keyword. You can insert variable values directly in a page using @ :


<!-- Storing a string -->
         @{ var welcomeMessage = "Welcome, new members!"; }
         <p>@welcomeMessage</p>
         <!-- Storing a date -->
         @{ var year = DateTime.Now.Year; }
         <!-- Displaying a variable -->
         <p>Welcome to our new members who joined in @year!</p>


Welcome, new members!
Welcome to our new members who joined in 2012!
5. You enclose literal string values in double quotation marks
A string is a sequence of characters that are treated as text. To specify a string, you enclose it in doublequotation marks:


@{ var myString = "This is a string literal"; }
          <p>Literal : @myString</p>
          <!-- Embedding a backslash in a string -->
          @{ var myFilePath = @"C:\MyFolder\"; }
          <p>The path is: @myFilePath</p>


          <!-- Embedding double quotation marks in a string -->
          @{ var myQuote = @"The person said: ""Hello, today is Monday."""; }
          <p>@myQuote</p>


Literal : This is a string literal
The path is: C:\MyFolder\
The person said: "Hello, today is Monday."
6. Code is case sensitive
In C#, keywords ( var, true, if ) and variable names are case sensitive.
The following lines of codecreate two different variables, lastName and LastName.
@{var lastName = 'Smith';var LastName = 'Jones';}
If you declare a variable as var lastName = "Smith"; and if you try to reference that variable in yourpage as @LastName , an error results because LastName won't be recognized.
7. Much of your coding involves objects
An object represents a thing that you can program with — a page, a text box, a file, an image, a webrequest, an email message, a customer record (database row), etc.


<table border="1" style="width:400px">
            <tr>
            <td>Requested URL</td>
            <td>Relative Path</td>
            <td>Full Path</td>
            <td>HTTP Request Type</td>
            </tr>
            <tr>
            <td>@Request.Url</td>
            <td>@Request.FilePath</td>
            <td>@Request.MapPath(Request.FilePath)</td>
            <td>@Request.RequestType</td>
            </tr>
            </table>




8. You can write code that makes decisions
A key feature of dynamic web pages is that you can determine what to do based on conditions. Themost common way to do this is with the if statement (and optional else statement).


@{var result = "";
              if(IsPost)
              {
                  result = "This page was posted using the Submit button.";
              }
              else
              {
                  result = "This was the first request for this page.";
              }
              }
              <input type="submit" name="Submit" value="Submit"/>
              <p>@result</p>


This was the first request for this page.

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <title>Time</title>
</head>
<body>
    <div>
        <h1>Hello World Page</h1>
        <p>Hello World !</p>
        <p>The Time is @DateTime.Now</p>
    </div>
</body>
</html>



You can follow the following steps to copy it from GAC (Global Assembly cache):

COPY Microsoft.ReportViewer. ProcessingObjectModel
1. Open a command prompt (select Start/Run and then enter "cmd" and press enter).

2. Type the following command and press enter:

cd C:\WINDOWS\assembly\GAC_MSIL\Microsoft.ReportViewer.ProcessingObjectModel

2 (i) Type 'dir' and press 'enter'. You would be able to see the following folder:
It depends on which version you have on your system. It can be either 8.0.0.0 OR 9.0.0.0.

8.0.0.0__b03f5f7f11d50a3a OR
9.0.0.0__b03f5f7f11d50a3a

2(ii). Type "cd 8.0.0.0__b03f5f7f11d50a3a" if you have 8.0.0.0 version OR
"cd 9.0.0.0__b03f5f7f11d50a3a" if you have 9.0.0.0 and press 'enter'.

2(iii). You should be able to see the following DLL in this folder:
Microsoft.ReportViewer.ProcessingObjectModel.dll

2(iv). Now use the following command to copy the dll file to your bin directory:
copy *.dll d:\YourProject\bin


3. COPY Microsoft.ReportViewer.Common
cd C:\WINDOWS\assembly\GAC_MSIL\Microsoft.ReportViewer.Common

3 (i) Type 'dir' and press 'enter'. You would be able to see the following folder:
It depends on which version you have on your system. It can be either 8.0.0.0 OR 9.0.0.0.

8.0.0.0__b03f5f7f11d50a3a OR
9.0.0.0__b03f5f7f11d50a3a

3(ii). Type "cd 8.0.0.0__b03f5f7f11d50a3a" if you have 8.0.0.0 version in step 3 OR
"cd 9.0.0.0__b03f5f7f11d50a3a" if you have 9.0.0.0 and press 'enter'.

3(iii). You should be able to see the following DLL in this folder:
Microsoft.ReportViewer.Common.dll

3(iv). Now use the following command to copy the dll file to your bin directory:
copy *.dll d:\YourProject\bin

Here the path shown in red color should be the path of your project's bin folder.

View


@model DatePickerTemp.Models.FooEditModel
@{
    ViewBag.Title = "Edit";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>
    Edit</h2>
@Model.Message
@using (Html.BeginForm())
{
    @Html.EditorFor(m => m.Foo)
    <input id="submit" name="submit" type="submit" value="Save" />
}

Models


using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using DatePickerTemp.Infrastructure;

namespace DatePickerTemp.Models
{
    public class Foo
    {
        public string Name { get; set; }

        [DataType(DataType.Date)]
        public DateTime Date1 { get; set; }

        [DateRange(Min = "2010/12/02")]
        public DateTime Date2 { get; set; }

        [DateRange(Max = "2010/12/20")]
        public DateTime Date3 { get; set; }

        [DateRange(Min = "2010/12/02", Max = "2010/12/20")]
        public DateTime Date4 { get; set; }
    }
}



namespace DatePickerTemp.Models
{
    public class FooEditModel
    {
        public string Message { get; set; }
        public Foo Foo { get; set; }
    }
}
DatePicker.zip

Model


  public DataSet displayPageLoad(Int64 opt6)
        {
            if (cn.State == ConnectionState.Open)
                cn.Close();
            cn.Open();
            ds = new DataSet();
            ds.Clear();
            SqlDataAdapter ad;
            sqlcmd = new SqlCommand();
            sqlcmd.Parameters.Clear();
            sqlcmd.Connection = cn;
            sqlcmd.CommandType = CommandType.StoredProcedure;
            sqlcmd.CommandText = "Outgoing_Calls_SP";
            sqlcmd.Parameters.AddWithValue("@opt", opt6);
            sqlcmd.Parameters.AddWithValue("@telecom_id", "");
            sqlcmd.Parameters.AddWithValue("@datee", "");
            sqlcmd.Parameters.AddWithValue("@timee_from", "");
            sqlcmd.Parameters.AddWithValue("@timee_to", "");
            sqlcmd.Parameters.AddWithValue("@contact_number", "");
            sqlcmd.Parameters.AddWithValue("@contact_person", "");
            sqlcmd.Parameters.AddWithValue("@communication_msg", "");
            sqlcmd.Parameters.AddWithValue("@response_msg", "");
            sqlcmd.Parameters.AddWithValue("@dept", "");
            sqlcmd.Parameters.AddWithValue("@callername", "");
            sqlcmd.Parameters.AddWithValue("@branch", "");
            sqlcmd.Parameters.AddWithValue("@status", "");
            sqlcmd.Parameters.AddWithValue("@alerttime", "");
            sqlcmd.Parameters.AddWithValue("@alert", "");
            sqlcmd.Parameters.AddWithValue("@cid", "");
            sqlcmd.Parameters.AddWithValue("@deptmanager", "");
            ad = new SqlDataAdapter(sqlcmd);
            ad.Fill(ds);
            return ds;
        }
        public List<IDictionary> FetchOutgoingDetails()
        {
            DataSet dsEmployee = new DataSet();
            Int64 opt6 = 6;
            dsEmployee = displayPageLoad(opt6);

            return ConvertToDictionary(dsEmployee.Tables[0]);
        }
        private List<IDictionary> ConvertToDictionary(DataTable dtObject)
        {
            var columns = dtObject.Columns.Cast<DataColumn>();

            var dictionaryList = dtObject.AsEnumerable()
                .Select(dataRow => columns
                    .Select(column =>
                        new { Column = column.ColumnName, Value = dataRow[column] })
                             .ToDictionary(data => data.Column, data => data.Value)).ToList().ToArray();

            return dictionaryList.ToList<IDictionary>();
        }

Controller


 public ActionResult OutgoingList(CabAutomationSystem.Models.Outgoing outgoinglist)
        {
            var resultSet = outgoinglist.FetchOutgoingDetails();
            return View(resultSet);
        }

View


@{
    ViewBag.Title = "OutgoingList";
    Layout = "~/Views/Admin/Master.cshtml";
}

<h2>OutgoingList</h2>

@section Styles
{
<link href="@Url.Content("~/Content/grid.css")" rel="stylesheet" type="text/css" />
}

@{
          ViewBag.Title = "List";
    }

    @using System.Dynamic
@model List<System.Collections.IDictionary>
@{
    var result = new List<dynamic>();

    foreach (var emprow in Model)
    {
        var row = (IDictionary<string, object>)new ExpandoObject();
        Dictionary<string, object> eachEmpRow = (Dictionary<string, object>)emprow;

        foreach (KeyValuePair<string, object> keyValuePair in eachEmpRow)
        {
            row.Add(keyValuePair);
        }
        result.Add(row);
    }

}

@{

    var grid = new WebGrid(source: result,
                                           defaultSort: "telecom_id",
                                           rowsPerPage:5, fieldNamePrefix:"wg_",
                                           canPage:true,canSort:true,
                                           pageFieldName:"pg",sortFieldName:"srt"
                                           );
 }

 <table cellpadding="0" cellspacing="0" width="100%">
    <tr>
        <td>
            @grid.GetHtml(tableStyle:"listing-border",headerStyle:"gridhead",footerStyle:"paging",rowStyle:"td-dark",alternatingRowStyle:"td-light",
                            columns:
                                grid.Columns(
                                grid.Column(header:"", format: @<text><input id="chk" type="checkbox" value="@item.telecom_id" /></text>),
                                    grid.Column("datee", "Date", style: "colFirstName"),
                                    grid.Column("timee_from", "Time from", style: "colLastName"),
                                    grid.Column("timee_to", "Time to", style: "colPhone"),
                                    grid.Column("contact_number", "Contact Number", style: "colEmail"),
                                    grid.Column("contact_person", "Contact Person", style: "colContactType"),
                                    grid.Column(header: "Edit", format: @<text><a href="@Url.Action("Edit", "Contact", new { id = item.telecom_id })" ><img src="../../Content/images/Edit.jpg" alt="" style="border:none;" /></a></text>, style: "colOperation"),
                                    grid.Column(header: "Delete", format: @<text><a href="@Url.Action("Delete", "Contact", new { id = item.telecom_id })" onclick="javascript:return ConfirmDelete();"><img src="../../Content/images/delete.jpg" alt="" style="border:none;" /></a></text>, style: "colOperation")
                                ),mode:WebGridPagerModes.Numeric)
        </td>
    </tr>
 </table>
<script type="text/javascript">
    function ConfirmDelete() {
        return confirm("Are you sure you want to delete contacts?");
    }
</script>



CSS


.listing-border { background: #fd7d0f;}
.gridhead { background:#FFAA5F;  font: bold 13px Arial, Helvetica, sans-serif; color:#000000; text-decoration: none; height: 27px; text-align: left;}
.gridhead th a {text-decoration:none;color:#000000;}
.gridhead th a:hover {text-decoration:underline;color:#FF0000;}
.td-dark { background: #ffffff; height: 20px; }
.td-light { background: #FFE2BF; height: 20px; }
.paging { background: #fd7d0f;text-align: right;color:#000000;}
.paging span { font: bold 12px Arial, Helvetica, sans-serif; color:#FFFFFF; margin-right: 3px; padding: 1px 3px 1px 3px }
.paging a { font: bold 12px Arial, Helvetica, sans-serif; color:#000000; text-decoration: none; margin-right: 3px; border: 1px solid #ffffff; background: #fd7d0f; padding: 1px 3px 1px 3px }
.paging a:hover { font: bold 12px Arial, Helvetica, sans-serif; color:#000000; text-decoration: none; border: 1px solid #ffffff; background: #ffffff; }
.colFirstName{width:18%;text-align:left;}
.colLastName{width:18%;text-align:left;}
.colPhone{width:14%;text-align:left;}
.colEmail{width:19%;text-align:left;}
.colContactType{width:18%;text-align:left;}
.colOperation{width:50px;text-align:center;}

Objects and Collections

Objects and Collections
Page Objects
The most basic object in ASP.NET is the page. You can access properties of the page object directlywithout any qualifying object. The following code gets the page's file path, using the Request object of the page:

        @{var path = Request.FilePath;}
        @path
        @{
        var pageUrl = this.Request.Url;
        }
        <br />
        <a href="@pageUrl">My page</a>
 
/Helper/Objects
My page
Collection Objects (Arrays and Dictionaries)
        @{
        <h3>Team Members</h3>
            string[] teamMembers = {"Matt", "Joanne", "Robert", "Nancy"};
            foreach (var person in teamMembers)
            {
                <p>@person</p>
            }
          }
@{
             <p>The number of names in the teamMembers array: @teamMembers.Length </p>
             <p>Robert is now in position: @Array.IndexOf(teamMembers, "Robert")</p>
             <p>The array item at position 2 (zero-based) is @teamMembers[2]</p>
             <h3>Current order of team members in the list</h3>
              foreach (var name in teamMembers){<p>@name</p>}
            <h3>Reversed order of team members in the list</h3>
              Array.Reverse(teamMembers);
              foreach (var reversedItem in teamMembers){<p>@reversedItem</p>}
            }

Team Members
Matt
Joanne
Robert
Nancy
The number of names in the teamMembers array: 4
Robert is now in position: 2
The array item at position 2 (zero-based) is Robert
Current order of team members in the list
Matt
Joanne
Robert
Nancy
Reversed order of team members in the list
Nancy
Robert
Joanne
Matt
Dictionary

            @{var myScores = new Dictionary<string, int>();
              myScores.Add("test1", 71);
              myScores.Add("test2", 82);
              myScores.Add("test3", 100);
              myScores.Add("test4", 59);}
              <p>My score on test 3 is: @myScores["test3"]%</p>
              @(myScores["test4"] = 79)
              <p>My corrected score on test 4 is: @myScores["test4"]%</p>          


My score on test 3 is: 100%
79 My corrected score on test 4 is: 79%
Private Sub dgvSubscriptions_RowPostPaint(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewRowPostPaintEventArgs) Handles dgvSubscriptions.RowPostPaint
        Try
            ' Dim b As SolidBrush = New SolidBrush(dgvSubscriptions.RowHeadersDefaultCellStyle.ForeColor)

            'e.Graphics.DrawString((e.RowIndex + 1).ToString(), e.InheritedRowStyle.Font, b, e.RowBounds.Location.X + 10, e.RowBounds.Location.Y + 4)
            Dim dg As DataGridView = DirectCast(sender, DataGridView)
            ' Current row record

            Dim rowNumber As String = String.Empty
            rowNumber = (e.RowIndex + 1).ToString()



            ' Format row based on number of records displayed by using leading zeros
            While rowNumber.Length < dg.RowCount.ToString().Length
                rowNumber = "0" & rowNumber
            End While

            ' Position text
            Dim size As SizeF = e.Graphics.MeasureString(rowNumber, Me.Font)
            If dg.RowHeadersWidth < CInt(size.Width + 20) Then
                dg.RowHeadersWidth = CInt(size.Width + 20)
            End If

            ' Use default system text brush
            Dim b As Brush = SystemBrushes.ControlText


            ' Draw row number
            e.Graphics.DrawString(rowNumber, dg.Font, b, e.RowBounds.Location.X + 15, e.RowBounds.Location.Y + ((e.RowBounds.Height - size.Height) / 2))
        Catch ex As Exception
            Utils.LogHandler.HandleError(ex)
        End Try
    End Sub





videourl = dt.Rows[0]["videourl"].ToString();
                        axWindowsMediaPlayer1.URL = videourl;
                        axWindowsMediaPlayer1.settings.rate = 1.0;
                        axWindowsMediaPlayer1.Ctlcontrols.play();
                        //axWindowsMediaPlayer1.settings.setMode("loop", true);


private void axWindowsMediaPlayer1_PlayStateChange(object sender, AxWMPLib._WMPOCXEvents_PlayStateChangeEvent e)
        {
            try
            {
                if (axWindowsMediaPlayer1.playState == WMPLib.WMPPlayState.wmppsMediaEnded)
                {
                    ShowImage(Files[selected], pictureBox);
                    timer2.Enabled = true;
                    pictureBox.Visible = true;
                    axWindowsMediaPlayer1.Visible = false;
                    axWindowsMediaPlayer1.Ctlcontrols.stop();
                }
                else if (axWindowsMediaPlayer1.playState == WMPLib.WMPPlayState.wmppsStopped)
                {
                }
            }
            catch (Exception ex)
            {
                Utils.LogHandler.HandleError(ex);
            }
        }  
   string[] Files;

                              var root = Application.ExecutablePath;

                                var temp = root.Split('\\');
                                temp[temp.Length - 1] = "";
                                temp[temp.Length - 2] = "Images";
                                var newpath = string.Join("\\", temp);
                                Files = Directory.GetFiles(newpath);

/// <summary>
        /// Show the image in the PictureBox.
        /// </summary>
        public static void ShowImage(string path, PictureBox pct)
        {
            pct.ImageLocation = path;
        }

        /// <summary>
        /// Show the next image.
        /// </summary>
        private void ShowNextImage()
        {
            ShowImage(this.Files[(++this.selected) % this.Files.Length], this.pictureBox);
        }

private void btnBrowseimage_Click(object sender, EventArgs e)
        {
            try
            {
             
                btnSubmit.Enabled = false;
                gbLabels.Visible = false;
                gbLabels.BackgroundImage = null;

                OpenFileDialog fDialog = new OpenFileDialog();
                fDialog.AddExtension = true;
                fDialog.CheckFileExists = true;
                fDialog.CheckPathExists = true;
                fDialog.Title = "Open Image Files";
                fDialog.Filter = "All files (*.*)|*.*|JPEG Files|*.jpeg|GIF Files|*.gif";
                fDialog.InitialDirectory = @"C:\";
                fDialog.Multiselect = true;
                if (fDialog.ShowDialog() == DialogResult.OK)
                {

                    imageFiles = fDialog.FileNames;
                    Files = new string[imageFiles.Length];
                    for (int j = 0; j <= imageFiles.Length - 1; j++)
                    {
                        System.Drawing.Image im = System.Drawing.Image.FromFile(imageFiles[j]);
                        int ActualWidth = im.Width;
                        int ActualHeight = im.Height;
                        im.Dispose();
                        if (ActualWidth > 3600 && ActualHeight > 2400)
                        {
                            MessageBox.Show("Please upload image with size less than  3600X2400", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                        else
                        {

                            txtImageName.Text = imageFiles[j];
                            FileStream fssource = new FileStream(txtImageName.Text, FileMode.Open);

                            var root1 = txtImageName.Text;
                            var temp1 = root1.Split('\\');
                            var image = temp1[temp1.Length - 1];

                            var root = Application.ExecutablePath;

                            var temp = root.Split('\\');
                            temp[temp.Length - 1] = "";
                            temp[temp.Length - 2] = "Images";
                            var newpath = string.Join("\\", temp);



                            bool folderExists = Directory.Exists(newpath);
                            if (!folderExists)
                                Directory.CreateDirectory(newpath);


                            newpath = newpath + "_" + DateTime.Now.Hour + DateTime.Now.Minute + DateTime.Now.Second + "ReceiptionBack" + "." + image.Split('.')[1];



                            txtImageName.Text = newpath;
                            Files[j] = txtImageName.Text;

                            FileStream fsdest = new FileStream(newpath, FileMode.Create);
                            while (true)
                            {
                                int i;
                                i = fssource.ReadByte();
                                if (i == -1)
                                    break;
                                fsdest.WriteByte(Convert.ToByte(i));
                            }
                            fsdest.Close();
                        }

                    }

                }
                btnSubmit.Enabled = true;


            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

private void btnfont_Click(object sender, EventArgs e)
        {
            try
            {
                if (fontDialog1.ShowDialog() == DialogResult.OK)
                {
                    Font font = fontDialog1.Font;


                    TypeConverter tc = TypeDescriptor.GetConverter(typeof(Font));
                    string fontString = tc.ConvertToString(font);

                 
                    txtFont.Text = fontString;
                }
            }
            catch (Exception ex)
            {
                Utils.LogHandler.HandleError(ex);
            }
        }

private void btnColor_Click(object sender, EventArgs e)
        {
            try
            {
                if (colorDialog1.ShowDialog() == DialogResult.OK)
                {
                    string color = colorDialog1.Color.ToArgb().ToString("x");
                    //color = color.Substring(2, 6);
                    //color = "#" + color;

                    txtColor.Text = color;
                }
            }
            catch (Exception ex)
            {
                Utils.LogHandler.HandleError(ex);
            }
        }

private void btnpreview_Click(object sender, EventArgs e)
        {
            try
            {
                dt = cs.getTable("select * from [View] where hall='Receiption'", con.con.ConnectionString.ToString());
                if (dt.Rows.Count > 0)
                {
                    Image im = Bitmap.FromFile(dt.Rows[0]["image"].ToString());
                    gbLabels.BackgroundImage = im;

                    TypeConverter converter = TypeDescriptor.GetConverter(typeof(Font));
                    // Saving Font object as a string
                    string fontString = dt.Rows[0]["font"].ToString();
                    string scrollfontString = dt.Rows[0]["scrollfont"].ToString();
                    // Load an instance of Font from a string
                    Font fon = (Font)converter.ConvertFromString(fontString);
                    Font scrollfon = (Font)converter.ConvertFromString(fontString);
                    string color = dt.Rows[0]["color"].ToString();
                    string scrollcolor = dt.Rows[0]["scrollcolor"].ToString();
                    Color col = System.Drawing.ColorTranslator.FromHtml("#" + color);
                    Color scrollcol = System.Drawing.ColorTranslator.FromHtml("#" + scrollcolor);

                    lblEventName.Font = fon;
                    lblEventName.ForeColor = col;
                    lblnotes.Font = fon;
                    lbltime.Font = fon;
                    label2.Font = fon;
                    label1.Font = fon;
                    lblnotes.ForeColor = col;
                    lbltime.ForeColor = col;
                    label2.ForeColor = col;
                    label1.ForeColor = col;
                    dougScrollingTextCtrl1.DougScrollingTextColor1 = scrollcol;
                    dougScrollingTextCtrl1.Font = scrollfon;
                    gbLabels.Visible = true;

                }
            }
            catch (Exception ex)
            {
                Utils.LogHandler.HandleError(ex);
            }
        }

This summary is not available. Please click here to view the post.

 if (fupimage.HasFile)
            {
                //getting length of uploaded file
                int length = fupimage.PostedFile.ContentLength;
                //create a byte array to store the binary image data
                imgbyte = new byte[length];
                //store the currently selected file in memeory
                HttpPostedFile img = fupimage.PostedFile;
                //set the binary data
                img.InputStream.Read(imgbyte, 0, length);
                string imagename = fupimage.PostedFile.FileName;
                //use the web.config to store the connection string            
            }
            else
            {        

                string fpath = Server.MapPath("~//images//face.gif");
                System.IO.FileInfo imageInfo = new System.IO.FileInfo(fpath);            
                imgbyte = new byte[imageInfo.Length];
                System.IO.FileStream imagestream = imageInfo.OpenRead();
                imagestream.Read(imgbyte, 0, imgbyte.Length);
                imagestream.Close();

            }


            cmd.Parameters.Add("@photo", SqlDbType.Image).Value = imgbyte;



Definition and Usage

The DATE_FORMAT() function is used to display date/time data in different formats.

Syntax

DATE_FORMAT(date,format)
Where date is a valid date and format specifies the output format for the date/time.

The formats that can be used are:

Format Description
%a Abbreviated weekday name
%b Abbreviated month name
%c Month, numeric
%D Day of month with English suffix
%d Day of month, numeric (00-31)
%e Day of month, numeric (0-31)
%f Microseconds
%H Hour (00-23)
%h Hour (01-12)
%I Hour (01-12)
%i Minutes, numeric (00-59)
%j Day of year (001-366)
%k Hour (0-23)
%l Hour (1-12)
%M Month name
%m Month, numeric (00-12)
%p AM or PM
%r Time, 12-hour (hh:mm:ss AM or PM)
%S Seconds (00-59)
%s Seconds (00-59)
%T Time, 24-hour (hh:mm:ss)
%U Week (00-53) where Sunday is the first day of week
%u Week (00-53) where Monday is the first day of week
%V Week (01-53) where Sunday is the first day of week, used with %X
%v Week (01-53) where Monday is the first day of week, used with %x
%W Weekday name
%w Day of the week (0=Sunday, 6=Saturday)
%X Year of the week where Sunday is the first day of week, four digits, used with %V
%x Year of the week where Monday is the first day of week, four digits, used with %v
%Y Year, four digits
%y Year, two digits

Example

The following script uses the DATE_FORMAT() function to display different formats. We will use the NOW() function to get the current date/time:

DATE_FORMAT(NOW(),'%b %d %Y %h:%i %p')
DATE_FORMAT(NOW(),'%m-%d-%Y')
DATE_FORMAT(NOW(),'%d %b %y')
DATE_FORMAT(NOW(),'%d %b %Y %T:%f')
The result would look something like this:

Nov 04 2008 11:45 PM
11-04-2008
04 Nov 08
04 Nov 2008 11:45:34:243