.

Thursday, December 22, 2016

Java Script Calendar control / Date picker

Best Java Script Calendar control / Date picker for MVC .NET, PHP, etc.

http://dynarch.com/jscal/

Best Multi Select Dropdown for MVC ASP .Net

Please check below URL for Multi select dropdown.
You will definitely love it.

http://wenzhixin.net.cn/p/multiple-select/docs/


Saturday, November 7, 2015

New features in ASP.NET MVC 5

The ASP.NET MVC 5 Framework is the latest update to Microsoft’s popular ASP.NET web platform. It provides an extensible, high-quality programming model that allows you to build dynamic, data-driven websites, focusing on a cleaner architecture and test-driven development.

ASP.NET MVC 5 contains a number of improvements over previous versions, including some new features, improved user experiences; native support for JavaScript libraries to build multi-platform CSS and HTML5 enabled sites and better tooling support.

In this article, we will be taking an overview of some of the exciting new fundamental features of MVC 5:
  • Scaffolding
  • ASP.NET Identity
  • One ASP.NET
  • Bootstrap
  • Attribute Routing
  • Filter Overrides 

Scaffolding

Visual Studio 2013 includes a new Scaffolding Framework for ASP.NET MVC 5 and the ASP.NET Web API 2. Simply put, Scaffolding is a code generation framework provided for ASP.NET Web Applications. Using this framework, you can quickly generate code that interacts with your data models. This feature reduces the amount of time required to build MVC application with standard data operations. Scaffolding uses code-first approach for data operations.
Note: Visual Studio 2013 does not currently support generating pages for an ASP.NET Web Forms project. The only way out is to add MVC dependencies to your Web Forms project and then use Scaffolding.
Let’s quickly explore Scaffolding in ASP.NET MVC 5.
Step 1: Open VS 2013 and create an ASP.NET MVC application with the name MVC5_Scaffolding. In the model folder, add a new class file with the name Product.cs and add the following class definition in it:
using System.ComponentModel.DataAnnotations;
namespace MVC5_Scaffolding.Models
{
public class Product
{
    [Key]
    public int Id { get; set; }
    public string ProdName { get; set; }
    public int ProdPrice { get; set; }
    }
}

Note that the class Product defines an Id property with the Key attribute representing a unique identification of the Product entity.
Step 2: In the project, right-click and select Add > New Scaffolded item as shown here:
new-scaffolded
A window for Add Scaffold will be displayed
mvc-scaffold
Select the scaffold for MVC 5 Controller with views, using Entity Framework as shown in the screenshot. After clicking the Add button, you should see a window similar to the following:
add-mvc-controller
Select the model class from the dropdown. Now to generate the Data Context, click on ‘New Data Context’. A window is displayed where the context class name needs to be entered:
new-data-context
Click on Add and the control will go back to the Add Controller window where you have to check the Generate Views checkbox as shown here:
add-product-controller
This step will add the ProductController, ProductContext classes and Product folder in Views folder with views for data operations:
add-scaffold-controller
This step will also add a connection string of the name ProductContext in the web.config file. The code for the Product context class will be as shown here:
public class ProductContext : DbContext
{
public ProductContext()
    : base("name=ProductContext")
{
}
public System.Data.Entity.DbSet Products { get; set; }
}

The context class uses Code-First approach and creates a table of the name Product using DbSet object of the EntityFramework. The Product Controller class interacts with the ProductContext class for performing CRUD operations using the views generated. Hence Scaffolding reduces the time for developing MVC data oriented applications.

ASP.NET Identity

In earlier days of ASP.NET 2.0 programming, a membership provider approach was introduced. This allowed the application to store user’s data in a SQL Server database. This membership model has changed over the years. The notion that a user can log-in by only using a user-name and password registered in the application, can now be ignored. In today’s world, the web has become more social and users connect to each other, and with applications, using social sites like Facebook, Twitter etc. So considering these social integrations, web applications too need to be enhanced to allow users to log-in using their social media credentials.
To get this done, the modern membership framework is now extended to integrate with social credentials and for this purpose, ASP.NET Identity has been introduced. The advantages of the ASP.NET Identity are explained here:
- One ASP.NET Identity System: Can be used across all the ASP.NET Frameworks like WebForms, MVC, Web Pages, Web API, SignalR etc.
- Ease of plugging-in profile data about the user: The user’s profile schema information can be integrated with the web application.
- Persistence Control: ASP.NET Identity system stores all user information in the database.
- Social Login Provider: Social log-in providers such as Microsoft Account, Facebook, Twitter, Google, and others can be easily added to the web application.
- Windows Azure Active Directory (WAAD): The Login-in information from WAAD can also be used for authenticating a web application.
- OWIN Integration: ASP.NET Identity is fully compliant with OWIN Framework. OWIN Authentication can be used for login. If you are new to OWIN, read this article.
All these features in the ASP.NET Identity membership system are available if you are using Visual Studio 2013. Alternatively, you can also obtain it via NuGet packages Microsoft.Aspnet.Identity.Core and Microsoft.Aspnet.Identity.EntityFramework.

