C# Database not updating using ASP and EF - c#

My database is not updating with new inserted values from text boxes, but when Account page has loaded, autocomplete with current values from DB works.
What did I miss there ?
It is affected from using Owin on Login/SignIn/LogOut form pages ?
Because Owin autogenerated few Tabels in my Database and one of them contains userID and password. But i don't think that should be the problem.
Here is my UserInfoModel class:
public UserInfo GetUserInformation(string uid)
{
FarmacieEntities db = new FarmacieEntities();
UserInfo info = (from x in db.UserInfoes where x.UID == uid select x).FirstOrDefault();
return info;
}
public void InsertUserInfo(UserInfo info)
{
FarmacieEntities db = new FarmacieEntities();
db.UserInfoes.Add(info);
db.SaveChanges();
}
public string UpdateUserInfo(int id, UserInfo userInfo)
{
try
{
FarmacieEntities db = new FarmacieEntities();
UserInfo p = db.UserInfoes.Find(id);
p.Nume = userInfo.Nume;
p.Prenume = userInfo.Prenume;
p.Adresa = userInfo.Adresa;
p.Telefon = userInfo.Telefon;
p.CodPostal = userInfo.CodPostal;
db.SaveChanges();
return p.Nume + " was succesfully updated";
}
catch (Exception e)
{
return "Error:" + e;
}
}
And here is my Page code:
protected void Page_Load(object sender, EventArgs e)
{
string id = User.Identity.GetUserId();
Completare(id);
}
private void Completare(string id)
{
UserInfoModel model = new UserInfoModel();
UserInfo user = model.GetUserInformation(id);
txtNume.Text = user.Nume;
txtPrenume.Text = user.Prenume;
txtAdresa.Text = user.Adresa;
txtTelefon.Text = user.Telefon;
txtcod.Text = user.CodPostal;
}
private int getID(string id)
{
UserInfoModel model = new UserInfoModel();
UserInfo user = model.GetUserInformation(id);
return user.ID;
}
private UserInfo CreateUser()
{
UserInfo user = new UserInfo();
user.Nume = txtNume.Text;
user.Prenume = txtPrenume.Text;
user.Adresa = txtAdresa.Text;
user.Telefon = txtTelefon.Text;
user.CodPostal = txtcod.Text;
return user;
}
protected void Button1_Click(object sender, EventArgs e)
{
UserInfoModel model = new UserInfoModel();
UserInfo user = CreateUser();
model.UpdateUserInfo(getID(User.Identity.GetUserId()), user);
Response.Redirect("~/Pages/Account/Comenzi.aspx");
}

Problem fixed:
At the page load function i forgot to add the 2 lines in this if: if(!IsPostBack).

Related

Realm/Xamarin.Forms/Android/C#: Data not being saved across runs

