Tuesday 30 August 2016

How to display database records in asp.net mvc view

1. First create a Model that will hold the values of the record. for instance:
public class Student
{
    public string FirstName {get;set;}
    public string LastName {get;set;}
    public string Class {get;set;}
    ....
}
2. Then load the rows from your reader to a list or something:
public ActionResult Students()
{
    String connectionString = "<THE CONNECTION STRING HERE>";
    String sql = "SELECT * FROM students";
    SqlCommand cmd = new SqlCommand(sql, conn);

    using(SqlConnection conn = new SqlConnection(connectionString))
    {
        conn.Open();
        SqlDataReader rdr = cmd.ExecuteReader();
        var model = new List<Student>();
        while(rdr.Read())
        {
            var student = new Student();
            student.FirstName = rdr["FirstName"];
            student.LastName = rdr["LastName"];
            student.Class = rdr["Class"];
            ....

            model.Add(student);
        }

    }

    return View(model);
}
3. Lastly in your View, declare the kind of your model:
@model List<Student>

<h1>Student</h1>

<table>
    <tr>
        <th>First Name</th>
        <th>Last Name</th>
        <th>Class</th>
    </tr>
    @foreach(var student in Model)
    {
    <tr>
        <td>@student.FirstName</td>  
        <td>@student.LastName</td>  
        <td>@student.Class</td>  
    </tr>
    }
</table>

Tuesday 23 August 2016

Dropdown menu in MVC4 using Bootstrap

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Menu</title>
  <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
  <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
    <nav class="navbar navbar-inverse" style="background-color:#808080;">
  <div class="container-fluid">
    <div class="navbar-header">
      <a class="navbar-brand" href="#">WebSiteName</a>
    </div>
    <ul class="nav navbar-nav" >
      <li class="active">@Html.ActionLink("Home","Home","TestHome")</li>
      <li class="dropdown"><a class="dropdown-toggle" data-toggle="dropdown" href="#">Child Detail <span class="caret"></span></a>
        <ul class="dropdown-menu">
          <li>@Html.ActionLink("New Child Registration","NewChildRegistration","TestHome")</li>
          <li>@Html.ActionLink("Update Detail","UpdateDetail","TestHome")</li>
          <li>@Html.ActionLink("Total","Total","TestHome")</li>
        </ul>
      </li>
      <li><a href="#">Page 2</a></li>
      <li><a href="#">Page 3</a></li>
    </ul>
  </div>
</nav>
 
<div class="container">
  <h3>Navbar With Dropdown</h3>
  <p>This example adds a dropdown menu for the "Page 1" button in the navigation bar.</p>
</div>
</body>
</html>

Thursday 11 August 2016

Difference between DateTime and DateTime2 DataType

DateTime2 is the new Data Type introduced in Sql Server 2008 for storing Date and Time value. As per MSDN, Microsoft Suggests to use this new Data Type for new work instead of DateTime.
Following table summarizes some of the major difference between this new DateTime2 and the old DateTime Data Type.

DateTime DateTime2[(n)]
Min Value 1753-01-01 00:00:00 0001-01-01 00:00:00
Max Value 9999-12-31 23:59:59.997 9999-12-31 23:59:59.9999999
Storage Size 8 Bytes 6 to 8 bytes
Note: Parameter n is optional and if it is not specified then fractional
seconds precision is 7 digit and it can be from 0 to 7 digit. For fractional seconds
precision <3, takes 6 bytes For fractional seconds precision 3 or 4 it will take
7 bytes For fractional seconds precision >4 it will take 8 bytes
Usage Declare @now datetime Declare @now datetime2(7)
Compliance Is not an ANSI/ISO compliant Is an ANSI/ISO compliant
Current Date and Time function GetDate() – It returns DB Current Date and Time of DateTime Data Type Example: SELECT GETDATE() Result: 2011-09-16 13:23:18.767 SYSDATETIME()– It returns DB Current Date and Time of DateTime2 Data Type Example:SELECT SYSDATETIME() Result: 2011-09-16 13:23:18.7676720
+/- days WORKS Example:
DECLARE
@nowDateTime DATETIME = GETDATE() SELECT @nowDateTime + 1
Result: 2011-09-17 13:44:31.247
FAILS – Need to use only DateAdd function Example:
DECLARE
@nowDateTime2 DATETIME2=
SYSDATETIME()
SELECT
@nowDateTime2+1
Result: Msg 206, Level 16, State 2, Line 2
Operand type clash: datetime2 is incompatible with int
DateTime2 with fractional seconds precision of 3 is same as DateTime data type. And DateTime2(3) uses 7 bytes of storage instead of 8 byte which old DateTime datatype uses and it also provides higher date range (i.e. 0001-01-01 to 9999-12-31 ) compared to DateTime data type. Now let us see this with an example:
DECLARE @nowDateTime DATETIME = GETDATE(),
        @nowDateTime2 DATETIME2(3)= SYSDATETIME()
 
