Returning Id from listbox - c#

I have two methods in my WCF, one to populate my ListBox and the other one to delete my selected ListBox items.
My issue is when I run my Delete method the Data shows null, there is also no errors or exceptions.
The coding runs smoothly but nothing changes and the Selected Item stays in the list box.
WPF
private void bnFeedDel_Click(object sender, RoutedEventArgs e)
{
using (TruckServiceClient service = new TruckServiceClient())
{
service.DelFeedAsync(new FeedView
{
Id = lbFeed.SelectedIndex
});
}
}
public async Task LoadFeeds()
{
TruckServiceClient TSC = new TruckServiceClient();
try
{
List<ClientItems> feeditems = new List<ClientItems>();
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;
}
}
WCF
public void DelFeed(FeedView feedview)
{
using (var result = new TruckDb())
{
var t = new Feed
{
Id = feedview.Id,
Title = feedview.Title,
Content = feedview.Content
};
result.Feed.Remove(t);
result.SaveChanges();
}
}
This is all kinda still new to me so any comments/suggestions for my coding would be appreciated.

In the call to your WCF service, you're passing in a new instance of FeedView, with only the Id property set:
service.DelFeedAsync(new FeedView { Id = lbFeed.SelectedIndex });
So when the the service method runs, both Title and Content do not have values to be set (assuming they're both strings, they'll be null or empty strings):
var t = new Feed {
Id = feedview.Id,
Title = feedview.Title,
Content = feedview.Content};
When you call result.Feed.Remove(t);, nothing is removed because there's no matching item to remove.
Additional note: using using with WCF Service Clients is against best practices: https://msdn.microsoft.com/en-us/library/aa355056(v=vs.110).aspx

Related

How to leave existing data unchanged is a condition is false

