KeyNotFoundException on SaveChanges() - mysql

Okey so i'm trying to update information in my database from a form.
But when i call db.SaveShanges() i get KeyNotFoundException.
I'm using MVC3 and EF 4.1.
I use Controller->Service->Repositry->EF design pattern.
The callstack:
at System.Collections.Generic.Dictionary`2.get_Item(TKey key)
at System.Data.Objects.EntityEntry.UpdateComplexObjectSnapshot(StateManagerMemberMetadata member, Object userObject, Int32 ordinal, Object currentValue)
at System.Data.Objects.EntityEntry.DetectChangesInProperties(Boolean detectOnlyComplexProperties)
at System.Data.Objects.ObjectStateManager.DetectChangesInScalarAndComplexProperties(IList`1 entries)
at System.Data.Objects.ObjectStateManager.DetectChanges()
at System.Data.Objects.ObjectContext.DetectChanges()
at System.Data.Entity.Internal.InternalContext.DetectChanges(Boolean force)
at System.Data.Entity.Internal.InternalContext.GetStateEntries(Func`2 predicate)
at System.Data.Entity.Internal.InternalContext.GetStateEntries()
at System.Data.Entity.Infrastructure.DbChangeTracker.Entries()
at System.Data.Entity.DbContext.GetValidationErrors()
at System.Data.Entity.Internal.InternalContext.SaveChanges()
at System.Data.Entity.Internal.LazyInternalContext.SaveChanges()
at System.Data.Entity.DbContext.SaveChanges()
My repositrory db is a dbContext with a DbSet for the model i'm using.
public bool Save()
{
try
{
db.SaveChanges();
}
catch(Exception e)
{
return false;
}
return true;
}
My Service that calls the repository
public bool UpdateUserInformationFromSettingsModel(UserSettingsModel model)
{
int userInfoID = _profile.GetUserInformationID(model.userName);
UserInformation userInfo = _repository.Get(userInfoID);
if (userInfo == null)
{
return false;
}
userInfo.firstName = model.firstName;
userInfo.lastName = model.lastName;
userInfo.phone = model.phone;
userInfo.invoiceReciever = model.invoiceReciever;
userInfo.invoiceAddress = model.invoiceAddress;
userInfo.address = model.address;
userInfo.preferedLanguage = model.preferedLanguage;
bool saveSuccess = _repository.Save();
if(!saveSuccess)
{
return false;
}
return true;
}
My controller
[HttpPost]
public ActionResult Edit(UserSettingsModel model)
{
if(ModelState.IsValid)
{
if (_userService.UpdateUserInformationFromSettingsModel(model))
{
return RedirectToAction("Settings");
}
ModelState.AddModelError("", GuiText.editSettingsError);
}
return View(model);
}
The UserInformation Model
public class UserInformation
{
public int ID { get; set; }
public string firstName { get; set; }
public string lastName { get; set; }
public string phone { get; set; }
public string invoiceSendOption { get; set; }
public string invoiceReciever { get; set; }
public Address invoiceAddress { get; set; }
public Address address { get; set; }
public string preferedLanguage { get; set; }
public string confirmCode { get; set; }
public UserSiteSettings siteSettings { get; set; }
public UserInformation()
{
firstName = "";
lastName = "";
phone = "";
invoiceSendOption = "";
invoiceReciever = "";
invoiceAddress = new Address();
address = new Address();
preferedLanguage = "";
confirmCode = "";
siteSettings = new UserSiteSettings();
}
The UserSettingsModel
public class UserSettingsModel
{
public string userName { get; set; }
[Display(Name = "name", ResourceType=typeof(GuiText))]
public string firstName { get; set; }
public string lastName { get; set; }
[Display(Name = "phone", ResourceType = typeof(GuiText))]
public string phone { get; set; }
[Display(Name = "invoiceInfo", ResourceType = typeof(GuiText))]
public string invoiceReciever { get; set; }
public Address invoiceAddress { get; set; }
[Display(Name = "address", ResourceType = typeof(GuiText))]
public Address address { get; set; }
[Display(Name = "prefLang", ResourceType = typeof(GuiText))]
public string preferedLanguage { get; set; }
public List<SelectListItem> preferedLanguageList { get; set; }
I have checked the variables in debugger and it all seems to be ok.
I'm using MySql connector v6.5.4.
So anyone got any ideas what the problem might be?

After some days of frustration and searching i found the problem.
I used a custom made equals method in my UserInformation and Address class. That caused the problems. Now i have removed it and changed my Unit Tests to work in another way.

Related

How make dropdownlist to access data on your SelectItemList using asp.net mvc?

I am using DropDownlist in order to get country of all the world. I have attached the file(country_list.txt) using srcFilePath. The error i am getting is "There is no ViewData item of type 'IEnumerable' that has the key 'SelectedCountryId'.What could be an issue, because my EditFormTrainingRegViewModel does have this field SelectedCountry as a primary key. Its been declared as public int? SelectedCountryId {get;set;}
// List for countries.
private IEnumerable<SelectListItem> GetCountryList()
{
SelectList listcn = null;
try
{
var list = this.LoadData().Select(p => new SelectListItem
{
Value = p.Country_Id.ToString(),
Text = p.Country_Name
});
listcn = new SelectList(list, "Value", "Text");
}catch(Exception ex)
{
throw ex;
}
return listcn;
}
public ActionResult DropDownSelect()
{
EditTrainingRegFormViewModel model = new EditTrainingRegFormViewModel();
model.SelectedCountryId = 0;
this.ViewBag.CountryList = this.GetCountryList();
return this. View(model);
}
// Loading data for country list.
private List<EditTrainingRegFormViewModel> LoadData()
{
List<EditTrainingRegFormViewModel> lst = new List<EditTrainingRegFormViewModel>();
try
{
string line = string.Empty;
string srcFilePath = "Content/files/country_list.txt";
var rootPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase);
var fullPath = Path.Combine(rootPath, srcFilePath);
string filePath = new Uri(fullPath).LocalPath;
StreamReader src = new StreamReader(new FileStream(filePath, FileMode.Open, FileAccess.Read));
// while to read the file
while((line = src.ReadLine()) !=null) {
EditTrainingRegFormViewModel infoLst = new EditTrainingRegFormViewModel();
string[] info = line.Split(',');
//Setting
infoLst.Country_Id = Convert.ToInt32(info[0].ToString());
infoLst.Country_Name = info[1].ToString();
lst.Add(infoLst);
}
src.Dispose();
src.Close();
}catch(Exception ex)
{
Console.Write(ex);
}
return lst;
}
//View
#Html.DropDownListFor(m=>m.SelectedCountryId, this.ViewBag.CountryList as SelectList, new {#class = "form-control"})
// Model class
public class EditTrainingRegFormViewModel
{
public string Title { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Position { get; set; }
public string Company { get; set; }
public string Address { get; set; }
[Display(Name = "Choose country")]
public int ? SelectedCountryId { get; set; }
public string Code { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Cell_Number { get; set; }
public List<string> Dietary_requirement { get; set; }
public string Email { get; set; }
public int Country_Id { get; set; }
public string Country_Name { get; set; }
}

How to create multiple Radiobutton group in ASP.Net Core 2 and Razor?

I want to create multiple grouped Radio buttons. So, basically I have multiple questions and 3 radio buttons with answers. The problem I'm facing is how to return the selected value for the multiple radio buttons.
Controller
public IActionResult Test()
{
SafetyObservationCardForm form = new SafetyObservationCardForm();
using (IDbConnection dbConnection = Connection)
{
dbConnection.Open();
var questions = dbConnection.Query<QuestionsViewModel>("SELECT * FROM SOCQuestions ORDER BY soc_order_id");
var observationType = new List<ObservationType>
{
new ObservationType { Id = 1, Name = "Safe" },
new ObservationType { Id = 2, Name = "At Risk" },
new ObservationType { Id = 3, Name = "N/A" }
};
var rb = new List<Answer>();
foreach (var item in questions)
{
rb.Add(new Answer { Id = item.soc_question_id, ObservationTypes = observationType });
};
form.Answers = rb;
form.Questions = questions.ToList();
return View(form);
}
}
Model
public class SafetyObservationCardForm
{
public List<QuestionsViewModel> Questions { get; set; }
public string Comments { get; set; }
public string Location { get; set; }
public string Observer { get; set; }
public DateTime TimeStamp { get; set; }
public string Task { get; set; }
public ObserverType ObserverType { get; set; }
public IEnumerable<Answer> Answers { get; set; }
}
public class ObserverType
{
public bool Supervisor { get; set; }
public bool Peer { get; set; }
public bool Self { get; set; }
public bool Other { get; set; }
}
public class ObservationType
{
public int Id { get; set; }
public string Name { get; set; }
}
public class Answer
{
public int Id { get; set; }
public IEnumerable<ObservationType> ObservationTypes { get; set; }
public int SelectedObservation { get; set; }
}
}
View
Here I'm trying the loop. Answers model is null when I submit the form for some reason.
#model DBI.Safety.Models.SafetyObservationCardForm
<form asp-action="CreateTest">
#foreach (var answer in Model.Answers)
{
<input name="#answer.Id" asp-for="#answer.SelectedObservation" type="radio"
value="#answer.Id" /> #answer.ObservationTypes
}
</form>

Deserialize multi-part JSON with DataContractJsonSerializer

I'm fairly new to the awesomeness that is JSON - I'm using the DataContractJsonSerializer. I cannot get the multiple instances of the Customer objects into the list.
The Attributes work as expected but there are no Customer objects in my List..??
{
"#attributes":
{"count":"2",
"offset":"0",
"limit":"100"
},
"Customer":
{
"firstName":"cust ",
"lastName":"one",
"title":"Owner",
"company":"CustOne Plants",
"companyRegistrationNumber":"",
"vatNumber":"",
"creditAccountID":"1",
"customerTypeID":"4",
"discountID":"0",
"taxCategoryID":"0",
"customerID":"1",
"createTime":"2017-06-19T23:36:11+00:00",
"timeStamp":"2017-06-20T18:55:11+00:00",
"archived":"false"
}
"Customer":
{
"firstName":"cust ",
"lastName":"two",
"title":"Owner",
"company":"CustTwo House of Games",
"companyRegistrationNumber":"",
"vatNumber":"",
"creditAccountID":"1",
"customerTypeID":"4",
"discountID":"0",
"taxCategoryID":"0",
"customerID":"1",
"createTime":"2017-06-19T23:36:11+00:00",
"timeStamp":"2017-06-20T18:55:11+00:00",
"archived":"false"
}
}
.NET code:
StreamReader stream = new StreamReader(#"C:\TMC Projects\PotteryManufacturing\CustomerJSON.txt");
string text = stream.ReadToEnd();
stream.Close();
byte[] byteArray = Encoding.UTF8.GetBytes(text);
MemoryStream stream1 = new MemoryStream(byteArray);
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(CustomersRoot));
var varInfo = serializer.ReadObject(stream1) as CustomersRoot;
stream1.Close();
and finally my classes/data contracts/data members:
[DataContract]
public class CustomersRoot
{
private List<Customer> m_Customers;
public CustomersRoot() { this.Customer = new List<Customer>(); }
[DataMember(Name ="#attributes")]
public Attributes attrs { get; set; }
[DataMember(Name = "Customer")]
public List<Customer> Customer
{
get { return m_Customers; }
set { m_Customers = value; }
}
}
[DataContract]
public class Customer
{
[DataMember(Name ="firstName")]
public string firstName { get; set; }
[DataMember(Name = "lastName")]
public string lastName { get; set; }
[DataMember(Name = "title")]
public string title { get; set; }
[DataMember(Name = "company")]
public string company { get; set; }
[DataMember(Name = "companyRegistrationNumber")]
public string companyRegistrationNumber { get; set; }
[DataMember(Name = "vatNumber")]
public string vatNumber { get; set; }
[DataMember(Name = "creditAccountID")]
public int creditAccountID { get; set; }
[DataMember(Name = "customerTypeID")]
public int customerTypeID { get; set; }
[DataMember(Name = "discountID")]
public int discountID { get; set; }
[DataMember(Name = "taxCategoryID")]
public int taxCategoryID { get; set; }
[DataMember(Name = "customerID")]
public int customerID { get; set; }
[DataMember(Name = "createTime")]
public string createTime { get; set; }
[DataMember(Name = "timeStamp")]
public string timeStamp { get; set; }
[DataMember(Name = "archived")]
public bool archived { get; set; }
}
[DataContract]
public class Attributes
{
[DataMember(Name = "count")]
public int count { get; set; }
[DataMember(Name = "offset")]
public int offset { get; set; }
[DataMember(Name = "limit")]
public int limit { get; set; }
}
I figured out what's going on here - the call can sometimes return an array of Customer objects (not formatted correctly above) OR a single instance of the object. When the web service returns a single Customer instance, the List code does not work. I will have to check on how to deal w/ this issue.

Deserialize OneNote Notebooks API Response

I'm getting an empty object when I try to Deserialize a OneNote GetAllNotebooks query.
string[] tempCapture = null;
var url = new Uri("https://graph.microsoft.com/v1.0/me/onenote/notebooks");
var client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
if (IsAuthenticated)
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authResult.AccessToken);
}
var response = await client.GetAsync(url);
var result = await response.Content.ReadAsStringAsync();
tbResponse.Text = result.ToString();
DataContractJsonSerializer ser1 = new DataContractJsonSerializer(typeof(List<Value>));
MemoryStream stream1 = new MemoryStream(Encoding.UTF8.GetBytes(tbResponse.Text.ToString()));
var obj1 = (List<Value>)ser1.ReadObject(stream1);
I'm trying to get a list of notebooks, names, links to add to a database. And my table structure matches the class below.
Here is my OneNote API class
public class Value
{
public bool isDefault { get; set; }
public string userRole { get; set; }
public bool isShared { get; set; }
public string sectionsUrl { get; set; }
public string sectionGroupsUrl { get; set; }
public Links links { get; set; }
public string name { get; set; }
public string self { get; set; }
public string createdBy { get; set; }
public string lastModifiedBy { get; set; }
public string lastModifiedTime { get; set; }
public string id { get; set; }
public string createdTime { get; set; }
}
Here is my new code with the RootObject. I'm still getting an error. It is in the catch exception.
var test = await client.GetAsync(url);
string testStr = await test.Content.ReadAsStringAsync();
DataContractJsonSerializer serial = new DataContractJsonSerializer(typeof(RootObject));
MemoryStream testStream = new MemoryStream(Encoding.UTF8.GetBytes(testStr));
try
{
var objx = (List<RootObject>)serial.ReadObject(testStream);
}
catch(Exception ex)
{
ex.ToString();
//"There was an error deserializing the object of type OneNoteSOAP2.RootObject. End element 'createdBy' from namespace '' expected. Found element 'user' from namespace ''."
}
You can use http://json2csharp.com/. Basically, just copy the value of our JSON being returned, and use the classes generated by this website. Use RootObject to deserialize.
I ran this for you and obtained these classes:
public class OneNoteClientUrl
{
public string href { get; set; }
}
public class OneNoteWebUrl
{
public string href { get; set; }
}
public class Links
{
public OneNoteClientUrl oneNoteClientUrl { get; set; }
public OneNoteWebUrl oneNoteWebUrl { get; set; }
}
public class Value
{
public string id { get; set; }
public string self { get; set; }
public string createdTime { get; set; }
public string name { get; set; }
public string createdBy { get; set; }
public string lastModifiedBy { get; set; }
public string lastModifiedTime { get; set; }
public bool isDefault { get; set; }
public string userRole { get; set; }
public bool isShared { get; set; }
public string sectionsUrl { get; set; }
public string sectionGroupsUrl { get; set; }
public Links links { get; set; }
}
public class RootObject
{
public List<Value> value { get; set; }
}

Parsing Json gMaps Api in windows Phone 8 using Serialization

I Have json file :
Google Maps Api - place Json
I want Parsing Json using System.Runtime.Serialization;
I can create 3 class :
public class Places
{
[DataMember(Name = "geometry")]
public string Geometry
{
get;
set;
}
[DataMember(Name = "location")]
public string Location { get; set; }
[DataMember(Name = "lat")]
public string Latitude { get; set; }
[DataMember(Name = "lng")]
public string Longitude { get; set; }
[DataMember(Name = "icon")]
public string Icon { get; set; }
[DataMember(Name = "id")]
public string Id { get; set; }
[DataMember(Name = "name")]
public string Name { get; set; }
[DataMember(Name = "photo")]
public string Photo { get; set; }
[DataMember(Name = "rating")]
public string Rating { get; set; }
[DataMember(Name = "reference")]
public string Reference { get; set; }
[DataMember(Name = "types")]
public string Types { get; set; }
[DataMember(Name = "vicinity")]
public string Vicinity { get; set; }
}
public class AppConstants
{
public static String baseUri = "https://maps.googleapis.com/maps/api/place/search/json?location=";
}
public class PlaceToMap
{
public GeoCoordinate Coordinate { get; set; }
public string Info { get; set; }
}
[DataContract]
public class PlacesList
{
[DataMember(Name ="results")]
public List<Places> PlaceList { get; set; }
}
MainPage.xaml.cs :
private void updateMap(PlacesList googlePlaceApiRespone)
{
int totalRecords = googlePlaceApiRespone.PlaceList.Count();
try
{
ObservableCollection<PlaceToMap> placeToMapObjs = new ObservableCollection<PlaceToMap>();
for (int index = 0; index < totalRecords; index++)
{
placeToMapObjs.Add(new PlaceToMap()
{
Coordinate = new GeoCoordinate(Convert.ToDouble(googlePlaceApiRespone.PlaceList.ElementAt(index).Latitude),
Convert.ToDouble(googlePlaceApiRespone.PlaceList.ElementAt(index).Longitude)),
Info = googlePlaceApiRespone.PlaceList.ElementAt(index).Name + Environment.NewLine + googlePlaceApiRespone.PlaceList.ElementAt(index).Vicinity
});
}
ObservableCollection<DependencyObject> children = MapExtensions.GetChildren(myMap);
var obj = children.FirstOrDefault(x => x.GetType() == typeof(MapItemsControl)) as MapItemsControl;
obj.ItemsSource = placeToMapObjs;
myMap.SetView(new GeoCoordinate(Convert.ToDouble(currentLatitude), Convert.ToDouble(currentLongitude)), 16);
}
catch (Exception)
{
}
}
But can't no show in pushpin.
toolkit:Pushpin GeoCoordinate="{Binding Coordinate}" Content="{Binding Info}"