One ASP.NET

One ASP.NET is a new unified project system for .NET Web Developers. This system makes it easier to work with multiple frameworks like Web Forms, MVC, Web API etc., in a single project. So essentially using the One ASP.NET project system, you can use ASP.NET Web Forms and MVC together, and can easily add ASP.NET Web API and SignalR too; in the same Web application.
In Visual Studio 2013, the ASP.NET MVC project template integrates with this new system. One of the useful features while creating a MVC project is that the authentication mechanism can be configured.
Step 1: Open VS 2013 and select File > New > Project, select Web from installed template as below:
one-aspnet-webtemplate
Step 2: Make sure that .NET Framework 4.5.1 is selected; click OK and the following window comes up
one-aspnet-mvc
As you can see, a New ASP.NET Project window displays various Web Templates, and based upon the selection of template, the necessary references will get added in the project. Checkboxes indicates the necessary folder structure and core references for the project.
Step 3: Click on Change Authentication and the authentication provider windows will be displayed:
change-authentication
There are four different authentication types that can be set for the application:
1. No Authentication: The application does not require authentication.
2. Individual User Accounts: SQL Server database is used to store user profile information. This authentication can also be extended to provide the end-user with the option to make use of their social profiles like Facebook, Google, Microsoft, Twitter or any other customized provider.
3. Organizational Accounts: The application can authenticate users using the user profiles stored in Active Directory, Windows Azure Active Directory, or Office 365. This provides Single Sign-on access level to the application. The Organizational Accounts require the following details:
organizational-account
Here the application can be configured for:
  • Cloud-Single Organization
  • Cloud-Multi Organization – This and the previous one can be used when the user authentication information is stored on the Windows Azure Activity Directory (WAAD)
  • On-Premises - Used for the Active Directory on-premises.
  • Domain - The WAAD domain for setting application in it.
  • Access Level - The application needs to query or update directory information.
  • Application ID URI - Created by appending the project name to the domain.
4. Windows Authentication: Used for intranet applications.
Enough theory, let’s see an example!

Using Google Authentication for MVC 5 Application

Let’s design an ASP.NET MVC 5 application which will enable users to log in using an external authentication provider like Google.
Step 1: Open Visual Studio 2013 and create a MVC application. Select Individual User Accounts from the change authentication window as shown here:
change-authentication
Step 2: To enable Google Open ID provider, open the Startup.Auth.cs file from App_Start folder. From the ConfigureAuth method of Startup class, uncomment the GoogleAuthentication method call as shown here:
public void ConfigureAuth(IAppBuilder app)
{
// Enable the application to use a cookie to store information for the signed in user
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
    AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
    LoginPath = new PathString("/Account/Login")
});
// Use a cookie to temporarily store information about a user logging in with a third party login provider
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

// Uncomment the following lines to enable logging in with third party login providers
app.UseGoogleAuthentication();}
Step 3: Run the application; from the Home menu, click on Log In. In the Login view, the Use another service to log in option will be displayed:
external-login-google
Google provider is now enabled for the application! Once the Google button is clicked, the Google Login page will be displayed where the credential information (Gmail ID/Password) needs to be entered. The URL on the Google login page contains openid2. This means that Google credentials will be used to login to the site. After entering the credential information, the web application will demand the following permissions:
  • View your email address
  • View basic information about your account.
login-google-permission
Once the Accept button is clicked, the Register view will be displayed as shown below:
google-register-auth
This step registers your Gmail credentials with the web site you just created. ASP.NET MVC 5 uses the code-first approach for creating database for storing user’s login information. Go to the App_Data folder, a database file of name aspnet-(your application name)-yyyymmdd.mdf will be generated. Open this file in the Server Explorer. In this database, the AspNetUserLogins table will be created. View data from this table and you will find the following information:
openid
Likewise, other authentication providers like Facebook, Microsoft, Twitter can also be used!
I would strongly recommend you read the ASP.NET MVC 5 Authentication Filters article by Raj Aththanayake where he explores the new IAuthenticationFilter in ASP.NET MVC 5 and explains the CustomAuthentication attribute and how you can use to change the current principal and redirect un-authenticated user to a login page.

Bootstrap

