I am trying to put some distributed caching into play, I'm using this indeXus.Net Shared Cache .
It Requires that the object being cached is serializable, which it is here is the class object.
[Serializable]
public class Members
{
public Members()
{}
public Members(string aspnetusername, string aspnetpassword,
string emailaddr,string location)
: this(0,0,aspnetusername, aspnetpassword,emailaddr,DateTime.Now, location,
0,0,DateTime.Now,DateTime.Now,DateTime.Now,false)
{ }
public Members(Int64? row,int memberid, string aspnetusername, string aspnetpassword,
string emailaddr,DateTime datecreated, string location, int daimokugoal, int previewimageid,
DateTime lastdaimoku, DateTime lastnotifed, DateTime lastactivitydate, bool isactivated)
{
this.Row = row;
this.MemberID = memberid;
this.Aspnetusername = aspnetusername;
this.Aspnetpassword = aspnetpassword;
this.EmailAddr = emailaddr;
this.DateCreated = datecreated;
this.Location = location;
this.DaimokuGoal = daimokugoal;
this.PreviewImageID = previewimageid;
this.LastDaimoku = lastdaimoku;
this.LastNotefied = lastnotifed;
this.LastActivityDate = lastactivitydate;
this.IsActivated = this.IsActivated;
this.Details = new LazyList<MemberDetails>();
this.Blogs = new LazyList<MemberBlogs>();
this.Daimoku = new LazyList<MemberDaimoku>();
this.Determinations = new LazyList<MemberDeterminations>();
this.Encouragements = new LazyList<MemberEncouragements>();
this.Entries = new LazyList<MemberEntries>();
this.Friends = new LazyList<MemberFriends>();
this.Stats = new LazyList<MemberStats>();
}
public Int64? Row { get; set; }
public int MemberID { get; set; }
public string Aspnetusername { get; set; }
public string Aspnetpassword { get; set; }
public string EmailAddr { get; set; }
public DateTime DateCreated { get; set; }
public string Location { get; set; }
public int DaimokuGoal { get; set; }
public int PreviewImageID { get; set; }
public DateTime LastDaimoku { get; set; }
public DateTime LastNotefied { get; set; }
public DateTime LastActivityDate { get; set; }
public bool IsActivated { get; set; }
public LazyList<MemberDetails> Details { get; set; }
public LazyList<MemberBlogs> Blogs { get; set; }
public LazyList<MemberDaimoku> Daimoku { get; set; }
public LazyList<MemberDeterminations> Determinations { get; set; }
public LazyList<MemberEncouragements> Encouragements { get; set; }
public LazyList<MemberEntries> Entries { get; set; }
public LazyList<MemberFriends> Friends { get; set; }
public LazyList<MemberStats> Stats { get; set; }
}
The LINQtoSql is this that populates this class.
public IQueryable<Members> GetMemberInfo()
{
using (var t = new TransactionScope(TransactionScopeOption.Required,
new TransactionOptions { IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted }))
{
var results = from m in _datacontext.ViewMembers
let details = GetMemberDetails(m.MemberID)
let determinations = GetMemberDeterminations(m.MemberID)
let daimoku = GetMemberDaimoku(m.MemberID)
let entries = GetMemberEntries(m.MemberID)
let blogs = GetMemberBlogs(m.MemberID)
let encouragements = GetMemberEncouragements(m.MemberID)
let friends = GetMemberFriends(m.MemberID)
let points = GetMemberStats(m.MemberID)
select new Members
{
Row = m.Row,
MemberID = m.MemberID,
Aspnetusername = m.Aspnetusername,
Aspnetpassword = m.Aspnetpassword,
EmailAddr = m.EmailAddr,
DateCreated = m.DateCreated,
Location = m.Location,
DaimokuGoal = m.DaimokuGoal,
PreviewImageID = m.PreviewImageID,
LastDaimoku = m.LastDaimoku.Value,
LastNotefied = m.LastNotefied.Value,
LastActivityDate = m.LastActivityDate.Value,
IsActivated = m.IsActivated,
Details = new LazyList<MemberDetails>(details),
Determinations = new LazyList<MemberDeterminations>(determinations),
Daimoku = new LazyList<MemberDaimoku>(daimoku),
Entries = new LazyList<MemberEntries>(entries),
Blogs = new LazyList<MemberBlogs>(blogs),
Encouragements = new LazyList<MemberEncouragements>(encouragements),
Friends = new LazyList<MemberFriends>(friends),
Stats = new LazyList<MemberStats>(points)
};
return results;
}
}
But for some reason I am getting this error
System.Runtime.Serialization.SerializationException: Type 'System.Data.Linq.DataQuery`1[[DaimokuBeta.MVC.Data.MemberDetails, DaimokuBeta.MVC.Data, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]' in Assembly 'System.Data.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' is not marked as serializable.
MemberDetails is serializable too..so not sure why it thinks it can't be serialized
Any ideas?
I believe that it's your LazyList implementation that cannot be serialized because the exception is telling us that the generic type DataQuery (from assembly System.Data.Linq) is not serializable. Is this type connected to your LazyList in any way?
If you are trying to cache the Members DTO (data transfer object) it's probably not a good idea to be applying lazy loading because it may only be executed in a very unpredictable moment.
Cache should usually be applied to data that has already been loaded/computed. Otherwise there may not be much point in using cache.
Related
I have an API request in my web application but every time I convert the response result to deserialize object it gives null value to my model.
Here's my code:
var contents = await responseMessage.Content.ReadAsStringAsync();
var statusInfo = responseMessage.StatusCode.ToString();
if (statusInfo == "OK")
{
var jsonresult = JObject.Parse(contents);
var respond = jsonresult["data"].ToString();
var result = JsonConvert.DeserializeObject<ResponseModel>(respond);
}
The contents value is
"{\"data\":{\"totalcount:\":8113,\"tpa:\":6107,\"tip:\":5705},\"message\":\"success\"}"
The respond value is
"{ \r\n"totalcount:\": 8113,\r\n \"tpa:\": 6107,\r\n \"tip:\": 5705\r\n}"
and my model is
public class ResponseModel
{
[JsonProperty(PropertyName = "totalcount")]
public int totalcount { get; set; }
[JsonProperty(PropertyName = "tpa")]
public int tpa { get; set; }
[JsonProperty(PropertyName = "tip")]
public int tip { get; set; }
}
Please help thank you.
you have an extra ":" at the end of property name of your json, so try this json property names. This code was tested in Visual Studio and working properly
ResponseModel result = null;
if ( responseMessage.IsSuccessStatusCode)
{
var json = await responseMessage.Content.ReadAsStringAsync();
var jsonObject = JObject.Parse(json);
var data=jsonObject["data"];
if (data!=null) result = data.ToObject<ResponseModel>();
}
public class ResponseModel
{
[JsonProperty("totalcount:")]
public int totalcount { get; set; }
[JsonProperty("tpa:")]
public int tpa { get; set; }
[JsonProperty("tip:")]
public int tip { get; set; }
}
or you can fix an API
In my model I added the colon ":" since the return value of the properties in the API has a ":" colon per property.
public class ResponseModel
{
[JsonProperty(PropertyName = "totalcount:")]
public int totalcount { get; set; }
[JsonProperty(PropertyName = "tpa:")]
public int tpa { get; set; }
[JsonProperty(PropertyName = "tip:")]
public int tip { get; set; }
}
public class ParentData :ObservableRangeCollection<ChildData>
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}
public class ChildData
{
public string ChildName { get; set; }
public int ChildAge { get; set; }
}
List<ParentData> lstParent = new List<ParentData>();
ParentData pData = new ParentData();
pData.Name = "John";
pData.Id = 111;
pData.Age = 45;
ChildData childData = new ChildData();
childData.ChildAge = 12;
childData.ChildName = "tommy";
pData.Add(childData);
lstParent.Add(pData);
string Json = JsonConvert.SerializeObject(lstParent, Formatting.None);
Upon serializing, the ParentData does not get serialized
[[{"ChildName":"tommy","ChildAge":12,"ErrorMessage":null}]]
How do I serialize the Parent Node?
Please I want to make request for this dataset https://web.stanford.edu/~hastie/ElemStatLearn/datasets/prostate.data and get it in json format.
But when I run it, I get this error "Unexpected character encountered while parsing value: l. Path '', line 1, position 1.". Below is the code I wrote using C#
public class Prostate
{
public string lcavol { get; set; }
public string lweight { get; set; }
public string age { get; set; }
public string lbph { get; set; }
public string svi { get; set; }
public string lcp { get; set; }
public string gleason { get; set; }
public string pgg45 { get; set; }
public string lpsa { get; set; }
public string train { get; set; }
}
public async Task<Prostate> Data()
{
HttpClient client = new HttpClient();
var resp = await client.GetAsync("https://web.stanford.edu/~hastie/ElemStatLearn/datasets/prostate.data");
var repsStr = await resp.Content.ReadAsStringAsync();
var newdata = JsonConvert.DeserializeObject(repsStr);
Prostate somedata = (Prostate) newdata;
return somedata;
}
I saved the file as txt and opened it in excel. I later saved it as csv then read it using this code
public async Task<List<Prostate>> Files()
{
List<Prostate> prostates = new List<Prostate>();
var file = Path.Combine(Directory.GetCurrentDirectory(), "[path to file]");
string[] linesofdata = await System.IO.File.ReadAllLinesAsync(file);
foreach(string line in linesofdata){
string[] linewords = line.Split(',');
Prostate newprostate = new Prostate();
newprostate.lcavol = linewords[0];
newprostate.lweight = linewords[1];
newprostate.age = linewords[2];
newprostate.lbph = linewords[3];
newprostate.svi = linewords[4];
newprostate.lcp = linewords[5];
newprostate.gleason = linewords[6];
newprostate.pgg45 = linewords[7];
newprostate.lpsa = linewords[8];
newprostate.train = linewords[9];
prostates.Add(newprostate);
}
return prostates.ToList();
}
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; }
}
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.