Monday, October 28, 2013

What is Cascade and Restrict in DROP table SQL?

RESTRICT specifies that table should not be dropped if any dependencies (i.e. triggers, stored procedure, primary key, foreign key etc) exist. Therefore, if there are dependencies then error is generated and the object is not dropped.


CASCADE specifies that even if there dependencies go ahead with the drop. That means drop the dependencies first and then the main object. So if the table has stored procedures and keys (primary and secondary keys) they are dropped first and then the table is finally dropped.

The DROP statement for Postgres

DROP TABLE table_name [CASCADE | RESTRICT];

SQL DROP TABLE statements allow whole tables to be removed from a database. Both the table data and the table structure itself will be removed. DROP TABLE statements are simply composed of a table name.
DROP TABLE table_name;

The optional CASCADE or RESTRICT suffix defines what happens if the named table is used by other objects in the database. For example foreign key references or views may exist on the named table. If RESTRICT is specified then attempting to delete a table with such references will disallow execution of the statement. If CASCADE is specified, then execution will be allowed, but referencing objects will be dropped as well (tables, views, etc.).
DROP TABLE table_name CASCADE;

To drop a view:
DROP VIEW view_name;

SQL DROP VIEW statements allow views to be removed from a database. DROP VIEW statements are composed of a view name.
DROP VIEW view_name RESTRICT;

As with the DROP TABLE statement, DROP VIEW allows the optional CASCADE or RESTRICT keyword to be suffixed to the statement. The restrict example above would result in the statement not executing if other objects in the database referenced the view in question.

Ranking functions in SQL

SQL Server 2005 has total of 4 ranking function. Ranking functions return a ranking value for each row in a partition. All the ranking functions are non-deterministic.

ROW_NUMBER () OVER ([<partition_by_clause>] <order_by_clause>)
Returns the sequential number of a row within a partition of a result set, starting at 1 for the first row in each partition.

RANK () OVER ([<partition_by_clause>] <order_by_clause>)
Returns the rank of each row within the partition of a result set.

DENSE_RANK () OVER ([<partition_by_clause>] <order_by_clause>)
Returns the rank of rows within the partition of a result set, without any gaps in the ranking.

NTILE (integer_expression) OVER ([<partition_by_clause>] <order_by_clause>)
Distributes the rows in an ordered partition into a specified number of groups.
Example
 
 
 

Friday, October 25, 2013

Some Mix Topics

Inproc session mode,

1. session data is stored in current application domain and so consumes memory of server machine.

2. if server restarts, all session data is lost.

Out-proc mode (which is generally state server),

1. session data is stored on state server and so web servers memory is not consumed.

2. in case of web server restart, session data is preserved.

Web Farm
big organization where there an millions of daily user hits then we need to host the sites on multiple Server. This is called web farms. Where single site hosted on multiple IIS Server and they are  running behind the Load Balancer.
This is the most common scenarios for any web based production environment. Where Client will hit an Virtual IP ( vIP) . Which is the IP address of Load Balancer. When Load balancer received the request based on the server load it will redirect the request to particular Server.
Web Garden
All IIS Request process by worker process ( w3wp.exe). By default each and every application pool contain single worker process. But An application pool with multiple worker process is called Web Garden.
Many workerprocesses with same Application Pool can sometimes provide better throughput performance and application response time. And Each Worker Process Should have there own Thread and Own Memory space.

Application Pool:  Application pool is the container of worker process.  Application pools is used to separate sets of IIS worker processes that share the same configuration.
Worker Process (w3wp.exe) runs the ASP.Net application in IIS. This process is responsible to manage all the request and response that are coming from client system.
handler :
http://www.c-sharpcorner.com/uploadfile/37db1d/create-your-first-http-handler-in-Asp-Net-3-5/

Application life cycle

application life cycle :
whenever a request comes from Client to Server, it will hit HTTP.SYS First.
Now, HTTP.SYS is Responsible for pass the request to particular Application pool.
(Whenever we creates a new Application Pool, the ID of the Application Pool is being generated and it’s registered with the HTTP.SYS. So whenever HTTP.SYS Received the request from any web application, it checks for the Application Pool and based on the application pool it send the request.)
When Application pool receive the request, it simply pass the request to worker process (w3wp.exe) . The workerprocess “w3wp.exe” looks up the URL of the request in order to load the correct ISAPI extension.
When Worker process loads the aspnet_isapi.dll, it start an HTTPRuntime, which is the entry point of an application.
The newly created application domain creates hosting environment, i.e. the ‘HttpRuntime’ object. Once the hosting environment is created, the necessary core ASP.NET objects like ‘HttpContext’ , ‘HttpRequest’ and ‘HttpResponse’ objects are created
After that HttpRuntime load an HttpApplication object
Once ‘HttpApplication’ is created, it starts processing requests.
All the request now passes from  httpModule to  respective HTTPHandler then method and the ASP.NET Page life cycle starts.

