Not able to edit in entity framework with asp.net/c# - 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;
....

Related

Creating a folder under Inbox using Mocrosoft.Graph 2.0.14

I'm trying to create a folder under my Inbox in Office 365 using MS Graph 2.0, but I'm finding surprisingly little information on the topic anywhere on the internet. The authentication works fine, and I was able to read the existing test folder. My method for doing this is below:
private void SetupMailBoxes()
{
SmartLog.EnterMethod("SetupMailBoxes()");
MailFolder inbox = null;
try
{
bool dbErrorFolder = false;
bool exchangeErrorFolder = false;
inbox = _journalMailbox.MailFolders.Inbox.Request().GetAsync().GetAwaiter().GetResult();
if (inbox.ChildFolderCount > 0)
{
inbox.ChildFolders = _journalMailbox.MailFolders.Inbox.ChildFolders.Request().GetAsync().GetAwaiter().GetResult();
}
if (inbox.ChildFolders != null)
{
for (int i = 0; i < inbox.ChildFolders.Count && (!dbErrorFolder || !exchangeErrorFolder); i++)
{
if (inbox.ChildFolders[i].DisplayName.ToLower() == "db-error-items")
{
dbErrorFolder = true;
}
else if (inbox.ChildFolders[i].DisplayName.ToLower() == "exchange-error-items")
{
exchangeErrorFolder = true;
}
}
}
if (!dbErrorFolder)
{
try
{
//inbox.ODataType = "post";
var folder = _journalMailbox.MailFolders.Inbox.Request().CreateAsync(
new MailFolder()
{
DisplayName = "DB-Error_Items",
}).GetAwaiter().GetResult();
//inbox.ChildFolders.Add(folder);
}
catch (Exception ex)
{
throw;
}
}
}
catch (Exception exp)
{
SmartLog.LeaveMethod("SetupMailBoxes()");
throw;
}
finally
{
}
SmartLog.LeaveMethod("SetupMailBoxes()");
}
Where _clientSecretCredential is created like this:
_graphServiceClient = null;
_options = new TokenCredentialOptions { AuthorityHost = AzureAuthorityHosts.AzurePublicCloud };
_clientSecretCredential = new ClientSecretCredential(
this.FindString(config.TenentID)
, this.FindString(config.AppID)
, this.FindString(config.Secret)
, _options);
string[] apiScope = new string[] { this.FindString(config.Scope) };
_token = _clientSecretCredential.GetToken(new Azure.Core.TokenRequestContext(apiScope));
graphServiceClient = new GraphServiceClient(_clientSecretCredential, apiScope);
IUserRequestBuilder _journalMailbox = _graphServiceClient.Users["journal#mycompany.com"];
The code seems correct, but everytime I execute "_journalMailbox.MailFolders.Inbox.Request().CreateAsync", I get the following error:
Code: ErrorInvalidRequest
Message: The OData request is not supported.
ClientRequestId:Some Guid.
From what I could figure out by searching on the internet, it has to do with the method using the wrong method to access the API. I mean like, its using "GET" in stead of "POST" or something like that, but that would mean its a bug in the MS code, and that would an unimaginably big oversight on Microsoft's part, so I can't think its that.
I've tried searching documentation on how to create subfolders, but of the preciously few results I'm getting, almost none has C# code samples, and of those, all are of the previous version of Microsoft Graph.
I'm really stumped here, I'm amazed at how hard it is to find any documentation to do something that is supposed to be simple and straight forward.
Ok, so it turned out that I was blind again. Here is the correct code for what I was trying to do:
private void SetupMailBoxes()
{
SmartLog.EnterMethod("SetupMailBoxes()");
MailFolder inbox = null;
try
{
bool dbErrorFolder = false;
bool exchangeErrorFolder = false;
inbox = _journalMailbox.MailFolders.Inbox.Request().GetAsync().GetAwaiter().GetResult();
if (inbox.ChildFolderCount > 0)
{
inbox.ChildFolders = _journalMailbox.MailFolders.Inbox.ChildFolders.Request().GetAsync().GetAwaiter().GetResult();
}
if (inbox.ChildFolders != null)
{
for (int i = 0; i < inbox.ChildFolders.Count && (!dbErrorFolder || !exchangeErrorFolder); i++)
{
if (inbox.ChildFolders[i].DisplayName.ToLower() == "db-error-items")
{
dbErrorFolder = true;
}
else if (inbox.ChildFolders[i].DisplayName.ToLower() == "exchange-error-items")
{
exchangeErrorFolder = true;
}
}
}
else
{
inbox.ChildFolders = new MailFolderChildFoldersCollectionPage();
}
if (!dbErrorFolder)
{
try
{
var folder = new MailFolder()
{
DisplayName = "DB-Error-Items",
IsHidden = false,
ParentFolderId = inbox.Id
};
folder = _journalMailbox.MailFolders[inbox.Id].ChildFolders.Request().AddAsync(folder).GetAwaiter().GetResult();
inbox.ChildFolders.Add(folder);
}
catch (Exception ex)
{
throw;
}
}
}
catch (Exception exp)
{
SmartLog.LeaveMethod("SetupMailBoxes()");
throw;
}
finally
{
}
SmartLog.LeaveMethod("SetupMailBoxes()");
}

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();
}