I've implemented what I think is a pretty vanilla usage of Realm:
public class MyObj : RealmObject
{
[PrimaryKey]
public string Key { get; set; }
public bool Value { get; set; }
}
then, in my app:
using(Realm r = Realm.GetInstance()) {
var c1 = r.All<MyObj>().Count();
}
which returns zero, as expected.
Then I add an object:
using(Realm r = Realm.GetInstance()) {
r.Write(() =>
{
var obj = new MyObj() { Key = "test", Value = true };
r.Add(obj);
});
}
then reopen it and get the count:
using(r = Realm.GetInstance()) {
var c2 = r.All<MyObj>().Count();
}
and c2 is one, as expected. So far, so good.
But when I close my app, and restart, c1 (the initial count) is zero, not one.
Any idea why?
Sorry,we couldn't see the other code of your app.
But you can refer to an article by entering key words Xamarin.Forms - Working With Realm Database in your browser. It works properly even after restarting the app.
You can also check the full sample here.
The main code is:
public partial class MainPage : ContentPage
{
List<OptionItems> optionItems = new List<OptionItems>();
Student editStudent;
public MainPage()
{
InitializeComponent();
imgBanner.Source = ImageSource.FromResource("XamarinFormsRelam.images.banner.png");
var realmDB = Realm.GetInstance();
List<Student> studentList = realmDB.All<Student>().ToList();
listStudent.ItemsSource=studentList;
}
private void btnAdd_Clicked(object sender, EventArgs e)
{
var realmDB = Realm.GetInstance();
var students= realmDB.All<Student>().ToList();
var maxStudentId = 0;
if (students.Count!=0)
maxStudentId = students.Max(s=>s.StudentID);
Student student = new Student()
{
StudentID = maxStudentId + 1,
StudentName = txtStudentName.Text
};
realmDB.Write(() =>
{
realmDB.Add(student);
});
txtStudentName.Text = string.Empty;
List<Student> studentList = realmDB.All<Student>().ToList();
listStudent.ItemsSource = studentList;
}
private async void listOptions_ItemSelected(object sender, SelectedItemChangedEventArgs e)
{
var realmDB = Realm.GetInstance();
OptionItems selectedItem = optionList.SelectedItem as OptionItems;
if (selectedItem != null)
{
switch (selectedItem.OptionText)
{
case "Edit":
popupOptionView.IsVisible = false;
popupEditView.IsVisible = true;
editStudent = realmDB.All<Student>().First(b => b.StudentID == selectedItem.StudentId);
txtEditStudentName.Text = editStudent.StudentName;
break;
case "Delete":
var removeStudent = realmDB.All<Student>().First(b => b.StudentID == selectedItem.StudentId);
using (var db = realmDB.BeginWrite())
{
realmDB.Remove(removeStudent);
db.Commit();
}
await DisplayAlert("Success", "Student Deleted", "OK");
popupOptionView.IsVisible = false;
List<Student> studentList = realmDB.All<Student>().ToList();
listStudent.ItemsSource = studentList;
break;
default:
popupOptionView.IsVisible = false;
break;
}
optionList.SelectedItem = null;
}
}
protected override void OnAppearing()
{
base.OnAppearing();
var realmDb = Realm.GetInstance();
}
private void listStudent_ItemSelected(object sender, SelectedItemChangedEventArgs e)
{
Student selectedStudent = listStudent.SelectedItem as Student;
if(selectedStudent!=null)
{
optionItems.Add(new OptionItems { OptionText = "Edit",StudentId=selectedStudent.StudentID});
optionItems.Add(new OptionItems { OptionText = "Delete", StudentId = selectedStudent.StudentID });
optionItems.Add(new OptionItems { OptionText = "Cancel"});
optionList.ItemsSource = optionItems;
popupOptionView.IsVisible = true;
}
}
private void Button_Clicked(object sender, EventArgs e)
{
popupEditView.IsVisible = false;
}
private async void Button_Clicked_1(object sender, EventArgs e)
{
var realmDB = Realm.GetInstance();
var selectedStudent = realmDB.All<Student>().First(b => b.StudentID == editStudent.StudentID);
using (var db = realmDB.BeginWrite())
{
editStudent.StudentName = txtEditStudentName.Text;
db.Commit();
}
await DisplayAlert("Success", "Student Updated","OK");
txtEditStudentName.Text = string.Empty;
popupEditView.IsVisible = false;
}
}
Are you deploying on a physical device? If that's the case, it's likely due to the automatic backup and restore functionality built into Android - when you deploy the app, it treats it as an install and restores the last known state.
You can read about it here: An Android app remembers its data after uninstall and reinstall but the tl;dr is - go to settings and turn off "Automatic Restore" or update your manifest to instruct Android not to backup the data.

Get string from a class to web api