In Visual Studio 2013, Twitter Bootstrap is added as the default user interface framework for an MVC application. Bootstrap is a free collection of HTML and CSS based design templates created at Twitter for designing forms, navigation, buttons, tables etc. Bootstrap can be downloaded from here. The advantage of Bootstrap is that it is used for rapid development of Responsive user interface using basic HTML and CSS based templates. In the MVC 5 project, bootstrap.js and bootstrap.css is already present:
bootstrap
In the MVC 5 project open _Layout.cshtml and you will find a
tag under the element as seen here: layout-navbar
Observe that the
tag is decorated with CSS classes like navbar, navbar-inverse, navbar-fixed-top. These classes are declared in the bootstrap.css and it means that the navigation bar showing Application name, Home, About and Contact is displayed on the top with fixed position, so even when the page is scrolled down; the Navigation bar will be fixed on the top as shown here: Navigation Bar at the beginning of the page:
nav-bar-1
After the page scrolls down, the Navigation bar location is still fixed to the top:
nav-bar-2

Attribute based Routing

The beauty of MVC is in its routing feature. Routing is how ASP.NET MVC matches a URL to an action. In earlier versions of MVC, the routing expressions were provided in the Global.asax class in Application_start event. (Note: In MVC 4, a separate class of name RouteConfig is provided in the App_Start folder.) The route expression set in MVC 4 is similar to the following:
public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
           
    routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}/{id}",
        defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
    );
}

In this code, the defaults are already set to Home controller and its Index action method. This means that when a new URI is requested through the browser addressbar, this expressions has to be re-generated for controller other than Home.
Why to use Attribute Routing?
In MVC 5, to have more control over the URIs of a Web application, we can implement the route definition along with the action methods in the controller class, using attributes. In other words, we use attributes to define routes. To enable attribute based routing, the RegisterRoutes method needs to be changed to the following:
public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    routes.MapMvcAttributeRoutes();
    routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}/{id}",
        defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
    );
}


Saturday, October 31, 2015

Special Effects with Jquery

jQuery provides a trivially simple interface for doing various kind of amazing effects. jQuery methods allow us to quickly apply commonly used effects with a minimum configuration.
This tutorial covers all the important jQuery methods to create visual effects.

Showing and Hiding elements

The commands for showing and hiding elements are pretty much what we would expect − show() to show the elements in a wrapped set and hide() to hide them.

Syntax

Here is the simple syntax for show() method −
[selector].show( speed, [callback] );
Here is the description of all the parameters −
  • speed − A string representing one of the three predefined speeds ("slow", "normal", or "fast") or the number of milliseconds to run the animation (e.g. 1000).
  • callback − This optional parameter represents a function to be executed whenever the animation completes; executes once for each element animated against.
Following is the simple syntax for hide() method −
[selector].hide( speed, [callback] );
Here is the description of all the parameters −
  • speed − A string representing one of the three predefined speeds ("slow", "normal", or "fast") or the number of milliseconds to run the animation (e.g. 1000).
  • callback − This optional parameter represents a function to be executed whenever the animation completes; executes once for each element animated against.

Example