SELECT DATALENGTH(@nowDateTime) 'DateTime Storage Size',
       DATALENGTH(@nowDateTime2) 'DateTime2(3) Storage Size'
Result:
DateTime Storage Size  DateTime2 Storage Size
 --------------------- ----------------------
 8                     7

Difference Between Sql Server VARCHAR and VARCHAR(MAX) Data Type

Ideally, it is better to compare Text and Varchar(MAX) data types, as in Sql Server 2005 Varchar(MAX) data type was introduced as an alternate for Text data type. Varchar(Max) data type provides multiple advantages over Text data type.
Like many initially when Varchar(MAX) datatype was introduced in Sql Server 2005, I too was not clear about the difference between Varchar and Varchar(Max) and which one to use when. Hope the differences listed in the below table clarifies these queries.

Varchar[(n)] Varchar(Max)
Basic Definition Non-Unicode Variable Length character data type.Example: DECLARE @FirstName AS VARCHAR(50) = ‘BASAVARAJ’
SELECT @FirstName
Non-Unicode large Variable Length character data type.Example: DECLARE @FirstName AS VARCHAR(Max)= ‘BASAVARAJ’
SELECT @FirstName
 Storage Capacity It can store maximum 8000 Non-Unicode characters (i.e. maximum storage capacity is 8000 bytes of storage). Optional Parameter n value can be from 1 to 8000. It can store maximum of 2 147 483 647 Non-Unicode characters (i.e. maximum storage capacity is: 2GB).
Index? You can create index on Varchar column data type. Example: CREATE TABLE dbo.Employee (id INT identity(1,1) PRIMARY KEY, FirstName VARCHAR(50)) GO CREATE INDEX IX_EmployeeFirstName ON dbo.Employee(FirstName) GO Index can’t be created on a Varchar(Max) data type columns. Example: CREATE TABLE dbo.Employee (id INT identity(1,1) PRIMARY KEY, FirstName VARCHAR(Max)) GO CREATE INDEX IX_EmployeeFirstName ON dbo.Employee(FirstName) GO 
Error Message:
Msg 1919, Level 16, State 1, Line 1 Column ‘FirstName’ in table ‘dbo.Employee’ is of a type that is invalid for use as a key column in an index.
How data is stored Physically? It uses the normal data pages to store the data i.e. it stores the value ‘in a row’. Sql server will try to store the value ‘in a row’ but if it could not then it will store the value ‘out of row’. i.e. It uses the normal data pages until the content actually fills 8k of data.When overflow happens, data is stored as old TEXT Data Type and a pointer is replacing the old content.
No. of Bytes required for each character It takes 1 byte per character Example:
DECLARE
@FirstName AS VARCHAR(50) = ‘BASAVARAJ’
SELECT @FirstName AS FirstNameDATALENGTH(@FirstName) AS Length

Result:
FirstName Length
BASAVARAJ 9
It takes 1 byte per characterExample:
DECLARE
@FirstName AS VARCHAR(MAX)= ‘BASAVARAJ’
SELECT @FirstName AS FirstNameDATALENGTH(@FirstName) AS Length
Result:
FirstName Length
BASAVARAJ 9
Which one to use? If we know that data to be stored in the column or variable is less than or equal to 8000 characters, then we can use this data type.For example First Name, Last Name etc, columns value can’t cross the max 8000 characters limit, in such scenario’s it is better to use this data type. If we know that the data to be stored in the column or variable can cross a 8KB Data page, then we can use this data type.
Performance There is not much performance difference between Varchar[(n)] and Varchar(Max). Varchar[(n)] provides better performance results compared to Varchar(Max). If we know that data to be stored in the column or variable is less than or equal to 8000 characters, then using this Varchar[(n)]  data type provides better performance compared to Varchar(Max).Example: When I ran the below script by changing the variable @FirstName type to Varchar(Max) then for 1 million assignments it is consistently taking double time than when we used data type as Varchar(50) for variable @ FirstName. DECLARE @FirstName VARCHAR(50), @COUNT INT=0, @StartTime DATETIME = GETDATE() WHILE(@COUNT < 1000000) BEGIN SELECT @FirstName = ‘BASAVARAJ’, @COUNT = @COUNT +1 END SELECT DATEDIFF(ms,@StartTime,GETDATE()) ‘Time Taken in ms’ GO 6
Note: Here GO 6 statement executes the statements above it 6 times.

Difference Between Sql Server VARCHAR and NVARCHAR Data Type

