Get value from combobox - c#

I have 2 tables in the database carrier and vendor. vendor has a foreign key of Carrier_Id. When the user want add a vendor, the user will select a carrier from a combobox where the valve from carrier table.
The problem I facing now is that,I don't know how to get the valve from combobox so that I can insert it into the database.
I use this code to get valve from carrier table to show in the combobox.
MyinvoiceDataDataContext contect = new MyinvoiceDataDataContext();
var st = from s in contect.Carriers
select new { s.CarrierID, s.CarrierName};
comVendorCarrier.ItemsSource = st;
comVendorCarrier.DisplayMemberPath = "CarrierName";
comVendorCarrier.SelectedValuePath = "CarrierID";

To get the value of this combobox (i.e. the selected carrier), all you need is just use the two properties SelectedValue to get the CarrierId or SelectedText to get the value (i.e. CarrierName).
For example, you could get the id of the selected carrier by using:
int SelectedCarrierId = int.parse(comVendorCarrier.SelectedValue.ToString());
Or if you need the CarrierName you should use:
string CarrierName = comVendorCarrier.SelectedText;
Edit: Assuming that your tables have the following structre:
Carrier:
CarrierId.
CarrierName.
Vendor:
VendorId.
CarrierId: a foreign key references Carriers(CarrierId).
VendorName.
These two tables should be mapped in your .dbml file to two entities Vendor and Carrier, in which the Vendor class has a property of type Carrier that represents the foreign key CarrierID.
Then in order to view CarrierName in the vendors list, you can do this:
var vendorsList = _db.Vendors
.Select( vendor => new
{
VendorId = vendor.Id,
VendorName = vendor.Name,
CarrierName = vendor.Carrier.Name
});

using (MyinvoiceDataDataContext connv = new MyinvoiceDataDataContext())
{
Vendor editven = (from s in connv.Vendors
where s.VendorID == vendor.VendorID
select s).FirstOrDefault();
editven.VendorAddress = editven.VendorAddress;
editven.VendorBalance = editven.VendorBalance;
editven.VendorContactName = editven.VendorContactName;
editven.VendorEmail = editven.VendorEmail;
editven.VendorFax = editven.VendorFax;
editven.VendorName = editven.VendorName;
editven.VendorPaymentTerms = editven.VendorPaymentTerms;
editven.VendorPhone = editven.VendorPhone;
editven.VendorRemark = editven.VendorRemark;
editven.VendorTax = editven.VendorTax;
editven.VendorWebsite = editven.VendorWebsite;
editven.CarrierID = editven.CarrierID;
connv.SubmitChanges();
}

Related

NetSuite - Search customers by complex query

I am trying to search customers who contain these fields : email or firstName or lastName or id.
must be an OR condition between of them.
for example
var freeText = "shomeone#gmai";
var customers = SearchForCustomersWhoContainsThisData(freeText)
how can i build this query in c#?
public List<Customer> SearchForCustomersWhoContainsThisData(string search_text)
{
CustomerSearch custSearch = new CustomerSearch();
SearchStringField searchField = new SearchStringField();
searchField.#operator = SearchStringFieldOperator.contains;
searchField.operatorSpecified = true;
searchField.searchValue = search_text;
CustomerSearchBasic custBasic1 = new CustomerSearchBasic();
custBasic1.firstName = searchField;
CustomerSearchBasic custBasic2 = new CustomerSearchBasic();
custBasic2.lastName = searchField;
custSearch.basic = custBasic1;
//custSearch.basic = custBasic2; how to add this with or between
// Search for the customer entity who contains this text
SearchResult response = _crmNetSuitService.search(custSearch);
var searchResults = response.recordList.Select(t => (Customer)t).ToList();
return searchResults;
}
I expect to find customers who one of these fields contains this search-text:
email, fName, lName, Id.
As per NetSuite SuiteAnswers id 31408
Web Services > Search > How to set a field filter for one value OR another value
Currently, expressions are not supported via Web Services searches.
In order to Search where a field is one value or another. It is necessary to submit two search requests, then merge the results in the application code.

c# Linq for XML : tag.descendants doesn't allow to interrogate all descendents