I have a string in one class, I would like to get the string in my web api for the get request and add the value to my query. This is my code to get data from my Mysql database:
Web api
// GET: api/Blog
[HttpGet]
public List<BlogViews> Get()
{
string sqlstring = "server=; port= ; user id =;Password=;Database=;";
MySqlConnection conn = new MySqlConnection(sqlstring);
try
{
conn.Open();
}
catch (MySqlException ex)
{
throw ex;
}
string Query = "SELECT * FROM test.blogtable where `Category` =" +;
MySqlCommand cmd = new MySqlCommand(Query, conn);
MySqlDataReader MSQLRD = cmd.ExecuteReader();
List<BlogViews> GetBlogList = new List<BlogViews>();
if (MSQLRD.HasRows)
{
while (MSQLRD.Read())
{
BlogViews BV = new BlogViews();
BV.id = (MSQLRD["id"].ToString());
BV.DisplayTopic = (MSQLRD["Topic"].ToString());
BV.DisplayMain = (MSQLRD["Summary"].ToString());
GetBlogList.Add(BV);
}
}
conn.Close();
return GetBlogList;
}
My Class
public class ItemsClass
{
public string id { get; set; }
public Entry IdEntry = new Entry{};
public Button DoneButton = new Button{};
public ItemsClass()
{
Content = new StackLayout
{
BackgroundColor = Color.FromHex("35ddcf"),
Padding = new Thickness(0, 50, 0, 10),
Children = { IdEntry,DoneButton }
};
}
private void DoneButton_Clicked(object sender, EventArgs e)
{
IdEntry.Text = id;
BlogContentsRestClient<BlogContentItemClass> restClient = new
BlogContentsRestClient<BlogContentItemClass>();
await restClient.GetAsync();
}
}
HttpRequest Class
public class BlogContentsRestClient<T>
{
private const string WebServiceUrl = "http://localhost:57645/api/BlogContents/";
public async Task<List<T>> GetAsync()
{
var httpClient = new HttpClient();
var json = await httpClient.GetStringAsync(WebServiceUrl);
var taskModels = JsonConvert.DeserializeObject<List<T>>(json);
return taskModels;
}
}
Question
In my Web api Querystring Query = "SELECT * FROM test.blogtable where 'Category' =" +;. I would like to add the value of string id in ItemsClass, so that I can get data from my Mysql database.
I don't quite get what you mean by add the value of a class to your API method. ItemsClass is an object definition and not an instance of it. However you can provide your API method a parameter so that you have:
[HttpGet]
public List<BlogViews> Get(string id)
You can now call your API passing that parameter: /api/?id={insert here the id}
Alternatively you can call it in your request's body.
[HttpGet]
public List<BlogViews> Get([FromQuery, BindRequired] string id)
EDIT:
Check if this solution fits:
1) Use the method I posted before replacing this:
public List<BlogViews> Get()
with this:
public List<BlogViews> Get(string id)
2) Edit the GetAsync() method as follow:
// Added string id as parameter
public async Task<List<T>> GetAsync(string id)
{
// webUrl now become the same as WebServiceUrl but with parameter added
string webUrl = "http://localhost:57645/api/BlogContents/?id=" + id;
var httpClient = new HttpClient();
var json = await httpClient.GetStringAsync(webUrl);
var taskModels = JsonConvert.DeserializeObject<List<T>>(json);
return taskModels;
}
3) Edit the DoneButton_Clicked this way:
private void DoneButton_Clicked(object sender, EventArgs e)
{
IdEntry.Text = id;
BlogContentsRestClient<BlogContentItemClass> restClient = new
BlogContentsRestClient<BlogContentItemClass>();
await restClient.GetAsync(id); // Here you call the Get API with the id as parameter
}
4) Finally you can edit the query inside your Get(string id) method adding the id to the end:
string Query = "SELECT * FROM test.blogtable where `Category` =" + id;

Adding items to a list with out overwriting the previous item