Wednesday, October 23, 2013

How to Edit and delete By jquery in gridview with database?


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="GridViewDelete.aspx.cs" Inherits="GridViewDelete" %>
<!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 runat="server">
<title>GridView and JQuery</title>
<style type="text/css">
.record{color:Green;}
.delbutton{color:Red;}
.Ex{color:Gray;}
</style>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script type="text/javascript">
 $(document).ready(function () {
 $(".delbutton").click(function () {
var record_id = $(this).attr("id");
var tr_id = $(this).parents(".record");
if (confirm("Do you want to delete this record?")) {
$.ajax({
 type: "POST",
url: "GridViewDelete.aspx/DeleteUser",
 data: "{'args': '" + record_id + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
 success: function () {
 tr_id.css("background-color", "lightgreen");
tr_id.fadeOut(500, function () {
tr_id.remove();
});
}
});
}
 return false;
});
 $(".delbutton1").click(function () {
var record_id = $(this).attr("id");
document.getElementById('Hdid').value = record_id;
document.getElementById('btnsubmit').value = 'Update';
 $("#<%=GridView1.ClientID %> tr").each(function () {
if (!this.rowIndex) return;
var age1 = $(this).find('td:first').html();
if (record_id == age1) {
document.getElementById('txtname').value = $(this).find('td:eq(1)').html();
document.getElementById('txtfname').value = $(this).find('td:eq(2)').html();
document.getElementById('txtlname').value = $(this).find('td:eq(3)').html();
}
});

});
 $("#btnsubmit").click(function () {
var record_id = document.getElementById('Hdid').value
$.ajax({
 type: "POST",
url: "GridViewDelete.aspx/adduser",
 data: "{'args': '" + record_id + "', uname:'" + document.getElementById('txtname').value + "',fname:'" + document.getElementById('txtfname').value + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
 success: function () { }
});
 if (record_id == 0) {
var stt = '<tr class=record ><td>15<td>' + document.getElementById('txtname').value + '</td>'+
'<td>' + document.getElementById('txtfname').value + '</td>'+
'<td>mname</td>'+
'<td>' + document.getElementById('txtlname').value + '</td>' +
'<td>Email</td>' +'<td> <a href=# id=15 class="delbutton">Delet</a></td>' +
'<td> <a href=# id=15 class="delbutton1">Edit</a></td>' +
'</tr>';
 $('#<%=GridView1.ClientID %>').append(stt);
 } else {
 $("#<%=GridView1.ClientID %> tr").each(function () {

if (!this.rowIndex) return;

var age1 = $(this).find('td:first').html();

if (record_id == age1) {

 $(this).find('td:eq(1)').html(document.getElementById('txtname').value);

 $(this).find('td:eq(2)').html(document.getElementById('txtfname').value);

 $(this).find('td:eq(3)').html(document.getElementById('txtlname').value);


}

 

});

}


 document.getElementById('Hdid').value = 0;


});

});


</script>

</head>

<body>

<form id="form1" runat="server">

<div>

<table><tr>

<td>User Name</td><td><asp:TextBox ID="txtname" runat="server" ></asp:TextBox></td>

<td>First Name</td><td><asp:TextBox ID="txtfname" runat="server" ></asp:TextBox></td>

<td>Last Name</td><td><asp:TextBox ID="txtlname" runat="server" ></asp:TextBox></td>

<td>Last Name</td><td><input type="button" ID="btnsubmit" runat="server" value="save" />

<asp:HiddenField ID="Hdid" Value="0" runat="server" />

</td>

</tr></table>

<asp:GridView CellPadding="5" CellSpacing="5" ID="GridView1" runat="server" RowStyle-CssClass="record" AutoGenerateColumns="False" >

<RowStyle CssClass="record"></RowStyle>

<Columns>

<asp:BoundField DataField="ID" HeaderText="ID" />

<asp:BoundField DataField="User_Name" HeaderText="User Name" />

<asp:BoundField DataField="First_Name" HeaderText="First Name" />

<asp:BoundField DataField="Middle_Name" HeaderText="Middle Name" />

<asp:BoundField DataField="Last_Name" HeaderText="Last Name" />

<asp:BoundField DataField="Email_Id" HeaderText="Email Id" />

<asp:TemplateField>

<ItemTemplate>

