Thursday, April 19, 2012

how to rename a column or table in SQL SERVER

Here I will tell you how to rename existing table in SQL Database and existing Column in table in SQL Server 

/*To rename a column*/

sp_RENAME 'TableName.[OldColumnName]' , '[NewColumnName]', 'COLUMN'

/*To rename a table*/

sp_RENAME '[OldTableName]' , '[NewTableName]'



By using these two statements we can rename existing table in database or we can rename existing Column in table.

Wednesday, April 18, 2012

how to disable copy, cut and paste (Ctrl + c/Ctrl + v/ Ctrl+ x) options in asp.net textbox

Introduction


Here I will explain how to disable copy, cut and paste functionality (Ctrl + c/Ctrl + v/ Ctrl+ x) in asp.net textbox using JavaScript.

Description

 I will explain how to disable copy, cut, paste or Ctrl+c, Ctrl+v, Ctrl+x options in textbox on aspx page in asp.net. To achieve this we have two methods first method is directly set copy, cut and paste options return false in textbox to disable and second one we can use JavaScript functionality to disable copy, cut and paste options to implement this one first create new website and design your Default.aspx page like this 

First Method


<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Sample to Disable Copy, Cut and Paste Options in textboxtitle>
head>
<body>
<form id="form1" runat="server">
<div>
<strong>First Method To disable copy, cut and paste options in textboxstrong><br />
<asp:TextBox ID="TextBox1" runat="server" oncopy="return false" oncut="return false" onpaste="return false">asp:TextBox>
div>
form>
body>
html>

Second Method


<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Sample to Disable Copy, Cut and Paste Options in textboxtitle>
<script language="javascript" type="text/javascript">
//Function to disable Cntrl key/right click
function DisableControlKey(e) {
// Message to display
var message = "Cntrl key/ Right Click Option disabled";
// Condition to check mouse right click / Ctrl key press
if (e.which == 17 || e.button == 2) {
alert(message);
return false;
}
}
script>
head>
<body>
<form id="form1" runat="server">
<div>
<strong>Second Method to Disable copy, cut and paste options in textboxstrong><br />
<asp:TextBox ID="txtUser" runat="server" onKeyDown="return DisableControlKey(event)" onMouseDown="return DisableControlKey(event)">asp:TextBox>
div>
form>
body>
html>

How do you find the Second highest Salary?

How do you find the Second highest Salary? 

 Answer: We can write a sub-query to achieve the result 

SELECT MAX(SALARY) FROM EMPLOYEE WHERE SALARY NOT IN (SELECT MAX(SALARY) FROM EMPLOYEE)

 The first sub-query in the WHERE clause will return the MAX SALARY in the table, the main query SELECT’s the MAX SALARY from the results which doesn’t have the highest SALARY.

ASP.NET 4.0 Features

The focus of Microsoft’s latest ASP.NET 4has mainly been on improving the performance and Search-engine Optimization (SEO). In this article, I'll be taking a look at what I think are the most important new features in ASP.NET 4.
  • Output cache extensibility
  • Session state compression
  • View state mode for individual control
  • Page.MetaKeyword and Page.MetaDescription properties
  • Response.RedirectPermanent method
  • Routing in ASP.NET
  • Increase the URL character length
  • New syntax for Html Encode
  • Predictable Client IDs
  • Web.config file refactoring
  • Auto-Start ASP.NET applications
  • Improvements on Microsoft Ajax Library
I’ll describe the details of each of these features in the following sections.

Output Cache extensibility

