delete procedure not call in sqldataadapter.Deletecommand in mvc3 razor - asp.net-mvc-3

i creat an accounting application in mvc3. i have journal voucher form in it.in this form master and detail data is on single view.i use html table and text boxes in html table for create my grid.I saved my data into sql server 2008 r2 database in 2 tables with help of json and wcf services on single button click.(means on save button click all the master and detail data is inserted in database.there is no edit button on each grid line for editing data into database.
Now I want to perform my form's edit functionality on single button click into database.
for this purpose i have an idea that i use sqltransaction object and delete data from database temporarily and then insert new data into database and then do the sqltran.commit or sqltrans.rollback on sucess/fail base of transaction.
for this purpose i create a function in DAL in which it firstly bind sqltransaction with command and then do delete functionality with dataadapter and stored procedure.
but my stored procedure is not called and data is not delete i monitor it in sql server profiler.
I paste my code here plzzz any one tell me where i do mistake.
public bool JVInsertDAL1(JVEntity Obj, bool FMode, bool EMode, bool DMode)
{
bool FinRes = false;
DataSet ObjDs = new DataSet();
//function call to fill tables scheme in dataset
ObjDs = FillDSDAL(ObjDs, "", "");
if (FMode == false && DMode == true)
{
ObjDs = FillDSDAL(ObjDs, Obj.VNo, Obj.Type);
}
//==============================
///*********MASTER DATA INSERTION************************
if (EMode != true || DMode != false)
{
if (sqlConnection.State == ConnectionState.Closed)
{
sqlConnection.Open();
}
sqlTransaction = sqlConnection.BeginTransaction();
}
try
{
if (FMode == false && DMode == true)
{
SqlCommand cmdDeleteLedg = new SqlCommand("SpGLdelete", sqlConnection, sqlTransaction);
cmdDeleteLedg.CommandType = CommandType.StoredProcedure;
SqlCommand cmdDeleteHead = new SqlCommand("SpGlHeadDelete", sqlConnection, sqlTransaction);
cmdDeleteHead.CommandType = CommandType.StoredProcedure;
cmdDeleteHead.Parameters.Add("#VNo", SqlDbType.Char, 10, "VNo").Value = Obj.VNo;
cmdDeleteHead.Parameters.Add("#Type", SqlDbType.Char, 2, "Type").Value=Obj.Type;
cmdDeleteLedg.Parameters.Add("#VNo", SqlDbType.Char, 10, "VNo").Value = Obj.VNo;
cmdDeleteLedg.Parameters.Add("#Type", SqlDbType.Char, 2, "Type").Value = Obj.Type;
//-----------------PROCEDURE FOR DELETE RECORD DURING EDIT MODE-------------
ObjDadp.DeleteCommand = cmdDeleteLedg;
ObjDadp.Update(ObjDs, "Gledg");
ObjDadp.DeleteCommand = cmdDeleteHead;
ObjDadp.Update(ObjDs, "Glhead");
ObjDs.AcceptChanges();
ObjDs.Clear();
}
if (FMode == true)
{
SqlCommand sqlCommand = new SqlCommand("SPJVHeadInsert", sqlConnection, sqlTransaction);
sqlCommand.CommandType = CommandType.StoredProcedure;
SqlCommand sqlCommand1 = new SqlCommand("SPJVLedgInsert", sqlConnection, sqlTransaction);
sqlCommand1.CommandType = CommandType.StoredProcedure;
sqlCommand.Parameters.Add("#Type", SqlDbType.Char, 2, "Type");
sqlCommand.Parameters.Add("#VNo", SqlDbType.Char, 10, "VNo");
sqlCommand.Parameters.Add("#VDate", SqlDbType.DateTime, 10, "VDate");
sqlCommand1.Parameters.Add("#Type", SqlDbType.Char, 2, "Type");
sqlCommand1.Parameters.Add("#VNo", SqlDbType.Char, 10, "VNo");
sqlCommand1.Parameters.Add("#VDate", SqlDbType.DateTime, 10, "VDate");
sqlCommand1.Parameters.Add("#Code", SqlDbType.Char, 10, "Code");
ObjRow = ObjDs.Tables["GlHead"].NewRow();
ObjRow["Type"] = Obj.Type;
ObjRow["VNo"] = Obj.VNo;
ObjRow["VDate"] = Obj.VDate;
ObjRow["RefRemarks"] = Obj.RefRemarks;
ObjDs.Tables["GlHead"].Rows.Add(ObjRow);
foreach (var trans in Obj.GLedg)
{
ObjRow = ObjDs.Tables["Gledg"].NewRow();
ObjRow["Type"] = trans.Type;
ObjRow["VNo"] = trans.VNo;
ObjRow["VDate"] = trans.VDate;
ObjRow["Code"] = trans.Code;
ObjDs.Tables["Gledg"].Rows.Add(ObjRow);
}
//----------------------------------------------------
ObjDadp.InsertCommand = sqlCommand;
ObjDadp.Update(ObjDs, "GlHead");
ObjDadp.InsertCommand = sqlCommand1;
ObjDadp.Update(ObjDs, "GLedg");
//----------------------------------------------------
}//END OF FMODE=TRUE CONDITION
//------------------------------------------------------
//****************************************
if (DMode != true || EMode != true)
// if (EMode != true || DMode != false)
{
sqlTransaction.Commit();
}
//************************************
}//end of try
catch (SqlException sqlError)
{
sqlTransaction.Rollback();
}
catch (Exception ex)
{
sqlTransaction.Rollback();
}
finally
{
if (EMode != true || DMode != true)
{
if (sqlConnection.State == ConnectionState.Open)
{
sqlConnection.Close();
}
}
}
//******end of detail insertion***************************************************
if (FMode == false && DMode == true)
{
if (ObjDs.HasErrors== false)
{
FinRes = true;
}
else
{
FinRes = false;
}
}
if (FMode == true)
{
if (ObjDs.HasErrors == false)
{
FinRes = true;
}
else
{
FinRes = false;
}
}
return FinRes;
}
In above code i pass FMode: true, EMode: false, DMode: false for save data and it insert data into database.
FMode: false, EMode: true, DMode: true when delete data from database in editing mode.
and finally FMode: true, EMode: true, DMode: false for insert data after deletion from database in editing mode.
Any suggestions for solve my problem?

From the code above it seems that you don't change the contents of the tables Glhead and Gledg.
Calling the Update method of the SqlDataAdapter when the rows of the mentioned tables are all in the state DataRowState.Unchanged result in no action on the database.
When an application calls the Update method, the DbDataAdapter
examines the RowState property, and executes the required INSERT,
UPDATE, or DELETE statements iteratively for each row, based on the
order of the indexes configured in the DataSet.
You need to delete the row from the datatable and then call the Update method of the SqlDataAdapter

Related

Keeping Data between refreshes in Blazor server

I have a multiple page Web Application that needs to be refreshed after a user has entered in data to then display the data on the table. I have Scoped dependencies so my users do not see the same data table as they are unique to each user. After they enter the data and the page refreshes the page goes blank and the scope is empty. How would I go about keeping the data from the scopes after refresh? I essentially needs a Singlton dependency that isn't shared between users. This is a Blazor Server Side Application. EDIT: Accept Button Method
if (Controlled_Variables.Attendance != null)
{
if (_JBS.CheckFields(_JBF.JobID, _JBF.WorkCenter, _JBF.SetupRun) == false)
{
string prompted = await jsRunTime.InvokeAsync<string>("alert", "Please Verify Job ID, Work Center, and Setup/Run are selected!");
}
else
{
FilledOut = true;
_JBF.transactionData = Guid.NewGuid();
_JBF.jobOperationID = _JBF.WorkCenter;
DateTime recordDate = DateTime.Now;
JobOperationRecord JOR = await _JBS.GetJobOperationRecordByOperationID(_JBF.WorkCenter);
WorkCenterRecord SingleWorkCenter = await _JBS.GetWorkCenterInformation(JOR.Work_Center);
EmployeeRecord Employee = await _JBS.GetEmployeeRecord(Controlled_Variables.Employee_ID);
try
{
if (Check.IsThisAnActiveJob(_JBF.JobID))
{
bool Complete = await First_Article_Complete(_JBF.jobOperationID, _JBF.SetupRun);
if (Complete)
{
Controlled_Variables.Sessions.Clear();
Controlled_Variables.Sessions = await _JBS.GetOpenJobOperationTimeSessionForUser(Controlled_Variables.Employee_ID);
bool activeNonGhostSession = false;
foreach (JobOperationSessionManager Session in Controlled_Variables.Sessions)
{
if (Session.ghost == "Y")
{
Controlled_Variables.ActiveSession = Session;
activeNonGhostSession = true;
}
}
_JBS.UpdateJobOperationStatus(JOR.Job_Operation.ToString(), JOR.Status == "C" ? "C" : "S");
if (!activeNonGhostSession && !_JBF.GhostedCheck)
{
_JBS.AddNewJobOperationTimeSessionForUser(Controlled_Variables.Employee_ID, "N", _JBF.transactionData.ToString(), JOR.Work_Center,
_JBF.jobOperationID, _JBF.JobID, recordDate.ToString("yyyy-MM-dd HH:mm:ss"), _JBF.jobOperationTime.ToString(), _JBF.SetupRun);
_JBF.sessionManagerCreated = true;
_JBS.InsertIntoTransactionDetail_NewEntry_JobOperation(_JBF.transactionData.ToString(), _JBF.jobOperationID, _JBF.jobOperationTime.ToString(),
JOR.Work_Center, _JBF.JobID);
_JBF.transDetailCreated = true;
_JBS.InsertIntoTransactionData_NewEntry_JobOperation(_JBF.transactionData.ToString(), Controlled_Variables.Employee_ID, recordDate.ToString());
_JBF.transDataCreated = true;
_JBS.InsertIntoJobOperationTime_NewEntry_JobOperationStart(_JBF.jobOperationID, Controlled_Variables.Employee_ID, recordDate.ToString(),
Employee.Hourly_Rate.ToString(), SingleWorkCenter.Labor_Burden.ToString(), SingleWorkCenter.Machine_Burden.ToString(), SingleWorkCenter.GA_Burden.ToString(),
_JBF.jobOperationTime.ToString(), JOR.Work_Center, _JBF.jobOperationTimeObjectID.ToString(), JOR.ObjectID.ToString(), Employee.ObjectID.ToString());
_JBF.jobOperationTimeCreated = true;
btnStartJob = true;
btnStopJob = false;
NavManage.NavigateTo(NavManage.Uri, forceLoad: true);
string prompted = await jsRunTime.InvokeAsync<string>("alert", "The job has been entered successfully.", "ERROR");
Sorry for the confusion for the use of refresh. I needed to reload the table to allow the data put in by users to be visable after they hit accept. To do this I added a navigation manager
NavManage.NavigateTo(NavManage.Uri, forceLoad: true);
Which force loads the page and displays the new data. If there may be another way to do this to keep the scope I am open to using a different method. As you can see I have tried to just recall the method in which the table data is loaded into to possibly get the new data populated but then the application never reiterates the loop to actually display the data on the page
#for (int i = 0; i < Controlled_Variables.TransactionData.Count; i++)
{
var TransacData = Controlled_Variables.TransactionData[i];
TransacData.index = i;
#for (int l = 0; l < Controlled_Variables.TransactionDetail.Count; l++)
{
var transacdetail = Controlled_Variables.TransactionDetail[l];
transacdetail.index = l;
TransactionDetailRecord selectData = Controlled_Variables.TransactionDetail[l];
#if (transacdetail.Transaction_Data == TransacData.Transaction_Data)
{
<div><input value="#selectData" type="radio" name="Select" onclick="#(() => ShowSelectedRecord(selectData, TransacData))"> </div>
<div>#transacdetail.Target_Integer</div>
<div>#transacdetail.Job</div>
<div>#Controlled_Variables.Job.Part_Number</div>
<div>#TransacData.Transaction_Start</div>
if (TransacData.Transaction_Type == 10)
{
<div>#TransacData.Transaction_Type</div>
btnStartJob = true;
btnStopJob = false;
}
else
{
<div>#TransacData.Transaction_Type</div>
btnStartJob = false;
btnStopJob = true;
}
<div>#Controlled_Variables.Job.Customer</div>
<div>#transacdetail.Work_Center</div>
<div>#transacdetail.Quantity</div>
<div>#TransacData.Transaction_End</div>
<div>#transacdetail.Entry_Type</div>
<div>#transacdetail.Labor_Hrs</div>
<div>#transacdetail.Machine_Hrs</div>
<div>#TransacData.Transaction_Data</div>
<div>#transacdetail.Transaction_Detail</div>
}
}
}

How to create excel file with multiple sheet name based on modules?

I work on c# desktop app I Can't export data to excel file with multiple tab(multi sheet).
only that i can do create excel file with only sheet based on data exist on data table module field.
I use open XML library
Data table data as below :
Divide Output Excel File To Multi Tab based On Module
PartId Company Files Tab Module
1222 micro Abc source 1
1321 silicon Abc source 1
1444 cd2 Abc types 2
1321 cd3 Abc types 2
1541 tvs Abc types 2
Expected Result :
Create File ABC.xlsx with two sheet first sheet name source and second sheet name types based on module and load data related to every sheet based on data exist on data table.
so if I have two modules meaning I have two sheet .
What I have tried:
public Boolean createExcelFile(DataTable Table,String FullFilePathName)
{
Boolean IsDone = false;
try
{
FileInfo CreatedFile = new FileInfo(FullFilePathName);
Boolean ISNew = false;
if (!CreatedFile.Exists)
{
ISNew = true;
}
using (var pck = new ExcelPackage(CreatedFile))
{
ExcelWorksheet ws;
if (ISNew == true)
{
ws = pck.Workbook.Worksheets.Add("Sheet");
ws.Cells[1, 1].LoadFromDataTable(Table, ISNew, OfficeOpenXml.Table.TableStyles.Light8);
}
else
{
ws = pck.Workbook.Worksheets.FirstOrDefault();
ws.Cells[2, 1].LoadFromDataTable(Table, ISNew);
}
pck.Save();
IsDone = true;
}
}
catch (Exception ex)
{
throw ex;
}
return IsDone;
}
but problem code above create one files with one sheet only
so How to create file with multi sheet based on module ?
I solved my issue by store multi data table on datasets then loop on it
DataSet ds = new DataSet();
var result = from rows in dt.AsEnumerable()
group rows by new { Module = rows["ModuleName"] } into grp
select grp;
foreach (var item in result)
{
ds.Tables.Add(item.CopyToDataTable());
}
Affected = new CExcel().createExcelFileForDs(ds, exportPath);
public Boolean createExcelFileForDs(DataSet ds, String FullFilePathName)
{
Boolean IsDone = false;
try
{
FileInfo CreatedFile = new FileInfo(FullFilePathName);
Boolean ISNew = false;
if (!CreatedFile.Exists)
{
ISNew = true;
}
using (var pck = new ExcelPackage(CreatedFile))
{
ExcelWorksheet ws;
foreach (DataTable Table in ds.Tables)
{
if (ISNew == true)
{
ws = pck.Workbook.Worksheets.Add(Convert.ToString(Table.Rows[0]["Tab name"]));
ws.Cells.Style.Font.Size = 11; //Default font size for whole sheet
ws.Cells.Style.Font.Name = "Calibri"; //Default Font name for whole sheet
if (System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.IsRightToLeft) // Right to Left for Arabic lang
{
ExcelWorksheetView wv = ws.View;
wv.ZoomScale = 100;
wv.RightToLeft = true;
ws.PrinterSettings.Orientation = eOrientation.Landscape;
ws.Cells.AutoFitColumns();
}
else
{
ExcelWorksheetView wv = ws.View;
wv.ZoomScale = 100;
wv.RightToLeft = false;
ws.PrinterSettings.Orientation = eOrientation.Landscape;
ws.Cells.AutoFitColumns();
}
ws.Cells.AutoFitColumns();
ws.Cells[1, 1].LoadFromDataTable(Table, ISNew, OfficeOpenXml.Table.TableStyles.Light8);
}
else
{
ws = pck.Workbook.Worksheets.FirstOrDefault();
ws.Cells[2, 1].LoadFromDataTable(Table, ISNew);
}
}
pck.Save();
IsDone = true;
}
}
catch (Exception ex)
{
throw ex;
}
return IsDone;
}

Comparing objects before and after update retrieved by LINQ query

I am using LINQtoSQL and I need to compare object before and after update.
In the example below Student 'before' and Student 'curStudent' are the same, because they was retrieved by the same query.
using(DataContext db = new DataContext())
{
Student before = db.Student.Where(q=>q.id == 1).SingleOrDefault();
Student curStudent = db.Student.Where(q=>q.id == 1).SingleOrDefault();
curStudent.Name = "NewName";
db.SubmitChanges();
}
if(before.Name != curStudent.Name) // this condition will never be true
{
//do something
}
The context will only keep one object per key value, so one way would be to use two separate contexts:
Student before;
using(DataContext db1 = new DataContext())
{
before = db.Student.Where(q=>q.id == 1).SingleOrDefault();
}
Student curStudent;
using(DataContext db2 = new DataContext())
{
curStudent = db.Student.Where(q=>q.id == 1).SingleOrDefault();
curStudent.Name = "NewName";
db.SubmitChanges();
}
if(before.Name != curStudent.Name)
{
//do something
}
Or if you're just interested in the name change, keep the previous value:
string before;
using(DataContext db = new DataContext())
{
Student curStudent = db.Student.Where(q=>q.id == 1).SingleOrDefault();
before = curStudent.Name; // cache the name
curStudent.Name = "NewName";
db.SubmitChanges();
}
if(before != curStudent.Name)
{
//do something
}

save new or update exist record with linq

this is the way i used to save record with linq: (my Q is below)
public void SaveEmployee(Employee employee)
{
using (BizNetDB db = new BizNetDB())
{
BizNet.SqlRep.Data.Employee oldEmployee = (from e in db.Employees
where e.EmployeeID == employee.EmployeeID
select e).SingleOrDefault();
if (oldEmployee == null)
{
oldEmployee = new BizNet.SqlRep.Data.Employee();
oldEmployee.BirthDate = employee.BirthDate;
oldEmployee.WorkRole = employee.WorkRole;
oldEmployee.CurrentFlag = employee.CurrentFlag;
oldEmployee.HireDate = employee.HireDate;
...
db.Employees.InsertOnSubmit(oldEmployee);
}
else
{
if (oldEmployee.BirthDate.Date != employee.BirthDate.Date)
oldEmployee.BirthDate = employee.BirthDate;
if (oldEmployee.CurrentFlag != employee.CurrentFlag)
oldEmployee.CurrentFlag = employee.CurrentFlag;
if (oldEmployee.HireDate.Date != employee.HireDate.Date)
oldEmployee.HireDate = employee.HireDate;
}
oldEmployee.ModifiedDate = DateTime.Now;
db.SubmitChanges();
employee.EmployeeID = oldEmployee.EmployeeID;
}
}
my questions are:
a. are the if statements nesccery? why not to make the assigning without the
check?
mybe the if block take more cpu..
b. why to spearate the new record block and the update block?
when the record is new it will do
db.Employees.InsertOnSubmit(oldEmployee);
and then proceed with the update routine...
The way you're doing it the only reason you need the if statement is to new it up and insert it, so I would use the if statement just for that.
I would do this instead:
public void SaveEmployee(Employee employee)
{
using (BizNetDB db = new BizNetDB())
{
BizNet.SqlRep.Data.Employee oldEmployee =
(from e in db.Employees
where e.EmployeeID == employee.EmployeeID
select e).SingleOrDefault();
if (oldEmployee == null)
{
oldEmployee = new BizNet.SqlRep.Data.Employee();
db.Employees.InsertOnSubmit(oldEmployee);
}
if (oldEmployee.BirthDate.Date != employee.BirthDate.Date)
oldEmployee.BirthDate = employee.BirthDate;
if (oldEmployee.CurrentFlag != employee.CurrentFlag)
oldEmployee.CurrentFlag = employee.CurrentFlag;
if (oldEmployee.HireDate.Date != employee.HireDate.Date)
oldEmployee.HireDate = employee.HireDate;
oldEmployee.ModifiedDate = DateTime.Now;
db.SubmitChanges();
employee.EmployeeID = oldEmployee.EmployeeID;
}
}
I also think there's a way to map one object's properties to the other, but it escapes me at the moment. It may not work for what you're trying to do anyway since it seems that you're doing some other things later anyway with the ModifiedDate and EmployeeID.

Update using LINQ to SQL

How can I update a record against specific id in LINQ to SQL?
LINQ is a query tool (Q = Query) - so there is no magic LINQ way to update just the single row, except through the (object-oriented) data-context (in the case of LINQ-to-SQL). To update data, you need to fetch it out, update the record, and submit the changes:
using(var ctx = new FooContext()) {
var obj = ctx.Bars.Single(x=>x.Id == id);
obj.SomeProp = 123;
ctx.SubmitChanges();
}
Or write an SP that does the same in TSQL, and expose the SP through the data-context:
using(var ctx = new FooContext()) {
ctx.UpdateBar(id, 123);
}
In the absence of more detailed info:
using(var dbContext = new dbDataContext())
{
var data = dbContext.SomeTable.SingleOrDefault(row => row.id == requiredId);
if(data != null)
{
data.SomeField = newValue;
}
dbContext.SubmitChanges();
}
AdventureWorksDataContext db = new AdventureWorksDataContext();
db.Log = Console.Out;
// Get hte first customer record
Customer c = from cust in db.Customers select cust where id = 5;
Console.WriteLine(c.CustomerType);
c.CustomerType = 'I';
db.SubmitChanges(); // Save the changes away
DataClassesDataContext dc = new DataClassesDataContext();
FamilyDetail fd = dc.FamilyDetails.Single(p => p.UserId == 1);
fd.FatherName=txtFatherName.Text;
fd.FatherMobile=txtMobile.Text;
fd.FatherOccupation=txtFatherOccu.Text;
fd.MotherName=txtMotherName.Text;
fd.MotherOccupation=txtMotherOccu.Text;
fd.Phone=txtPhoneNo.Text;
fd.Address=txtAddress.Text;
fd.GuardianName=txtGardianName.Text;
dc.SubmitChanges();
I found a workaround a week ago. You can use direct commands with "ExecuteCommand":
MDataContext dc = new MDataContext();
var flag = (from f in dc.Flags
where f.Code == Code
select f).First();
_refresh = Convert.ToBoolean(flagRefresh.Value);
if (_refresh)
{
dc.ExecuteCommand("update Flags set value = 0 where code = {0}", Code);
}
In the ExecuteCommand statement, you can send the query directly, with the value for the specific record you want to update.
value = 0 --> 0 is the new value for the record;
code = {0} --> is the field where you will send the filter value;
Code --> is the new value for the field;
I hope this reference helps.

Resources