Delete row in gridview using linq - c#

I wrote this code to delete rows from Gridview but its not working.
code in class.cs:
public bool bDeleteItem(int nItemID)
{
bool flag = false;
try
{
Training_sNairoukhEntities1 sNairoukhEntities1 = new Training_sNairoukhEntities1();
IMS_Items oIMS_Items = sNairoukhEntities1.IMS_Items.Where(Entity => Entity.ItemID == nItemID).Single();
sNairoukhEntities1.IMS_Items.Remove(oIMS_Items);
int nResult = sNairoukhEntities1.SaveChanges();
if (nResult > 0)
{
flag = true;
}
}
catch (Exception ex)
{
}
return flag;
}
code in Aspx.cs:
int nId = Convert.ToInt32(gvManageItem.DataKeys[Convert.ToInt32(e.CommandArgument)]["ItemID"].ToString());
if (e.CommandName == "cmDelete")
{
ManageItem oManageItem = new ManageItem();
if (oManageItem.bDeleteItem(nId))
{
lblValidation.Text = "Delete is successfully";
}
else
{
lblValidation.Text = "isnt delete";
}
}

Remove method "Marks the given entity as Deleted such that it will be deleted from the database when SaveChanges is called. Note that the entity must exist in the context in some other state before this method is called."
Below command will work:
sNairoukhEntities1.Entry(oIMS_Items).State = System.Data.Entity.EntityState.Deleted;
sNairoukhEntities1.SaveChanges();

Related

SQLite table doesn't get updated

I have a problem. I created a SwitchButton and want to store the state in a database table. So I created this code to debug:
SettingSwitch.CheckedChange += (s, b) =>
{
SettingDb testsetting = new SettingDb
{
Name = mItems[position].Name,
};
SettingDb test = MainActivity.db.SelectRowFromTableSettings(testsetting);
if (test != null)
{
bool SwitchValueBool = Convert.ToBoolean(test.Value);
}
bool isChecked = ValueDictionary[position];
if(isChecked == true)
{
isChecked = false;
}
else if(isChecked == false)
{
isChecked = true;
}
SettingDb setting = new SettingDb()
{
Name = SettingName.Text,
Type = "Switch",
Value = isChecked.ToString()
};
MainActivity.db.UpdateTableSettings(setting);
ValueDictionary[position] = isChecked;
SettingDb test2 = MainActivity.db.SelectRowFromTableSettings(testsetting);
if (test2 != null)
{
bool SwitchValueBool = Convert.ToBoolean(test2.Value);
}
};
The expected outcome should be:
test.Value = False
test2.Value = Opposite of test.Value, so True
But now the value I get from the table is always False. Here is the update function:
string folder = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
public bool UpdateTableSettings(SettingDb setting)
{
try
{
using (var connection = new SQLiteConnection(System.IO.Path.Combine(folder, "Settings.db")))
{
connection.BeginTransaction();
connection.Query<SettingDb>("UPDATE SettingDb SET Value=? WHERE Name=?", setting.Value, setting.Name);
//connection.Update(setting);
connection.Commit();
return true;
}
}
catch (SQLiteException ex)
{
Log.Info("SQLiteEx", ex.Message);
return false;
}
}
public SettingDb SelectRowFromTableSettings(SettingDb setting)
{
try
{
using (var connection = new SQLiteConnection(System.IO.Path.Combine(folder, "Settings.db")))
{
return connection.Query<SettingDb>("SELECT * FROM SettingDb WHERE Name=?", setting.Name).FirstOrDefault();
}
}
catch (SQLiteException ex)
{
Log.Info("SQLiteEx", ex.Message);
return null;
}
}
The table value doesn't get updated!!!
Can someone tell me what I am doing wrong?
Please let me know!
According to your description, you want to update sqlite database table, please take a look the following code and modify the update function.
static void UpdateDatabase(int primaryKey, string newText, int newValue)
{
string path = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments), "mydatabase.db");
var db = new SQLiteConnection(path, false);
string sql = "UPDATE MyTable SET MyTextColumn = ?, MyValueColumn = ? WHERE MyPrimaryKey= ?";
string[] parms = new String[] { newText, newValue.ToString(), primaryKey.ToString() };
var cmd = db.CreateCommand(sql, parms);
cmd.ExecuteNonQuery();
}