I am trying to send form data to a confirmation page where you would enter your cc info to complete the transaction. I add all the information to a list that i will later code as hidden fields on the new form to send the information off as paid. However when I do a repsonse.write to see what the information stored is. i always get the same name over and over. not exactly sure where i am missing it. Thanks for your help!
protected void Page_Load(object sender, EventArgs e)
{
if (Request.HttpMethod == "POST"){
formData attendee = new formData();
NameValueCollection nvc = Request.Form;
List<formData> attendees = new List<formData>();
if (!string.IsNullOrEmpty(nvc["fn1"]))
{
var fn = nvc["fn1"];
var ln = nvc["ln1"];
var email = nvc["email1"];
var wife = nvc["wife1"];
var luncheon = nvc["lucheon1"];
attendee.firstName = fn; attendee.lastName = ln; attendee.email = email; attendee.wife = wife; attendee.luncheon = luncheon;
attendees.Add(attendee);
}
if (!string.IsNullOrEmpty(nvc["fn2"]))
{
var fn = nvc["fn2"];
var ln = nvc["ln2"];
var email = nvc["email2"];
var wife = nvc["wife2"];
var luncheon = nvc["lucheon2"];
attendee.firstName = fn; attendee.lastName = ln; attendee.email = email; attendee.wife = wife; attendee.luncheon = luncheon;
attendees.Add(attendee);
}
foreach(var person in attendees)
{
Response.Write(person.firstName.ToString());
Response.Write(person.lastName.ToString());
Response.Write(person.email.ToString());
Response.Write(person.wife.ToString());
Response.Write(person.luncheon.ToString());
}
}
}
public class formData
{
public string firstName { get; set; }
public string lastName { get; set; }
public string email { get; set; }
public string wife { get; set; }
public string luncheon { get; set; }
}
}
I assume your array of Attendees is going to be of a data type like this... each attendee has a {fn, ln, email, wife, and luncheon} property. Looks like they're stored in the POST like {fn1, ln1, email1, wife1, luncheon1} is attendee(0), {fn2, ln2, email2, wife2, luncheon2} is attendee(1), etc.
You might try looping like this
var count = 1;
while (!string.IsNullOrEmpty(nvc["fn" + count]))
{
attendee(count).firstname=nvc["fn" + count]
attendee(count).lastname=nvc["ln" + count]
//...for the rest of the fields
count++; //be sure and increment count
}
Until there's data fn# that is null, it keeps looping through and creating attendees.
You are creating the list in the Page_Load event. The Page_Load event fires each time the page loads, postback or not and recreating the list every time that event fires.
You can create and use a session variable. As an example:
protected void Page_Load(object sender, EventArgs e)
{
List<formData> attendees;
if(Session["attendees"] == null)
{
attendees = new List<formData>();
// your logic logic ...
Session["attendees"] = attendees;
}
else
{
var attendees = (List<formData>)Session["attendees"];
// your logic ...
Session["attendees"] = attendees;
}
}
I'd also consider breaking your code out a bit. Perhaps putting the code that adds to the list in a separate method.
ASP.NET Session State Overview.

pivot view with dynamic data

i'm working on a windows phone application using pivot view to preview data for the user, the data comes from a web service, then i put it in List then i add the item to the pivot view
but when i call the web service the view doesn't wait till i get the data from the server to add to the view and the view adds nothing , here is my code
public class downloads : List<Downloaded>
{
List<string> downoladedList = new List<string>();
public downloads()
{
BuildCollection();
}
//private const string IMG_PATH = "../Images/";
public ObservableCollection<Downloaded> DataCollection { get; set; }
public ObservableCollection<Downloaded> BuildCollection()
{
// int x=0;
Downloaded downObject = new Downloaded();
ServiceReference1.Service1Client service = new ServiceReference1.Service1Client();
service.GetDownloadsCompleted += new EventHandler<ServiceReference1.GetDownloadsCompletedEventArgs>(GetDownLoads);
System.Threading.Thread.Sleep(100000);
service.GetDownloadsAsync(20019);
DataCollection = new ObservableCollection<Downloaded>();
foreach (var elem in downoladedList)
{
string[] elemProp = new string[8];
elemProp = elem.Split('=');
if (elemProp[3] == "1")
elemProp[3] = "downloaded";
else
elemProp[3] = "in progress";
DataCollection.Add(new Downloaded(elemProp[1], elemProp[3], "test.png"));
}
return DataCollection;
}
public void GetDownLoads(object sender, ServiceReference1.GetDownloadsCompletedEventArgs e)
{
try
{
downoladedList = e.Result.ToList<string>();
}
catch (Exception ee)
{
}
}
}
You cannot call thread.sleep. This will block entire UI thread.
Declare DataCollection = new ObservableCollection();
outside scope.
You should put all your code on completed like this :
public void GetDownLoads(object sender, ServiceReference1.GetDownloadsCompletedEventArgs e)
{
try
{
downoladedList = e.Result.ToList<string>();
foreach (var elem in downoladedList)
{
string[] elemProp = new string[8];
elemProp = elem.Split('=');
if (elemProp[3] == "1")
elemProp[3] = "downloaded";
else
elemProp[3] = "in progress";
DataCollection.Add(new Downloaded(elemProp[1], elemProp[3], "test.png"));
}
}
catch (Exception ee)
{
}
}

