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;



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

Friday, October 18, 2013

Tell me About Yorself?

1>>  I did B.Tech degree in Computer Science from Dr. RML Avadh Universty Faizabad (U.P.), I have been in IT industry for 5 years.

I've gained extensive experience in all aspects of software engineering,

including software design, systems architecture,

application programming, and QA testing.

Currently I'm a software engineer with WCT and have worked on several software development projects for our clients.

As the lead developer, I designed and developed a E-commerce based Wesite to help the company increase productivity.

I'm skilled in the Good techniques such as asp.net ,c# , web services and SOA,

proficient with the new languages like C# and MSSQL.

I'm always focused on building robust software systems to meet our customers needs.

One of my major strengths is that I work very hard and continually look for ways to provide the highest quality products

and services while reducing the time and costs to complete the project.

I am self-motivated and enjoy working in a team environment.

I'm looking for an opportunity to work for a growing company where I can contribute my hands-on experience and grow my career with the company.

By some research I found that yours is the type of companies I really want to work with.

Thursday, October 3, 2013

How to reduce images size by c# code?

 
protected void btnsave_Click(object sender, EventArgs e)



{
 
string filename = Path.GetFileName(fileupload1.PostedFile.FileName);

string targetPath = Server.MapPath("Images1/" + filename);

Stream strm = fileupload1.PostedFile.InputStream;

var targetFile = targetPath;



GenerateThumbnails(1, strm, targetFile);



}
 
 
 
 





private void GenerateThumbnails(double scaleFactor, Stream sourcePath, string targetPath)



{

using (var image = System.Drawing.Image.FromStream(sourcePath))



{

var newWidth = (int)(image.Width * scaleFactor);

var newHeight = (int)(image.Height * scaleFactor);

var thumbnailImg = new Bitmap(newWidth, newHeight);

var thumbGraph = Graphics.FromImage(thumbnailImg);

thumbGraph.CompositingQuality = CompositingQuality.HighQuality;

thumbGraph.SmoothingMode = SmoothingMode.HighQuality;

thumbGraph.InterpolationMode = InterpolationMode.HighQualityBicubic;

var imageRectangle = new Rectangle(0, 0, newWidth, newHeight);



thumbGraph.DrawImage(image, imageRectangle);

//thumbnailImg.Save(targetPath, image.RawFormat);

thumbnailImg.Save(targetPath, System.Drawing.Imaging.ImageFormat.Jpeg);



}

}


Tuesday, October 1, 2013

Concept of Caching

Introduction

The concept of Caching was introduced in ASP.NET 1.X and has been improved significantly in ASP.NET 2.0. Caching allows you to store commonly used items in the memory and thus not create them from scratch when they are requested. There are different types of Caching available in the .NET framework. In this article I will introduce you to Caching dependencies.

Caching Dependencies

Caching can depend on several items which include user request, file, database tables, table rows, duration, user controls, query strings, browsers and also other cached items. Let's start with the Caching dependency on other cached items.

Caching Dependency on Cached Items

It is interesting to note that your cached item can depend on other cached items. This means that if the item A is removed from the cache you can also remove item B from the cache. Let's start by creating and inserting the item A and item B in the Cache object.
protected void Button3_Click(object sender, EventArgs e)
{
    // create item A and item B
    string itemA = "ItemA";
    string itemB = "ItemB";
    Cache.Insert("ItemA", itemA, null, DateTime.Now.AddMinutes(10), 
    TimeSpan.Zero,
    CacheItemPriority.Default, MyItemRemovedCallBack);
    Cache.Insert("ItemB", itemB, null, DateTime.Now.AddMinutes(10), 
    TimeSpan.Zero,
    CacheItemPriority.Default, MyItemRemovedCallBack);
}
In the code above I am creating two items "itemA" and "itemB". After creating the items I simply put the items in the Cache object using the Insert method. The last parameter is the callback method "MyItemRemovedCallBack" which will be fired when either of the two items is removed from the Cache.

It is not a good idea to insert the items into the Cache inside the callback method because you might not need the item right away and hence you will be wasting valuable resources to create them.

Let's take a look at the MyItemRemovedCallBack implementation.
private void MyItemRemovedCallBack(string key, object value,
                   CacheItemRemovedReason reason)
{
    // remove the item from the cache
    if (key == "ItemA" ) Cache.Remove("ItemB");
    else if (key.Equals == "ItemB") Cache.Remove("ItemB");
}
The MyItemRemovedCallBack method takes three parameters.
key: This is the key which is used to identify the items in the Cache.
value: The value assigned to the item which is inserted in the Cache.
reason: The variable "reason" is of type CacheItemRemovedReason enumeration and it identifies the reason the item was removed from the Cache.
The code given below removes an item from the Cache and as soon as the item is removed the "MyItemRemovedCallBack" method is fired and removed the other item from the Cache.
protected void Btn_RemoveCacheItem(object sender, EventArgs e)
{
    Cache.Remove("ItemA");
}

Cache Dependency on a File

Next, let's see the Cache dependency on a file. Making the Cache dependent on the file means that when the file contents changes the Cache is expired and the contents are fetched again. Take a look at the simple XML file below which contains the information about the web site menu.
<?xml version="1.0" encoding="utf-8"?>
<MenuItems>
    <MenuItem>
        <Text>Home</Text>
    </MenuItem>
    <MenuItem>
        <Text>About us</Text>
    </MenuItem>
    <MenuItem>
        <Text>Contact us</Text>
    </MenuItem>
    <MenuItem>
        <Text>Help</Text>
    </MenuItem>
    <MenuItem>
        <Text>Feature</Text>
    </MenuItem>