Thread abort in Window Service in C#

I have a window Service which converts the PDF file to html and it is running in 5 threads.
Each thread picks the record from database where status is 0.Once it picks the record from database we are making the status to 64 and making an entry in log file so that other thread should not pick the same record,after successful conversion we are making the status to 256 if any exception we are making the stratus to 128.
Some records are updated to 64 with out any entry in log and they are not even processed further.
Below is the Stored Procedure to pick the single record from database.
Create PROCEDURE [SGZ].[p_GetNextRequestForProcessing]
#InstanceId int
AS
BEGIN
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;
set nocount on
Declare #RequestID bigint = null;
SET #RequestID= (
Select
TOP(1) RequestID
From
sgz.PDFTransformationQueue
Where
RequestStatusID=0
);
If (#RequestID is not null)
BEGIN
Begin Transaction;
Update
sgz.PDFTransformationQueue
SET
RequestStatusid=64,
ProcessedInstanceID =#InstanceId,
ProcessStartTime = getutcdate(),
ModifiedDate=getutcdate()
Where
RequestID=#RequestID and
RequestStatusid =0 and
ProcessedInstanceID is null;
if ##rowcount = 0
set #RequestID=null;
Commit Transaction;
END
Select
RQ.VersionNumber,RQ.RequestID, RP.Payload
From
SGZ.RequestPayload RP WITH (NOLOCK),
SGZ.PDFTransformationQueue RQ WITH (NOLOCK)
Where
RP.RequestId=RQ.RequestID AND
ProcessedInstanceID=#InstanceId AND
RequestStatusid =64 AND
RQ.RequestId = #RequestID;
END
And below is the window service code:-
protected override void OnStart(string[] args)
{
PDFTransAutoProcessManager pdfTransAutoProcessManager = new
PDFTransAutoProcessManager();
pdfTransAutoProcessManager.OnProcessStart();
}
And PDFTransAutoProcessManager class:-
private int _runningAsyncThread = 0;
private int _totalAsynThread = 5;
public void OnProcessStart()
{
_logMgr.Info("Process started # " + DateTime.Now);
mainThread = new Thread(new ThreadStart(StartAutoProcess));
mainThread.Priority = ThreadPriority.Highest;
mainThread.Start();
}
private void StartAutoProcess()
{
try
{
while (true)
{
if (_runningAsyncThread < _totalAsynThread)
{
Thread childThread = new Thread(() => ProcessAsync());
Interlocked.Increment(ref _runningAsyncThread);
childThread.Start();
}
Thread.Sleep(100);
}
}
catch (Exception ex)
{ }
}
private void ProcessAsync()
{
try
{
PDFGenieManager pdfGenieManager = new
PDFGenieManager(_logMgr,gmi);
pdfGenieManager.ProcessRawData();
}
catch (Exception ex)
{
_logMgr.Info(ex.Message);
_logMgr.Info(ex.StackTrace);
}
finally
{
Interlocked.Decrement(ref _runningAsyncThread);
}
}
And in PDFGenieManager Class actual database call and conversion will happen.
When it is trying to get records from database some records are updated to 64 with out any entry in log.
Is it related to threading pattern or any problem with stored procedure.
Kindly help thanks in advance.
Below is the PDFGenieManager class code:-
namespace PDFConvertion
{
public class PDFGenieManager
{
public Logger _logMgr;
public GmiManager _gmi;
string _environment;
static readonly object _object = new object();
Dictionary<string, string> _ResourceMetadata = new Dictionary<string, string>();
public PDFGenieManager(Logger logMgr, GmiManager gmi)
{
_logMgr = logMgr;
_gmi = gmi;
_environment = ConfigurationManager.AppSettings["Envoirnment"];
}
public void ProcessRawData()
{
try
{
string unlockKey = string.Empty;
string languageRepair = string.Empty;
bool IsUnicodeRepair = false;
double confidenceScore = 1.0;
var Vendor = string.Empty;
string hiddenText = string.Empty;
DataTable rawData = new DataTable();
RuntimeCacheMgr _runtimeCacheMgr = new RuntimeCacheMgr();
DAL dal = new DAL();
try
{
rawData = dal.GetRawData();
if (rawData != null && rawData.Rows.Count > 0)
{
_logMgr.Info("Picked the record from datbase" + rawData.Rows[0]["Payload"].ToString());
}
if (!_runtimeCacheMgr.Exists(_environment))
{
_ResourceMetadata = dal.getResourcemetaDataValue(_environment);
_runtimeCacheMgr.Add(_environment, _ResourceMetadata);
}
else
{
_ResourceMetadata = _runtimeCacheMgr.Get<Dictionary<string, string>>(_environment);
}
}
catch (SqlException exe)
{
_logMgr.Error("Sql Database Error While Picking the records from database" + exe.Message + exe.StackTrace, exe.InnerException);
}
catch (Exception ex)
{
if (ex != null && !ex.ToString().ToLower().Contains("already exist"))
{
if (rawData != null && rawData.Rows.Count > 0)
{
_logMgr.Error("Exception block Picked the record from datbase" + rawData.Rows[0]["Payload"].ToString());
}
_logMgr.Error("Exception block" + ex.Message);
return;
}
else
{
if (rawData != null && rawData.Rows.Count > 0)
{
_logMgr.Error("Cache block Picked the record from datbase" + rawData.Rows[0]["Payload"].ToString());
}
_logMgr.Error("Cache block" + ex.Message + "" + ex.StackTrace);
}
}
finally
{
if (rawData != null && rawData.Rows.Count > 0)
{
_logMgr.Info("Finally block Picked the record from datbase" + rawData.Rows[0]["Payload"].ToString());
}
}
List<PDFGenieTran> ids = new List<PDFGenieTran>(rawData.Rows.Count);
rawData.AsEnumerable().ToList().ForEach(row => ids.Add(new PDFGenieTran() { Payload = row["Payload"].ToString(), RequestID = Convert.ToInt64(row["RequestID"]), VersionNumber = row["VersionNumber"].ToString() }));
PDFNetStatus PDFstatus = new PDFNetStatus();
foreach (PDFGenieTran pdf in ids)
{
}

Not able to edit in entity framework with asp.net/c#

public ReturnMessage EditCategories(Category objCategory)
{
ReturnMessage objReturnMessage = new ReturnMessage();
try
{
Category objCategoryNew = db.Categories.Where(x => x.CategoryId == objCategory.CategoryId).FirstOrDefault();
if (objCategoryNew != null)
{
objCategoryNew = objCategory;
db.SaveChanges();
objReturnMessage.isSuccessfull = true;
objReturnMessage.responseMessage = "Successfully updated.";
}
else
{
objReturnMessage.isSuccessfull = false;
objReturnMessage.responseMessage = "Category not present.";
}
}
catch (Exception ex)
{
objReturnMessage.isSuccessfull = false;
objReturnMessage.responseMessage = ex.Message;
}
return objReturnMessage;
}
Everything goes fine there are no exceptions still the data isn't getting updated. I don't know what's the issue. Please help?
The line:
objCategoryNew = objCategory;
will not work out since you change the reference objCategoryNew to objCategory, not the object itself, what you have to do is to assign each property of objCategory to objCategoryNew, something like:
objCategoryNew.Pro1 = objCategory.Pro1;
objCategoryNew.Pro2 = objCategory.Pro2;
....

EventStore duplicate commit exception

UPDATE:
We are getting getting System.Data.SqlClient.SqlException. The message is:
Violation of PRIMARY KEY constraint 'PK_Commits'. Cannot insert duplicate key in object 'dbo.Commits'.\r\nThe statement has been terminated
It seems like EventStore is using streamid and commitid as unique id.
We use event store to append events as below.
public bool TryAppend(object[] content)
{
if (content == null)
throw new ArgumentNullException("content");
try
{
using (var stream = m_storage.OpenStream(m_streamID, 0, int.MaxValue))
{
var versionInStore = stream.StreamRevision;
content.ToList().ForEach(m =>
{
var version = ++versionInStore;
var key = string.Format("{0}-{1:00000000}", m.GetType().Name, version);
var savedMessage = new SavedRecord(key, version, m);
stream.Add(new EventMessage { Body = savedMessage });
});
stream.CommitChanges(Guid.NewGuid());
}
return true;
}
catch (Exception e)
{
m_logger.LogError(e);
return false;
}
}
The configuration of EventStore is as below. We are using Sql Serer 2008 as persistance store.
return Wireup.Init()
.LogToOutputWindow()
.UsingSqlPersistence(m_connectionName)
.WithDialect(new MsSqlDialect())
.EnlistInAmbientTransaction() // two-phase commit
.InitializeStorageEngine()
.UsingJsonSerialization()
.Compress()
.UsingSynchronousDispatchScheduler()
.DispatchTo(new DelegateMessageDispatcher(DispatchCommit))
.Build();
Any ideas why are gettin the dupplicate commit exception?
Thanks
Have got the same issue; in my case it was probably because of different threads was adding different events to the stream with same id at the same time.
Have writtent the following code to be able to retry adding events:
private void TryAddEvent(IStoreEvents storeEvents, IUserEvent anEvent, Guid streamId)
{
var isCommitSuccessful = false;
for (var i = 0; i < 10 && !isCommitSuccessful; i++)
{
try
{
using (var stream = storeEvents.OpenStream(streamId, 0, int.MaxValue))
{
stream.Add(new EventMessage {Body = anEvent});
if (stream.UncommittedEvents.All(e => e.Body != anEvent))
{
stream.Add(new EventMessage {Body = anEvent});
}
stream.CommitChanges(Guid.NewGuid());
}
isCommitSuccessful = true;
}
catch (Exception ex)
{
if (!(ex is SqlException) && !(ex is ConcurrencyException))
{
throw;
}
using (var stream = storeEvents.OpenStream(streamId, 0, int.MaxValue))
{
if (stream.CommittedEvents.Any(e => e.Body == anEvent))
{
isCommitSuccessful = true;
}
}
}
}
if (!isCommitSuccessful)
{
throw new ConcurrencyException(String.Format("Cannot add {0} to event store", anEvent.GetType()));
}
}
Hope it would help.

LINQ to SQL submitchanges not doing anything

My issue is the following: i'm trying to build a function to which i could pass a list of items, which would then go to the db with each of those items and update them. I believe the issue is within the way datacontexts are being used but i cannot figure out this issue.
Here is my function that builds the list of items that were changed:
protected void btnSave_Click(object sender, EventArgs e)
{
List<AFF_CMS_FMA> fmasToSave = new List<AFF_CMS_FMA>();
AFF_CMS_FMA newFmaItem = new AFF_CMS_FMA();
foreach (AFF_CMS_FMA fmaItem in FmaLib.fetchAllActiveAssetsInFMA())
{
if (fmaItem.SortOrder != Convert.ToInt32(Request.Form["fmaItem_" + fmaItem.ID + "_SortOrder"]))
{
newFmaItem = fmaItem;
newFmaItem.Name = SecurityLib.SqlSafeString(Request.Form["fmaItem_" + fmaItem.ID + "_Name"]);
newFmaItem.AssetID = Convert.ToInt32(Request.Form["fmaItem_" + fmaItem.ID + "_AssetID"]);
newFmaItem.SortOrder = Convert.ToInt32(Request.Form["fmaItem_" + fmaItem.ID + "_SortOrder"]);
newFmaItem.ImagePathEn = SecurityLib.SqlSafeString(Request.Form["fmaItem_" + fmaItem.ID + "_ImagePathEn"]);
newFmaItem.ImagePathCh = SecurityLib.SqlSafeString(Request.Form["fmaItem_" + fmaItem.ID + "_ImagePathCh"]);
newFmaItem.StartDate = DateTime.Parse(SecurityLib.SqlSafeString(Request.Form["fmaItem_" + fmaItem.ID + "_StartDate"]));
newFmaItem.EndDate = DateTime.Parse(SecurityLib.SqlSafeString(Request.Form["fmaItem_" + fmaItem.ID + "_EndDate"]));
newFmaItem.ClickToUrl = SecurityLib.SqlSafeString(Request.Form["fmaItem_" + fmaItem.ID + "_ClickToUrl"]);
fmasToSave.Add(newFmaItem);
}
}
FmaLib.saveEditedFmas(fmasToSave);
}
here is the function that the foreach loops calls to get all the items that are in the db:
public static List<AFF_CMS_FMA> fetchAllActiveAssetsInFMA()
{
List<AFF_CMS_FMA> results = null;
using (fmaDataContext db = new fmaDataContext())
{
using (TransactionScope ts = new TransactionScope())
{
try
{
if (HttpContext.Current.Cache["fmaActiveList"] == null)
{
db.LoadOptions = loadAll;
results = clsCompiledQuery.getAllActiveFmas(db).ToList();
HttpContext.Current.Cache["fmaActiveList"] = results;
}
else
results = (List<AFF_CMS_FMA>)HttpContext.Current.Cache["fmaActiveList"];
ts.Complete();
}
catch (Exception ex)
{ Transaction.Current.Rollback(); }
}
return results;
}
}
here are the queries being used:
protected static class clsCompiledQuery
{
public static Func<DataContext, IOrderedQueryable<AFF_CMS_FMA>>
getAllActiveFmas = CompiledQuery.Compile((DataContext db)
=> from fma in db.GetTable<AFF_CMS_FMA>()
where fma.IsArchived == false
orderby fma.SortOrder ascending
select fma);
public static Func<DataContext, int,IQueryable<AFF_CMS_FMA>>
getFmaById = CompiledQuery.Compile((DataContext db, int ID)
=> from fma in db.GetTable<AFF_CMS_FMA>()
where fma.ID == ID
select fma);
}
and finally this were im trying to get the save to happen to the db but no exeptions are throwns, yet the db does not change
public static bool saveEditedFmas(List<AFF_CMS_FMA> fmaToSaveList)
{
using (fmaDataContext db = new fmaDataContext())
{
using (TransactionScope ts = new TransactionScope())
{
try
{
foreach (AFF_CMS_FMA fmaItemToSave in fmaToSaveList)
{
AFF_CMS_FMA fmaItemToUpdate = clsCompiledQuery.getFmaById(db, fmaItemToSave.ID).ToList()[0];
fmaItemToUpdate = fmaItemToSave;
db.SubmitChanges();
}
return true;
}
catch (Exception ex)
{
Transaction.Current.Rollback();
return false;
}
}
}
}
I have checked and the table does contain a primary key in the designer. If i do the save from the btnSave_click function by passing a datacontext to the fetchAllActiveAssetsInFMA() then doing submitchanges on that context it works .. but im trying to abstract that from there.
thanks all in advance
Your not calling ts.Complete in function saveEditedFmas.
Also I would recommend calling db.SubmitChanges(); outside of the for loop. And why do you have a transaction in function fetchAllActiveAssetsInFMA? It's only fetching data right? And I'm not quite sure whats happening inside the for loop in save function, looks strange.
I think you should map the properties from fmaItemToSave to fmaItemToUpdate
foreach (var fmaItemToSave in fmaToSaveList)
{
var fmaItemToUpdate = clsCompiledQuery.getFmaById(db, fmaItemToSave.ID).First();
fmaItemToUpdate.Name = fmaItemToSave.Name;
fmaItemToUpdate.AssetID = fmaItemToSave.AssetID;
//And the rest of the properties
}
db.SubmitChanges();

Categories