I'm fairly new on this website, it's my first question. I read the documentation, but I'm sorry in advance if I brake any code of conduct.
Here is my question :
I have an XML file in a stream. My goal is to get the attribute "Name", "Type", and the key or keys (they've been changed for obvious reason ).
<YourKey>
<Product_Key Name="eMbedded Visual C++ 4.0">
<Key ID="5" Type="Static Activation Key" ClaimedDate="">BBBBB-QW36D-DPT6T-BBBB-ZZZZZ</Key>
</Product_Key>
<Product_Key Name="Windows 10 Home">
<Key ID="1251" Type="Retail" ClaimedDate="1/25/2017">ZZZZZ-6GBG7-ZZZZZ-8JG23-FM47H</Key>
<Key ID="1251" Type="Retail" ClaimedDate="8/23/2016">FEFEF-FVD7K-EEEEF-BEBEB-VMHX7</Key>
<Key ID="1251" Type="Retail" ClaimedDate="4/28/2016">EEZZE-GYB6P-ZZZEE-R72PQ-EEEEZ</Key>
</Product_Key>
</YourKey>
I created a class to hold the data
public class MsProduct
{
public string Name { get; set; }
public string Type { get; set; }
public List<string> key { get; set; }
}
And I created a list of MsProduct to add every elements of var list(see after) to my object.
I created a Linq query, it compiles without the Key = (List<string>)keys, but I only get the value Name, Type is empty (I have a check if the data doesn't exists(ie == null), it replace it by " ").
When I add the Key = (List<string>)keys, the system throws a "System.InvalidCastException".
here is my query :
var productName = XDocument.Load(fileXml);
var list = from product in productName.Descendants("YourKey")
let name = product.Attribute("Name")
let type = product.Attribute("Type")
let keys = product.Elements("Key")
select new MsProduct
{
Name = (string)name,
Type = (string)type,
Key = (List<string>)keys
};
Does anyone have any idea how to query my file in order to populate my class?
Thanks in advance!
Your keys are not strings, but XElements, you couldn't cast it to string. Depending on what do you want to get, you could do:
Key = (List<string>)keys.Select(x=>x.Value).ToList()
or
Key = (List<string>)keys.Select(x=>x.ToString()).ToList()
But you will get nothing on your xml, because you query not products, but YourKey's , to get products change first line to:
var list = from product in productName.Descendants("Product_Key")
If you want to get the type, you should consider, that you have more than one Type pro product. Either you query types to the list as keys, or you are sure they all are the same, so you could take just the first one:
var list = from product in productName.Descendants("Product_Key")
let name = product.Attribute("Name")
let keys = product.Elements("Key")
select new MsProduct
{
Name = (string)name,
Type = keys.First().Attribute("Type").Value,
Key = (List<string>)keys.Select(x=>x.Value).ToList()
};
You don't need those let statements. You do need to get the values form your keys.
var list = from product in productName.Descendants("Product_Key")
where product.Attribute("Name").Value == "YourKey"
// let name = product.Attribute("Name")
// let type = product.Attribute("Type")
// let keys = product.Elements("Key")
select new MsProduct
{
Name = (string)product.Attribute("Name"),
Type = product.Elements("Type").First().Attribute("Type").Value,
Key = product.Elements("Key").Select(e=>e.Value).ToList()
};
But Elements("Type").First() is of course a questionable definition.
There is no such thing as the Type of a ProductKey. It can have many Types.

Setting the orderLine property on an item when updating an invoice

My problem is that after creating an invoice, I can never get new line items to reference their corresponding sales order line item.
I have been generating invoices via SuiteTalk. When I initially create an invoice, I empty the lineItemList and add back in the items I need. I make sure the orderLine property matches the sales order line item line number. This works great.
But when I try and update the invoice with additional line items, I can never get the new items to retain their orderLine property. The orderLine property is used for the "Invoiced" column on the Sales Order.
In order to get the referencing to be correct, I need to delete the invoice and create it again with all of the line items I need.
Does anyone know if what I am trying to do is possible?
In this example, I use this CreateInvoice function to create the invoice from scratch and add it to NetSuite. Everything works as expected.
public void CreateInvoice(SalesOrder salesOrder) {
Invoice brandNewInvoice = new Invoice() {
createdFrom = new RecordRef() {
internalId = salesOrder.internalId,
},
entity = salesOrder.entity,
tranDate = endDate,
tranDateSpecified = true,
startDate = startDate,
startDateSpecified = true,
endDate = endDate,
endDateSpecified = true,
itemList = new InvoiceItemList(),
};
invoice.itemList.item = GetInvoiceItemList(salesOrder); //see the function shown further down
netSuiteService.add(brandNewInvoice);
}
In this example, the invoice is already created and so I get it from NetSuite and then replace the existing itemList with a new one. After the update, the invoice will now have NO orderLine property for any of the line items. The invoice also loses its "Created From" field because there are no line items with the orderLine property set.
public void UpdateInvoice(SalesOrder salesOrder, String invoiceInternalId) {
Invoice invoice = GetNetSuiteInvoice(invoiceInternalId);
invoice.itemList.item = GetInvoiceItemList(salesOrder); //see the function shown further down
netSuiteService.update(invoice);
}
this is the function used to create the itemList:
public InvoiceItem[] GetInvoiceItemList(SalesOrder salesOrder) {
InvoiceItem[] invoiceItemList = new InvoiceItem[salesOrder.itemList.item.Length];
for (int i = 0; i < salesOrder.itemList.item.Length; i++) {
SalesOrderItem soItem = salesOrder.itemList.item[i];
double quantity = 1;
invoiceItemList[i] = new InvoiceItem() {
item = new RecordRef() {
internalId = soItem.item.internalId,
name = soItem.item.name,
},
amount = quantity * Double.Parse(soItem.rate),
amountSpecified = true,
quantity = quantity,
quantitySpecified = true,
price = new RecordRef() {
internalId = soItem.price.internalId,
name = soItem.price.name,
},
rate = soItem.rate,
orderLine = soItem.line, //this will establish the link between the invoice and the sales order
orderLineSpecified = true,
taxRate1 = soItem.taxRate1,
taxRate1Specified = true,
};
}
return invoiceItemList;
}
Actually what you are looking for is the intialize operation. You need to use initialize in order for Netsuite to properly fill in the created from and orderline props. From the NS Help there is a C# example of creating a Cash Sale:
private void Initialize()
{
this.login(true);
InitializeRef ref1 = new InitializeRef();
ref1.type = InitializeRefType.salesOrder;
//internal id of the sales order to be converted to cash sale
ref1.internalId = "792";
ref1.typeSpecified = true;
InitializeRecord rec = new InitializeRecord();
rec.type = InitializeType.cashSale;
rec.reference = ref1;
ReadResponse read1 = _service.initialize(rec);
}
This is normal, when transforming a transaction to another transaction (e.g. SO to Inv, PO to IR). When you transform, most of the information from the source transaction will be carried over. Like what you are doing which is creating an Invoice from Sales Order(Base on your code below).
createdFrom = new RecordRef() {
internalId = salesOrder.internalId,
},
You don't need to get the line item information from the Sales Order and put it in the Invoice because it will be pre-populated once you create it form Sales Oder(unless you need to change a value of a line item column).
One behavior of a transformed record(Invoice in your case), if you remove a line item from the Invoice you will lose the link to the Sales order(orderLine) and if you remove all the line item you will totally lose the link between the two transactions (createdfrom). This is what you are experiencing. orderLine/createdFrom is a field populated by the system, it looks like you are populating it but you are not.

Entity Framework C# change value in table by id

I have Estate and Contract tables. Estate table has Boolean property (Available). When clients are confirms their contract Available property in Estate table changing its value to false. Estate selects from combobox by EstateID. Problem is that I don’t know how to get access to Available property by ID selected in EstateCombobox.
contract.ContractDate = Convert.ToDateTime(ContractDateTextBox.Text);
contract.OperationType = OperationTypeComboBox.SelectedItem.ToString();
contract.Description = DescriptionTextBox.Text;
contract.EstateID = Convert.ToInt32(EstateComboBox.SelectedValue);
contract.ClientID = Convert.ToInt32(ClientComboBox.SelectedValue);
contract.EmployeeID = Convert.ToInt32(EmployeeComboBox.SelectedValue);
contract.NewOwnerID = Convert.ToInt32(NewClientOwnerComboBox.SelectedValue)
EstateComboBox.DataSource = AgencyContext.Estate.ToList();
EstateComboBox.DisplayMember = "EstateName";
EstateComboBox.ValueMember = "EstateID";
EstateComboBox.Invalidate();
I hope I understand you correctly:
int eid = Convert.ToInt32(EstateComboBox.SelectedValue.ToString());
var myEstate = AgencyContext.Estate.Single(e => e.EstateID == eid);
myEstate.Available = false; //new value
dbcontext.SaveChanges();

Entity Framework 4 - Duplicate Key Upon Update

I'm having trouble performing an update in the Entity Framework. I don't really understand the behaviour I am seeing.
I am using the AdventureWorks database.
The starting value for the StateProvince is Micronesia. If I change it to Maryland, the update is successful. However, if I then try to change it back to Micronesia, I get the following error:
"Cannot insert duplicate key row in object 'Sales.SalesTerritory' with
unique index 'AK_SalesTerritory_Name'.\r\nThe statement has been
terminated."
The DAL method in question is:
public static void UpdateCustomer(CustomerDetails customerDetails)
{
AWEntities context = Common.GetContext();
var customerQuery = from c in context.Individuals
.Include("Contact")
.Include("Customer.CustomerAddresses.Address.StateProvince.SalesTerritory")
//.Include("Customer.SalesTerritory.StateProvinces")
.Where(id => id.CustomerID == customerDetails.CustomerId)
select c;
var individual = customerQuery.ToList().ElementAt(0);
Contact contact = individual.Contact;
contact.LastName = customerDetails.LastName;
contact.MiddleName = customerDetails.MiddleName;
contact.FirstName = customerDetails.FirstName;
contact.EmailAddress = customerDetails.EmailAddress;
contact.Phone = customerDetails.Phone;
contact.Title = customerDetails.Title;
AWModel.Customer customer = individual.Customer;
customer.CustomerID = customerDetails.CustomerId;
customer.SalesTerritory.Name = customerDetails.SalesTerritory;
Address address = individual.Customer.CustomerAddresses.ElementAt(0).Address;
address.AddressLine1 = customerDetails.AddressLine1;
address.AddressLine2 = customerDetails.AddressLine2;
address.City = customerDetails.City;
address.PostalCode = customerDetails.PostalCode;
address.StateProvinceID = customerDetails.SalesProvinceId;
context.SaveChanges(SaveOptions.AcceptAllChangesAfterSave);
}
Can anyone identify the correct way to do what I am attempting.
This is occurring when you update the SalesTerritory.Name property:
customer.SalesTerritory.Name = customerDetails.SalesTerritory;
The effect is to change the SalesTerritory entity, rather than the customer entity. I believe you want something more like:
customer.SalesTerritoryID = customerDetails.SalesTerritoryID;

Categories

Resources