I am currently working on a project where I need to be able to rent a truck to a customer but also need to add the customer details if not existing. My problem is even though through the WPF form I input the exact same details of a customer, there would be a new set of data added thus creating a new Customer ID for one person. How would I be able to get the database disregard the existing customer details?
My data service code:
public class DataService
{
public static void rentTruck(TruckRental toRent, bool isNewCustomer)
{
using (var ctx = new DAD_TruckRental_RGMContext())
{
if (!isNewCustomer)
{
ctx.Entry(toRent.Customer).State = EntityState.Unchanged;//doesnt leave existing customer unchanged
}
ctx.Entry(toRent.Truck).State = EntityState.Modified;
ctx.TruckRental.Add(toRent);
ctx.SaveChanges();
}
}
My cs code:
private void Button_Click(object sender, RoutedEventArgs e)
{
TruckCustomer cust = new TruckCustomer();
cust.Age = int.Parse(ageTextBox.Text);
cust.LicenseNumber = licenseNumberTextBox.Text;
cust.LicenseExpiryDate = licenseExpiryDateDatePicker.SelectedDate.Value.Date;
TruckPerson per = new TruckPerson();
per.Address = addressTextBox.Text;
per.Telephone = telephoneTextBox.Text;
per.Name = nameTextBox.Text;
cust.Customer = per;
int truckId = int.Parse(truckIdTextBox.Text);
IndividualTruck truck = DataService.searchTruckByID(truckId);
decimal priceTotal = decimal.Parse(totalPriceTextBox.Text);
TruckRental toRent = new TruckRental();
toRent.TotalPrice = priceTotal;
toRent.RentDate = rentDateDatePicker.SelectedDate.Value.Date;
toRent.ReturnDueDate = returnDueDateDatePicker.SelectedDate.Value.Date;
toRent.Customer = cust;
toRent.Truck = truck;
truck.Status = "Rented";
DataService.rentTruck(toRent, true);
MessageBox.Show("Truck rented succesfully");
}
Here is my suggestion
1- First check if customer details already exist in db using LicenseNumber
2- The first step will be either null or have details, so if null then add received customer details otherwise update
here is the code
public class DataService
{
public static void rentTruck(TruckRental toRent, bool isNewCustomer, TruckCustomer tcustomer)
{
using (var ctx = new DAD_TruckRental_RGMContext())
{
var ob = ctx.TruckCustomer.Where(c => c.LicenseNumber == customer.LicenseNumber);
if ( ob != null) //not exist
{
//create new here
ctx.TruckCustomer.Add(tcustomer);
}
//exist then just update State
ctx.ob.State = EntityState.Modified;
ctx.AddOrUpdate(ob);
ctx.TruckRental.Add(toRent);
ctx.SaveChanges();
}
}
I hope this can help you

Executing multiple requests xrm sdk [duplicate]

I am using ExecuteMultipleResponse method to insert 10 account records at a time using SSIS.
List<Entity> _Accounts = new List<Entity>();
// Check the batch size and process
public override void InputAccount_ProcessInput(InputAccountBuffer Buffer)
{
//List<int> personIDs = new List<int>();
int index = 0;
while (Buffer.NextRow())
{
_Accounts.Add(InputAccountFromBuffer(Buffer));
//personIDs.Add(int.Parse(Buffer.sPersonID));
index++;
if (index == 10)
{
ImportBatch();
index = 0;
}
}
ImportBatch();
}
private void ImportBatch()
{
if (_Accounts.Count > 0)
{
var multipleRequest = new ExecuteMultipleRequest()
{
Settings = new ExecuteMultipleSettings()
{
ContinueOnError = true,
ReturnResponses = true
},
Requests = new OrganizationRequestCollection()
};
foreach (var profContact in _Accounts)
{
CreateRequest reqCreate = new CreateRequest();
reqCreate.Target = profContact;
reqCreate.Parameters.Add("SuppressDuplicateDetection", false);
multipleRequest.Requests.Add(reqCreate);
}
ExecuteMultipleResponse multipleResponses = (ExecuteMultipleResponse)organizationservice.Execute(multipleRequest);
var responses = (ExecuteMultipleResponseItemCollection)multipleResponses.Results["Responses"];
foreach (var response in responses)
{
if (response.Fault != null)
{
// A fault has occurred, handle it here
}
else
{
// THIS IS WHERE I KNOW THE GUID VALUE EXIST.
}
}
//IEnumerator f = multipleResponses.Responses.GetEnumerator();
_Accounts.Clear();
}
}
Above code is working fine, however, I now need to read and store Guids from response to a List. This information is essential for the next step in the package. I know, if I am creating single record I can simply say,
Guid newRecord = _service.Create(account);
I even managed to get down to check if the response have 'Fault' or not and if it doesn't have fault then Guid value should exist in the response.
Running response.Response.Results.Values in QuickWatch shows me the guid but I just can't find a way to read it directly and store it as a Guid.
The guid of a created record should be stored in the OrganizationResponse which can be found inside the ExecuteMultipleResponseItem
Try the following to get the guid as a string:
string id = response.Response.Results["id"].ToString()
If it works as expected you should also be able to instantiate a guid, if needed:
Guid guid = new Guid(id);

unit testing a function that takes IEnumerable<IClient> clients parameter

I have a function that saves multiple clients one client at a time. I am struggling to create and populate one of the parameters IEnumerable with string type client properties: clientKey , clientName, and clientTypeCode
public void SaveMultipleClients(IEnumerable<IClient> clients, TransactionMetadata metadata)
{
try
{
if (clients == null)
{
throw new ArgumentNullException("clients");
}
var abstractClients = clients.ToList();
var concreteClients = new List<Client>();
for (int i = 0; i < abstractClients.Count; i++)
{
concreteClients.Add(abstractClients[i].ToConcreteType<IClient, Client>());
var cleanClients = this.RemoveErroneousClient(concreteClients[i]);
foreach (var client in cleanClients)
{
this.SaveClient(client, metadata);
}
}
this.SavePending(concreteClients, metadata);
}
catch (Exception e)
{
throw e.WrapException();
}
}
Thanks in advance for the help!
I was able to instantiate and populate a list of clients and passed it to the clients parameter.
var myClientsList = new List<IClient>();
myClientsList.Add(individualClient);
myClientsList.Add(individualClient1);
var clients = clientDataManager.SaveMultipleClientsOneAtATime(myClientsList, new TransactionMetadata(DateTime.UtcNow));

ExecuteMultipleResponse; How to read and store Guids from the response

I am using ExecuteMultipleResponse method to insert 10 account records at a time using SSIS.
List<Entity> _Accounts = new List<Entity>();
// Check the batch size and process
public override void InputAccount_ProcessInput(InputAccountBuffer Buffer)
{
//List<int> personIDs = new List<int>();
int index = 0;
while (Buffer.NextRow())
{
_Accounts.Add(InputAccountFromBuffer(Buffer));
//personIDs.Add(int.Parse(Buffer.sPersonID));
index++;
if (index == 10)
{
ImportBatch();
index = 0;
}
}
ImportBatch();
}
private void ImportBatch()
{
if (_Accounts.Count > 0)
{
var multipleRequest = new ExecuteMultipleRequest()
{
Settings = new ExecuteMultipleSettings()
{
ContinueOnError = true,
ReturnResponses = true
},
Requests = new OrganizationRequestCollection()
};
foreach (var profContact in _Accounts)
{
CreateRequest reqCreate = new CreateRequest();
reqCreate.Target = profContact;
reqCreate.Parameters.Add("SuppressDuplicateDetection", false);
multipleRequest.Requests.Add(reqCreate);
}
ExecuteMultipleResponse multipleResponses = (ExecuteMultipleResponse)organizationservice.Execute(multipleRequest);
var responses = (ExecuteMultipleResponseItemCollection)multipleResponses.Results["Responses"];
foreach (var response in responses)
{
if (response.Fault != null)
{
// A fault has occurred, handle it here
}
else
{
// THIS IS WHERE I KNOW THE GUID VALUE EXIST.
}
}
//IEnumerator f = multipleResponses.Responses.GetEnumerator();
_Accounts.Clear();
}
}
Above code is working fine, however, I now need to read and store Guids from response to a List. This information is essential for the next step in the package. I know, if I am creating single record I can simply say,
Guid newRecord = _service.Create(account);
I even managed to get down to check if the response have 'Fault' or not and if it doesn't have fault then Guid value should exist in the response.
Running response.Response.Results.Values in QuickWatch shows me the guid but I just can't find a way to read it directly and store it as a Guid.
The guid of a created record should be stored in the OrganizationResponse which can be found inside the ExecuteMultipleResponseItem
Try the following to get the guid as a string:
string id = response.Response.Results["id"].ToString()
If it works as expected you should also be able to instantiate a guid, if needed:
Guid guid = new Guid(id);

Entity Framework won't save changes to model

I'm using Database First in my website and i'm trying to update the data of one entry of the database but the changes are not being saved in one part but are working in another one.
This is where i populate the form with the model data or create a new one to reserve the ID:
public ActionResult Editar(int ID = 0)
{
var banner = new Banner();
var siteVM = new SiteViewModel();
if (ID == 0)
{
db.Banner.Add(banner);
db.SaveChanges();
}
else
{
banner = db.Banner.Find(ID);
siteVM.iePaginas = db.Pagina.ToList().Select(x => new SelectListItem
{
Value = x.ID.ToString(CultureInfo.InvariantCulture),
Text = x.nome.ToUpper()
}).ToList();
foreach (var pagina in siteVM.iePaginas)
{
foreach (var bannerPagina in banner.BannerPagina)
{
if (int.Parse(pagina.Value) == bannerPagina.paginaID)
{
pagina.Selected = true;
}
}
}
}
siteVM.Banner = banner;
return View(siteVM);
}
And this is where i save it:
[HttpPost]
public ViewResult Editar(SiteViewModel model)
{
try
{
var banner = model.Banner;
banner.rascunho = !banner.ativo;
if (banner.ID == 0)
{
db.Banner.Add(banner);
}
else
{
db.Entry(banner).State = EntityState.Modified;
}
//Remove the related pages
foreach (var source in db.BannerPagina.Where(x => x.bannerID == banner.ID))
{
db.BannerPagina.Remove(source);
}
//Record related pages
foreach (var pag in model.PaginasSelecionadas)
{
db.BannerPagina.Add(new BannerPagina { paginaID = int.Parse(pag.Value), bannerID = banner.ID });
}
db.SaveChanges();
ViewBag.Salvo = 1;
return View(model);
}
catch
{
ViewBag.Error = 1;
return View(model);
}
}
The db.Entry(banner).State = EntityState.Modified; doesn't work, i get the data in the model and my ModeState is valid but the data isn't changed on the database. Just below that i have:
db.BannerPagina.Remove(source); //BannerPagina contains a set of pages that are related to my banner so i can choose the pages i want this banner displayed
db.BannerPagina.Add(new BannerPagina { paginaID = int.Parse(pag.Value), bannerID = banner.ID });
And they work fine. I also have tried to use the attach method but it also doesn't work.
EDIT
Kind of found my problem, earlier i had changed the StoreGeneratedPattern option on my table properties to Computed instead of None (I did that so i could create an empty object in the database using it's default values), once i changed it back my changes started to be saved in the DB.
Is there a way to make the Computed configuration work ?

Categories

Resources