SharePoint / WSS3.0 : Creating static webpart connections at runtime

I've created several master / detail webparts that need to be connected. We have a requirement the the webparts self discover and connect to other connectable webparts on the page. I've acheived this in a standard ASP.NET page with the following code:
protected override void OnLoad(EventArgs e)
{
WebPartManager manager = WebPartManager.GetCurrentWebPartManager(Page);
manager.StaticConnections.Add(new WebPartConnection()
{
ID = string.Format("WebPartConnection{0}{1}", this.ID, provider.ID),
ConsumerID = this.ID,
ConsumerConnectionPointID = "WebPartConnectableConsumer",
ProviderID = provider.ID,
ProviderConnectionPointID = "WebPartConnectableProvider"
});
}
This approach, however, does not work in SharePoint. Using the SharePoint version of these objects results in a generic sharepoint error:
protected override void OnLoad(EventArgs e)
{
SPWebPartManager spManager = SPWebPartManager.GetCurrentWebPartManager(Page) as SPWebPartManager;
spManager.StaticConnections.Add(new WebPartConnection()
{
ID = string.Format("WebPartConnection{0}{1}", this.ID, provider.ID),
ConsumerID = this.ID,
ConsumerConnectionPointID = "WebPartConnectableConsumer",
ProviderID = provider.ID,
ProviderConnectionPointID = "WebPartConnectableProvider"
});
}
The following approach works, but creates the connection as part of the user's personalization:
protected override void OnLoad(EventArgs e)
{
SPWebPartConnection connection = (from SPWebPartConnection c in spManager.SPWebPartConnections where c != null && c.Consumer == this && c.ConsumerConnectionPointID == "WebPartConnectableConsumer" && c.Provider == provider select c).FirstOrDefault();
if (connection == null)
{
try
{
ProviderConnectionPointCollection providerCollections = spManager.GetProviderConnectionPoints(provider);
ConsumerConnectionPointCollection consumerConnections = spManager.GetConsumerConnectionPoints(this);
connection = spManager.SPConnectWebParts(provider, providerCollections["WebPartConnectableProvider"], this, consumerConnections["WebPartConnectableConsumer"]);
}
catch { }
}
}
Hidden in the logs was an error stating that the StaticConnections property cannot be used in SharePoint/WSS environments. Instead, the SPWebPartConnections property must be used. Moreover, connections must be added prior to the load event (eg. OnInit).
Working code:
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
SetUpProviderConnection();
}
private bool SetUpProviderConnection()
{
bool connectionCreated = false;
WebPartManager manager = WebPartManager.GetCurrentWebPartManager(Page);
foreach (System.Web.UI.WebControls.WebParts.WebPart webPart in manager.WebParts)
{
BaseWebPart provider = webPart as BaseWebPart;
if (provider != null && (provider != this))
{
if (manager is Microsoft.SharePoint.WebPartPages.SPWebPartManager)
{
SPWebPartManager spManager = SPWebPartManager.GetCurrentWebPartManager(Page) as SPWebPartManager;
spManager.SPWebPartConnections.Add(new SPWebPartConnection()
{
ID = string.Format("WebPartConnection{0}{1}", this.ID, provider.ID),
ConsumerID = this.ID,
ConsumerConnectionPointID = "WebPartConnectableConsumer",
ProviderID = provider.ID,
ProviderConnectionPointID = "WebPartConnectableProvider"
});
}
else
{
manager.StaticConnections.Add(new WebPartConnection()
{
ID = string.Format("WebPartConnection{0}{1}", this.ID, provider.ID),
ConsumerID = this.ID,
ConsumerConnectionPointID = "WebPartConnectableConsumer",
ProviderID = provider.ID,
ProviderConnectionPointID = "WebPartConnectableProvider"
});
}
connectionCreated = true;
}
}
return connectionCreated;
}

Categories

Resources