Below table lists out the major difference between the VARCHAR and NVARCHAR Data Type in Sql Server:

Varchar[(n)] NVarchar[(n)]
Basic Definition Non-Unicode Variable Length character data type.
Example:
DECLARE @FirstName AS VARCHAR(50) =‘BASAVARAJ’ SELECT @FirstName
UNicode Variable Length character data type. It can store both non-Unicode and Unicode (i.e. Japanese, Korean etc) characters.
Example:
DECLARE @FirstName AS NVARCHAR(50)= ‘BASAVARAJ’ SELECT @FirstName
No. of Bytes required for each character It takes 1 byte per character Example:
DECLARE
@FirstName AS VARCHAR(50) = ‘BASAVARAJ’
SELECT @FirstName AS FirstName, DATALENGTH(@FirstName) AS
Length
Result:
FirstName Length
BASAVARAJ 9
It takes 2 bytes per Unicode/Non-Unicode character.
Example:
DECLARE
@FirstName AS NVARCHAR(50)= ‘BASAVARAJ’
SELECT @FirstName AS FirstName, DATALENGTH(@FirstName) AS Length
Result:
FirstName Length
BASAVARAJ 18
Optional Parameter n range Optional Parameter n value can be from 1 to 8000.Can store maximum 8000 Non-Unicode characters. Optional Parameter n value can be from 1 to 4000.Can store maximum 4000 Unicode/Non-Unicode characters
If Optional Parameter n is not specified in the variable declaration or column definition If Optional parameter value n is not specified in the variable declaration or column definition then it is considered as 1.
Example:
DECLARE
@firstName VARCHAR = ‘BASAVARAJ’
SELECT
@firstName FirstName, DATALENGTH(@firstName) Length

Result:
FirstName Length
B 1
If Optional parameter value n is not specified in the variable declaration or column definition then it is considered as 1.
Example:
DECLARE @firstName NVARCHAR = ‘BASAVARAJ’ SELECT
@firstName FirstName, DATALENGTH(@firstName) Length

Result:
FirstName Length
B 2
If Optional Parameter n is not
specified in while using
CAST/ CONVERT functions
When this optional parameter n is not specified while using the CAST/CONVERT functions, then it is considered as 30.Example: DECLARE @firstName VARCHAR(35) =
‘BASAVARAJ PRABHU BIRADAR INDIA ASIA’
SELECT CAST(@firstName AS VARCHAR) FirstName,
DATALENGTH
(CAST(@firstName AS VARCHAR)) Length

Result:

FirstName Length
BASAVARAJ PRABHU BIRADAR INDIA 30
When this optional parameter n is not specified while using the CAST CONVERT functions, then it is considered as 30.Example: DECLARE @firstName NVARCHAR(35) =
‘BASAVARAJ PRABHU BIRADAR INDIA ASIA’
SELECT CAST(@firstName AS NVARCHAR) FirstName,
DATALENGTH
(CAST(@firstName AS NVARCHAR)) Length

Result:
FirstName Length
BASAVARAJ PRABHU BIRADAR INDIA 60
Which one to use? If we know that data to be stored in the column or variable doesn’t have any Unicode characters. If we know that the data to be stored in the column or variable can have Unicode characters.
Storage Size Takes no. of bytes equal to the no. of Characters entered plus two bytes extra for defining offset. Takes no. of bytes equal to twice the no. of Characters entered plus two bytes extra for defining offset.
As both of these are variable length datatypes, so irrespective of the length (i.e. optional parameter n value) defined in the variable declaration/column definition it will always take the no. of bytes required for the actual charcters stored. The value of n defines maximum no. of characters that can be stored.

How to display 12 months name in sql server

DECLARE @YEAR INT
SET @YEAR = (SELECT YEAR(GETDATE()))
DECLARE @MONTH INT
SET @MONTH = (SELECT MONTH(GETDATE()))

DECLARE @DT TABLE(ID INT, MONTHNAME NVARCHAR(20))

INSERT INTO @DT SELECT NUMBER AS ID,
   DATENAME(MONTH, CAST(@YEAR*100+NUMBER AS VARCHAR) + '01')  AS MONTHNAME
FROM MASTER.DBO.SPT_VALUES  
WHERE TYPE = 'P' AND 
  NUMBER BETWEEN @MONTH AND 12

INSERT INTO @DT SELECT NUMBER AS ID,
   DATENAME(MONTH, CAST(@YEAR*100+NUMBER AS VARCHAR) + '01')  AS MONTHNAME

FROM MASTER.DBO.SPT_VALUES  
WHERE TYPE = 'P' AND 
  NUMBER BETWEEN 1 AND @MONTH -1

SELECT * FROM @DT