Wednesday, January 29, 2014


I found a blog post about fixing Kerberos problems using a new tool from Microsoft, the Kerberos Configuration Manager for SQL Server. This tool will go through your settings and SPNs and what-not, to help you resolve the problem.

Json to Xml using sqlserver

Execute Below Code

CREATE FUNCTION dbo.fn_parse_json2xml(
    @json    varchar(max)

    DECLARE @output varchar(max), @key varchar(max), @value varchar(max),
        @recursion_counter int, @offset int, @nested bit, @array bit,
        @tab char(1)=CHAR(9), @cr char(1)=CHAR(13), @lf char(1)=CHAR(10);

    --- Clean up the JSON syntax by removing line breaks and tabs and
    --- trimming the results of leading and trailing spaces:
    SET @json=LTRIM(RTRIM(
        REPLACE(REPLACE(REPLACE(@json, @cr, ''), @lf, ''), @tab, '')));

    --- Sanity check: If this is not valid JSON syntax, exit here.
    IF (LEFT(@json, 1)!='{' OR RIGHT(@json, 1)!='}')
        RETURN '';

    --- Because the first and last characters will, by definition, be
    --- curly brackets, we can remove them here, and trim the result.
    SET @json=LTRIM(RTRIM(SUBSTRING(@json, 2, LEN(@json)-2)));

    SELECT @output='';
    WHILE (@json!='') BEGIN;

        --- Look for the first key which should start with a quote.
        IF (LEFT(@json, 1)!='"')
            RETURN 'Expected quote (start of key name). Found "'+
                LEFT(@json, 1)+'"';

        --- .. and end with the next quote (that isn't escaped with
        --- and backslash).
        SET @key=SUBSTRING(@json, 2,
            PATINDEX('%[^\\]"%', SUBSTRING(@json, 2, LEN(@json))+' "'));

        --- Truncate @json with the length of the key.
        SET @json=LTRIM(SUBSTRING(@json, LEN(@key)+3, LEN(@json)));

        --- The next character should be a colon.
        IF (LEFT(@json, 1)!=':')
            RETURN 'Expected ":" after key name, found "'+
                LEFT(@json, 1)+'"!';

        --- Truncate @json to skip past the colon:
        SET @json=LTRIM(SUBSTRING(@json, 2, LEN(@json)));

        --- If the next character is an angle bracket, this is an array.
        IF (LEFT(@json, 1)='[')
            SELECT @array=1, @json=LTRIM(SUBSTRING(@json, 2, LEN(@json)));

        IF (@array IS NULL) SET @array=0;
        WHILE (@array IS NOT NULL) BEGIN;

            SELECT @value=NULL, @nested=0;
            --- The first character of the remainder of @json indicates
            --- what type of value this is.

            --- Set @value, depending on what type of value we're looking at:
            --- 1. A new JSON object:
            ---    To be sent recursively back into the parser:
            IF (@value IS NULL AND LEFT(@json, 1)='{') BEGIN;
                SELECT @recursion_counter=1, @offset=1;
                WHILE (@recursion_counter!=0 AND @offset<LEN(@json)) BEGIN;
                    SET @offset=@offset+
                        PATINDEX('%[{}]%', SUBSTRING(@json, @offset+1,
                    SET @recursion_counter=@recursion_counter+
                        (CASE SUBSTRING(@json, @offset, 1)
                            WHEN '{' THEN 1
                            WHEN '}' THEN -1 END);

                SET @value=CAST(
                    dbo.fn_parse_json2xml(LEFT(@json, @offset))
                        AS varchar(max));
                SET @json=SUBSTRING(@json, @offset+1, LEN(@json));
                SET @nested=1;

            --- 2a. Blank text (quoted)
            IF (@value IS NULL AND LEFT(@json, 2)='""')
                SELECT @value='', @json=LTRIM(SUBSTRING(@json, 3,

            --- 2b. Other text (quoted, but not blank)
            IF (@value IS NULL AND LEFT(@json, 1)='"') BEGIN;
                SET @value=SUBSTRING(@json, 2,
                        SUBSTRING(@json, 2, LEN(@json))+' "'));
                SET @json=LTRIM(
                    SUBSTRING(@json, LEN(@value)+3, LEN(@json)));

            --- 3. Blank (not quoted)
            IF (@value IS NULL AND LEFT(@json, 1)=',')
                SET @value='';

            --- 4. Or unescaped numbers or text.
            IF (@value IS NULL) BEGIN;
                SET @value=LEFT(@json,
                    PATINDEX('%[,}]%', REPLACE(@json, ']', '}')+'}')-1);
                SET @json=SUBSTRING(@json, LEN(@value)+1, LEN(@json));

            --- Append @key and @value to @output:
            SET @output=@output+@lf+@cr+
                REPLICATE(@tab, @@NESTLEVEL-1)+
                        REPLACE(@value, '\"', '"'), '\\', '\'), '')+
                    (CASE WHEN @nested=1
                        THEN @lf+@cr+REPLICATE(@tab, @@NESTLEVEL-1)
                        ELSE ''

            --- And again, error checks:
            --- 1. If these are multiple values, the next character
            ---    should be a comma:
            IF (@array=0 AND @json!='' AND LEFT(@json, 1)!=',')
                RETURN @output+'Expected "," after value, found "'+
                    LEFT(@json, 1)+'"!';

            --- 2. .. or, if this is an array, the next character
            --- should be a comma or a closing angle bracket:
            IF (@array=1 AND LEFT(@json, 1) NOT IN (',', ']'))
                RETURN @output+'In array, expected "]" or "," after '+
                    'value, found "'+LEFT(@json, 1)+'"!';

            --- If this is where the array is closed (i.e. if it's a
            --- closing angle bracket)..
            IF (@array=1 AND LEFT(@json, 1)=']') BEGIN;
                SET @array=NULL;
                SET @json=LTRIM(SUBSTRING(@json, 2, LEN(@json)));

                --- After a closed array, there should be a comma:
                IF (LEFT(@json, 1) NOT IN ('', ',')) BEGIN
                    RETURN 'Closed array, expected ","!';

            SET @json=LTRIM(SUBSTRING(@json, 2, LEN(@json)+1));
            IF (@array=0) SET @array=NULL;


    --- Return the output:
    RETURN CAST(@output AS xml);
And here’s how to test the query:

DECLARE @json varchar(max);

SET @json='{
"Person": {
    "firstName": "John",
    "lastName": "Smith",
    "age": [25, 26, 27],
    "Address": {
        "streetAddress":"21, 2nd Street",
        "city" :"New York",
        "PhoneNumbers": {
            "home":"212 555-1234",
            "fax":"646 555-4567"

SELECT dbo.fn_parse_json2xml(@json);

Data compression sql server

How data compression works

SQL Server stores its databases in large files on logical disks/volumes, which in turn represent a physical storage medium such as a RAID set, SAN drives or just a simple local disk such as a harddrive or SSD. These database files are internally subdivided into pages, where each page holds up to 8 kB of data (including a small 96-byte header). Different types of pages are used for data rows, indexes, blobs as well as a few other special applications that are beyond the scope of this article. Whenever SQL Server accesses data, it reads/writes entire pages at a time.

With this in mind, data compression i SQL Server can be performed on rows or pages that contain indexes or data.

Row compression compresses individual column values in each row. The gain for column values of different datatypes can vary a lot, because different column values can be compressed differently (see this article on MSDN for details).

Page compression compresses entire leaf-level pages, i.e. the pages that contain the leaf levels of clustered indexes or heaps. Generally speaking, using page level compression is often a better choice than row-level compression, but your milage may vary. The specifics of page compression can be read in this MSDN article.


Adding compression to a table or index hardly requires any code at all. Here, compression is set on a table/heap:

CREATE TABLE dbo.tbl (
    a    int NOT NULL,
    b    varchar(100) NULL
There are three valid, mutually exclusive arguments for the DATA_COMPRESSION switch:

ROW, to enable row-level compression,
PAGE, to enable page-level compression, and
NONE, to disable compression
The same switch can be used when creating indexes or primary key constraints.

CREATE TABLE dbo.tbl (
    a    int NOT NULL,
    b    varchar(100) NULL,
    ON dbo.tbl (a)
For tables without clustered indexes (heaps) the data compression setting on the table defines if and how data is compressed. For tables with clustered indexes, the data compression setting on the table or clustered index defines how data is compressed, because it is the clustered index that actually stores and organizes the data.

Individual non-clustered indexes can also be compressed, and you’ll have to add the DATA_COMPRESSION switch to each of them. This means that you can mix non-compressed tables with compressed (non-clustered) indexes or vice versa if you should need to.

To read up on heaps and indexes, see the article Indexing basics.

Benefits of data compression

Depending on how your server is set up, a significant performance bottleneck may be in I/O speed, i.e. how fast SQL Server can read and write the physical storage medium. One way to speed up I/O is to use data compression, because when you compress data that is stored on the physical disks, it results in smaller amounts of physical bits and bites to read/write, which is faster.

However, there are no free lunches, and in this case the trade-off is that when you compress data you need a certain amount of processing power to do the actual compression/decompression work, which means that the choice of whether or not to use compression is a balance between how fast your I/O subsystem is vs. how much processing power you can spare.

When not to use compression

First, not all tables/indexes are compressible. If the (uncompressed) potential maximum size of your row would exceed the size of a page (8 kB minus the compression overhead), you could still create the table without compression, although you will get a warning message, but you won’t be able to create a compressed table. This applies for instance to variable-size datatypes such as varchar, nvarchar, vardecimal, etc. This, however, is a minor problem if you stick to good design practices.

Second, if you’re building a database that is going to be deployed on a non-Enterprise Edition server, you may not want to design optimizations around the fact that you have data compression built in.

Third, and most important, maybe your disks are faster than your processor cores. Depending on your server setup, uncompressed may just be faster.

Backup compression

Backup compression compresses backup files to save disk space and improve backup and restore performance, but does not really affect day-to-day database performance. Read more on backup compression on MSDN.

web request from sql server

Starting a new C# project

In Visual C#, create a new project and select “Class library”, so your code will compile to a DLL file. This may differ between versions of Visual Studio and SQL Server, but you’ll figure it out.

The C# code

Here’s the example code of a C# procedure that we’re going to use. Starting off, we’re including Microsoft.SqlServer.Server because we’re going to need this to communicate with the server – retrieving arguments and returning values or recordsets.
using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.Collections;
using System.Globalization;

// For the SQL Server integration
using Microsoft.SqlServer.Server;

// Other things we need for WebRequest
using System.Net;
using System.Text;
using System.IO;
We’re setting up two basic functions, GET() and POST(), corresponding to their respective HTTP equivalents. We’re going to create a class, simply called Functions, but you could call it what you like.
public partial class Functions
Partial, in this case means that you can split the code over several different files if you want. You will notice that both functions are prefixed with an attribute (the stuff within brackets). The attribute is there for Visual Studio, so it knows that we are building an SQL Server function. Here’s the GET() function in its entirety, with comments:
    // Function to return a web URL as a string value.
    public static SqlString GET(SqlString uri, SqlString username, SqlString passwd)
        // The SqlPipe is how we send data back to the caller
        SqlPipe pipe = SqlContext.Pipe;
        SqlString document;

        // Set up the request, including authentication
        WebRequest req = WebRequest.Create(Convert.ToString(uri));
        if (Convert.ToString(username) != null & Convert.ToString(username) != "")
            req.Credentials = new NetworkCredential(
        ((HttpWebRequest)req).UserAgent = "CLR web client on SQL Server";

        // Fire off the request and retrieve the response.
        // We'll put the response in the string variable "document".
        WebResponse resp = req.GetResponse();
        Stream dataStream = resp.GetResponseStream();
        StreamReader rdr = new StreamReader(dataStream);
        document = (SqlString)rdr.ReadToEnd();

        // Close up everything...

        // .. and return the output to the caller.
        return (document);
The POST() function looks fairly similar:
    // Function to submit a HTTP POST and return the resulting output.
    [Microsoft.SqlServer.Server.SqlFunction(DataAccess = DataAccessKind.Read)]
    public static SqlString POST(SqlString uri, SqlString postData, SqlString username, SqlString passwd)
        SqlPipe pipe = SqlContext.Pipe;
        SqlString document;
        byte[] postByteArray = Encoding.UTF8.GetBytes(Convert.ToString(postData));

        // Set up the request, including authentication, 
        // method=POST and encoding:
        WebRequest req = WebRequest.Create(Convert.ToString(uri));
        ((HttpWebRequest)req).UserAgent = "CLR web client on SQL Server";
        if (Convert.ToString(username) != null & Convert.ToString(username) != "")
            req.Credentials = new NetworkCredential(
        req.Method = "POST";
        req.ContentType = "application/x-www-form-urlencoded";

        // Submit the POST data
        Stream dataStream = req.GetRequestStream();
        dataStream.Write(postByteArray, 0, postByteArray.Length);

        // Collect the response, put it in the string variable "document"
        WebResponse resp = req.GetResponse();
        dataStream = resp.GetResponseStream();
        StreamReader rdr = new StreamReader(dataStream);
        document = (SqlString)rdr.ReadToEnd();

        // Close up and return

        return (document);
You’ll notice that I haven’t bothered trapping errors in this tutorial code, but I suppose this could be a good idea in production code, or you could write a TRY-CATCH block in T-SQL when calling the function.
Finally, we just need to close the curly brackets on the class, then it’s compile time! :)

How to enable the server to run CLR code

If you haven’t enabled CLR integration on the server (it’s disabled by default), you need to do this using sp_configure:
sp_configure 'clr enabled', 1;
Before you enable CLR execution, you should be aware of what it means to server security, and you should probably check with the server’s owner.
If you haven’t enabled CLR execution, you’ll get the following error message when you try to execute your code:
Msg 6263, Level 16, State 1, Line 1
Execution of user code in the .NET Framework is disabled. Enable
        "clr enabled" configuration option.
Also, in order to run “unsafe” managed code (i.e. code that has access to stuff outside the SQL Server context), you need to mark the database as trustworthy. This is done using the ALTER DATABASE statement:
If you’ve forgotten this last step, you’ll get the following error:
Msg 10327, Level 14, State 1, Line 1
CREATE ASSEMBLY for assembly 'SqlWebRequest' failed because assembly
      'SqlWebRequest' is not authorized for PERMISSION_SET = UNSAFE.
      The assembly is authorized when either of the following is true:
      the database owner (DBO) has UNSAFE ASSEMBLY permission and the
      database has the TRUSTWORTHY database property on; or the assembly
      is signed with a certificate or an asymmetric key that has a
      corresponding login with UNSAFE ASSEMBLY permission.

Setting up your assembly and function in the database

You have to load the DLL (the assembly) into the database. This is done in the database you’re going to work in. The assembly is actually stored in the database, so you don’t need to keep the DLL file once you’ve registered the assembly.
USE myDatabase

FROM 'D:\Stuff\SqlWebRequest.dll'
The UNSAFE clause means that the assembly has more privileges, which is needed in this case to get “outside access”, in this case to the networking functionality. If you’re simply doing arithmetics, string parsing or something like that, PERMISSION_SET=SAFE is probably a better idea.
Finally, all you need to do is create the CLR functions that reference the functions in the assembly. This follows the basics of the CREATE FUNCTION statement, except we’re using the EXTERNAL NAME clause to point to the assembly, class and C# function name:
CREATE FUNCTION dbo.fn_get_webrequest(
     @uri        nvarchar(max),
     @user       nvarchar(255)=NULL,
     @passwd     nvarchar(255)=NULL
RETURNS nvarchar(max)
EXTERNAL NAME SqlWebRequest.Functions.GET;


CREATE FUNCTION dbo.fn_post_webrequest(
     @uri         nvarchar(max),
     @postdata    nvarchar(max),
     @user        nvarchar(255)=NULL,
     @passwd      nvarchar(255)=NULL
RETURNS nvarchar(max)

EXTERNAL NAME SqlWebRequest.Functions.POST;


How to call the function in T-SQL

Now your CLR function is ready to use! Try using it to get stock prices from Yahoo, for instance:
PRINT dbo.fn_get_webrequest(''+
       's=AAPL+YHOO+GOOG+GE+MSFT&f=snl1t1ghc1', DEFAULT, DEFAULT);
This is what the output should look like:
"AAPL","Apple Inc.",449.07,"3:40pm",437.66,451.54,+6.27
"YHOO","Yahoo! Inc.",20.78,"3:40pm",20.575,20.85,+0.05
"GOOG","Google Inc.",789.77,"3:40pm",784.40,795.9499,-1.00
"GE","General Electric ",23.09,"3:40pm",22.91,23.15,+0.28
"MSFT","Microsoft Corpora",27.38,"3:40pm",27.34,27.60,+0.0
Hope you found this tutorial useful. Again, let me know in the comment section if there’s anything I’ve missed.

Tuesday, January 28, 2014

Sorting in Gridview

Step 1. Create new project in visual studio.

Step 2. Open default.aspx and drag and drop GridView control in design view.

Step 3. Open default.aspx.cs and add following line in using directives:

using System.Data.SqlClient;

Step 4. Open Web.config and add following line just above <system.web>:

    <add name="con" connectionString="Data Source=.\sqlexpress;initial catalog=database_name;integrated security=true;" providerName="System.Data.SqlClient"/>

Step 5. Open properties of GridView, change AllowSorting and AllowPaging property to True.

Step 6. Open default.aspx.cs and add following lines:

SqlConnection conn = newSqlConnection(ConfigurationManager.ConnectionStrings["con"].ToString());
    protected void Page_Load(object sender, EventArgs e)
            DataSet ds = new DataSet();
            DataView dv = new DataView();
dv = binddata();
            GridView1.DataSource = dv;
    private DataView binddata()
  SqlDataAdapter adp = new SqlDataAdapter("select data from table", conn);
        if (ViewState["sortexp"] != null)
            dv = new DataView(ds.Tables[0]);
            dv.Sort = (string)ViewState["sortexp"];
            dv = ds.Tables[0].DefaultView;
        return dv;
    protected void paging(object sender, GridViewPageEventArgs e)
        GridView1.PageIndex = e.NewPageIndex;
        GridView1.DataSource = binddata();
    protected void sorting(object sender, GridViewSortEventArgs e)
        ViewState["sortexp"] = e.SortExpression;
        GridView1.DataSource = binddata();

Step 7. Open properties of GridView and click on events, change PageIndexChanging to paging and Sorting to sorting.

Step 8. Build the project.

Monday, January 27, 2014

ASP.NET Session modes

ASP.NET session state supports several different storage options for session data. Each option is identified by a value in the SessionStateMode enumeration. The following list describes the available session state modes: 
  • InProc mode, which stores session state in memory on the Web server. This is the default.
  • StateServer mode, which stores session state in a separate process called the ASP.NET state service. This ensures that session state is preserved if the Web application is restarted and also makes session state available to multiple Web servers in a Web farm.
  • SQLServer mode stores session state in a SQL Server database. This ensures that session state is preserved if the Web application is restarted and also makes session state available to multiple Web servers in a Web farm.
  • Custom mode, which enables you to specify a custom storage provider.
  • Off mode, which disables session state.

In Process session mode

In-process mode stores session state values and variables in memory on the local Web server. This is the simplest of all settings and will fail to work in a web garden or web farm scenario. 
<sessionState mode="InProc" 

State Server mode

StateServer mode stores session state in a process, referred to as the ASP.NET state service, that is separate from the ASP.NET worker process or IIS application pool. Using this mode ensures that session state is preserved if the Web application is restarted and also makes session state available to multiple Web servers in a Web farm. 

To use StateServer mode, you must first be sure the ASP.NET state service is running on the server used for the session store. The ASP.NET state service is installed as a service when ASP.NET and the .NET Framework are installed. The ASP.Net state service is installed at the following location: 

To configure an ASP.NET application to use StateServer mode, in the application's Web.config file do the following: 

  • Set the mode attribute of the sessionState element to StateServer.
  • Set the stateConnectionString attribute to tcpip=serverName:42424.

        <sessionState mode="StateServer"

Note that objects stored in session state must be serializable if the mode is set to StateServer or SQL Server (described below).


SQL Server mode

SQLServer mode stores session state in a SQL Server database. Using this mode ensures that session state is preserved if the Web application is restarted and also makes session state available to multiple Web servers in a Web farm.

To use SQLServer mode, you must first be sure the ASP.NET session state database is installed on SQL Server. You can install the ASP.NET session state database using the Aspnet_regsql.exe tool.

To configure an ASP.NET application to use SQLServer mode, do the following in the application's Web.config file:

  • Set the mode attribute of the sessionState element to SQLServer.
  • Set the sqlConnectionString attribute to a connection string for your SQL Server database.

      <sessionState mode="SQLServer"
         sqlConnectionString="Integrated Security=SSPI;data 
         source=SampleSqlServer;" />

Soap Vs Rest

Web services overview

A Web service, in very broad terms, is a method of communication between two applications or electronic devices over the World Wide Web (WWW). Web services are of two kinds: Simple Object Access Protocol (SOAP) and Representational State Transfer (REST).
SOAP defines a standard communication protocol (set of rules) specification for XML-based message exchange. SOAP uses different transport protocols, such as HTTP, JMS and SMTP. The standard protocol HTTP makes it easier for SOAP model to tunnel across firewalls and proxieswithout any modifications to the SOAP protocol. SOAP can sometimes be slower than middleware technologies like CORBA or ICE due to its verbose XML format.
REST describes a set of architectural principles by which data can be transmitted over a standardized interface (such as HTTP). REST does not contain an additional messaging layer and focuses on design rules for creating stateless services. A client can access the resource using the unique URI and a representation of the resource is returned. With each new resource representation, the client is said to transfer state. While accessing RESTful resources with HTTP protocol, the URL of the resource serves as the resource identifier and GET, PUT, DELETE, POST and HEAD are the standard HTTP operations to be performed on that resource.


Multiple factors need to be considered when choosing a particular type of Web service, that is between REST and SOAP. The table below breaks down the features of each Web service based on personal experience.
  • The RESTful Web services are completely stateless. This can be tested by restarting the server and checking if the interactions are able to survive.
  • Restful services provide a good caching infrastructure over HTTP GET method (for most servers). This can improve the performance, if the data the Web service returns is not altered frequently and not dynamic in nature.
  • The service producer and service consumer need to have a common understanding of the context as well as the content being passed along as there is no standard set of rules to describe the REST Web services interface.
  • REST is particularly useful for restricted-profile devices such as mobile and PDAs for which the overhead of additional parameters like headers and other SOAP elements are less.
  • REST services are easy to integrate with the existing websites and are exposed with XML so the HTML pages can consume the same with ease. There is hardly any need to refactor the existing website architecture. This makes developers more productive and comfortable as they will not have to rewrite everything from scratch and just need to add on the existing functionality.
  • REST-based implementation is simple compared to SOAP.
  • The Web Services Description Language (WSDL) contains and describes the common set of rules to define the messages, bindings, operations and location of the Web service. WSDL is a sort of formal contract to define the interface that the Web service offers.
  • SOAP requires less plumbing code than REST services design, (i.e., transactions, security, coordination, addressing, trust, etc.) Most real-world applications are not simple and support complex operations, which require conversational state and contextual information to be maintained. With the SOAP approach, developers need not worry about writing this plumbing code into the application layer themselves.
  • SOAP Web services (such as JAX-WS) are useful in handling asynchronous processing and invocation.
  • SOAP supports several protocols and technologies, including WSDL, XSDs, SOAP, WS-Addressing
In this article I am introducing the use of Data Annotations in MVC 5 using Microsoft Visual Studio 2013 Preview. As you know I previously deployed a MVC Application in which I used various types of techniques like Adding View,Adding ModelLoginCRUD OperationsCode MigrationSearching. These are very necessary in MVC Applications but when you develop applications, it is necessary to apply validations on that app. So, here you will learn how to validate an app in MVC 5.
In that context, validations are applied in MVC applications by the following assembly:

using System.ComponentModel.DataAnnotations;

Here I will tell you that I am creating validation logic in my Cricketers Model. When a user creates or edits any cricketer. You can see the validation on my page in the following image:

Don't Repeat Yourself
Whenever you design an ASP.NET MVC application, Don't Repeat Yourself (DRY) is the basic assumption that you need to use. This makes your code clean, reduces the amount of code and easy to maintain because the more code you write with fewer errors the more your code functions better.
In ASP.NET MVC applications, validations are defined in the Model Class and applied all over the application. The Entity Framework Code First approach and MVC are the pillar for the validation.
So, let's begin to take advantage of Data Annotation of MVC in your application with the following criteria.
Use of Data Annotation
You need to add some logic for validation in your MVC application. For adding let's start step-by-step.
Step 1: Open Cricketers.cs from the Solution Explorer.

Step 2: Add the following assembly reference at the top of your Cricketers.cs file:
using System.ComponentModel.DataAnnotations;
Step 3: Change your code with the following code (depends on your logic):
using System.ComponentModel.DataAnnotations;
using System.Data.Entity;

namespace MvcCricket.Models
    public class Cricketer
        public int ID { getset; }

        [StringLength(50, MinimumLength=4)]
        public string Name { getset; }
        public int ODI { getset; }
        public int Test { getset; }
        public string Grade { getset; }
In the code above, you can see that the Required attribute is used in each property. That means that the user needs to enter the value in it. In the Name property the StringLength attribute defines the min and max length of the Name. In the ODI and TEST property the Range attribute is defined to min and max length.
Step 4: Open a Library Package Manager Console and write the following command in it:
add-migration DataAnnotations
After pressing Enter:

Step 5: Again write the following command in the Library Package Manager Console:
What does Visual Studio do? Visual Studio opens the DataAnnotations.cs file and you will see the DbMigration class is the base class of DataAnnotations. There are two methods in it. In the Up() and Down(), you will see the updated database schema. Check it out with the following code:
namespace MvcCricket.Migrations
    using System;
    using System.Data.Entity.Migrations;
    public partial class DataAnnotations : DbMigration
        public override void Up()
            AlterColumn("dbo.Cricketers""Name", c => c.String(nullable: false, maxLength: 50));
            AlterColumn("dbo.Cricketers""Grade", c => c.String(nullable: false));
        public override void Down()
            AlterColumn("dbo.Cricketers""Grade", c => c.String());
            AlterColumn("dbo.Cricketers""Name", c => c.String());
You can see in the code above that the Name and Grade property are no longer nullable. You need to enter values in it. Code First ensures that the validation rules you specify on a model class are enforced before the application saves changes in the database.
Step 6: Debug your application and open the Cricketers folder.

Click on Create New Link to create some new cricketer.

That's It

Source :

Friday, January 24, 2014

How to prevent logged out user from revisiting previous page using back button in asp .net?

Option #1: Set Response Cache settings in code-behind file for a page
// Code disables caching by browser.
Option #2: Set META tag for HTTP cache settings in your ASPX page header
<META Http-Equiv="Cache-Control" Content="no-cache"/>
<META Http-Equiv="Pragma" Content="no-cache"/>
<META Http-Equiv="Expires" Content="0"/>
Option #3: Clear browser's history through JavaScript using script tag
//clears browser history and redirects url
<SCRIPT LANGUAGE="javascript">
function ClearHistory()
     var backlen = history.length;
     window.location.href = loggedOutPageUrl
Option #4: Clear browser's history through JavaScript injecting through code-behind file via Response
protected void LogOut()
     string loggedOutPageUrl = "Logout.aspx";
     Response.Write("<script language="'javascript'">");
     Response.Write("function ClearHistory()");
     Response.Write(" var backlen=history.length;");
     Response.Write(" history.go(-backlen);");
     Response.Write(" window.location.href='" + loggedOutPageUrl + "'; ");
Option #5: Clear browser's history through JavaScript injecting through code-behind file via Page.ClientScript