<a href="#" id='<%# Eval("ID") %>' class="delbutton">Delet</a>

</ItemTemplate>

</asp:TemplateField>

<asp:TemplateField>

<ItemTemplate>

<a href="#" id='<%# Eval("ID") %>' class="delbutton1">Edit</a>

</ItemTemplate>

</asp:TemplateField>

</Columns>

</asp:GridView>

</div>

</form>

</body>

</html>

















==========================================================

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Data;

using System.Configuration;

using System.Data.SqlClient;

public partial class GridViewDelete : System.Web.UI.Page


{


 protected void Page_Load(object sender, EventArgs e)


{


 if (!IsPostBack)


{

LoadData();

}

}


 [System.Web.Services.WebMethod]

public static void DeleteUser(string args)


{


 string conString = ConfigurationManager.ConnectionStrings["MyConnection"].ConnectionString;

SqlConnection sqlConn = new SqlConnection(conString);

try


{


 SqlCommand sqlCmd = new SqlCommand("DeleteUser", sqlConn);

sqlCmd.CommandType = CommandType.StoredProcedure;

sqlCmd.Parameters.AddWithValue("@id", Convert.ToInt32(args.Trim()));


sqlConn.Open();

sqlCmd.ExecuteNonQuery();

}


 catch


{


 //Handle Error


}


 finally


{

sqlConn.Close();

}

}




 [System.Web.Services.WebMethod]

public static void adduser(string args,string uname,string fname)


{


 string conString = ConfigurationManager.ConnectionStrings["MyConnection"].ConnectionString;

SqlConnection sqlConn = new SqlConnection(conString);

try


{


 SqlCommand sqlCmd = new SqlCommand("addUser", sqlConn);

sqlCmd.CommandType = CommandType.StoredProcedure;

sqlCmd.Parameters.AddWithValue("@id", Convert.ToInt32(args.Trim()));

sqlCmd.Parameters.AddWithValue("@uname", Convert.ToString(uname.Trim()));

sqlCmd.Parameters.AddWithValue("@fname", Convert.ToString(fname.Trim()));


sqlConn.Open();

sqlCmd.ExecuteNonQuery();


 if (args == "0") {

// LoadData();


}

}


 catch


{


 //Handle Error


}


 finally


{

sqlConn.Close();

}

}

 


 private void LoadData()


{


 string conString = ConfigurationManager.ConnectionStrings["MyConnection"].ConnectionString;

SqlConnection sqlConn = new SqlConnection(conString);

try


{


 SqlCommand sqlCmd = new SqlCommand("GetUserRecords", sqlConn);

sqlCmd.CommandType = CommandType.StoredProcedure;


sqlConn.Open();


 SqlDataReader rdr = sqlCmd.ExecuteReader();


GridView1.DataSource = rdr;

GridView1.DataBind();

rdr.Close();

}


 catch


{


 //Handle Error


}


 finally


{

sqlConn.Close();

}

}

}


 

WYSIWYG not support google chrome browser?

http://karenian.wordpress.com/2013/01/23/chrome-fix-openwysiwyg/

Here is the fix — just remove the Safari condition. To be very specific, here is the code:
isBrowserCompatible: function() {
// Validate browser and compatiblity
//if ((navigator.userAgent.indexOf('Safari') != -1 )  ||
 !document.getElementById || !document.designMode) 
if (!document.getElementById || !document.designMode) {
 //no designMode (Safari lies)
 return false;
 }
 return true;
 },
 Opened the file wysiwyg.js inside the /scripts folder.

DDL TRIGGER

DDL triggers are a special kind of trigger that fire in response to Data Definition Language (DDL) statements(Create,Alter,Drop).

They can be used to perform administrative tasks in the database such as auditing and regulating database operations.

Use DDL triggers when you want to do the following:

1.You want to prevent certain changes to your database schema.

2.You want something to occur in the database in response to a change in your database schema.

3.You want to record changes or events in the database schema.



=======================

create TRIGGER safety

ON DATABASE

FOR CREATE_TABLE, DROP_TABLE, ALTER_TABLE

AS

PRINT 'You must disable Trigger "safety" to drop or alter tables!'

ROLLBACK



;

======================

alter TRIGGER safety

ON DATABASE

FOR CREATE_TABLE, DROP_TABLE, ALTER_TABLE

AS

PRINT 'You must disable Trigger "safety" to drop or alter tables!!'

ROLLBACK




;

======================

drop TRIGGER [safety] ON DATABASE;



====================

Disable TRIGGER [safety] ON DATABASE;



======================

ENABLE TRIGGER [safety] ON DATABASE;



===========================================