Output caching, or Page-Level Caching, caches the entire rendered markup of an ASP.NET web page for a specific time-period. This has always been one of the essential features for ASP.NET that is used extensively to increase application performance. However there have been some limitations on the feasible extent of caching, because cached content always had to be stored in-memory.
But with ASP.NET 4.0 developers can extend their caching by using Output-cache providers. Developers can now create ‘output-cache providers’ that store the cache contents to any persistence mechanism such as databases, disks, cloud storage and distributed cache engines.
To create a custom output-cache provider, a class which derived from System.Web.Caching.OutputCacheProvider has to be created in ASP.NET 4.0. There are four public methods which you have to override in order to provide your own implementation for add, remove, retrieve and update functionality. Also, the output-cache provider has to be registered in the web.config file as shown in the following screen capture.
You can also set this custom output-cache provider as your default cache mechanism. So once you add the page cache directives all of your contents will be stored using the custom output-cache provider.
Moreover, developers can also dynamically configure which output-cache Provider is used. For example you might want to cache the frequently access pages in the memory for faster access and less frequent pages on disk. By overriding the GetOutputCacheProviderName() method you can configure which output cache provider to use for different requests. These additions to the output-cache can enable developers to write extensible and more efficient cache mechanisms to their web application and thereby improve its responsiveness.

Session State compression

The ASP.NET session state is a mechanism to maintain session-specific data through subsequent requests. In some instances, you may wish to store your session state data in a session-state server or in Microsoft SQL server. However, these two options require you to store data out of the web application’s worker process. To send across to the relevant sources, (State server or Microsoft SQL Server), session-state data has to be serialized. This can take a significant time if the size of the data to be serialized grows significantly. This will increase the latency of the application.
This latency can be reduced if the size of the data is lessened by compression. ASP.NET 4.0 introduces a new mechanism to compress your session state data for both Session-state server and Microsoft SQL server.  Compression can be enabled by setting the compressionEnable to true in the web.config file. In this example, the session-state data will be serialized/desterilized using System.IO.Compression.GZipStream.
  mode="SqlServer"  sqlConnectionString="data source=DB;Initial Catalog=LudmalDB"  allowCustomSqlDatabase="true"  compressionEnabled="true"/>
With this compression feature, developers can often reduce the time it takes for a web application to respond by reducing the size of session data.

View State mode for Individual Controls

View state is a mechanism to maintain page controls’ state on subsequent post backs. ASP.NET stores the view state data for controls that are in the page, even if it’s not necessary. Since the view state data is stored in the pages’ html, the size of the request object will be increased, and make performance worse.
In ASP.NET 4.0, each web control will include a ViewStateMode property which lets developers disable view-state by default, and enable it just for the controls for which a persistence of state is required. ViewStateMode has the following three values;
  • Enabled – enables the view state for this control and any child control.
  • Disabled – disable the view state.
  • Inherits – this specify the control uses the settings from its parent control.
By setting these values in page controls accordingly, a significant performance improvement can be gained in response-time.

Page.MetaKeywords and Page.MetaDescription properties

To increase the relevance of pages in searches, developers should  include relevant “keyword” and “description” meta tags in the html section.     Unfortunately, it takes some time to add these tags for each and every page, and the alternative of adding these tags programmatically was difficult.
But with ASP.NET 4.0, there are two new properties in the code behind file;
  • Page.MetaDescription – equivalent to meta name “description”
  • Page.MetaKeywords – equivalent to meta name “keywords”
This will enable developers to easily and programmatically add the relevant keywords and description.
This will even be useful for Master pages—where you only have to add these properties in the master page. In addition to “keywords” and “description” settings in the code behind, developers can also set these values within the @Page directive.

Response.RedirectPermanent Method

ASP.NET 4.0 has improved SEO (Search-engine Optimization) facilities. Typically developers use Response.Redirect(string url) to handle requests for old URLs. However, this leads to an extra round trip to access the old URLs and so will negatively affect your page-ranking  in search-engines.
ASP.NET 4.0 introduces a new Response.RedirectPermanent(string url) helper method to be used as HTTP 301 (Moved permanently) to handle requests. This will enable search-engines to index URLs and content efficiently and thus improve the page rankings. 

Routing in ASP.NET