</MenuItems>
We will use the Cache.Insert method to make the Cache dependent on the file. Take a look at the code below:
private void CreateMenu()
{
    string menuPath = "MyFiles/Menu.xml";
    string folderName = "MyFiles/";

    DataSet ds = null;
    if (Cache["Menu"] == null) 
We will use the Cache.Insert method to make the Cache dependent on the file. Take a look at the code below:


private void CreateMenu()
{
    string menuPath = "MyFiles/Menu.xml";
    string folderName = "MyFiles/";

    DataSet ds = null;
    if (Cache["Menu"] == null)
    {
        ds = new DataSet();
        ds.ReadXml(Server.MapPath(menuPath));

        // menu is created
        Cache.Insert("Menu", ds, new System.Web.Caching.CacheDependency(
            Server.MapPath(menuPath)),DateTime.Now.AddMinutes(60),
            TimeSpan.Zero,
            System.Web.Caching.CacheItemPriority.Default,
            new System.Web.Caching.CacheItemRemovedCallback(
                                  CacheItemRemovedCallBack));

       DisplayCacheCreationTime("Object was not in the cache and created at:",
             DateTime.Now.ToLongTimeString());
    }
    else
    {
        // menu is created from the cache
        DisplayCacheCreationTime("Object was in the cache",String.Empty);
    }
}
The CreateMenu method is responsible for creating the Cache dependency on a file. As, you can see I have used the DataSet's ReadXML method to read the contents from the XML file and later inserted the DataSet into the Cache. The CacheDependency method is responsible for setting Cache dependent on the file. I have also included an ItemRemovedCallBack callback method which is fired whenever the Cache dependency is expired (in this case whenever the file changes). If you execute the code above the first time the method CreateMenu is executed it will read the contents from the file since, initially the Cache is empty but for all the later requests the contents are fetched from the Cache object.
You can also create a Cache dependency on the folder. This will mean that whenever a file or a subfolder is added, deleted then the Cache is expired and a new (fresh) copy is fetched.

Cache Dependency on SQL

One of the biggest improvements in ASP.NET 2.0 Caching is the feature of Cache dependency on database tables. This means that the data will be present in the Cache as long as the table entries does not change. As, soon as the database table is changed the Cache is expired. You can enable the SQL Cache dependency by using theaspnet_regsql.exe command line tool. Simply, type the following command on the Visual Studio.NET 2005 command line.
aspnet_regsql -ed -E -d School
The command above will enable the Cache dependency on the "School" database. The next step is to enable the caching on the individual table. You can do that by using the following line.
aspnet_regsql -et -E -d School -t Users
The above line will enable the caching on the Users table which is contained in the School database.
The next step is to create the connectionString in the connectionStrings section andsqlCacheDependency in the web.config file. Take a look at the code below:
<connectionStrings>
    <add name="ConnectionString"
         connectionString="Server=localhost;Database=School;
Trusted_Connection=true"/>
</connectionStrings>

<system.web>
    <caching>
        <sqlCacheDependency pollTime="10000" enabled="true" >
            <databases>
                <add connectionStringName="ConnectionString" name="School"/>
            </databases>
        </sqlCacheDependency>
    </caching>lt;/caching>
As, you have noticed that the sqlCacheDependency have a pollTime attribute which is set to "1000" milliseconds. This means that the ASP.NET will check the database table for any changes every 10 seconds. The database section of the <caching> contains the connectionString which is used to connect to the database.
The final step is to use the caching in your code. You can do this in various ways. Take a look at the following code which uses caching programmatically.
private void BindData()
{
    // if null then fetch from the database
    if (Cache["Users"] == null)
    {
        // Create the cache dependency
        SqlCacheDependency dep = new SqlCacheDependency("School", "Users");
        string connectionString = ConfigurationManager.ConnectionStrings[
                                        "ConnectionString"].ConnectionString;
        SqlConnection myConnection = new SqlConnection(connectionString);
        SqlDataAdapter ad = new SqlDataAdapter("SELECT FirstName, LastName " +
                                               "FROM Users", myConnection);
        DataSet ds = new DataSet();
        ad.Fill(ds);

        // put in the cache object
        Cache.Insert("Users", ds, dep);
    }

    gvUsers.DataSource = Cache["Users"] as DataSet;
    gvUsers.DataBind();
}
The line SqlCacheDependency dep = new SqlCacheDependency("School""Users"); is used to create the caching on the School database and Users table. In the beginning of the BindData method I check that if the item is already in the Cache. If it is then I simply return the item using caller by casting it from the Cache object. If the item is not in the Cache then the data is fetched from the database and inserted into the Cache object. The Cache will be discarded anytime you make a change in the database table "Users". This means that if you INSERT, DELETE, UPDATE any data in any row in the Users table then the Cache will be considered obsolete and a copy of the fresh data will be fetched from the database.
Caching in SQL Server 2005 have a different architecture then in SQL Server 2000. You don't have to write any lines in web.config to enable Caching in SQL Server 2005. Also, in SQL Server 2005 the Cache is only expired when the row is changed in the database table.