Wednesday 23 October 2013

Show the Content in Grid Format using WebGrid and Foreach

Displaying data using Webgrid with ajax 

Controller.cs

public ActionResult WebgridSample()
{
            ObservableCollection<Student> FeeRemaining = new ObservableCollection<Student>();
            FeeRemaining.Add(new Student { RollNo = "08330001", Name = "Surbhi", Branch = "C.S", FeeRemaining = 18000 });
            FeeRemaining.Add(new Student { RollNo = "08330004", Name = "Arun", Branch = "C.S", FeeRemaining = 2500 });
            FeeRemaining.Add(new Student { RollNo = "08329006", Name = "Ankita", Branch = "I.T", FeeRemaining = 31000 });
            FeeRemaining.Add(new Student { RollNo = "08329007", Name = "Anshika", Branch = "I.T", FeeRemaining = 9450 });
            FeeRemaining.Add(new Student { RollNo = "08329014", Name = "Anubhav", Branch = "I.T", FeeRemaining = 2670 });
            FeeRemaining.Add(new Student { RollNo = "08311023", Name = "Girish", Branch = "E.N", FeeRemaining = 11200 });
            FeeRemaining.Add(new Student { RollNo = "08311024", Name = "Yogesh", Branch = "E.N", FeeRemaining = 3370 });
            return View(FeeRemaining);
}

View.cshtml