Routing will let developers serve meaningful URLs to users and map them with the actual physical files. This URL-rewriting mechanism enables developers to write high ranking, search-engine optimized web applications. For example, URL for a page which displays an actual product might look like the following;
http://www.ludmal.net/showproducts.aspx?prodId=24
By using routing the URL will look like the following
http://www.ludmal.net/products/ipod
In this way, the URLs will be more easily remembered by users.  It will also significantly improve the search-engine page rankings of the web site.
The following example shows how to implement routing behavior in ASP.NET 4 using new MapPageRoute in Route class.
public class Global : System.Web.HttpApplication {   void Application_Start(object sender, EventArgs e)   {     RouteTable.Routes.MapPageRoute("ProductsRoute",       "product/{prodId}", "~/products.aspx");       } }

Increase the URL character length

In previous versions of ASP.NET,  URLs were limited to 260 characters in length. But in ASP.NET 4.0 developers have the option of increasing or decreasing  the length of URLs by using  the new maxRequestPathLength and maxQueryStringLength. I’ll illustrate this in an example.
In previous versions of ASP.NET you were limited to a fixed set of characters but in v4, developers can also validate the invalid characters by specifying values in the requestPathInvalidChars attribute.

New syntax for Html Encode

Html Encode method encodes a particular string to be displayed in a browser. It is important to encode strings prior it’s rendering in the page, mainly to avoid cross-site script injection (XSS) and HTML injection attacks. However, developers so often forget to call the encode function.
In previous .NET versions, Server.HtmlEncode() or HttpUtility.Encode() methods has been used for string encoding as shown in the following example.
ASP.NET 4.0 introduced new code expression syntax for encoding a particular string.  While the syntax will render the output it also encodes the relevant string as shown below. Note “:” character after opening tag (“<%”).
The new encoding syntax provides an easy and concise way of encoding a particular string.

Predictable Client IDs

ASP.NET 4 now supports a new ClientIDMode property for server control. This property indicates how the Client ID should be generated to a particular control when they render. Client ID has been an important property of the server controls recently—especially with the success of jQuery and other Ajax scripting technologies.  The ClientIDMode property has four values;
  • AutoID – This renders the output as it was before (example: ctl00_ContentPlaceholder1_ListView1_ctrl0_Label1)
  • Predictable (Default)– Trims all “ctl00” strings in the Client Id property.
  • Static – Full control over the Client ID (developer can set the Client Id and it will not be changed after the control renders)
  • Inherit – Allow control to inherit the behavior from its parent control
Client ID property can be set in three different ways;
  • Directly on individual control
  • On the container control. (All the child controls will inherit the settings from parent/container control)
  • Page or User Control level using <%@ Page%>  or <%@ Control %> directives.
  • Directly in the web.config file. All the controls within the web application will inherit the settings.
New ClientIDRowSuffix property on databound controls also gives a similar functionality when rendering an each data item. Once you set the relevant databound property to ClientIDRowSuffix, the value will be added as a suffix to individual row elements.
After the control renders the “State” value will be added as a suffix to each data row element.

Web.config refactoring

Over the past few years web.config file has grown significantly as ASP.NET has used it for more and more features such as routing, Ajax, IIS 7 and version compatibility. This has made it trickier to maintain even with the Visual Studio environment.
With ASP.NET 4, most of the major elements have been moved to the machine.config file. This has enabled developers to maintain a cleaner, less cluttered, web.config file. The new web.config file is either empty, or includes just the .NET framework version details as shown in the following example.
             

Auto-Start ASP.NET Applications

Most application requires initial data load or caching operations to be done before serving the client requests. Typical this happens only when the first user request a page. However, often developers and web administrators write fake requests to keep the application alive to increase the response time. To overcome this issue, ASP.NET 4 introduce new Auto-Start feature. Auto-start feature available with IIS 7.5 and it initialize the ASP.NET application to accept requests.
To configure the Auto-start, you need to configure the “Application pool” worker process by setting the startMode attribute to “AlwaysRunning” in the applicationHost.config file. (C:\Windows\System32\inetsrv\config\applicationHost.config)
As soon you save the applicationHost.config file the worker process will start and initialize the required application operations before the first user has been served.

