SQLite no such table error when table exists in xamarin - xamarin

This is How I define my table as what this link: SQLite no such table error when table exists said
[Table("RegUserTable")]
[Serializable]
[DataContract]
public class RegUserTable
{
[PrimaryKey]
[DataMember]
public Guid UserId { get; set; }
[DataMember]
public string Username { get; set; }
[DataMember]
public string Password { get; set; }
[DataMember]
public string Email { get; set; }
[DataMember]
public string Gender { get; set; }
}
This is my Login code:
public void Button_Clicked_1(object sender, EventArgs e)//LOGIN!
{
var dbpath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "Userdatabase.db");
var db = new SQLiteConnection(dbpath);
var loginquery = db.Table<RegUserTable>().Where(u => u.Username.Equals(EntryLoginUsername.Text) && u.Password.Equals(EntryLoginPassword.Text)).FirstOrDefault();
if (string.IsNullOrWhiteSpace(EntryLoginUsername.Text) && string.IsNullOrWhiteSpace(EntryLoginPassword.Text))
{
DisplayAlert("Blank Fields", "Please Input Your Username and Password!", "OK");
}
else if (loginquery != null)
{
App.Current.MainPage = new NavigationPage(new MainPage(EntryLoginUsername.Text, GenderIdentifier.Text));
}
}
If I run this in my emulator it works 100%, but when I run it on my device it throws this error:
What am I doing wrong here?

Creating the table something like below solves the issue
public async void Button_Clicked_1(object sender, EventArgs e)//LOGIN!
{
var dbpath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "Userdatabase.db");
var db = new SQLiteConnection(dbpath);
var connection = new SQLiteAsyncConnection(dbpath);
await connection.CreateTableAsync<RegUserTable>();
var loginquery = db.Table<RegUserTable>().Where(u => u.Username.Equals(EntryLoginUsername.Text) && u.Password.Equals(EntryLoginPassword.Text)).FirstOrDefault();
if (string.IsNullOrWhiteSpace(EntryLoginUsername.Text) && string.IsNullOrWhiteSpace(EntryLoginPassword.Text))
{
DisplayAlert("Blank Fields", "Please Input Your Username and Password!", "OK");
}
else if (loginquery != null)
{
App.Current.MainPage = new NavigationPage(new MainPage(EntryLoginUsername.Text, GenderIdentifier.Text));
}
}

Related

How insert multiple value in Intermediate table through API