Consider the following HTML file with a small JQuery coding −
<html>
   <head>
      <title>The jQuery Example</title>
      <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
  
      <script type="text/javascript" language="javascript">
         $(document).ready(function() {

            $("#show").click(function () {
               $(".mydiv").show( 1000 );
            });

            $("#hide").click(function () {
               $(".mydiv").hide( 1000 );
            });
         });
      </script>
  
      <style>
         .mydiv{ margin:10px;padding:12px; border:2px solid #666; width:100px; height:100px;}
      </style>

   </head>
 
   <body>
 
      <div class="mydiv">
         This is a SQUARE
      </div>

      <input id="hide" type="button" value="Hide" />   
      <input id="show" type="button" value="Show" />   

   </body>
 
</html>

Toggling the elements

jQuery provides methods to toggle the display state of elements between revealed or hidden. If the element is initially displayed, it will be hidden; if hidden, it will be shown.

Syntax

Here is the simple syntax for one of the toggle() methods −
[selector]..toggle([speed][, callback]);
Here is the description of all the parameters −
  • speed − A string representing one of the three predefined speeds ("slow", "normal", or "fast") or the number of milliseconds to run the animation (e.g. 1000).
  • callback − This optional parameter represents a function to be executed whenever the animation completes; executes once for each element animated against.

Example

We can animate any element, such as a simple <div> containing an image −
<html>
   <head>
      <title>The jQuery Example</title>
      <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
  
      <script type="text/javascript" language="javascript">

         $(document).ready(function() {
            $(".clickme").click(function(event){
               $(".target").toggle('slow', function(){
                  $(".log").text('Transition Complete');
               });
            });
         });
      </script>
  
      <style>
         .clickme{ margin:10px;padding:12px; border:2px solid #666; width:100px; height:50px;}
      </style>
  
   </head>
 
   <body>
 
      <div class="content">
         <div class="clickme">Click Me</div>
         <div class="target">
            <img src="./images/jquery.jpg" alt="jQuery" />
         </div>
         <div class="log"></div>
      </div>   
   </body>
 
</html>

JQuery Effect Methods

You have seen basic concept of jQuery Effects. Following table lists down all the important methods to create different kind of effects −
S.No. Methods & Description
1 animate( params, [duration, easing, callback] )
A function for making custom animations.
2 fadeIn( speed, [callback] )
Fade in all matched elements by adjusting their opacity and firing an optional callback after completion.
3 fadeOut( speed, [callback] )
Fade out all matched elements by adjusting their opacity to 0, then setting display to "none" and firing an optional callback after completion.
4 fadeTo( speed, opacity, callback )
Fade the opacity of all matched elements to a specified opacity and firing an optional callback after completion.
5 hide( )
Hides each of the set of matched elements if they are shown.
6 hide( speed, [callback] )
Hide all matched elements using a graceful animation and firing an optional callback after completion.
7 show( )
Displays each of the set of matched elements if they are hidden.
8 show( speed, [callback] )
Show all matched elements using a graceful animation and firing an optional callback after completion.
10 slideDown( speed, [callback] )
Reveal all matched elements by adjusting their height and firing an optional callback after completion.
11 slideToggle( speed, [callback] )
Toggle the visibility of all matched elements by adjusting their height and firing an optional callback after completion.
12 slideUp( speed, [callback] )
Hide all matched elements by adjusting their height and firing an optional callback after completion.
13 stop( [clearQueue, gotoEnd ])
Stops all the currently running animations on all the specified elements.
14 toggle( )
Toggle displaying each of the set of matched elements.
15 toggle( speed, [callback] )
Toggle displaying each of the set of matched elements using a graceful animation and firing an optional callback after completion.
16 toggle( switch )
Toggle displaying each of the set of matched elements based upon the switch (true shows all elements, false hides all elements).
17 jQuery.fx.off
Globally disable all animations.

UI Library Based Effects

To use these effects you can either download latest jQuery UI Library jquery-ui-1.11.4.custom.zip from jQuery UI Library or use Google CDN to use it in the similar way as we have done for jQuery.
We have used Google CDN for jQuery UI using following code snippet in the HTML page so we can use jQuery UI −
<head>
   <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.3/jquery-ui.min.js"></script>
</head>
S.No. Methods & Description
1 Blind
Blinds the element away or shows it by blinding it in.
2 Bounce
Bounces the element vertically or horizontally n-times.
3 Clip
Clips the element on or off, vertically or horizontally.
4 Drop
Drops the element away or shows it by dropping it in.
5 Explode
Explodes the element into multiple pieces.
6 Fold
Folds the element like a piece of paper.
7 Highlight
Highlights the background with a defined color.
8 Puff
Scale and fade out animations create the puff effect.
9 Pulsate
Pulsates the opacity of the element multiple times.
10 Scale
Shrink or grow an element by a percentage factor.
11 Shake
Shakes the element vertically or horizontally n-times.
12 Size
Resize an element to a specified width and height.
13 Slide
Slides the element out of the viewport.
14 Transfer
Transfers the outline of an element to another.

Jquery effects example

jQuery UI Effects - Effect demo

Effect

Etiam libero neque, luctus a, eleifend nec, semper at, lorem. Sed pede. Nulla lorem metus, adipiscing ut, luctus sed, hendrerit vitae, mi.

jQuery Selectors

Selector Example Selects
* $("*") All elements
#id $("#lastname") The element with id="lastname"
.class $(".intro") All elements with class="intro"
.class,.class $(".intro,.demo") All elements with the class "intro" or "demo"
element $("p") All <p> elements
el1,el2,el3 $("h1,div,p") All <h1>, <div> and <p> elements
:first $("p:first") The first <p> element
:last $("p:last") The last <p> element
:even $("tr:even") All even <tr> elements
:odd $("tr:odd") All odd <tr> elements
:first-child $("p:first-child") All <p> elements that are the first child of their parent
:first-of-type $("p:first-of-type") All <p> elements that are the first <p> element of their parent
:last-child $("p:last-child") All <p> elements that are the last child of their parent
:last-of-type $("p:last-of-type") All <p> elements that are the last <p> element of their parent
:nth-child(n) $("p:nth-child(2)") All <p> elements that are the 2nd child of their parent
:nth-last-child(n) $("p:nth-last-child(2)") All <p> elements that are the 2nd child of their parent, counting from the last child
:nth-of-type(n) $("p:nth-of-type(2)") All <p> elements that are the 2nd <p> element of their parent
:nth-last-of-type(n) $("p:nth-last-of-type(2)") All <p> elements that are the 2nd <p> element of their parent, counting from the last child
:only-child $("p:only-child") All <p> elements that are the only child of their parent
:only-of-type $("p:only-of-type") All <p> elements that are the only child, of its type, of their parent
parent > child $("div > p") All <p> elements that are a direct child of a <div> element
parent descendant $("div p") All <p> elements that are descendants of a <div> element
element + next $("div + p") The <p> element that are next to each <div> elements
element ~ siblings $("div ~ p") All <p> elements that are siblings of a <div> element
:eq(index) $("ul li:eq(3)") The fourth element in a list (index starts at 0)
:gt(no) $("ul li:gt(3)") List elements with an index greater than 3
:lt(no) $("ul li:lt(3)") List elements with an index less than 3
:not(selector) $("input:not(:empty)") All input elements that are not empty
:header $(":header") All header elements <h1>, <h2> ...
:animated $(":animated") All animated elements
:focus $(":focus") The element that currently has focus
:contains(text) $(":contains('Hello')") All elements which contains the text "Hello"
:has(selector) $("div:has(p)") All <div> elements that have a <p> element
:empty $(":empty") All elements that are empty
:parent $(":parent") All elements that are a parent of another element
:hidden $("p:hidden") All hidden <p> elements
:visible $("table:visible") All visible tables
:root $(":root") The document's root element
:lang(language) $("p:lang(de)") All <p> elements with a lang attribute value starting with "de"
[attribute] $("[href]") All elements with a href attribute
[attribute=value] $("[href='default.htm']") All elements with a href attribute value equal to "default.htm"
[attribute!=value] $("[href!='default.htm']") All elements with a href attribute value not equal to "default.htm"
[attribute$=value] $("[href$='.jpg']") All elements with a href attribute value ending with ".jpg"
[attribute|=value] $("[title|='Tomorrow']") All elements with a title attribute value equal to 'Tomorrow', or starting with 'Tomorrow' followed by a hyphen
[attribute^=value] $("[title^='Tom']") All elements with a title attribute value starting with "Tom"
[attribute~=value] $("[title~='hello']") All elements with a title attribute value containing the specific word "hello"
[attribute*=value] $("[title*='hello']") All elements with a title attribute value containing the word "hello"
:input $(":input") All input elements
:text $(":text") All input elements with type="text"
:password $(":password") All input elements with type="password"
:radio $(":radio") All input elements with type="radio"
:checkbox $(":checkbox") All input elements with type="checkbox"
:submit $(":submit") All input elements with type="submit"
:reset $(":reset") All input elements with type="reset"
:button $(":button") All input elements with type="button"
:image $(":image") All input elements with type="image"
:file $(":file") All input elements with type="file"
:enabled $(":enabled") All enabled input elements
:disabled $(":disabled") All disabled input elements
:selected $(":selected") All selected input elements
:checked $(":checked") All checked input elements

Wednesday, December 19, 2012

Captcha with Javascript

Here I create a Captcha Code with JavaScript.

Step 1:

In the (.aspx) page we write the following Code:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title></title>
<script language="javascript">
var a = 49, b = 65;
var c = 100;
var d = 70;
functionshow() {
if(a == 57) {
a = 49;
}
varmain = document.getElementById('txt11');
vara1 = String.fromCharCode(a);
varb1 = String.fromCharCode(b);
varc1 = String.fromCharCode(c);
vard1 = String.fromCharCode(d);
main.value = a1 + b1 + c1 + d1;
a = a + 1;
b = b + 1;
c = c + 1;
d = d + 1;
}
</script>
<style type="text/css">
#form1
{
height: 95px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<input type="text" id="txt11" runat="server"
style="border-style: none; border-color: inherit; border-width: medium; background-color:black; color:red; font-family: 'Curlz MT'; font-size: x-large; font-weight: bold; font-variant: normal; letter-spacing: 10pt; width: 120px; background-image: url('back.gif');"
value="4GdT" />
<input type="button" onclick="show()" value="Change" />
</div>
<asp:TextBox ID="txtverification" runat="server"></asp:TextBox>
    
<asp:Button ID="Button1" runat="server" Text="Verification"
onclick="Button1_Click" />
    
<asp:Label ID="lblmsg" runat="server" Font-Bold="True" ForeColor="Red"></asp:Label>
</form>
</body>
</html>

Step 2:

In the (.cs) page I write the following code for verification:

protected voidButton1_Click(object sender, EventArgs e)
{
if(txtverification.Text == txt11.Value)
{
lblmsg.Text = "Successful";
}
else
{
lblmsg.Text = "Failure";
}
}

Introduction of MVC

Why should I use MVC?
  1. Test Driven Development support.
  2. Search Engine Optimization friendly URL by design (though now this is possible in ASP.NET 4 as well)
  3. No ViewState (this may seem a bit of moving backward to some), but overall a good design decision.
  4. Clean View Markup (no additional HTML emitted)
  5. 100% extensible. You can add your own controller, switch view engines at will, control model binding at wish etc.
  6. Rich UI support (possible through client side JS libraries like jQuery UI and others). Telerik has released some controls for MVC which includes Grid control as well (which are merely HTMLHelpers)
  7. Session, JS, Ajax works. Validation is even more powerful with DataAnnotations and jquery.
  8. Performance, faster.
  9. Full control over rendered HTML
  10. Pluggable architecture
Introduction to MVC

MVC is a programming architecture that aids developers with separating different components of an application

The Model

The model in an MVC application stores the application data or state of the application. The model is often a database, an XML file, etc. However, because the model is designed to encapsulate the data layer in the application, you will typically not see the data source correlated with the model with regards to MVC.

In an ASP.NET MVC application, the model typically uses LINQ to SQL or LINQ to Entities.

The View

The view is the user interface that your site visitors to see data from your model. In an ASP.NET MVC application, web forms (ASPX pages) are typically used to display the view, but there's a significant difference between an MVC view's page and a typical ASP.NET web form. Most specifically, an MVC view doesn't use the typical postback model and the page lifecycle that you are used to when using web forms doesn't exist with MVC views.

It's easy to make the mistake of thinking of the view as the component in MVC that handles user input and controls the interaction with the user. In fact, it's the controller that takes on this role. The view is strictly limited to displaying data from the model.

The Controller

The controller is responsible for handling the interaction with the user, for communicating with the model, and for determining which view to display to the user. The controller is derived from System.Web.Mvc.Controller.

The controller defines one or more actions that can be invoked using an URL entered into a web browser. For example, consider the following URL:

http://www.arvind.com/products/display/43

A request such as this one would be handed off to the ProductsController where the display action would be invoked. In this particular case, that action might then display a view of product number 43. The routing of the URL to a particular controller is configured using routes that are defined in the global.asax of the MVC application.

Asp.net MVC is slightly different from a normal asp.net application. In an ASP.NET Web site, URLs typically map to files that are stored on disk (usually .aspx files). These .aspx files include markup and code that is processed in order to respond to the request.

In MVC, Instead of mapping URLs to ASP.NET pages or handlers, the framework maps URLs to controller classes. Controller classes handle incoming requests, such as user input and interactions, and execute appropriate application and data logic, based on user input. A controller class typically calls a separate view component that generates HTML output as the response.

URL routing

The ASP.NET MVC framework uses the ASP.NET routing engine. We can define routing rules that the ASP.NET MVC framework uses in order to evaluate incoming URLs and to select the appropriate controller. You can also have the routing engine automatically parse variables that are defined in the URL, and have the ASP.NET MVC framework pass the values to the controller as parameter arguments.

MVC & Post backs

ASP.NET MVC framework does not use the ASP.NET Web Forms post back model for interactions with the server. Instead, all end-user interactions are routed to a controller class. This maintains separation between UI logic and business logic and helps testability. As a result, ASP.NET view state and ASP.NET Web Forms page life-cycle events are not integrated with MVC-based views.

MVC Project Structure

By default, MVC projects include the following folders:

  • App_Data, which is the physical store for data. This folder has the same role as it does in ASP.NET Web sites that use Web Forms pages.
  • Content, location to add content files such as cascading style sheet files, images, and so on. In general, the Content folder is for static files.
  • Controllers.
  • Models.
  • Scripts, which is the recommended location for script files that support the application. By default, this folder contains ASP.NET AJAX foundation files and the jQuery library.
  • Views.
MVC3 & Razor:

What is Razor?

ASP.NET MVC has always supported the concept of "view engines" - which are the pluggable modules that implement different template syntax options. The "default" view engine for ASP.NET MVC uses the same .aspx/.ascx/. master file templates as ASP.NET Web Forms. Other popular ASP.NET MVC view engines are Spart & Nhaml.

MVC 3 has introduced a new view engine called Razor.

Why is Razor?

  1. Compact & Expressive.
  2. Razor minimizes the number of characters and keystrokes required in a file, and enables a fast coding workflow. Unlike most template syntaxes, you do not need to interrupt your coding to explicitly denote server blocks within your HTML. The parser is smart enough to infer this from your code. This enables a really compact and expressive syntax which is clean, fast and fun to type.
  3. Easy to Learn: Razor is easy to learn and enables you to quickly be productive with a minimum of effort. We can use all your existing language and HTML skills.
  4. Works with any Text Editor: Razor doesn't require a specific tool and enables you to be productive in any plain old text editor (notepad works great).
  5. Has great Intellisense:
  6. Unit Testable: The new view engine implementation will support the ability to unit test views (without requiring a controller or web-server, and can be hosted in any unit test project - no special app-domain required).
Why do we use HTML Helper?

We can use HTML helpers to encapsulate some small HTML fragments which are repeated all over your pages. And to avoid writing those HTML snippets all over again you use helpers.

Tuesday, December 18, 2012

Features of SQL Server 2012

1. AlwaysOn Availability Groups -- This feature takes database mirroring to a whole new level. With AlwaysOn, users will be able to fail over multiple databases in groups instead of individually. Also, secondary copies will be readable, and can be used for database backups. The big win is that your DR environment no longer needs to sit idle.

2. Windows Server Core Support -- If you don't know what Windows Server Core is, you may want to come up to speed before Windows 8 (MS is making a push back to the command line for server products). Core is the GUI-less version of Windows that uses DOS and PowerShell for user interaction. It has a much lower footprint (50% less memory and disk space utilization), requires fewer patches, and is more secure than the full install. Starting with SQL 2012, it is supported for SQL Server.

3. Columnstore Indexes -- This a cool new feature that is completely unique to SQL Server. They are special type of read-only index designed to be use with Data Warehouse queries. Basically, data is grouped and stored in a flat, compressed column index, greatly reducing I/O and memory utilization on large queries.

4. User-Defined Server Roles -- DBAs have always had the ability to create custom database role, but never server wide. For example, if the DBA wanted to give a development team read/write access to every database on a shared server, traditionally the only ways to do it were either manually, or using undocumented procedures. Neither of which were good solutions. Now, the DBA can create a role, which has read/write access on every DB on the server, or any other custom server wide role.

5. Enhanced Auditing Features -- Audit is now available in all editions of SQL Server. Additionally, users can define custom audit specifications to write custom events into the audit log. New filtering features give greater flexibility in choosing which events to write to the log.

6. BI Semantic Model -- This is replacing the Analysis Services Unified Dimensional Model (or cubes most people referred to them). It's a hybrid model that allows one data model will support all BI experiences in SQL Server. Additionally, this will allow for some really neat text infographics

7. Sequence Objects -- For those folks who have worked with Oracle, this has been a long requested feature. A sequence is just an object that is a counter -- a good example of it's use would be to increment values in a table, based a trigger. SQL has always had similar functionality with identity columns, but now this is a discrete object.

8. Enhanced PowerShell Support -- Windows and SQL Server admins should definitely start brushing up on their PowerShell scripting skills. Microsoft is driving a lot of development effort into instrumenting all of their server-based products with PowerShell. SQL 2008 gave DBAs some exposure to it, but there are many more in cmdlets in SQL 2012.

9. Distributed Replay -- Once again this is answer to a feature that Oracle released (Real Application Testing). However, and in my opinion where the real value proposition of SQL Server is, in Oracle it is a (very expensive) cost option to Enterprise Edition. With SQL, when you buy your licenses for Enterprise Edition, you get everything. Distributed replay allows you to capture a workload on a production server, and replay it on another machine. This way changes in underlying schemas, support packs, or hardware changes can be tested under production conditions.

10. PowerView -- You may have heard of this under the name "Project Crescent" it is a fairly powerful self-service BI toolkit that allows users to create mash ups of BI reports from all over the Enterprise.

11. SQL Azure Enhancements -- These don't really go directly with the release of SQL 2012, but Microsoft is making some key enhancements to SQL Azure. Reporting Services for Azure will be available, along with backup to the Windows Azure data store, which is a huge enhancement. The maximum size of an Azure database is now up to 150G. Also Azure data sync allows a better hybrid model of cloud and on-premise solutions

12. Big Data Support -- I saved the biggest for last, introduced at the PASS (Professional Association for SQL Server) conference last year, Microsoft announced a partnership with Hadoop provider Cloudera. One part of this involves MS releasing a ODBC driver for SQL Server that will run on a Linux platform. Additionally, Microsoft is building connectors for Hadoop, which is an extremely popular NoSQL platform. With this announcement, Microsoft has made a clear move into this very rapidly growing space.

Wednesday, August 3, 2011

Sample Nested Grid

private static string connString = "Data Source=RxDotnet;Initial Catalog=iCATCloud;User ID=dotnet;Password=dotnet;";
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
SqlConnection conn = new SqlConnection(connString);
conn.Open();
SqlCommand cmd = new SqlCommand("Select * from Category", conn);
SqlDataAdapter adpt = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adpt.Fill(ds);
dt1.DataSource = ds;
dt1.DataBind();
conn.Close();
}
}
protected void dt1_ItemDataBound(object sender, DataListItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item e.Item.ItemType == ListItemType.AlternatingItem)
{
CheckBox chkData = (CheckBox)e.Item.FindControl("dtlchkBox");
int i = e.Item.ItemIndex;
string CurrentId = dt1.DataKeys[e.Item.ItemIndex].ToString();
SqlConnection conn = new SqlConnection(connString);
conn.Open();
SqlCommand cmd = new SqlCommand("Select * from Item where CategoryId=" + CurrentId, conn);
SqlDataAdapter adpt = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adpt.Fill(ds);
GridView gv1 = (GridView)e.Item.FindControl("gv1");
gv1.DataSource = ds;
gv1.DataBind();
conn.Close();
}
}
protected void gv1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string CurrentItemId = ((Label)e.Row.FindControl("lblItemId")).Text;
SqlConnection conn = new SqlConnection(connString);
conn.Open();
SqlCommand cmd = new SqlCommand("Select * from Model where ItemId=" + CurrentItemId, conn);
SqlDataAdapter adpt = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adpt.Fill(ds);
GridView gv2 = (GridView)e.Row.FindControl("gv2");
gv2.DataSource = ds;
gv2.DataBind();
conn.Close();
}
}
protected void btnCheckAll_Click(object sender, EventArgs e)
{
for (int cat = 0; cat < dt1.Items.Count; cat++)
{
CheckBox dtlchkBox = (CheckBox)dt1.Items[cat].FindControl("dtlchkBox");
dtlchkBox.Checked = true;
GridView gv1 = (GridView)dt1.Items[cat].FindControl("gv1");
for (int i = 0; i < gv1.Rows.Count; i++)
{
//if (i == 0)
//{
// CheckBox gv1All = (CheckBox)gv1.HeaderRow.FindControl("gv1All");
// gv1All.Checked = true;
//}
CheckBox gvbox = (CheckBox)gv1.Rows[i].FindControl("gvbox");
gvbox.Checked = true;
GridView gv2 = (GridView)gv1.Rows[i].FindControl("gv2");
for (int mod = 0; mod < gv2.Rows.Count; mod++)
{
if (mod == 0)
{
CheckBox gv2All = (CheckBox)gv2.HeaderRow.FindControl("gv2All");
gv2All.Checked = true;
}
CheckBox gv2box = (CheckBox)gv2.Rows[mod].FindControl("gv2box");
gv2box.Checked = true;
}
}
}
}
protected void btnDelete_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(connString);
conn.Open();
 