Improvements on Microsoft Ajax Library

Microsoft Ajax library is client side library which includes high performance server –based user controls and asynchronous page rendering controls. Ajax Library enables developers to easily and quickly write responsive database-driven applications.
There are some significant improvements in the Ajax Library in the ASP.NET 4. of which the most important seem to be...
  • Scrip Loader – the new script loader control enable developers to load all the required scripts only once, thereby eliminating the unnecessary subsequent requests to the server. It supports the ‘lazy load’ pattern which loads scripts only when necessary, and loads scripts in combination, in order to increase the performance of loading a page. It also supports the jQuery script and custom scripts.
  • JQuery IntegrationJQuery is very popular third party javascript library. ASP.NET 4 extensively supports the integration for jQuery by mixing the jQuery and Ajax plug-ins seamlessly.
  • Client Data Access – by using pre-defined client controls inside the Ajax Library, developers can easily build asynchronous data-driven applications. For example client DataView control will display one or more records by consuming a WCF service. All the relevant time-consuming operations will be handled by the Ajax library asynchronously.

Conclusion

ASP.NET 4 includes plethora of new features which will enable developers to write high performance, search-engine friendly web application quickly. The features I’ve mentioned seem to be the most important of all the new features in ASP.NET 4. By upgrading your existing web applications to up-coming ASP.NET 4, you are likely to see an improvement in performance and search-engine optimization.

Main Differences between ASP.NET 3.5 and ASP.NET 4.0.

Main Differences between ASP.NET 3.5 and ASP.NET 4.0.

ASP.NET 3.5 is having the following main features which are not availablle in the prior releases


1) AJAX integration

2) LINQ
3) Automatic Properties
4) Lambda expressions

I hope it would be useful for everyone to know about the differences about asp.net 3.5 and its next version asp.net 4.0


Because of space consumption I'll list only some of them here.


1) Client Data access:



ASP.NET 3.5: There is no direct method to access data from client side. We can go for any of these methods


1) Pagemethods of script manager

2) ICallbackEventHandler interface
3) XMLHttphanlder component

ASP.NET 4.0: In this framework there is an inbuilt feature for this. Following are the methods to implement them.


1) Client data controls

2) Client templates
3) Client data context

i.e we can access the data through client data view & data context objects from client side.


2) Setting Meta keyword and Meta description:



Meta keywords and description are really useful for getting listed in search engine.


ASP.NET 3.5: It has a feature to add meta as following tag








ASP.NET 4.0: Here we can add the keywords and description in Page directives itself as shown below.



< %@ Page Language="C#" CodeFile="Default.aspx.cs"

Inherits="_Default"
Keywords="Keyword1,Key2,Key3,etc"
Description="description" %>



3) Enableviewstage property for each control


ASP.NET 3.5: this property has two values "True" or "false"


ASP.NET 4.0: ViewStateMode property takes an enumeration that has three values: Enabled, Disabled, and Inherit.

Here inherit is the default value for child controls of a control.

4) Setting Client IDs

Some times ClientID property creates head ach for the programmers.

ASP.NET 3.5: We have to use ClientID property to find out the id which is dynamically generated


ASP.NET 4.0: The new ClientIDMode property is introduced to minimize the issues of earlier versions of ASP.NET.


It has following values.


AutoID - Same as ASP.NET 3.5

Static - There won't be any separate clientid generated at run time
Predictable-These are used particularly in datacontrols. Format is like clientIDrowsuffix with the clientid vlaue
Inherit- This value specifies that a control's ID generation is the same as its parent.

Friday, April 13, 2012

Asp.net show alert message from code behind using javascript