I use to add value from the VUEJS where write code like this.
<multiselect v-model="schoolTypeform.schoolTypeId" :options="SchoolTypes" :multiple="true" :close-on-select="false" :clear-on-select="false" :preserve-search="true" placeholder="Pick School Type" label="name" track-by="name" :preselect-first="true">
and the JS code for this is written like this:
async addSchool() {
this.isbtnLoading = true;
this.isException = false;
await this.axios.post(this.school, this.form).then(response => {
this.addSchoolType(response.data);
})
},
async addSchoolType(id) {
this.isbtnLoading = true;
this.isException = false;
this.schoolTypeform.shoolId = id;
await this.axios.post(this.apiBasedUrl + '/SchoolsSchoolType', this.schoolTypeform).then(response => {
this.isbtnLoading = false;
});
Now my ER structure is given like this:
School:(Table1)
public partial class Schools
{
public Guid ID { get; set; }
public string Name{ get; set; }
// Navigation
public ICollection<SchoolsSchoolType> SchoolsSchoolTypes { get; set; }
}
SchoolType:(Table2)
public class SchoolType
{
public Guid Id { get; set; }
public string Name { get; set; }
//Navigation
public ICollection<SchoolsSchoolType> SchoolsSchoolTypes { get; set; }
}
SchoolsSchoolType (It is Intermediate table): Here the relation between the above is many to many.
public class SchoolsSchoolType
{
public Guid Id { get; set; }
public Guid ShoolId { get; set; }
public Schools Schools { get; set; }
public Guid SchoolTypeId { get; set; }
public SchoolType SchoolType { get; set; }
}
Here is repository method write for single value input, but I want to add here multiple value in the intermediates or junction table.
public async Task<Guid> CreateSchoolsAsync(SchoolsCreateVm schoolsCreateVm)
{
if (_GpsContext != null)
{
var schoolsEntity = new Schools()
{
ID = Guid.NewGuid(),
Name = schoolsCreateVm.Name,
SchoolsSchoolTypes = new List<SchoolsSchoolType>()
};
var schoolType = new SchoolType();
schoolsEntity.SchoolsSchoolTypes = new List<SchoolsSchoolType>
{
new SchoolsSchoolType
{
ShoolId =schoolsEntity.ID,
SchoolTypeId =schoolType.Id
}
};
return schoolsEntity.ID;
}
return Guid.Empty
}
Controller code is written here:
[HttpPost]
public async Task<IActionResult> PostSchool([FromBody]SchoolsCreateVm schoolsCreateVm)
{
var result = await _schoolsRepository.CreateSchoolsAsync(schoolsCreateVm);
if (result != null)
{
return Ok(result);
}
return NotFound();
}
Here is viewmodel used by me:
public class SchoolsCreateVm
{
public string Name { get; set; }
public List<Guid> SchoolTypeId{ get; set; } // List type of for intermediate table
public SchoolsCreateVm()
{
SchoolTypeId = new List<Guid>();
}
How can insert many schooltype for a single school in the intermediates(many to many) relation table through the VUEJS multiple selects.
Finally I am able to find the solution...
public async Task<Guid> CreateSchoolsAsync(SchoolsCreateVm schoolsCreateVm)
{
if (_GpsContext != null)
{
var schoolId = Guid.NewGuid();
var schoolsEntity = new Schools()
{
ID = schoolId, // 1--[1,2,3]
Name = schoolsCreateVm.Name,
};
// Here the code in which we can enter in the multiple table and Intermediate table
var SchoolsSchoolTypeList = new List<SchoolsSchoolType>();
foreach(var item in schoolsCreateVm.SchoolTypeId)
{
SchoolsSchoolTypeList.Add(new SchoolsSchoolType
{
Id = Guid.NewGuid(),
ShoolId = schoolId,
SchoolTypeId = item,
});
}
await _GpsContext.School.AddAsync(schoolsEntity);
_GpsContext.SchoolsSchoolTypes.AddRange(SchoolsSchoolTypeList);//Enter here for intermediate table that is 'SchoolsSchoolTypes'
await _GpsContext.SaveChangesAsync();
return schoolsEntity.ID;
}
return Guid.Empty;
}

HttpClient Xamarin.Forms

I have an application that allows users to log in via facebook. I am trying to save each user to my database using my WebApi. However, I am encountering this exception error: System.NullReferenceException: Object reference not set to an instance of an object. Can anyone see what I am doing incorrectly to cause this. Thanks.
CustomerService class:
public async Task<int> AddCustomer(Customer cust)
{
var data = JsonConvert.SerializeObject(cust);
var content = new StringContent(data, Encoding.UTF8, "application/json");
client.DefaultRequestHeaders.Add("X-Giftworx-App", "Posworx");
var response = await client.PostAsync("http/my api address/api/Customer/Insert", content);
var result = JsonConvert.DeserializeObject<int>(response.Content.ReadAsStringAsync().Result);
return result;
}
Customer class:
public class Customer
{
public string Token { get; set; }
public bool Authenticated { get; set; }
public string SecretKey { get; set; }
public int StoreCustomerID { get; set; }
public string Number { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
public object Address { get; set; }
public string Email { get; set; }
public string City { get; set; }
public string Region { get; set; }
public string Country { get; set; }
public string MobilePhone { get; set; }
public DateTime DOB { get; set; }
public object Phone { get; set; }
public object DeviceToken { get; set; }
public object Details { get; set; }
public object Gender { get; set; }
public bool IsError { get; set; }
public object ErrorMessage { get; set; }
public bool PhoneVerified { get; set; }
}
FacebookRender
public class FacebookRender : PageRenderer
{
CustomerService customerService;
public FacebookRender()
{
var activity = this.Context as Activity;
var auth = new OAuth2Authenticator(
clientId: "my app client's id",
scope: "",
authorizeUrl: new Uri("https://www.facebook.com/dialog/oauth/"),
redirectUrl: new Uri("https://www.facebook.com/connect/login_success.html")
);
auth.Completed += async (sender, eventArgs) =>
{
if (eventArgs.IsAuthenticated)
{
await AccountStore.Create().SaveAsync(eventArgs.Account, "FacebookProviderKey");
var accessToken = eventArgs.Account.Properties["access_token"].ToString();
var expiresIn = Convert.ToDouble(eventArgs.Account.Properties["expires_in"]);
var expiryDate = DateTime.Now + TimeSpan.FromSeconds(expiresIn);
var request = new OAuth2Request("GET", new Uri("https://graph.facebook.com/me"), null, eventArgs.Account);
var response = await request.GetResponseAsync();
var obj = JObject.Parse(response.GetResponseText());
var id = obj["id"].ToString().Replace("\"", "");
var name = obj["name"].ToString().Replace("\"", "");
Customer cust = new Customer();
cust.Token = accessToken;
cust.Name = name;
await customerService.AddCustomer(cust);
App.NavigateToProfile(string.Format(name));
}
else
{
App.NavigateToProfile("Invalid Login");
}
};
activity.StartActivity(auth.GetUI(activity));
}
}

Check, Nothing is changed in Model values MVC3

I've a Model like following:
public class Page
{
private readonly IndianTime _g = new IndianTime();
public Page()
{
CreatedOn = _g.DateTime;
Properties = "Published";
Tags = "Page";
RelativeUrl = string.Empty;
}
public string Path
{
get { return (ParentPage != null) ? ParentPage.Heading + " >> " + Heading : Heading; }
}
[Key]
public int Id { get; set; }
[StringLength(200), Required, DataType(DataType.Text)]
public string Title { get; set; }
[StringLength(200), Required, DataType(DataType.Text)]
public string Heading { get; set; }
[MaxLength, Required, DataType(DataType.Html)]
public string Content { get; set; }
[Display(Name = "Reference Code"), ScaffoldColumn(false)]
public string ReferenceCode { get; set; }
[Required]
[Remote("CheckDuplicate", "Page", ErrorMessage = "Url has already taken", AdditionalFields = "initialUrl")]
public string Url { get; set; }
[Display(Name = "Created On"), ScaffoldColumn(false)]
public DateTime CreatedOn { get; set; }
//Parent Page Object (Self Reference: ParentId = > Id)
[Display(Name = "Parent Page")]
public int? ParentId { get; set; }
[DisplayFormat(NullDisplayText = "Root")]
public virtual Page ParentPage { get; set; }
public virtual ICollection<Page> ChildPages { get; set; }
}
During Update, is there any to check Model values are "Changed" or "Nothing has changed" after POST method?
Say for example: (See the commented lines)
[HttpPost, ValidateAntiForgeryToken]
public ActionResult Edit(WebPage webpage)
{
try
{
if (ModelState.IsValid)
{
// If (webpage object values are unchanged, submitted as it is
// {
// Do not insert any values into Another Table
// }
// else
// {
// Inert into another table
// }
_db.Entry(webpage).State = EntityState.Modified;
_db.SaveChanges();
return RedirectToAction("Index");
}
}
catch (DataException)
{
ModelState.AddModelError("", ErrorCode.Msg.ContactSystemAdmin.ToString());
}
return View(webpage);
}
You can do something like this
[HttpPost, ValidateAntiForgeryToken]
public ActionResult Edit(WebPage webpage)
{
try
{
if (ModelState.IsValid)
{
var dbEntry=_db.GetEntryById(webpage.Id);
//check here if properties in webPage and column values in dbEntry are
//same then decide whether to insert in another table or not
_db.Entry(webpage).State = EntityState.Modified;
_db.SaveChanges();
return RedirectToAction("Index");
}
}
catch (DataException)
{
ModelState.AddModelError("", ErrorCode.Msg.ContactSystemAdmin.ToString());
}
return View(webpage);
}
Or Not Sure if this works
Try using $(form).serialize() at client side
CHECK THIS FIDDLE

Troubleshoot object reference error when filling mvc models with datareader?

I am using MVC 3 and I am using a datareader to create a list of items that have subItems. When I add the subitem I get "Object reference not set to an instance of an object." With the following code:
QuestionaireLine question = new QuestionaireLine();
question.Question_ID = Convert.ToInt32(reader["Question_ID"]);
question.Question_Answer = reader["Question_Answer"].ToString();
...etc..
currentGroup.Lines.Add(question); //exception thrown here
The models:
public class Questionaire
{
public int Question_Group_Id { get; set; }
public string Question_Group_Name { get; set; }
public int Question_Group_Indent { get; set; }
public int Question_Group_Order { get; set; }
public List<QuestionaireLine> Lines { get; set; }
}
public class QuestionaireLine
{
public int Question_ID { get; set; }
public string Question_Label { get; set; }
public string Question_Answer { get; set; }
public int Data_Type { get; set; }
public int Control_Type { get; set; }
public string Data_Choices { get; set; }
public int Data_Max_Length { get; set; }
public bool Issue_Tagged { get; set; }
public int Question_Order { get; set; }
public string NumberedQuestion
{
get { return String.Format("{0}. {1}", Question_Order, Question_Label); }
}
}
The whole code:
// what am I missing??
using (var conn = new SqlConnection(_connectionString))
{
List<Questionaire> groups = new List<Questionaire>();
var com = new SqlCommand();
com.Connection = conn;
com.CommandType = CommandType.StoredProcedure;
com.Parameters.Add(new SqlParameter
{
ParameterName = "#Review_ID",
Value = reviewID
});
com.CommandText = "Review_Get_Question_Groups_Answers";
conn.Open();
// Get the reader
SqlDataReader reader = com.ExecuteReader();
// Process each result in the result set
int currQuestionGroupId = 0;
Questionaire currentGroup = null;
while (reader.Read())
{
var questionGroupId = Convert.ToInt32(reader["Question_Group_Id"]);
if (questionGroupId != currQuestionGroupId)
{
currQuestionGroupId = questionGroupId;
if (currentGroup != null)
{
groups.Add(currentGroup);
}
currentGroup = new Questionaire();
currentGroup.Question_Group_Id = Convert.ToInt32(reader["Question_Group_Id"]);
currentGroup.Question_Group_Indent = Convert.ToInt32(reader["Question_Group_Indent"]);
currentGroup.Question_Group_Name = reader["Question_Group_Name"].ToString();
currentGroup.Question_Group_Order = Convert.ToInt32(reader["Question_Group_Order"]);
}
if (reader["Question_ID"] != DBNull.Value)
{
QuestionaireLine question = new QuestionaireLine();
question.Question_ID = Convert.ToInt32(reader["Question_ID"]);
question.Question_Answer = reader["Question_Answer"].ToString();
question.Issue_Tagged = Convert.ToBoolean(reader["Issue_Tagged"]);
question.Data_Type = Convert.ToInt32(reader["Data_Type"]);
question.Data_Max_Length = Convert.ToInt32(reader["Data_Max_Length"]);
question.Data_Choices = reader["Data_Choices"].ToString();
question.Question_Label = reader["Question_Label"].ToString();
question.Question_Order = Convert.ToInt32(reader["Question_Order"]);
question.Control_Type = Convert.ToInt32(reader["Control_Type"]);
currentGroup.Lines.Add(question);
}
if (currentGroup != null)
{
groups.Add(currentGroup);
}
}
reader.Close();
com.Dispose();
return groups;
}
Your Lines property on your Questionaire instance is Null. Change to:
public class Questionaire
{
public int Question_Group_Id { get; set; }
public string Question_Group_Name { get; set; }
public int Question_Group_Indent { get; set; }
public int Question_Group_Order { get; set; }
public List<QuestionaireLine> Lines { get; set; }
public Questionaire() {
Lines = new List<QuestionaireLine>();
}
b.t.w. stepping through your code would have shown you that.

"An entity object cannot be referenced by multiple instances of IEntityChangeTracker in C#"

Need help with this please.
I need to save some data in session to DB on controller action. But i get the "An entity object cannot be referenced by multiple instances of IEntityChangeTracker in C#" error on
answer.Add(answer);
can anybody help me with this?
Questionare questionare = unitOfWork.QuestionareRepository.GetByID(id);
SADEntitiesContext db = new SADEntitiesContext();
foreach (Question question in questionare.Questions)
{
//check if there are data in Session and save it
_question = "question"+question.QuestionID.ToString();
if (Session[_question] != null)
{
var answer = new Answers();
if (TryUpdateModel(answer))
{
questionanswer = (QuestionAnswerData)Session[_question];
int qID = Int16.Parse(questionanswer.QuestionID);
var answertoupdate = answer.GetAnswer(qID, questionanswer.UserID, questionanswer.EmployeID);
//db.Answers.Remove(answertoupdate);
answer.UserName = questionanswer.UserID;
answer.Answer = db.AnswerChoices.Find(Int16.Parse(questionanswer.AnswerID));
answer.AnsweredAt = DateTime.Now;
answer.locked = false;
answer.Question = question;
answer.Questionare = questionare;
if (questionanswer.EmployeID != null)
{
answer.AnswerAboutUser = questionanswer.EmployeID;
}
if (answertoupdate != null)
{
answertoupdate = answer;
ok = (answertoupdate.Save() > 0);
}
else
{
answer.Add(answer);
ok = (answer.Save() > 0);
}
}
}
answers class
public class Answers
{
SADEntitiesContext db = new SADEntitiesContext();
public int AnswersId { get; set; }
//[Display(Name = "DataResposta", ResourceType = typeof(Resources))]
public DateTime AnsweredAt { get; set; }
//[Display(Name = "bloqueado", ResourceType = typeof(Resources))]
public bool locked { get; set; }
// [Display(Name = "UserName", ResourceType = typeof(Resources))]
public string UserName { get; set; }
//[Display(Name = "AnswersAboutUser", ResourceType = typeof(Resources))]
public string AnswerAboutUser { get; set; }
//[Display(Name = "Resposta", ResourceType = typeof(Resources))]
public virtual AnswerChoices Answer { get; set; }
//[Display(Name = "Questionare", ResourceType = typeof(Resources))]
public virtual Questionare Questionare { get; set; }
//[Display(Name = "QuestionID", ResourceType = typeof(Resources))]
public virtual Question Question { get; set; }
//
// Persistence
public int Save()
{
return db.SaveChanges();
}
public Answers GetAnswer(int questionID, string employeID, string userID)
{
return db.Answers
.Where(e => e.UserName == userID
&& e.Question.QuestionID == questionID
&& e.AnswerAboutUser == employeID)
.FirstOrDefault();
}
public Answers GetAnswer(int id)
{
return db.Answers.SingleOrDefault(d => d.AnswersId == id);
}
//
// Insert/Delete Methods
public void Add(Answers _answer)
{
db.Answers.Add(_answer);
db.SaveChanges();
}
}
}
Your problem is you're calling an answer from one context:
answer.Answer = db.AnswerChoices.Find(Int16.Parse(questionanswer.AnswerID));
and then attempting to save it using a different in your Answer class:
SADEntitiesContext db = new SADEntitiesContext();
The quickest solution to your problem would be to be able to set the context in your Answer class, so that your not jumping contexts, or you could Detach the answer after pulling it from the db the first time, and then reattach it in the save.
However, I think you have a more fundamental problem. Are you sure it's a good idea to have a class be able to create it's own context, and save itself? You'll have problems like this all over the place.

Resources