Validating digitaly signed PDF Spire.Pdf C#

So I am developing a web app that generates a PDF contract from a partial view, and then validates the digital signiture. I came accross an example here . The problem is that an exception is thrown when validating the signiture and for the life of me I cant figure out why...
Here is the code :
public async Task<ActionResult> Upload(HttpPostedFileBase FileUpload)
{
ActionResult retVal = View();
AspNetUser user = DbCtx.AspNetUsers.Find(User.Identity.GetUserId());
bool signitureIsValid = false;
string blobUrl = string.Empty;
if (FileUpload != null && FileUpload.ContentLength > 0)
{
string fileName = Guid.NewGuid().ToString() + RemoveAllSpaces(FileUpload.FileName);
string filePath = Path.Combine(System.Web.Hosting.HostingEnvironment.MapPath("~/Content/pdfs"), fileName);
FileUpload.SaveAs(filePath);
List<PdfSignature> signatures = new List<PdfSignature>();
using (var doc = new PdfDocument(filePath))
{
var form = (PdfFormWidget) doc.Form;
int count = 0;
try
{
count = form.FieldsWidget.Count;
}
catch
{
count = 0;
}
for (int i = 0; i < count; ++i)
{
var field = form.FieldsWidget[i] as PdfSignatureFieldWidget;
if (field != null && field.Signature != null)
{
PdfSignature signature = field.Signature;
signatures.Add(signature);
}
}
}
PdfSignature signatureOne = signatures[0];
try
{
signitureIsValid = signatureOne.VerifySignature(); // HERE SHE BLOWS !
if (signitureIsValid)
{
blobPactUrl = await BlobUtil.BasicStorageBlockBlobOperationsAsync(System.IO.File.ReadAllBytes(filePath));
if (!string.IsNullOrEmpty(blobPactUrl))
{
ApplicantInfo info = DbCtx.ApplicantInfoes.FirstOrDefault(x => x.UserId == user.Id);
info.URL = blobUrl;
info.SignatureIsValid = true;
info.ActivationDate = DateTime.Now;
info.ActiveUntill = DateTime.Now.AddYears(1);
DbCtx.Entry(info).State = System.Data.Entity.EntityState.Modified;
DbCtx.SaveChanges();
retVal = RedirectToAction("Publications");
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
System.IO.File.Delete(filePath);
}
}
return retVal;
}
Here is an image of
what it looks like when I'm debuging:
I have checked the signiture and it is valid and cerified... I know I'm missing something basic here... Please help me internet!
Just noticed that I posted this. . . Turns out that the problem was due to bug in the package itself. Upon asking the lovely people at E-Iceblue, the bug was recreated, solved and a new version of Spire.PDF was up on nuget within a week.
great job E-Iceblue, it worked fine :)

Delete row in gridview using linq

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();

ItemUpdated Event, After or Before Property Title name is null. Sharepoint 2010

No matter what I do, before and after for title are always null. This is an item updated receiver in the meetings or event list
!
[public override void ItemUpdated(SPItemEventProperties properties)
{
Logger.LogDebug("MeetingCalendarEvents", "ItemUpdated(SPItemEventProperties properties)", "BEGIN");
base.ItemUpdated(properties);
try
{
base.EventFiringEnabled = false;
SPSite site = properties.Web.Site;
string sitename= properties.BeforeProperties\["Title"\].ToString();
SPWeb web = site.RootWeb.Webs\[sitename\];
web.AllowUnsafeUpdates = true;
string prefix = properties.BeforeProperties\["Title"\].ToString().Substring(0, 2);
web.Title = properties.AfterProperties\["Title"\].ToString();
DateTime eventDate = properties.AfterProperties.GetValueAsDateTime(MeetingsCommon.Constants.FIELDS_EVENTDATE_NAME);
if (eventDate != DateTime.MinValue)
{
string titleMeetingCalendarItem = eventDate.ToString("yyyyMMdd");
titleMeetingCalendarItem = string.Format("{0}{1}", prefix, titleMeetingCalendarItem);
properties.AfterProperties.SetAfterPropertyValue("Title", titleMeetingCalendarItem);
web.ServerRelativeUrl = "/" + titleMeetingCalendarItem;
}
web.Update();
web.AllowUnsafeUpdates = false;
base.EventFiringEnabled = true;
}
catch (Exception ex)
{
Logger.LogError("MeetingCalendarEvents", "ItemUpdated(SPItemEventProperties properties)", ex);
properties.ErrorMessage = ex.Message;
properties.Cancel = true;
}
finally
{
base.EventFiringEnabled = true;
}
Logger.LogDebug("MeetingCalendarEvents", "ItemUpdated(SPItemEventProperties properties)", "END");
}]
answer here:
http://www.synergyonline.com/Blog/Lists/Posts/Post.aspx?ID=122

Categories