Introduction:

In this article I will explain how to call JavaScript function from code behind and show JavaScript alert message from code behind using asp.net.
Description:
  
I explained many articles relating to
Asp.net, C#.NET, JavaScript, Gridview, JQuery etc. During working with those articles I came across one situation that is show alert message from code behind after completion of my code execution like our JavaScript alert message.

To display JavaScript alert message from code behind we can do by using ScriptManager.RegisterStartupScript() method. This method will allow us to show alert message direclty from code behind or we can call javascript function from code behind in asp.net.

Declaration of ScriptManager.RegisterStartupScript() metod:

ScriptManager.RegisterStartupScript(Control control, Type type,string key, string script,
bool addScriptTags)
Here I will explain how to show JavaScript alert message in code behind and how to call JavaScript function from code behind in asp.net. For that first create new website and write following code in aspx page


<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Call Javascript functions and show alert message from code behind file in asp.net Pagetitle>
<script type="text/javascript">
function Showalert() {
alert('Call JavaScript function from codebehind');
}
script>
head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="btnSubmit" runat="server" Text="Show alert" onclick="btnSubmit_Click" />
<asp:Button ID="btnClick" runat="server" Text="Call JavaScript Function"
onclick="btnClick_Click" />
div>
form>
body>
html>
Now add following namespaces in codebehind file

using System;
using System.Web.UI;
After that write the following code in code behind

C# code


protected void Page_Load(object sender, EventArgs e)
{
}
//This button click event is used to show alert message directly
protected void btnSubmit_Click(object sender, EventArgs e)
{
ScriptManager.RegisterStartupScript(this,GetType(),"showalert","alert('Only alert Message');",true);
}
// This button click event is used to show alert message from JavaScript function
protected void btnClick_Click(object sender, EventArgs e)
{
ScriptManager.RegisterStartupScript(this, GetType(), "displayalertmessage", "Showalert();", true);
}

ASP.NET Role Based Security

ASP.NET Role Based Security: The Basics

Authentication and authorization is the two basic part of the user-end security in asp.net web applications. After to successful authentication of a user, authorization takes the place according to which the authenticated user are allowed to access to the corresponding resources in the web application.
Role based security is very basic requirements in the current trend of web applications. Mostly there are two roles involved, which are registered user and the admin users. However in a web application a user can have multiple roles which can be authorized on page and page control level. Today we'll check a basic sample which includes page based authorizations for specific roles.
To implement the basic role based security, there are three points to be considered. In this example we are considering two different roles "member" and "admin". There are two separate folders named "member", which can be accessed by any logged in user, including admin users and "admin", where only the user who contains the "admin" role can access the child resources (page, images etc).
1. Defining the authorization regions in web.config
The following xml tags are required to be added under the "configuration" node of the web.config.
Defining security authorization for "member" users
  <location path="member">
    <system.web>
      <authorization>
        <deny users="?"/>
      authorization>
    system.web>
  location>
Defining security authorization for "admin" users
  <location path="admin">
    <system.web>
      <authorization>
        <allow roles="admin"/>
        <deny users="*"/>
      authorization>
    system.web>
  location>