for (int cat = 0; cat < dt1.Items.Count; cat++)
{
CheckBox dtlchkBox = (CheckBox)dt1.Items[cat].FindControl("dtlchkBox");
if (dtlchkBox.Checked)
{
Response.Write("DataList Id : " + dt1.DataKeys[cat].ToString());
Response.Write("
");
}
else
{
GridView gv1 = (GridView)dt1.Items[cat].FindControl("gv1");
for (int i = 0; i < gv1.Rows.Count; i++)
{
CheckBox gvbox = (CheckBox)gv1.Rows[i].FindControl("gvbox");
if (gvbox.Checked)
{
Response.Write("Grid 1 (Delete Item) : " + ((Label)gv1.Rows[i].FindControl("lblItemName")).Text);
Response.Write("
");
}
else
{
GridView gv2 = (GridView)gv1.Rows[i].FindControl("gv2");
for (int mod = 0; mod < gv2.Rows.Count; mod++)
{
if (mod == 0)
{
CheckBox gv2All = (CheckBox)gv2.HeaderRow.FindControl("gv2All");
if (gv2All.Checked)
{
Response.Write("Grid 2 (Delete All Model) : ");
Response.Write("
");
break;
}
}
CheckBox gv2box = (CheckBox)gv2.Rows[mod].FindControl("gv2box");
if (gv2box.Checked)
{
Response.Write("Grid 2 (Delete Model ) : " + ((Label)gv2.Rows[mod].FindControl("lblModname")).Text);
Response.Write("
");
}
}
}//*********
}
}//*********
}
}

Friday, July 29, 2011

Advantages and Disadvantages of LINQ

LINQ (Language Integrated Query) is a Microsoft programming model and methodology that gives a formal query capabilities into Microsoft .NET-based programming languages.

It offers a compact, expressive, and intelligible syntax for manipulating data. The real value of LINQ comes is to apply the same query to an SQL database, a DataSet, an array of objects in memory and to many other types of data as well. It requires the presence of specific language extensions.

LINQ may be used to access all types of data, whereas embedded SQL is limited to addressing only databases that can handle SQL queries.

Below are the advantages and Disadvantages of LINQ


Advantages:


It is a cleaner and typesafety.
It is checked by the compiler instead of at runtime
It can be debugged easily.
It can be used against any datatype - it isn't limited to relational databases, you can also use it against XML, regular objects.
It can able to query not just tables in a relational database but also text files and XML files.

Disadvantages:


LINQ sends the entire query to the DB hence takes much network traffic but the stored procedures sends only argument and the stored procedure name. It will become really bad if the queries are very complex.
Preformance is degraded if we don't write the linq query correctly.
If you need to make changes to the way you do data access, you need to recompile, version, and redeploy your assembly.

.