I am new to the windows azure world, I am trying to send an item to the SQL DB and track it by a specific "usrID" to then hopefully update it.
Right now I also have a class:
public class Item
{
public int Id { get; set; }
[JsonProperty(PropertyName = "url")]
public string url { get; set; }
[JsonProperty(PropertyName = "usrID")]
public string usrID { get; set; }
[JsonProperty(PropertyName = "complete")]
public bool Complete { get; set; }
}
To save/insert Data I use:
private void ButtonSave_Click(object sender, RoutedEventArgs e)
{
var todoItem = new Item { usrID = "helloworld", url = Input.Text };
InsertTodoItem(todoItem);
}
When I am trying to update, I am using this:
private void btns_Tap(object sender, System.Windows.Input.GestureEventArgs e)
{
Item item;
item = new Item();
item.url = "hello";
UpdateItem(item);
}
* Trying to do this will not work. It also wont let me do Item item = new Item();
The update function is:
private async void UpdateItem(Item item)
{
await todoTable.UpdateAsync(item);
items.Remove(item);
}
So, what I am trying to do is, the last/only item inserted by "usrID" to get that data and show it. But also if something changes, I want that one specific insert from "usrID" that includes url to be updated (opposed from deleted entirely).
Any help would be great!
List<Item> items = await App.MobileService.GetTable<Item>().OrderBy(item => item.usrID).ToListAsync();
int mas = items.Count();
await Table.UpdateAsync(new Item {Id = mas, usrID = "helloworld", url = "itworked" });
Related
I have a list MemoryClienti with items based on the ClienteModel class.
The method i use to add a new item to MemoryClienti is:
public bool CreateCliente(ClienteModel model)
{
bool empty = !MemoryClienti.Any();
if (empty)
{
ClienteModel clienteModel = new ClienteModel();
clienteModel.Cognome = model.Cognome;
clienteModel.Nome = model.Nome;
clienteModel.Indirizzo = model.Indirizzo;
clienteModel.IDCliente = StartID;
MemoryClienti.Add(clienteModel);
MessageBox.Show("Cliente aggiunto correttamente.");
}
else
{
int maxID = MemoryClienti.Count;
ClienteModel clienteModel = new ClienteModel();
clienteModel.Cognome = model.Cognome;
clienteModel.Nome = model.Nome;
clienteModel.Indirizzo = model.Indirizzo;
clienteModel.IDCliente = maxID;
MemoryClienti.Add(clienteModel);
MessageBox.Show("Cliente aggiunto correttamente.");
}
return true;
This method makes me able to add a new item, count for the number of items in the list, and set the new item's id as the result of the count, so it happpens for every item i add, and it's working.
Datas for item's "model" comes from form's textboxes:
private void aggiungiClienteButton_Click(object sender, EventArgs e)
{
if (cognomeTextBox.Text == "")
{
MessageBox.Show("Uno o più campi sono vuoti");
}
else if (nomeTextBox.Text=="")
{
MessageBox.Show("Uno o più campi sono vuoti");
}
else if (indirizzoTextbox.Text == "")
{
MessageBox.Show("Uno o più campi sono vuoti");
}
else
{
clienteModel.Cognome = cognomeTextBox.Text;
clienteModel.Nome = nomeTextBox.Text;
clienteModel.Indirizzo = indirizzoTextbox.Text;
dbMemoryManager.CreateCliente(clienteModel);
cognomeTextBox.Text = String.Empty;
nomeTextBox.Text = String.Empty;
indirizzoTextbox.Text = String.Empty;
}
}
My class is:
public class ClienteModel
{
public int IDCliente { get; set; }
public string Cognome { get; set; }
public string Nome { get; set; }
public string Indirizzo { get; set; }
}
The problem is: how can i update one of those items using textboxes without changing the id?
Here's a quick and dirty solution. You don't specify what kind of textboxes you are using. I'm assuming it's Windows Forms.
I modified your ClienteModel so that it looks like this:
public class ClienteModel
{
private static int _currentId = 0;
public int IDCliente { get; set; } = _currentId++;
public string Cognome { get; set; }
public string Nome { get; set; }
public string Indirizzo { get; set; }
public override string ToString()
{
return Nome;
}
}
Note that it manages the IDCliente field now and that it has a ToString member (you can set this to whatever string you want). You may want to show the IDCliente field in a read-only textbox on your form.
Then I created a simple Windows Forms form that has your three text boxes, a ListBox named ModelsListBox and two buttons AddButton (caption: "Add") and UpdateButton ("Update").
In the form class I created a little validation method (since I use it in two places). Note that you will only get one MessageBox even if you have multiple errors:
private bool ValidateFields()
{
var errors = new List<string>();
foreach (var tb in new[] {cognomeTextBox, nomeTextBox, indirizzoTextbox})
{
if (string.IsNullOrWhiteSpace(tb.Text))
{
errors.Add($"{tb.Name} must not be empty");
}
}
if (errors.Count > 0)
{
MessageBox.Show(string.Join(Environment.NewLine, errors), "Errors", MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
//otherwise
return true;
}
Then I added three event handlers (wiring them up in the normal fashion from within the designer). The first is when the Add button is pressed:
private void AddButton_Click(object sender, EventArgs e)
{
if (!ValidateFields())
{
return;
}
var model = new ClienteModel
{
Cognome = cognomeTextBox.Text,
Nome = nomeTextBox.Text,
Indirizzo = indirizzoTextbox.Text,
};
ModelsListBox.Items.Add(model);
}
It creates a new ClienteModel and adds it to the listbox (assuming validation passes).
Then, I created a handler that updates the text boxes whenever the selection in the listbox changes:
private void ModelsListBox_SelectedIndexChanged(object sender, EventArgs e)
{
if (ModelsListBox.SelectedItem is ClienteModel model)
{
cognomeTextBox.Text = model.Cognome;
nomeTextBox.Text = model.Nome;
indirizzoTextbox.Text = model.Indirizzo;
}
}
and finally, an update button handler:
private void UpdateButton_Click(object sender, EventArgs e)
{
if (!ValidateFields())
{
return;
}
if (ModelsListBox.SelectedItem is ClienteModel model)
{
model.Cognome = cognomeTextBox.Text;
model.Nome = nomeTextBox.Text;
model.Indirizzo = indirizzoTextbox.Text;
}
}
This isn't perfect. You should disable the Update button until a selection is made (and maybe enable only after a change is made in the text box).
More importantly, the string shown in the listbox for an item is based on the results of a call to ClienteModel.ToString made when the item is first added to the list. If you change the value of a field that is used to compute .ToString, the listbox doesn't update. There are a few ways around this (findable on Stack Overflow), but I thought this would be enough to get you started.
I have a form with several text boxes. I want to use the input in the text boxes to append to a list in c# which I then want to show in a datagrid as the enteries are entered. But I have an issue. I add the data to the textboxes hit the display to datagrid button I have created and it seems ever time instead of appending items to the list the list is recreated. What am I doing wrong?
'''
{
public LotScan()
{
InitializeComponent();
}
public class LotData
{
public string Lot;
public string Description { get; set; }
public int PO { get; set; }
public string MfgPart { get; set; }
}
// code to add from control data to list
private List<LotData> LoadCollectionData()
{
List<LotData> lot = new List<LotData>();
lot.Add(new LotData()
{
Lot = LotNo.Text,
Description = frmDescription.Text,
PO = int.Parse(frmPO.Text),
MfgPart = frmMfgPart.Text,
});
return lot;
}
//button to add list data to datagrid on form
private void Button_Click(object sender, RoutedEventArgs e)
{
gridLotData.ItemsSource = LoadCollectionData();
LotNo.Text = String.Empty;
frmMfgPart.Text = string.Empty;
frmDescription.Text = String.Empty;
frmMfgPart.Text = string.Empty;
frmPO.Text = string.Empty;
}
'''
Move this variable to be a private Member variable (just put it a line above the classes constructor method):
List<LotData> lot = new List<LotData>();
public LotScan()
{
InitializeComponent();
gridLotData.ItemsSource = LotDataList;
}
private LotData LoadCollectionData()
{
return new LotData()
{
Lot = LotNo.Text,
Description = frmDescription.Text,
PO = int.Parse(frmPO.Text),
MfgPart = frmMfgPart.Text,
};
}
public class LotData
{
public string Lot;
public string Description { get; set; }
public int PO { get; set; }
public string MfgPart { get; set; }
}
public ObservableCollection<LotData> LotDataList = new ObservableCollection<LotData>();
private void Button_Click(object sender, RoutedEventArgs e)
{
LotDataList.Add(LoadCollectionData());
LotNo.Text = String.Empty;
frmMfgPart.Text = string.Empty;
frmDescription.Text = String.Empty;
frmMfgPart.Text = string.Empty;
frmPO.Text = string.Empty;
}
I have a class and have added objects to a list, then binded the list to a checkboxlist. When the user checks the list, the answer goes into a new list and put in a session, then redirected to a new page. On the new page I want the result in an asp:Literal. But Im not sure how to do that.
The class:
public class Frukter
{
public string Navn { get; set; }
public string Farge { get; set; }
public string BildeSrc { get; set; }
public Frukter(string navn, string farge, string bildeSrc)
{
Navn = navn;
Farge = farge;
BildeSrc = bildeSrc;
}
}
First page:
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
List<Frukter> frukt = new List<Frukter>();
frukt.Add(new Frukter("Appelsin", "Oransj", "~/Appelsin.jpg"));
frukt.Add(new Frukter("Banan", "Gul", "~/Banan.jpg" ));
frukt.Add(new Frukter("Eple", "Rød", "~/Eple.jpg" ));
if (!this.IsPostBack)
{
chklst.DataSource = frukt;
chklst.DataTextField = "Navn";
chklst.DataBind();
}
protected void Resultat_Click(object sender, EventArgs e)
{
List<object> ChkListe = new List<object>();
foreach (ListItem item in chklst.Items)
{
if(item.Selected)
// If the item is selected, add the value to the list.
ChkListe.Add(item);
}
Session["selectedChkList"] = ChkListe;
Response.Redirect("Default2.aspx", false);
}
}
Second page where I take the list out of session, but not sure how to get it into the asp:literal.
public partial class Default2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
List<object> ResultatList = new List<object>();
if (Session["selectedChkList"] != null)
{
ResultatList = (List<object>)Session["selectedStrList"];
ResultatLliteral.Text = String.Format("<p>{0} {1}</p> <img src ={3} />", Frukter.Navn, Frukter.farge, Frukter.BildeSrc);
}
}
}
}
Some critique on your code and some different approaches, not sure what your assignment is but I'll provide feedback that may be beneficial for your course.
public class Fruit
{
public Fruit(string name, string color, string image)
{
Name = name;
Color = color;
Image = image;
}
public string Name { get; }
public string Color { get; }
public string Image { get; }
}
You defined a Constructor that will always set a value upon creation, so unless you intend to modify the object after the fact you can set your properties to read only.
Personally I would use a database or another way to persist my data, but for your example you should be able to do the following:
var fruits = new List<Fruit>()
{
new Fruit("Apple", "Red", "..."),
new Fruit("Grapefuit", "Yellow", "...")
};
// Grab the selected checkbox in the checkbox list item (You'll have to see if a collection is returned or not)
var selectedFruit = chkLFruit.Items.Cast<ListItem>().Where(item => item.Selected);
// Take selected item and pass full object into session.
var filter = fruits.Where(fruit => selectedFruit.Select(t => t.Text).FirstOrDefault(x => String.Compare(x, fruit.Name, true) == 0);
// Create Session
HttpContext.Session["FruitSelection"] = filter;
On your other page before you attempt to use simply do the following:
var selectedFruits = (List<Fruit>)HttpContext.Session["FruitSelection"];
I Have one table of data:
tblFeed
Id
Title
Content
And I populated a Listbox in my WPF application with this table.
I have the issue now of using the Id value for an event but the Id keeps returning 0.
Any Suggestions?
WCF
public List<Feed> GetFeed()
{
List<Feed> r = new List<Feed>();
List<Feed> e;
using (TruckDb db = new TruckDb())
e = db.Feed.Where(x => x.Id != null).ToList();
foreach (var a in e)
{
var feed = new Feed()
{
Id = a.Id,
Title = a.Title,
Content = a.Content
};
r.Add(feed);
}
return r;
}
WPF
public async Task LoadFeeds()
{
TruckServiceClient TSC = new TruckServiceClient();
try
{
List<ClientItems> feeditems = new List<ClientItems>();
if (lbFeed.Items.Count <= 0)
foreach (var item in await TSC.GetFeedAsync())
{
feeditems.Add(new ClientItems
{
FId = item.Id,
FTitle = item.Title,
FContent = item.Content
});
}
lbFeed.ItemsSource = (feeditems.ToArray());
lbFeed.DisplayMemberPath = "FTitle";
}
catch (Exception)
{
throw;
}
}
public class ClientItems
{
public int FId { get; set; }
public string FTitle { get; set; }
public string FContent { get; set; }
public override string ToString()
{
return FTitle;
}
}
Delete Event
WCF
private void bnFeedDel_Click(object sender, RoutedEventArgs e)
{
TruckServiceClient service = new TruckServiceClient();
service.DelFeedAsync(new FeedView
{
Id = lbFeed.SelectedIndex
});
}
WPF
public void DelFeed(FeedView feedview)
{
using (var result = new TruckDb())
{
var t = new Feed
{
Id = feedview.Id
};
result.Feed.Remove(t);
result.SaveChanges();
}
}
In your bnFeedDel_Click method you are doing this:
Id = lbFeed.SelectedIndex
I think this is your problem as you don't want to set Id to a SelectedIndex value but rather:
[EDIT after some discussion]
Set SelectedValuePath inside LoadFeeds:
lbFeed.SelectedValuePath = "FId";
And use SelectedValue instead of SelectedIndex:
private void bnFeedDel_Click(object sender, RoutedEventArgs e)
{
TruckServiceClient service = new TruckServiceClient();
service.DelFeedAsync(new FeedView
{
// Of course you may want to check for nulls etc...
Id = (int)lbFeed.SelectedValue;
});
}
Also, you should use DbSet.Attatch() before deleting a record:
public void DelFeed(FeedView feedview)
{
using (var result = new TruckDb())
{
var t = new Feed
{
Id = feedview.Id
};
result.Feed.Attatch(t);
result.Feed.Remove(t);
result.SaveChanges();
}
}
my Insert Script:
function insert(item, user, request) {
item.userId= user.userId;
var table = tables.getTable('mytabble');
table.where({
name: item.name
}).read({
success: upsertItem
});
function upsertItem(existingItems) {
if (existingItems.length === 0) {
request.execute();
} else {
item.id = existingItems[0].id;
table.update(item, {
success: function(updatedItem) {
request.respond(200, updatedItem)
}
});
}
}
}
mytable:
public class myTabble
{
public string Id { get; set; }
[JsonProperty(PropertyName = "name")]
public string name { get; set; }
[JsonProperty(PropertyName = "age")]
public int age { get; set; }
[JsonProperty(PropertyName = "fname")]
public string fname { get; set; }
}
my Insert Function:
private async void InsertTodoItem(myTabble todoItem)
{
await todoTable.InsertAsync(todoItem);
items.Add(todoItem);
}
The update button function
private void Save_Button_Click(object sender, RoutedEventArgs e)
{
try
{
var name1 = name.Text;
var age1 = Convert.ToInt32(age.Text);
var fname1 = fname.Text;
var todoItem = new myTabble { name = name1, age = age1, fname = fname1 };
InsertTodoItem(todoItem);
//NavigationService.Navigate(new Uri("/Page2.xaml", UriKind.Relative));
}
catch
{
MessageBox.Show("Invalid input");
}
}
When I am trying to insert info for previously existing name It is updated properly but at the same time i am getting an exception at my insert function.
Since the exception is coming from items.add(), you should verify the item is not already in the items collection. Something like this should work for you:
if (items.IndexOf(item) == -1)
{
items.Add(todoItem);
}
Depending on what you are changing, you may need to remove and read add the item instead from the collection.