2. Authenticating the user
After the successful authentication, the following codes are required to establish the form based authentication for the corresponding user.
//Authenticating the user Identity. 
System.Web.Security.FormsAuthentication.RedirectFromLoginPage
("member1", this.CheckBox1.Checked);
3. Implementing the role based security
The "Application_AuthenticateRequest" event which was defined in the "Global.asax" file, will include the appropriate codes regarding the role info of the logged in user, which will be accesses each time for any web request in this web application. This can be done in either "cache" or "cookie" mechanism.
Cache based mechanism
    protected void Application_AuthenticateRequest(Object sender, EventArgs e)
    {
        if (HttpContext.Current.User != null)
        {
            if (HttpContext.Current.User.Identity.IsAuthenticated)
            {
                if (HttpContext.Current.User.Identity.AuthenticationType != "Forms")
                    throw new Exception("Only forms authentication is supported, not " +
                        HttpContext.Current.User.Identity.AuthenticationType);
                System.Security.Principal.IIdentity userId = HttpContext.Current.User.Identity;
                //if role info is already NOT loaded into cache, put the role info in cache
                if (System.Web.HttpContext.Current.Cache[userId.Name] == null)
                {
                    string[] roles;
                   
                    if (userId.Name == "admin1")
                        roles = new string[1] { "admin" };//this info will be generally collected from database
                    else if (userId.Name == "member1")
                        roles = new string[1] { "member" };//this info will be generally collected from database
                    else
                        roles = new string[1] { "public" };//this info will be generally collected from database                  
                   
                    //1 hour sliding expiring time. Adding the roles in chache. This will be used in Application_AuthenticateRequest event located in Global.ascx.cs file to attach user Principal object.
                    System.Web.HttpContext.Current.Cache.Add(userId.Name, roles, null, DateTime.MaxValue, TimeSpan.FromHours(1), System.Web.Caching.CacheItemPriority.BelowNormal, null);
                }
               
                //now assign the user role in the current security context
                HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(userId, (string[])System.Web.HttpContext.Current.Cache[userId.Name]);
            }
        }
    }
Cookie based mechanism 
 
    protected void Application_AuthenticateRequest(Object sender, EventArgs e)
    {
        if (HttpContext.Current.User != null)
        {
            if (Request.IsAuthenticated == true)
            {
                if (HttpContext.Current.User.Identity.AuthenticationType != "Forms")
                    throw new Exception("Only forms authentication is supported, not " +
                        HttpContext.Current.User.Identity.AuthenticationType);
                //Create/Retrieve cookie and initizalyze the role info in the current security context
                string userInformation = String.Empty;//where the cookie info will be placed
                string[] roles;//where the user role will be placed
                // Create the roles cookie if it doesn't exist yet for this session.
                if ((Request.Cookies["cnstUserRole"] == null) || (Request.Cookies["cnstUserRole"].Value == ""))
                {
                    if (HttpContext.Current.User.Identity.Name == "admin1")
                        roles = new string[1] { "admin" };//this info will be generally collected from database
                    else if (HttpContext.Current.User.Identity.Name == "member1")
                        roles = new string[1] { "member" };//this info will be generally collected from database
                    else
                        roles = new string[1] { "public" };//this info will be generally collected from database                   
                    // Create a string to persist the role and user id
                    userInformation = roles[0] + ";" + Context.User.Identity.Name;
                    // Create a cookie authentication ticket.
                    FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
                        1,                              // version
                        User.Identity.Name,             // user name
                        DateTime.Now,                   // issue time
                        DateTime.Now.AddHours(1),       // expires every hour
                        false,                          // don't persist cookie
                        userInformation
                        );
                    // Encrypt the ticket
                    String cookieStr = FormsAuthentication.Encrypt(ticket);
                    // Send the cookie to the client
                    Response.Cookies["cnstUserRole"].Value = cookieStr;
                    Response.Cookies["cnstUserRole"].Path = "/";
                    Response.Cookies["cnstUserRole"].Expires = DateTime.Now.AddMinutes(1);
                }//if role cookie not found in local pc
                else//we are getting the role info from cookie
                {
                    // Get roles from roles cookie
                    FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(Context.Request.Cookies["cnstUserRole"].Value);
                    userInformation = ticket.UserData;
                    //info[0] contains the single role and info[1] contains the user name
                    string[] cookieInfo = userInformation.Split(new char[] { ';' });
                    roles = new string[1] { cookieInfo[0] };
                }
                //now assign the user role in the current security context
                Context.User = new System.Security.Principal.GenericPrincipal(Context.User.Identity, roles);
            }//if (Request.IsAuthenticated == true)
        }
    }