Showing posts with label Linq. Show all posts
Showing posts with label Linq. Show all posts
Saturday, June 8, 2013
Labels:
Asp.net
,
Linq
Read More
Optimistic Record locking using linq to resolve Concurrency in ASP.NET with C# - Example
Introduction:-
Here I want to provide the Record locking concept in Linq to resolve the
concurrency. First we have to know what is Optimistic Locking Model? And how it
works?
Concurrency Problem
When
multiple users tries to update same data at same at that time concurrency
problems are arise that are as per following.
- Lost Update
- Dirty Read
- Nonrepeatable read
- Phantom reads.
But
here we only discuss only Loss Update problem.
In this problem at a time two users access the same record first user submit it
changes before second user. But when second user submit his changes the he does
not aware of the changes made by first user so at last second user will
overwrite the changes of first user.
Example:
Users Name Category
Record in DB Jhone worker
User -A Abhay worker (only change the name)
User -B Jhone supervisor (only change the Category)
Record in DB Jhone supervisor (the changes of user A is lost)
There
are two types of record locking models which are as per following.
Optimistic locking
The
optimistic locking model, also known as optimistic concurrency control, is a
concurrency control method used in relational databases that does not provide
record locking. Optimistic locking model allows multiple users to update the
same record without informing the users who are also attempting to update the
record. The record changes are validated only when user submit the updated
record. If one user successfully updates the record, the other users try to
commit their concurrent updates at that time they are informed that a conflict
exists.
An
advantage of the optimistic locking is that it avoids the burden of locking a
record. This model provides fast updates and also secure from Deadlock
situation.
Pessimistic locking
In
The pessimistic locking model two or more users can not edit record at the same
time. When one user starts to edit a record, a lock is placed on record. Other
users who try to edit that record are informed that another user has an update
in progress so he/she cannot edit that record. The other users must wait until
the first user has finished editing and submit the changes, then after releasing
the record lock the other user can edit that record. An advantage of the
pessimistic locking model is that it avoids the issue of confliction.
Pessimistic
locking is a useful model when you need high level of consistency. But there is
also possibility of Deadlock generation.
So,
I thought that Optimistic lock is reliable.
Listen
I had a requirement that when one user “Abhay” editing a record but he still
not submitted the changes at that time one other user “Kashyap” edit that
record and submit the changes. When Abhay try to submit his changes he will be
informed someone change the data and new version of data is available for Abhay.
Here
is my table design which I have created in database.
- id int Unchecked (autogenerate)
- name varchar(50) Checked
- category varchar(50) Checked
To
use Linq first you have show older post. Here is the link for that. Add Linq to SQL File.
Code Behind (in C#):-
SourceSource Code (in asp.net):-
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<%@ Register Assembly="System.Web.Entity, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
Namespace="System.Web.UI.WebControls" TagPrefix="asp" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
<!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>Record Locking</title>
</head>
<body>
<form id="form1" runat="server">
<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
</asp:ToolkitScriptManager>
<div>
<asp:GridView ID="grdTerms" runat="server" AutoGenerateColumns="False" CellPadding="4"
DataKeyNames="id" DataSourceID="EntityDataSource1" ForeColor="#333333" GridLines="None"
OnRowDeleted="grdTerms_RowDeleted" OnRowUpdated="grdTerms_RowUpdated">
<Columns>
<asp:BoundField DataField="id" HeaderText="ID" InsertVisible="False" ReadOnly="True">
<HeaderStyle HorizontalAlign="Left" Width="100px" />
</asp:BoundField>
<asp:BoundField DataField="fname" HeaderText="Name">
<HeaderStyle HorizontalAlign="Left" Width="175px" />
</asp:BoundField>
<asp:BoundField DataField="category" HeaderText="Category">
<HeaderStyle HorizontalAlign="Left" Width="100px" />
</asp:BoundField>
<asp:CommandField ButtonType="Button" ShowEditButton="True" />
<asp:CommandField ButtonType="Button" CausesValidation="False" ShowDeleteButton="True" />
</Columns>
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<RowStyle BackColor="#EFF3FB" />
<AlternatingRowStyle BackColor="White" />
<EditRowStyle BackColor="#2461BF" />
</asp:GridView>
<asp:LinqDataSource ID="EntityDataSource1" runat="server" EnableDelete="True" EnableUpdate="True"
ContextTypeName="dbLockDSDataContext" TableName="aby_temps">
</asp:LinqDataSource>
<br />
To create new terms, enter the terms information and click Add New Terms<br />
<asp:Label ID="lblError" runat="server" EnableViewState="False" ForeColor="Red">
</asp:Label>
<br />
<br />
<table>
<tr>
<td>
Name:
</td>
<td>
<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
</td>
<td>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="txtName"
Display="Dynamic" ErrorMessage="Description is a required field." ValidationGroup="Add"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td>
Category:
</td>
<td>
<asp:TextBox ID="txtCategory" runat="server" Width="50px">
</asp:TextBox>
</td>
<td>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="txtCategory"
Display="Dynamic" ErrorMessage="Due days is a required field." ValidationGroup="Add">
</asp:RequiredFieldValidator>
</td>
</tr>
</table>
<br />
<asp:Button ID="btnAdd" runat="server" Text="Add New Terms" ValidationGroup="Add"
OnClick="btnAdd_Click" />
</div>
</form>
</body>
</html>
Code Behind (in C#):-
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.Linq;
public partial class _Default : System.Web.UI.Page
{
dbLockDSDataContext dbcontext = new dbLockDSDataContext();
protected void btnAdd_Click(object sender, EventArgs e)
{
aby_temp tblObj= new aby_temp();
tblObj.category=txtCategory.Text;
tblObj.fname=txtName.Text;;
try
{
dbcontext.aby_temps.InsertOnSubmit(tblObj);
dbcontext.SubmitChanges();
grdTerms.DataBind();
txtName.Text = "";
txtCategory.Text = "";
}
catch (Exception ex)
{
lblError.Text = "An error has occurred. " + ex.Message;
}
}
protected void grdTerms_RowUpdated(object sender, GridViewUpdatedEventArgs e)
{
if (e.Exception != null)
{
if (e.Exception.GetType() == typeof(ChangeConflictException))
{
lblError.Text = "Another user has updated or deleted " +
"those terms. Please try again.";
}
else
{
lblError.Text = "A database error occurred. " +
e.Exception.Message;
e.KeepInEditMode = true;
}
e.ExceptionHandled = true;
}
}
protected void grdTerms_RowDeleted(object sender, GridViewDeletedEventArgs e)
{
if (e.Exception != null)
{
if (e.Exception.GetType() == typeof(ChangeConflictException))
{
lblError.Text = "Another user has updated or deleted " +
"those terms. Please try again.";
}
else
{
lblError.Text = "A database error occurred. " +
e.Exception.Message;
}
e.ExceptionHandled = true;
}
}
}
Labels:
Asp.net
,
Linq
Read More
Simple Insert Update Delete query in Linq to Sql in ASP.NET with C# - Example
Introduction:-
Here I want to provide the linq query for select, Insert, Update, Delete, Join and
may more operations.
LINQ provides the object-oriented programming principles to relational data. It is model based programing, so it provide fracility to querying data from different types of data sources, and extends data capabilities directly into the C# and Visual Basic languages
What is Linq?
LINQ is an entity framework. which hase new features then SQL.it supports .net version 3.0 and above. It called as LANQUAGE INTEGRATED QUERY there are different ways to use LINQ like LINQ TO SQL, LINQ TO XML etc.LINQ provides the object-oriented programming principles to relational data. It is model based programing, so it provide fracility to querying data from different types of data sources, and extends data capabilities directly into the C# and Visual Basic languages
Friday, April 5, 2013
Labels:
Ajax Controls
,
Asp.net
,
Gridview
,
Linq
When you try to display another ModalPopupExtender on the first one, it does not hide the first ModalPopupExtender. We can interact with the first ModalPopupExtender. Sometimes it spoils the application logic.
That’s why I am solving this problem by a User Control named UpdatePanel . It sets the child model popup on the parent model popup. You can add multiple UpdatePanel controls to set multiple relations between model pops. We can nest many model pop controls to any level.
Here In this Example I used the Nested ModelPopupExtender. In first popup Gridview is opened and for Insert and Update Operation Nested popup will open which has simple textboxes and buttons.
Note:
- When you use ModelPopupExtender you have to put one button in ModelPopupExtender to close that model popup.
- I am using Linq for Insert, Update, Delete operations on Database.
click The Button First Popup Will Open
When you click on Edit Link Button or Insert Button then next Popup will open
Read More
Nested ModelPopupExtender with GridView in popup and Linq Query is used for Insert,Update Delete in asp.net with c#-Example
Introduction:-
We all have used the ModalPopupExtender and know how it works. It displays a detail part as a model, which means we cannot interact with rest of the part of page except the detail part. But there is a problem in ModalPopupExtender.When you try to display another ModalPopupExtender on the first one, it does not hide the first ModalPopupExtender. We can interact with the first ModalPopupExtender. Sometimes it spoils the application logic.
That’s why I am solving this problem by a User Control named UpdatePanel . It sets the child model popup on the parent model popup. You can add multiple UpdatePanel controls to set multiple relations between model pops. We can nest many model pop controls to any level.
Here In this Example I used the Nested ModelPopupExtender. In first popup Gridview is opened and for Insert and Update Operation Nested popup will open which has simple textboxes and buttons.
Note:
- When you use ModelPopupExtender you have to put one button in ModelPopupExtender to close that model popup.
- I am using Linq for Insert, Update, Delete operations on Database.
click The Button First Popup Will Open
When you click on Edit Link Button or Insert Button then next Popup will open
Source Code(in asp.net):-
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Popup.aspx.cs" Inherits="Popup" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
<!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>
<style type="text/css">
.ModalPopupBG
{
background-color: #C0C0C0;
filter: alpha(opacity=50);
opacity: 0.7;
}
.DetailPopup
{
min-width: 200px;
min-height: 150px;
background: white;
}
.detailpopup1
{
font-size: larger;
font-weight: bold;
font-style: normal;
color: #000000;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
</asp:ToolkitScriptManager>
<asp:Button ID="btnMain" runat="server" Text="Click me to View" />
<asp:ModalPopupExtender ID="ModalPopupExtender2" runat="server" TargetControlID="btnMain"
PopupControlID="Mainpan" CancelControlID="btnMainCancle" Drag="true" BackgroundCssClass="ModalPopupBG">
</asp:ModalPopupExtender>
<asp:Panel ID="Mainpan" runat="server">
<asp:UpdatePanel ID="updateParent" runat="Server">
<ContentTemplate>
<asp:HiddenField ID="hid" runat="server" />
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="4"
ForeColor="#333333" GridLines="None">
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<Columns>
<asp:TemplateField HeaderText="Pid">
<ItemTemplate>
<asp:Label ID="lpid" runat="server" Text='<% #Eval("pid")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:Label ID="lpname" runat="server" Text='<% #Eval("pname")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Description">
<ItemTemplate>
<asp:Label ID="ldes" runat="server" Text='<% #Eval("des")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lbedit" runat="server" OnClick="lbedit_Click">Edit</asp:LinkButton>
<asp:LinkButton ID="lbdel" runat="server" OnClick="lbdel_Click">Delete</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<EditRowStyle BackColor="#999999" />
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
</asp:GridView>
<asp:Button ID="bntinsert" runat="server" Text="Insert" OnClick="bntinsert_Click" />
<asp:Button ID="btnMainCancle" runat="server" Text="Cancle" OnClick="btnMainCancle_Click" />
<asp:ModalPopupExtender ID="ModalPopupExtender1" runat="server" TargetControlID="hid"
PopupControlID="pan" BehaviorID="bntinsert_Click" PopupDragHandleControlID="PopupHeader"
Drag="true" BackgroundCssClass="ModalPopupBG">
</asp:ModalPopupExtender>
<asp:Panel runat="server" ID="pan">
<table class="DetailPopup">
<tr>
<td colspan="2">
<h1>
<asp:Label ID="lpopuphead" runat="server" Text=""></asp:Label></h1>
</td>
</tr>
<tr>
<td>
Product Name:-
</td>
<td>
<asp:TextBox ID="txtpnm" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ErrorMessage="Plz Enter Product Name"
ControlToValidate="txtpnm" ValidationGroup="vpopup"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td>
Product Description:-
</td>
<td>
<asp:TextBox ID="txtpdes" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="Plz Enter Description"
ControlToValidate="txtpdes" ValidationGroup="vpopup"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td>
<asp:Button ID="btnOkay" runat="server" Text="OK" OnClick="btnOkay_Click" ValidationGroup="vpopup" />
<asp:Button ID="btnCncle" runat="server" Text="CANCLE" OnClick="btnCncle_Click" />
</td>
</tr>
</table>
</asp:Panel>
</ContentTemplate>
</asp:UpdatePanel>
</asp:Panel>
</form>
</body>
</html>
Code Behind(in C#):-
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Popup : System.Web.UI.Page
{
DataClassesDataContext dc = new DataClassesDataContext();
SqlFun.SqlFun sqlobj = new SqlFun.SqlFun();
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
grbind();
}
}
protected void grbind()
{
GridView1.DataSource = dc.aby_Productnews;
GridView1.DataBind();
}
protected void lbedit_Click(object sender, EventArgs e)
{
LinkButton lb=(LinkButton)sender;
GridViewRow gr = (GridViewRow)lb.NamingContainer;
Label lpid1 = (Label)gr.FindControl("lpid");
hid.Value=lpid1.Text;
Label lpname1 = (Label)gr.FindControl("lpname");
txtpnm.Text = lpname1.Text;
Label ldes1 = (Label)gr.FindControl("ldes");
txtpdes.Text = ldes1.Text;
lpopuphead.Text = "Edit Record";
ModalPopupExtender1.Show();
}
protected void lbdel_Click(object sender, EventArgs e)
{
LinkButton lb = (LinkButton)sender;
GridViewRow gr = (GridViewRow)lb.NamingContainer;
Label lpid1 = (Label)gr.FindControl("lpid");
//sqlobj.Cmd_Non_Query("delete from aby_Productnew where pid=" + lpid1.Text);
grbind();
}
protected void btnOkay_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
if (lpopuphead.Text.Equals("Edit Record"))
{
aby_Productnew urec = dc.aby_Productnews.Single(u=>u.pid==Convert.ToInt32(hid.Value));
urec.pname = txtpnm.Text;
urec.des = txtpdes.Text;
dc.SubmitChanges();
//sqlobj.Cmd_Non_Query("update aby_Productnew set pname='" + txtpnm.Text + "', des='" + txtpdes.Text + "' where pid=" + hid.Value);
}
else
{
aby_Productnew abrec = new aby_Productnew();
abrec.pname = txtpnm.Text;
abrec.des = txtpdes.Text;
dc.aby_Productnews.InsertOnSubmit(abrec);
dc.SubmitChanges();
//sqlobj.Cmd_Non_Query("insert into aby_Productnew values('" + txtpnm.Text + "','" + txtpdes.Text + "')");
}
grbind();
}
clr();
}
private void clr()
{
lpopuphead.Text = "";
txtpdes.Text = "";
txtpnm.Text = "";
}
protected void bntinsert_Click(object sender, EventArgs e)
{
lpopuphead.Text = "Insert Record";
ModalPopupExtender1.Show();
}
protected void btnCncle_Click(object sender, EventArgs e)
{
clr();
ModalPopupExtender1.Hide();
}
protected void btnMainCancle_Click(object sender, EventArgs e)
{
ModalPopupExtender2.Hide();
}
}
Subscribe to:
Posts
(
Atom
)