<html>
<head>
    <title>Fee Remaining in Webgrid</title>
    <script src="../../Scripts/jquery-1.7.1.min.js" type="text/javascript"></script>
    <style type="text/css">
        .table { margin: 4px;  width: 500px;  background-color:#FCFCFC;}
        .head { background-color: #C1D4E6; font-weight: bold; color: #FFF; }
        .webGrid th, .webGrid td { border: 1px solid #C0C0C0; padding: 5px; }
        .altRow { background-color: #E4E9F5; color: #000; }
        .gridHead a:hover {text-decoration:underline;}
        .description { width:auto}
        .selectRow{background-color: #389DF5}
    </style>
</head>
<body>
@{
    WebGridSampleApplication.Models.Student Student = new WebGridSampleApplication.Models.Student();
}
    @{
    var gd = new WebGrid(Model, canPage: true, rowsPerPage: 5, selectionFieldName: "selectedRow",ajaxUpdateContainerId: "gridContent");
        gd.Pager(WebGridPagerModes.NextPrevious);}
        <div id="gridContent">
        @gd.GetHtml(tableStyle: "table",
                headerStyle: "head",
                alternatingRowStyle: "altRow",
                selectedRowStyle: "selectRow",
                columns: gd.Columns(
                gd.Column("RollNo", format: (item) => item.GetSelectLink(item.RollNo)),
                gd.Column("Name", " Name"),
                gd.Column("Branch", "Branch", style: "description"),
                gd.Column("FeeRemaining", "FeeRemaining")
         ))
    @if (gd.HasSelection)
         {
             Student = (WebGridSampleApplication.Models.Student)gd.Rows[gd.SelectedIndex].Value;
             <b>Roll No</b> @Student.RollNo<br />
             <b>Name</b>  @Student.Name<br />
             <b>Branch</b> @Student.Branch<br />
             <b>Remaining Fee</b> @Student.FeeRemaining<br />
         }
    </div>    
</body>
</html>

Displaying data using foreach loop

 <table>
        @foreach (var item in Model)
        {
            <thead>
                <tr>
                    <th>RollNo</th>
                    <th>Name</th>
                    <th>Branch</th>
                    <th>Fee Remaining</th>
                </tr>
            </thead>
            <tr>
                <td class="left">@item.RollNo</td>
                <td class="left">@item.Name</td>
                <td class="left">@item.Branch</td>
                <td class="right">@item.FeeRemaining</td>
            </tr>
 
        }

    </table>

Saturday 6 July 2013

Potentially dangerous Request.Form value was detected from the client




'A Potentially dangerous Request.Form value was detected from the client'

This is a common error that ASP.NET developers have run into many times. We will see in this post a few ways on how to avoid it. 

Reason
       By default, ASP.NET performs request validation to prevent people from uploading HTML markup or script to your site. ASP.NET checks the content of the form sent to the server to prevent cross-site scripting(xss).  

This error is caused by a newly introduced feature of .NET Framework 1.1, called "Request Validation."  This feature is designed to help prevent script-injection attacks whereby client script code or HTML is unknowingly submitted to a server, stored, and then presented to other users.

Note that anything between '<' and '>' is considered dangerous, and it doesn't have to necessarily closes the tag with '<' ("<a" would have be considered potentially dangerous). ASP.NET validates query string as well.

Try it:
To overcome this error first try to disable the request validation feature, because the validation is done by ASP.NET before any of your code.
<%@ Page ValidateRequest="false" %>

Or you can disable it for your entire application in the web.config file:
<configuration>
    <system.web>
        <pages validateRequest="false" />
    </system.web>
</configuration>

ASP.Net 4.0?
        In ASP.Net 2.0, request validation is enabled for only ASP.Net pages and validated when those pages are executing. Whereas in ASP.Net 4.0, by default request validation is enabled for all requests. As a result validation applies to not only to ASP.Net pages but also to the Web service calls, Http handlers etc.. To prevent this error simply revert ASP.Net behavior back to 2.0. 
To do this, add a configuration element in Web.Config.
<httpRuntime requestValidationMode="2.0" />

Thursday 27 June 2013

Image upload with CKEditor

CKeditor is one of the most widely used WYSIWYG editors for web applications. Overtime, the CKeditor continued to evolve by adding new features that made HTML text editing a lot easier. When using a WYSIWYG editor, we will often need to upload image to server and embed it in the HTML content. By default, the CKeditor will support embedding an image that are already uploaded or from an external source by providing its URL.

In this article, let’s see how we can upload image to our website and embed it in CKeditor by below easy solution. The CKeditor has a property called filebrowserImageUploadUrl which will provide an option to upload images to the server when configured. This property takes a file uploader (a page or a handler) url to upload the selected image to the server. The handler that is responsible for uploading the image should return back the URL of the image to display in the CKeditor. Once filebrowserImageUploadUrl property is configured, you will be able to see a new tab called “Upload” in Image Properties pop-up of CKeditor.

Follow the below steps to integrate image upload functionality with CKEditor in ASP.NET. Here the solution.
1. Create a New ASP.NET Website “CKeditorDemo”.
2. 
 Download CKEditor and extract in your web folder root.
3. Create a new folder named “Images” in your web folder root.
4. Add the new ASHX Handler file (.ashx) “Upload.ashx” and Copy Paste below code into “Upload.ashx”

<%@ WebHandler Language="C#" Class="Upload" %>
using System;
using System.Web;
public class Upload : IHttpHandler {   
    public void ProcessRequest (HttpContext context) {
       HttpPostedFile uploads = context.Request.Files["upload"];
       string CKEditorFuncNum = context.Request["CKEditorFuncNum"];
       string file = System.IO.Path.GetFileName(uploads.FileName);
       uploads.SaveAs(context.Server.MapPath(".") + "\\Images\\" + file);
//provide direct URL here
       string url = "http://localhost/CKeditorDemo/Images/" + file; 
       
context.Response.Write("<script>window.parent.CKEDITOR.tools.callFunction(" +                                             CKEditorFuncNum + ", \"" + url + "\");</script>");
       context.Response.End();            
    }

    public bool IsReusable {
        get { return false; }
    }
}

5. Call the script and declare Textbox with ID="txtCkEditor" in .aspx file
<script type="text/javascript" src="Scripts/jquery-1.4.1.min.js"></script>
<script type="text/javascript" src="ckeditor/ckeditor.js"></script>
<script type="text/javascript" src="ckeditor/adapters/jquery.js"></script>
<script type="text/javascript">
    $(function () {
CKEDITOR.replace('<%=txtCkEditor.ClientID %>', { filebrowserImageUploadUrl:  '/CKeditorDemo/Upload.ashx' }); //path to “Upload.ashx”
    });
</script>

<asp:TextBox ID="txtCkEditor" TextMode="MultiLine" runat="server"></asp:TextBox>

6. You are done with the setting. Now run the website you will see the CKEditor configured in the page.


7. Then choose the image icon in the CKEditor to upload the Image.

8. Select the image by clicking Browse button in Upload tab and select “Send it to the Server” button to save the image in server.

9. The uploaded image is displayed in the CKEditor after clicking “OK”.

Thursday 23 May 2013

Working with Knockout.js


Knockout(KO) is a JavaScript library that helps you to create rich, responsive display and editor user interfaces with a clean underlying data model. KO provides a simple two-way data binding mechanism between your data model and UI means any changes to data model are automatically reflected in the DOM (UI) and any changes to the DOM are automatically reflected to the data model.

Since Knockout is a purely client-side library, it has the flexibility to work with any server-side technology (e.g., ASP.NET, Rails, PHP, etc.), and any architectural pattern, database, whatever. As long as your server-side code can send and receive JSON data — a trivial task for any half-decent web technology

Key Concepts:
  • Declarative Bindings - Easily associate DOM elements with model data using a concise, readable syntax.
  • Automatic UI Refresh - When your data model's state changes, your UI updates automatically.
  • Dependency Tracking - Implicitly set up chains of relationships between model data, to transform and combine it.
  • TemplatingQuickly generate sophisticated, nested UIs as a function of your model data.

Additional benefits:
  • Declarative Bindings - Pure JavaScript library - works with any server or client-side technology.
  • Can be added on top of your existing web application without requiring major architectural changes.
  • Comprehensive suite of specifications (developed BDD-style) means its correct functioning can easily be verified on new browsers and platforms.
More Features:
  • Free, open source.
  • Pure JavaScript — works with any web framework
  • Small & lightweight — 40kb minified. (... reduces to 14kb when using HTTP compression)
  • No dependencies
  • Supports all mainstream browsers
    IE 6+, Firefox 2+, Chrome, Opera, Safari (desktop/mobile)

Knockout.js uses a Model-View-ViewModel (MVVM) design pattern in which the model is your stored data, and the view is the visual representation of that data (UI) and ViewModel acts as the intermediary between the model and the view.

                                         Model   <---------> View Model <---------> View

ViewModel is a JavaScript representation of the model data, along with associated functions for manipulating the data. Knockout.js creates a direct connection between the ViewModel and the view, which helps to detect changes to the underlying model and automatically update the right element of the UI.

Simple Example

1. View(HTML)
<h2>Your Seat reservations</h2>
<table>
    <thead><tr>
        <th>Passenger name</th><th>Meal</th><th>Surcharge</th><th></th>
    </tr></thead>
    <tbody data-bind="foreach: seats">
    <tr>
        <td data-bind="text: name"></td>
        <td data-bind="text: meal().mealName"></td>
        <td data-bind="text: meal().price"></td>
    </tr> 
</tbody>
</table>

2. View Model(Javascript)
// Class to represent a row in the seat reservations grid
function SeatReservation(name, initialMeal) {
    var self = this;
    self.name = name;
    self.meal = ko.observable(initialMeal);
}
// Overall viewmodel for this screen, along with initial state
function ReservationsViewModel() {
    var self = this;
    // Non-editable catalog data - would come from the server
    self.availableMeals = [
        { mealName: "Standard (sandwich)", price: 10.11 },
        { mealName: "Premium (lobster)", price: 34.95 },
        { mealName: "Ultimate (whole zebra)", price: 290 }
    ]; 

    // Editable data
    self.seats = ko.observableArray([
        new SeatReservation("Steve", self.availableMeals[0]),
        new SeatReservation("Bert", self.availableMeals[1])
    ]);
}

ko.applyBindings(new ReservationsViewModel());

3. OUTPUT

Wednesday 15 May 2013

SQL Query to find starting and ending date of every week in a month


DECLARE @iloop int
DECLARE @Tot_Weeks Int
DROP TABLE #Weeks
CREATE TABLE #Weeks(Weekno int identity(1,1),[Start Of Week] date, [End Of Week] date )
---Input the date Here
declare @dt date = cast('2013-06-01' as date);
declare @dtstart date =  DATEADD(day, -DATEPART(day, @dt) + 1, @dt);
declare @dtend date = dateadd(DAY, -1, DATEADD(MONTH, 1, @dtstart));
--Find the Total Number of Weeks
SELECT @Tot_Weeks = DATEDIFF (week, DATEADD (m, DATEDIFF (m, 0, @dtend), 0), @dtend) + 1
Set @iloop = 0
WHILE (@iloop < @Tot_Weeks)
BEGIn
PRINT @iloop
If(@iloop = 0)
Begin
INSERT INTO #Weeks
SELECT @dtstart as [Start Of Week] , Cast( DATEADD(s,-1,DATEADD(WK, DATEDIFF(WK,0,CAST(@dtstart AS DATE))+1,0))-1 as DATE) as [End Of Week]
End
ELSE IF(@iloop = (@Tot_Weeks-1))
BEGIN
INSERT INTO #Weeks
SELECT  Cast( DATEADD(WK, DATEDIFF(WK,0,CAST(@dtstart AS DATE)),-1) as Date) as [Start Of Week] ,  @dtend as [End Of Week]
END
Else
Begin
INSERT INTO #Weeks
SELECT  Cast(DATEADD(WK, DATEDIFF(WK,0,CAST(@dtstart AS DATE)),-1) as Date) as [Start Of Week] , Cast( DATEADD(s,-1,DATEADD(WK, DATEDIFF(WK,0,CAST(@dtstart AS DATE))+1,0))-1 as DATE) as [End Of Week]
End
Set @dtstart = DATEADD(DD,7,CAST(@dtstart AS DATE))
Print @dtstart
SET @iloop = @iloop + 1
END

Select * from #Weeks

Monday 6 May 2013

What is .Net ?


What is .Net 

.Net is a software development platform developed by Microsoft. It is developed by microsoft to compete Java in the market. Using .net there is no need to learn new programming language. It supports 48 programming languages like as C, C++, C#, J#, VB etc. Hence we can do programming in any programming language in which you feel comfortable to yourself. Infact .Net is a collection of :
  1. .Net products :

    Visual Studio 2001, 2003, 2005, 2008, 2010, 2012
  2. .Net Service :

    Webservices, Window comunication foundation (WCF), Web API
  3. .Net framework :

    Integrated development environment (IDE), Software development kit (SDK)

.Net versions released

  1. 1.0 released on 13 feb 2002.
  2. 1.1 released in apr 2003.
  3. 2.0 released on 7 nov 2005.
  4. 3.0 released on 6 nov 2006.
  5. 3.5 released on 19 nov 2007.
  6. 4.0 released on 12 apr 2010.
  7. 4.5 released on 15 aug 2012.

Platform support

  1. .Net framework runs on Window Xp, Window 2000, NT4, ME/98, SP6a, Vista, Window 7 & 8, Window Server 2003, 2008 & 2012
  2. Window 95 is not supported.
  3. Window 98/ME can't be used for development.

.Net Framework

.Net framework is a tool of .Net platform for building, deploying and running webservices, web applications and window applications. Mazor elements of .Net framework are CLR (common language runtime), FCL(framework class library), webservices, window & webforms/applications.

Features of .Net framework

  1. It is a layer between operating system(OS) and programming language.
  2. It supports many programming languages.
  3. .Net provides a common set of class library which can be accessed from any .Net based programming language.      

Friday 3 May 2013

Shortcut Key in SQL Server Management Studio



Shortcut Key in Sql Server Management Studio

Launching SSMS

START -> Run or press Windows + R, type ssms and click OK (or hit ENTER) which will launch SSMS.
You can also specify different parameters or switches
  • The -E switch will let you connect to the local instance using Windows authentication.
  • The -U switch is used to specify a user and -P to specify the password
  • If you want SSMS to connect to a specific database you can use the -d switch
  • If you want a script file to be opened in SSMS you can specify the location and name of the file. This will just open the file in SSMS and will not execute the code. If you need to execute a script file you can use the SQLCMD utility.
  • To close SSMS you can use ALT+F4.

You can simply open the SSMS or you can specify the -E switch to open SSMS and connect using Windows authentication. If the current user does not have sufficient permissions obviously it will fail.

When we open SSMS a splash screen appears while loading SSMS in the memory. You can specify -nosplash switch which opens SSMS without the splash screen.

You can use -? which gives you the different command options as shown below. 


Table Details

            If you select a table name in the query window of Sql Server Management Studio
and press ALT + F1 it will display the details of that table.

In the background shortcut key will execute sp_help on your behalf, so in this example it executes: sp_help users, which is much quicker than typing it.


Otherwise you can also use sp_columns test_tbl


Changing Databases

Once you are in a Query Window in SSMS you can use CTRL+U to change the database. When you press this combination, the database combo-box will be selected as shown below. You can then use the UP and DOWN arrow keys to change between databases (or type a character to jump to databases starting with that character) select your database and hit ENTER to return back to the Query Window.


Changing Code Case (Upper or Lower)

When you are writing code you may not bother with using upper or lower case to make your code easier to read. To fix this later, you can select the specific text and hit CTRL+SHIFT+U to make it upper case or use CTRL+SHIFT+L to make it lower case as shown below.


Commenting Out Code

When writing code sometimes you need to comment out lines of code. You can select specific lines and hit CTRL+K followed by CTRL+C to comment it out and CTRL+K followed by CTRL+U to uncomment it out as shown below.

 Indenting Code

As a coding best practice you should to indent your code for better readability. To increase the indent, select the lines of code (to be indented) and hit TAB as many times as you want to increase the indent likewise to decrease the indent again select those lines of code and hit SHIFT+TAB.


There are many shortcut keys that are listed below.

Action
SSMS-Shortcut Key
Display the Query Designer
CTRL+SHIFT+Q
Close a menu or dialog box, canceling the action
ESC
Cancel a query
ALT+BREAK
Connect
CTRL+O
Disconnect
CTRL+F4
Disconnect and close child window
ALT+F4
Database object information
ALT+F1
Go to a line number
CTRL+G
Remove comments
CTRL+SHIFT+R
Execute a query
F5 or Ctrl + E
New Query window
CTRL+N
Object Browser (show/hide)
F8
Parse the query and check syntax
CTRL+F5
Display results in grid format
CTRL+D
Display results in text format
CTRL+T
Use database
CTRL+U

Wednesday 1 May 2013

HTML Codes for Punctuation and Other Characters

HTML codes to put punctuation characters on your Web page

The following list includes the HTML codes for punctuation characters not in the standard character set. Not all browsers support all the codes, so be sure to test your HTML codes before you use them.
Some punctuation characters are part of the Unicode character set, so you need to declare that in the head of your documents:
<meta http-equiv="content-type" content="text/html;charset=utf-8" />

Display Friendly Code Numerical Code Hex Code Description
&#09; &#x09; Horizontal Tab
&#10; &#x10; Line Feed
&#32; &#x20; Space
! ! &#33; &#x21; Exclamation Point
" &quot; &#34; &#x22; Double Quote
# # &#35; &#x23; Number Sign
& &amp; &#38; &#x26; Ampersand
' ' &#39; &#x27; Single Quote
( ( &#40; &#x28; Left Parenthesis
) ) &#41; &#x29; Right Parenthesis
* * &#42; &#x2A; Asterisk (Star)
, , &#44; &#x2C; Comma
- - &#45; &#x2D; Hyphen
. . &#46; &#x2E; Period
/ / &#47; &#x2F; Forward Slash
: : &#58; &#x3A; Colon
; ; &#59; &#x3B; Semi-Colon
? ? &#63; &#x3F; Question Mark
@ @ &#64; &#x40; At Sign
[ [ &#91; &#x5B; Left Square Bracket
\ \ &#92; &#x5C; Back Slash
] ] &#93; &#x5D; Right Square Bracket
^ ^ &#94; &#x5E; Caret
_ _ &#95; &#x5F; Underscore
{ { &#123; &#x7B; Left Curly Brace
| | &#124; &#x7C; Vertical Bar
} } &#125; &#x7D; Right Curly Brace
~ &tilde; &#126; &#x7E; Vertical Bar
&sbquo; &#130; &#x82; Single Low Quote
&dbquo; &#132; &#x84; Double Low Quote
&#133; &#x85; Elipsis
&dagger; &#134; &#x86; Dagger
&Dagger; &#135; &#x87; Double Dagger
&lsaquo; &#139; &#x8B; Left Single Angle Quote
&lsquo; &#145; &#x91; Left Single Quote
&rsquo; &#146; &#x92; Right Single Quote
&ldquo; &#147; &#x93; Left Double Quote
&rdquo; &#148; &#x94; Right Double Quote
&#149; &#x95; Small Bullet
&ndash; &#150; &#x96; En Dash
&mdash; &#151; &#x97; Em Dash
&trade; &#153; &#x99; Trademark
&rsaquo; &#155; &#x9B; Right Single Angle Quote
&nbsp; &#160; &#xA0; Non-Breaking Space
¡ &iexcl; &#161; &#xA1; Inverted Exclamation Point
¦ &brvbar; &#166; &#xA6; Broken Vertical Bar
© &copy; &#169; &#xA9; Copyright
ª &ordf; &#170; &#xAA; Feminine Ordinal Indicator
« &laquo; &#171; &#xAB; Left Angle Quote
¬ &not; &#172; &#xAC; Not Sign
­ &shy; &#173; &#xAD; Soft Hyphen
® &reg; &#174; &#xAE; Registered Symbol
° &deg; &#176; &#xB0; Degree
² &sup2; &#178; &#xB2; Superscript 2
³ &sup3; &#179; &#xB3; Superscript 3
µ &micro; &#181; &#xB5; Micro Sign
&para; &#182; &#xB6; Pilcrow (Paragraph Sign)
· &middot; &#183; &#xB7; Middle Dot
¹ &sup1; &#185; &#xB9; Superscript 1
º &ordm; &#186; &#xBA; Masculine Ordinal Indicator
» &raquo; &#187; &#xBB; Right Angle Quote
¿ &iquest; &#191; &#xBF; Inverted Question Mark
&#8453; &#x2105; Care Of
&#8319; &#x207F; Superscript N
§ &sect; &#167; &#xA7; Section Mark
¨ &iquest; &#191; &#xBF; Inverted Question Mark
&#8213; &#x2015; Horizontal Bar
&#8227; &#x2023; Triangle Bullet
&oline; &#8254; &#x203E; Overline
&#8252; &#x203C; Double Exclamation Point
&#8470; &#x2116; Number Word

Other Character Codes

Note: not all of these characters will display on every browser, be sure to test before you rely on them for your Web site.

Display Friendly Code Numerical Code Hex Code Description
&spades; &#9824; &#x2660; Spade card suit
&clubs; &#9827; &#x2663; Clubs card suit
&diams; &#9830; &#x2666; Diamonds card suit
&hearts; &#9829; &#x2665; Hearts card suit
&larr; &#8592; &#x2190; Left arrow
&rarr; &#8594; &#x2192; Right arrow
&uarr; &#8593; &#x2191; Up arrow
&darr; &#8595; &#x2193; Down arrow
&#9792; &#x2640; Female Indicator
&#9794; &#x2642; Male Indicator
&#9833; &#x2669; Quarter Note
&#9834; &#x266A; Eighth Note
&#9836; &#x266C; Two Eighth Notes
&#9837; &#x266D; Flat
&#9839; &#x266F; Sharp

Saturday 23 February 2013

ASP.NET Advantages

 ASP.NET Advantages

ASP.NET Is Integrated with the .NET Framework

The massive collection of functionality that the .NET Framework provides is organized in a way that traditional Windows programmers will see as a happy improvement. Each one of the thousands of classes in the .NET Framework is grouped into a logical, hierarchical container called a namespace. Different namespaces provide different features. Taken together, the .NET namespaces offer functionality for nearly every aspect of distributed development from message queuing to security. This massive toolkit is called the class library.

ASP.NET Is Compiled, Not Interpreted

One of the major reasons for performance degradation in classic ASP pages is its use of interpreted script code. Every time an ASP page is executed, a scripting host on the web server needs to interpret the script code and translate it to lower-level machine code, line by line. This process is visibly slow.

ASP.NET applications are always compiled - in fact, it’s impossible to execute C# or Visual Basic code without it being compiled first.

ASP.NET Is Multilanguage

With ASP.NET there is no matter what language you use to develop your application, as the code is compiled in IL (Intermediate Languge).

IL is a stepping stone for every managed application. (A managed application is any application that’s written for .NET and executes inside the managed environment of the CLR.) In a sense, IL is the language of .NET, and it’s the only language that the CLR recognizes.

ASP.NET Is Hosted by the Common Language Runtime

Perhaps the most important aspect of the ASP.NET engine is that it runs inside the runtime environment of the CLR. The whole of the .NET Framework - that is, all namespaces, applications, and classes - is referred to as managed code.

ASP.NET Is Object-Oriented

Asp provides a relatively feeble object model, On the other hand Asp.net is truly object oriented.

Not only does your code have full access to all objects in the .NET Framework, but you can also exploit all the conventions of an OOP (object-oriented programming) environment. For example, you can create reusable classes, standardize code with interfaces, extend existing classes with inheritance, and bundle useful functionality in a distributable, compiled component.

ASP.NET Is Multi-device and Multi-browser

One of the greatest challenges web developers face is the wide variety of browsers they need to support. Different browsers, versions, and configurations differ in their support of HTML. Web developers need to choose whether they should render their content according to HTML 3.2, HTML 4.0, or something else entirely.

ASP.NET addresses this problem in a remarkably intelligent way. Although you can retrieve information about the client browser and its capabilities in an ASP. NET page.
For example: ASP.NET’s validation controls, which use JavaScript and DHTML (Dynamic HTML) to enhance their behavior if the client supports it. This allows the validation controls to show dynamic error messages without the user needing to send the page back to the server for more processing.

ASP.NET Is Easy to Deploy and Configure

ASP.NET simplifies deployment process as :- Every installation of the .NET Framework provides the same core classes. As a result, deploying an ASP.NET application is relatively simple. For no-frills deployment, you simply need to copy all the files to a virtual directory on a production server (using an FTP program or even a command-line command like XCOPY). As long as the host machine has the .NET Framework, there are no time consuming registration steps.

Monday 28 January 2013

New Built-In functions in 2012

Microsoft SQL Server 2012 introduces 14 new built-in functions. These new functions are:
Conversion functions
  • PARSE
  • TRY_CONVERT
  • TRY_PARSE
Date and time functions
  • DATEFROMPARTS
  • DATETIME2FROMPARTS
  • DATETIMEFROMPARTS
  • DATETIMEOFFSETFROMPARTS
  • EOMONTH
  • SMALLDATETIMEFROMPARTS
  • TIMEFROMPARTS
Logical functions
  • CHOOSE
  • IIF
String functions
  • CONCAT
  • FORMAT


CHOOSE
This function can be used to return the value out of a list based on its index number (Note: Index no. here starts from 1) This function takes at-least 2 arguments, where the first must be an INT and the second onwards can be varchar.
The following example returns the Second item from the list of values that are provided.
Select Choose (2, 'January', 'February', 'March');

You can further enhance this functionality and make it dynamic, just declare a variable and depending upon the logic set the value and pass the variable as the first parameter.
Here’s the example for this:
declare @a int
set @a =2
SELECT CHOOSE ( @a, 'January', 'February', 'March');


IIF
If you’ve ever done some programming in Java or VB you must’ve realized what is this? Yes this is the same Conditional function which will return the value based on the condition you specified as the first argument. It takes three parameters where the first declares the condition and rest two are the results you want it to return in case the condition comes out to be true or false respectively.
A. Simple IIF example
DECLARE @a int = 45;
DECLARE @b int = 40;
SELECT IIF (@a > @b, 'TRUE', ‘FALSE’) AS Result;
You can also put multiple conditions using ‘and’, ‘or’ keywords which will help you to evaluate the condition based on multiple things.
B. Complex IIF example
DECLARE @a int = 45;
DECLARE @b int = 40;
SELECT IIF (@a>@b and @b>30, 'TRUE', ‘FALSE’) AS Result;

‘And’ keyword specifies that both the conditions @a>@b and @b>30 should be satisfied in order to make it true, whereas if you replace ‘and’ with ‘or’ keyword then the condition will be accepted as true even if one of them fails.



4. CONCAT
It’s the same concatenate function that we use in excel, it will concatenate two or more strings to make it single string.  It implicitly converts all arguments to string types. It accepts a minimum of 2 (at-least) Arguments and maximum of 254 Arguments.
The return type depends on the type of the arguments. The following table illustrates the mapping.
Input type Output type and length
If any argument is a SQL-CLR system type, a SQL-CLR UDT, or nvarchar(max) nvarchar(max)
Otherwise, if any argument is varbinary(max) or varchar(max) varchar(max) unless one of the parameters is an nvarchar of any length. If so, then the result is nvarchar(max).
Otherwise, if any argument is nvarchar(<= 4000) nvarchar(<= 4000)
Otherwise, in all other cases varchar(<= 8000)unless one of the parameters is an nvarchar of any length. If so, then the result is nvarchar(max).
A. Using CONCAT
SELECT CONCAT (‘Today ', 'is ', 6th, '-', ‘December’) AS Result;
Today is 6th-December

PARSE

This function will parse the value and return the result. In case if it is not able to parse, it will throw an error. You can use this function to convert strings/datetime to datetime or numeric values. Please trust me this function has performance issues compared to CAST/CONVERT.
PARSE ( string_value AS data_type [ USING culture ] )
This function expects three parameters:
  • String_value - The expression which needs to be parsed.
  • Data_type - To which data type we are converting to.
  • CULTUre - To which culture, i.e., language such as gb-en, us-en. This is an optional parameter.
Let us see some examples to see how it works.
SELECT PARSE('08-04-2012' AS datetime USING 'en-US') AS Date
select cast('08-04-2012' AS datetime) as Date
Now the output is


So many people wonder why we have to use Parse when it produces the same output as the CAST function.
Suppose if you are not using ‘en-US’ culture, you are working in Paris, and your server date settings are native to  ‘fr-FR’, and you display date in DD/MM/YYYY format, then what will happen if you use the CAST function?
See the below queries:
SELECT PARSE('08-04-2012' AS datetime USING 'fr-fr') AS Date
select cast('08-04-2012' AS datetime) as Date
Now the output will be:

So now you might understand the real use of Parse I guess. And this is not the only one.
In my database I save inserted date as varchar and in the format “14-Aug-2012” like this. Then how will you convert that into normal datetime? That’s where the Parse function comes into use.
Consider my below queries and see the outputs.
SELECT PARSE('14-Aug-2012' AS datetime USING 'en-us') AS Date
SELECT PARSE('August 14,2012' AS datetime USING 'en-us') AS Date

Isn’t it good?? Saves developer’s time.
We have seen for datetime, now what about numeric? Let us see another example. In many countries, in decimals, instead of ‘.’  comma ‘,’ is used, especially in European countries. 125.00 is the same as 125,00 in France.
So in the database, I am having a varchar column but saving values in decimals and have records like
125,00
134,00
456,00
Now we have to go for culture options in the Parse function.
select parse('125,00' as decimal using 'en-US')
select parse('125,00' as decimal USING 'fr-FR')
These queries will give me output as

So the main advantage of the Parse function is to parse the expression for different cultures.


TRY_PARSE

It is similar to the Parse function, the only difference is when it is not able to parse, it will return a NULL instead of throwing an error as the Parse function.
TRY_PARSE ( string_value AS data_type [ USING culture ] )
This function expects three parameters:
  • String_value - The expression which needs to be parsed
  • Data_type - To which data type we are converting to
  • CULTUre - To which culture i.e language such as gb-en, us-en; this is an optional parameter
Let us see some examples to understand how it works.
--try_parse demo
SELECT PARSE('13-04-2012' AS datetime USING 'en-us') AS Date
SELECT try_PARSE('13-04-2012' AS datetime USING 'en-us') AS Date
The output will be

And if you see in the message tab,

Because when Parse function is not able to parse, it will throw an error. But try_parse just returns null.
Now let us see another example. What will happen if I try to parse an alphanumeric string to integer?
select parse('df23' as int using 'en-US')
select try_parse('df34' as int USING 'en-US')
The output will be:

And if you check in the messages tab,

So try_parse avoids throwing an exception and returns null if it is not able to parse.

TRY_CONVERT

This function is similar to the existing Convert function but the difference is whenever it is not able to convert, it will return null.
TRY_CONVERT ( data_type [ ( length ) ], expression [, style ] )
This function expects three parameters:
  • Data_type - To which data type we are converting to.
  • Expression - The value to be converted/cast.
  • style - Integer parameter that specifies how the cast expression should be. This is an optional parameter.
Let us see some examples to understand how it works.
SELECT CONVERT(datetime, '8/13/2012', 103) AS date
SELECT try_CONVERT(datetime, '8/13/2012', 103) AS date
Note here I am passing month as 13, so the conversion will fail. The first statement will throw an error. But what will happen with the secondone ?
See the output below.

And in the messages tab,

Now one of my varchar column always holds an integer value. But by mistake I saved an alphabet character once. So whenever I try to convert to integer using Cast or Convert, it throws me an error. But I don’t want error. If there are no integer values, then it should return null.
See the below queries and the output.
select try_convert(int,'a')
select convert(int,'a') 


So in general try_convert is similar to try_parse that whenever it is not able to convert, it will return null.

DateTime Functions

1. EOMONTH
This function takes two parameters first being start_date which is mandatory and the second one is Month_to_add which is optional. This function will return the last day of the month (also termed as EOM or end of the month) for the given date, By passing the second argument also it will add the months to the start_date and then returns the last day of the month as per the final date (start_date + Month_to_add)
This can be easily understood with the help of an example:
DECLARE @date DATETIME;  
SET @date = '12/06/2010';  
SELECT EOMONTH (@date) AS Result;
 
--or
 
DECLARE @date VARCHAR(255);  
SET @date = '12/06/2010';  
SELECT EOMONTH (@date) AS Result;

Both of these queries will return the same output i.e.,
-->   2010-12-31 00:00:00.000
In order to find the last day of the month for any future\previous month you must use the second parameter. You can provide a positive or negative value to the second argument based on the requirements. The example below explains it in a better way.
DECLARE @date DATETIME;  
SET @date = GETDATE();  
SELECT EOMONTH ( @date ) as ThisMonth;  
SELECT EOMONTH ( @date, 1 ) as NextMonth;  
SELECT EOMONTH ( @date, -1 ) as LastMonth;

DateFromParts

This function returns a date for the specified year, month, and day.
DATEFROMPARTS ( YEAR,MONTH,DAY )
  • Year - Year value in integer
  • Month - Month value in integer, between 1 and 12
  • Day - Day value in integer, between 1 and 31
Returns: Date
Let us see an example of how to use this function. Before MS SQL Server 2012, when we want to form date from year, month, and day, we used to do like this:
declare @year int=2012
declare @month int=4
declare @day int=8
 
SELECT Date=Convert(datetime,convert(varchar(10),@year)+'-'+convert(varchar(10),@day)+'-'+convert(varchar(10),@month),103)


And a few people used to do like this also:
declare @year int=2012
declare @month int=4
declare @day int=8
select dateadd(month,@month-1,dateadd(year,@year-1900,@day-1))

But with SQL Server 2012, the datefromparts function will make this simple.
declare @year int=2012
declare @month int=4
declare @day int=8
select date=DATEFROMPARTS(@year,@month,@day)

Remember it returns date and not datetime.

DateTimeFromParts

Remember the last line I said, the DateFromParts function will only return you the date. So what if I need to get a datetime value from year, month, day, and time as well? That’s where the DateTimeFromParts function comes into picture.
This function returns a datetime for the specified year, month, day, hour, minute, second, and precision.
DATETIMEFROMPARTS(year, month, day, hour, minute, seconds,milliseconds )
  • Year - year value in integer
  • Month - month value in integer, between 1 and 12
  • Day - day value in integer, between 1 and 31
  • Hour - hour value in integer
  • Minute - minute value in integer
  • Seconds - seconds value in integer
  • Milliseconds - milliseconds value in integer
Returns: DateTime
Consider the below query.
declare @year int=2012
declare @month int=4
declare @day int=8
declare @hour int=5
declare @minute int=35
declare @seconds int=34
declare @milliseconds int=567
select date=DATETIMEFROMPARTS(@year,@month,@day,@hour,@minute,
            @seconds,@milliseconds)
The output will be

What will happen if I pass only 6 parameters like this?
declare @year int=2012
declare @month int=4
declare @day int=8
declare @hour int=5
declare @minute int=35
declare @seconds int=34
declare @milliseconds int=567
select date=DATETIMEFROMPARTS(@year,@month,@day,@hour,@minute,@seconds)
it will throw an error..
OK, what will happen if I pass six parameters and the 7th parameter as null?
declare @year int=2012
declare @month int=4
declare @day int=8
declare @hour int=5
declare @minute int=35
declare @seconds int=34
declare @milliseconds int=567
select date=DATETIMEFROMPARTS(@year,@month,@day,@hour,@minute,@seconds,null)
This will return null. So whenever if one or more parameters are null, then the result also will be null.

DateTime2FromParts

This is similar to the above function but the difference is here we can set precision for time part and this function returns DateTime2.
DATETIME2FROMPARTS ( year, month, day, hour, minute, seconds, fractions, precision )
  • year - year value in integer
  • month - month value in integer, between 1 and 12
  • day - day value in integer, between 1 and 31
  • hour - hour value in integer
  • minute - minute value in integer
  • fractions - fractions value in integer
  • precision - precision value in integer
Return: DateTime2
Consider this below query.
declare @year int=2012
declare @month int=4
declare @day int=8
declare @hour int=5
declare @minute int=35
declare @seconds int=34
select date=DATETIME2FROMPARTS(@year,@month,@day,@hour,@minute,@seconds,0,0)
Here I am setting the fraction and precision both to 0. So the output will be

In the above query I am just changing precision to 2. Let us see what happens:
declare @year int=2012
declare @month int=4
declare @day int=8
declare @hour int=5
declare @minute int=35
declare @seconds int=34
select date=DATETIME2FROMPARTS(@year,@month,@day,@hour,@minute,@seconds,0,2)

Now you might be able to see the difference and understand what precision does. Yes it decides the precision of the datetime2 value to be returned. Let us see some more queries for this.
declare @year int=2012
declare @month int=4
declare @day int=8
declare @hour int=5
declare @minute int=35
declare @seconds int=34
select date=DATETIME2FROMPARTS(@year,@month,@day,@hour,@minute,@seconds,50,7)
This will return

declare @year int=2012
declare @month int=4
declare @day int=8
declare @hour int=5
declare @minute int=35
declare @seconds int=34
select date=DATETIME2FROMPARTS(@year,@month,@day,@hour,@minute,@seconds,567,2)
In the above query I set fractions as 567 and precision as 2, guess what will happen? Yes, it will throw an error. Unless I give precision 3 or more, this will throw an error.

SmallDateTimeFromParts

This function returns a smalldatetime value for the specified year, month, day, hour, and minute.
SMALLDATETIMEFROMPARTS ( year, month, day, hour, minute )
  • Year - year value in integer
  • Month - month value in integer, between 1 and 12
  • Day - day value in integer, between 1 and 31
  • Hour - hour value in integer
  • Minute - minute value in integer
Return: SmallDateTime.
Consider this below query.
declare @year int=2012
declare @month int=4
declare @day int=8
declare @hour int=5
declare @minute int=35
select date=SmallDatetimeFromparts(@year,@month,@day,@hour,@minute)
The output will be

DateTimeOffsetFromParts

This function returns a datetimeoffset value for the specified date and time. The OFFSET argument is basically used to represent the time zone offset value hour and minutes.
DATETIMEOFFSETFROMPARTS ( year, month, day, hour, minute, 
             seconds, fractions, hour_offset, minute_offset, precision )
  • Year - year value in integer
  • Month - month value in integer, between 1 and 12
  • Day - day value in integer, between 1 and 31
  • Hour - hour value in integer
  • Minute - minute value in integer
  • Seconds - seconds value in integer
  • fractions - fractions value in integer
  • Hour_offset - hour portion of the time zone offset in integer
  • Minute_offset - minute portion of the time zone offset in integer
  • Precision - precision value in integer
Return: DateTimeOffset.
The offset arguments are used to represent the time zone offset. If the offset arguments are omitted, then the time zone offset is assumed to be 00:00, that is, there is no time zone offset. If the offset arguments are specified, then both arguments must be present and both must be positive or negative.
Consider the below query,
declare @year int=2012
declare @month int=4
declare @day int=8
declare @hour int=5
declare @minute int=35
declare @seconds int=45
select date=DATETIMEOFFSETFROMPARTS(@year,@month,@day,@hour,@minute,@seconds,567,12,40,3)
The output is

TimeFromParts

This function returns a time value for the specified  hour, minute, seconds, fractions, and precision.

TIMEFROMPARTS ( hour, minute, seconds, fractions, precision )
  • Hour - hour value in integer
  • Minute - minute value in integer
  • Seconds - seconds value in integer
  • fractions - fractions value in integer
  • precision - precision value in integer
Return: Time.
Consider this below query.
declare @hour int=5
declare @minute int=35
declare @seconds int=45
select date=TIMEFROMPARTS(@hour,@minute,@seconds,567,3)
The output will be