I have a list of class Contact that are read from a CSV file. I want to append a record to that and eventually write it out as a new file.
The CSV is read into a List of Contact called records.
If I add a breakpoint at the line that reads records.Append(cCust); and then step over it with watches on records and cCust, I can see that records contains the CSV data and that cCust contains the data to append, but as I step over the append, nothing happens; no errors and no additional record in the records list.
What am I doing wrong?
Here's the offending code:
private void Btn_Merge_Click(object sender, EventArgs e)
{
IEnumerable<Contact> records;
IEnumerable<dynamic> MondayRows;
// Read the CSV into 'records'
StreamReader Shopifyreader = new StreamReader(textBox_Shopify.Text);
using (var ShopifyCSV = new CsvReader(Shopifyreader, CultureInfo.InvariantCulture))
{
records = ShopifyCSV.GetRecords<Contact>().ToList();
}
// Test adding a new record
Contact cCust = new Contact();
cCust.First_Name = "";
cCust.Last_Name = "";
cCust.Email = "Hello.World#business.com";
cCust.Accepts_Email_Marketing = "";
cCust.Company = "";
cCust.Address1 = "";
cCust.Address2 = "";
cCust.City = "";
cCust.Province = "";
cCust.Province_Code = "";
cCust.Country = "";
cCust.Country_Code = "";
cCust.Zip = "";
cCust.Phone = "";
cCust.Accepts_SMS_Marketing = "";
cCust.Total_Spent = "";
cCust.Total_Orders = "";
cCust.Tags = "Send me Lead Marketing";
cCust.Note = "";
cCust.Tax_Exempt = "";
records.Append(cCust);
// We can now write out the modified file
using (var writer = new StreamWriter(#"C:\temp\Output.csv"))
using (var outputCSV = new CsvWriter(writer, CultureInfo.InvariantCulture))
{
outputCSV.WriteRecords(records);
}
}
public class Contact
{
[Name("First Name")] // This 'attribute' allows the class property First_Name to be matched to the CSV header "First Name"
public string First_Name { get; set; }
[Name("Last Name")]
public string Last_Name { get; set; }
public string Email { get; set; }
[Name("Accepts Email Marketing")]
public string Accepts_Email_Marketing { get; set; }
public string Company { get; set; }
public string Address1 { get; set; }
public string Address2 { get; set; }
public string City { get; set; }
public string Province { get; set; }
[Name("Province Code")]
public string Province_Code { get; set; }
public string Country { get; set; }
[Name("Country Code")]
public string Country_Code { get; set; }
public string Zip { get; set; }
public string Phone { get; set; }
[Name("Accepts SMS Marketing")]
public string Accepts_SMS_Marketing { get; set; }
[Name("Total Spent")]
public string Total_Spent { get; set; }
[Name("Total Orders")]
public string Total_Orders { get; set; }
public string Tags { get; set; }
public string Note { get; set; }
[Name("Tax Exempt")]
public string Tax_Exempt { get; set; }
}
}
This is the problem:
records.Append(cCust);
That's a LINQ extension method, which returns a sequence containing the original sequence and the new value afterwards. It doesn't modify the existing sequence.
So you could use:
records = records.Append(cCust);
However, I'd suggest changing the declared type of records to List<Contact> and then calling the Add method to add directly into the list:
records.Add(cCust);
Related
I am able to set the values for each item in ROOT, such as Address_to and Line_items, but when I try to pass the populated class to Post, it's empty.
public class OrdersClass
{
public class Line_items
{
public string sku { get; set; }
public int quantity { get; set; }
}
public class Address_to
{
public string first_name { get; set; }
public string last_name { get; set; }
public string address1 { get; set; }
public string address2 { get; set; }
public string city { get; set; }
public string zip { get; set; }
}
public class Root
{
public string external_id { get; set; }
public IList<Line_items> line_items { get; set; }
public Address_to address_to { get; set; }
}
}
My c# code:
OrdersClass.Root thisOrder = new OrdersClass.Root();
thisOrder.address_to = new OrdersClass.Address_to();
IList<OrdersClass.Line_items> lineItems = new List<OrdersClass.Line_items>();
I can populate address_to as
thisOrder.address_to.first_name "my first name";
and line_items using:
lineItems.Add(new OrdersClass.Line_items());
lineItems[0].sku = ProductSKU;
lineItems[0].quantity = cartQuantity;
but..I know I'm doing this wrong.
Thanks.
You need to add Line_items:
IList<OrdersClass.Line_items> lineItems = new List<OrdersClass.Line_items>();
var lineItem1 = new OrdersClass.Line_items()
{
quantity = 1,
sku = "sku1"
};
lineItems.Add(lineItem1);
var lineItem2 = new OrdersClass.Line_items()
{
quantity = 2,
sku = "sku2"
};
lineItems.Add(lineItem2);
try to use
lineitems.Add(new OrderClass.Line_items(){
sku = ProductSKU,
quantity = cartQuantity
});
Thanks to those who helped me get my thinking cap back on. Resolved.
line_items.Add did not add the iList to the main "thisOrder" class.
I had instantianted it syntactically correct, but it programmatically correct.
This worked:
thisOrder.line_items = new List<OrdersClass.Line_items>();
Then adding a new ilist:
var lineItem = new OrdersClass.Line_items()
{
quantity = cartQuantity,
sku = printifyProductSKU
};
thisOrder.line_items.Add(lineItem);
Yea. Now on the to the programming challenge:ASYNC Post vs Put.
Thanks.
I Have the following query but its not allowing me to select the properties of my custom class for some reason.
This is my class here:
public class PersonalDetails
{
public string LineType { get; set; }
public string EnquirerTitle { get; set; }
public string ForeName { get; set; }
public string Surname { get; set; }
public int Age { get; set; }
public DateTime Dob { get; set; }
public string MaritalStatus { get; set; }
public string HomePhone { get; set; }
public string MobilePhone { get; set; }
public string Email { get; set; }
public string Address { get; set; }
public string Employment { get; set; }
public string Occupation { get; set; }
}
And here I want to use a query to access the data my end goal is to pass this object to a csv selrilizer which I have created to produce a csv file in a custom format.
IQueryable<tblapertureNetAppointment> _personadetails;
var personalDetails = from _appointments in _dal.apertureNetEntities.tblapertureNetAppointments
.AsEnumerable()
.Select(x => new PersonalDetails { x.LineType its not allowing me to find line type})
.ToList();
Try this way -
var personalDetails = (from _appointments in _dal.apertureNetEntities.tblapertureNetAppointments.AsEnumerable()
select new PersonalDetails {
LineType = _appointments.LineType,
EnquirerTitle = _appointments.EnquirerTitle,
ForeName = _appointments.ForeName,
Surname = _appointments.Surname,
// .......
}).ToList();
Update
Using LinqToCsv you can write csv file from your linq object. LinqToCsv is available as nuget package.
From Package Manager Console -
Install-Package LinqToCsv
Now you can write your linq object to csv file this way -
CsvFileDescription outputFileDescription = new CsvFileDescription
{
SeparatorChar = '\t', // tab delimited
FirstLineHasColumnNames = true,
FileCultureName = "nl-NL" // use formats used in The Netherlands
};
CsvContext cc = new CsvContext();
string fileName = String.Format(#"{0}products2.csv", Server.MapPath("/csvFiles"));
cc.Write(personalDetails,fileName,outputFileDescription);
I have EditText field and WebClient.
In EditText user write city.
EditText misto = FindViewById<EditText>(Resource.Id.misto) ;
TextView one = FindViewById<TextView>(Resource.Id.parentContainer);
TextView two = FindViewById<TextView>(Resource.Id.clicklistener1);
TextView three = FindViewById<TextView>(Resource.Id.clicklistener2);
TextView four = FindViewById<TextView>(Resource.Id.clicklistener3);
misto.TextChanged += (object sender, Android.Text.TextChangedEventArgs e) => {
var city = e.Text.ToString ();
};
I need to place text from EditText to xml string.
Code of POST request with xml
nadislati.Click += delegate
{
using (var client = new WebClient())
{
var values = new NameValueCollection();
values["Order"] = "<Order \n CallConfirm=\"1\"\n PayMethod=\"Безнал\" \n QtyPerson=\"2\" \n Type=\"2\" \n PayStateID=\"0\" \n Remark=\"тестовый заказ с мобильного приложения. просьба при получении заказа переслать скриншот на имейл ....#\" \n RemarkMoney=\"0\" \n TimePlan=\"\" \n Brand=\"1\" \n DiscountPercent=\"0\" \n BonusAmount=\"0\"\n Department=\"\"\n >\n <Customer Login=\"suhomlineugene#gmail.com\" FIO=\"Evgenyi Sukhomlin\"/>\n <Address \n CityName=\"\" \n StationName=\"\" \n StreetName=\"\" \n House=\"\" \n Corpus=\"\" \n Building=\"\" \n Flat=\"\" \n Porch=\"\" \n Floor=\"\" \n DoorCode=\"\"\n />\n\n <Phone Code=\" 096\" Number=\"50 526-43-19\" />\n <Products>\n <Product Code=\"574\" Qty=\"1\" />\n </Products>\n </Order>";
values["OrderText"] = "hello";
var response = client.UploadValues("http://193.203.48.54:5000/fastoperator.asmx/AddOrder", values);
var responseString = Encoding.UTF8.GetString(response);
}
Vibrator vib = (Vibrator)this.GetSystemService(Context.VibratorService);
vib.Vibrate(30);
var intent31 = new Intent(this, typeof(Cart3Activity));
StartActivity(intent31);
};
How I can realize this?
Normally you would have a data contract (a set of classes which represent the XML). You then populate this data contract with values. When you are done and want to send it as XML to the server, you take that object and serialize it into XML or JSON or whatever format the service requires. Taking the XML you have shown in the Order and throwing it through a XML 2 C# generator you get this:
using System;
using System.Xml.Serialization;
using System.Collections.Generic;
namespace Xml2CSharp
{
[XmlRoot(ElementName="Customer")]
public class Customer {
[XmlAttribute(AttributeName="Login")]
public string Login { get; set; }
[XmlAttribute(AttributeName="FIO")]
public string FIO { get; set; }
}
[XmlRoot(ElementName="Address")]
public class Address {
[XmlAttribute(AttributeName="CityName")]
public string CityName { get; set; }
[XmlAttribute(AttributeName="StationName")]
public string StationName { get; set; }
[XmlAttribute(AttributeName="StreetName")]
public string StreetName { get; set; }
[XmlAttribute(AttributeName="House")]
public string House { get; set; }
[XmlAttribute(AttributeName="Corpus")]
public string Corpus { get; set; }
[XmlAttribute(AttributeName="Building")]
public string Building { get; set; }
[XmlAttribute(AttributeName="Flat")]
public string Flat { get; set; }
[XmlAttribute(AttributeName="Porch")]
public string Porch { get; set; }
[XmlAttribute(AttributeName="Floor")]
public string Floor { get; set; }
[XmlAttribute(AttributeName="DoorCode")]
public string DoorCode { get; set; }
}
[XmlRoot(ElementName="Phone")]
public class Phone {
[XmlAttribute(AttributeName="Code")]
public string Code { get; set; }
[XmlAttribute(AttributeName="Number")]
public string Number { get; set; }
}
[XmlRoot(ElementName="Product")]
public class Product {
[XmlAttribute(AttributeName="Code")]
public string Code { get; set; }
[XmlAttribute(AttributeName="Qty")]
public string Qty { get; set; }
}
[XmlRoot(ElementName="Products")]
public class Products {
[XmlElement(ElementName="Product")]
public Product Product { get; set; }
}
[XmlRoot(ElementName="Order")]
public class Order {
[XmlElement(ElementName="Customer")]
public Customer Customer { get; set; }
[XmlElement(ElementName="Address")]
public Address Address { get; set; }
[XmlElement(ElementName="Phone")]
public Phone Phone { get; set; }
[XmlElement(ElementName="Products")]
public Products Products { get; set; }
[XmlAttribute(AttributeName="CallConfirm")]
public string CallConfirm { get; set; }
[XmlAttribute(AttributeName="PayMethod")]
public string PayMethod { get; set; }
[XmlAttribute(AttributeName="QtyPerson")]
public string QtyPerson { get; set; }
[XmlAttribute(AttributeName="Type")]
public string Type { get; set; }
[XmlAttribute(AttributeName="PayStateID")]
public string PayStateID { get; set; }
[XmlAttribute(AttributeName="Remark")]
public string Remark { get; set; }
[XmlAttribute(AttributeName="RemarkMoney")]
public string RemarkMoney { get; set; }
[XmlAttribute(AttributeName="TimePlan")]
public string TimePlan { get; set; }
[XmlAttribute(AttributeName="Brand")]
public string Brand { get; set; }
[XmlAttribute(AttributeName="DiscountPercent")]
public string DiscountPercent { get; set; }
[XmlAttribute(AttributeName="BonusAmount")]
public string BonusAmount { get; set; }
[XmlAttribute(AttributeName="Department")]
public string Department { get; set; }
}
}
You probably need to fix some of the types on some of the properties as the generator is not super clever about this.
Anyways, populate those properties with your values and when you want to create XML from it:
public static string SerializeObject<T>(this T toSerialize)
{
var xmlSerializer = new XmlSerializer(toSerialize.GetType());
using(var textWriter = new StringWriter())
{
xmlSerializer.Serialize(textWriter, toSerialize);
return textWriter.ToString();
}
}
var myXml = SerializeObject<Order>(order);
Where order is an instance of Order. myXml will be your XML string you can pass on to the server.
EDIT
Since you already have that XML string, you will need to deserialize it into the object, so you can manipulate it:
public static T DeserializeObject<T>(string xml)
{
using (var ms = new MemoryStream())
using (var writer = new StreamWriter(ms))
{
writer.Write(xml);
ms.Position = 0;
var serializer = new XmlSerializer(typeof(T));
using (var reader = XmlReader.Create(ms))
return (T)serializer.Deserialize(reader);
}
}
var order = DeserializeObject<Order>(xmlOrder);
Then you can manipulate order and when you are done, convert it back to XML with:
var myXml = SerializeObject<Order>(order);
You have to make sure your XML is well formed when you use these methods.
I have a layer of Data like this to bring me all Admins:
public List<Datos_Admin> SelectAllAdmin()
{
return (from u in contexto.Datos_Admin select u).ToList() ;
}
In my layer of Entities have this:
public class EDatos_Admin
{
public int Id_Admin { get; set; }
public string User_Name { get; set; }
public char Password { get; set; }
public string Nombre { get; set; }
public string Ap_Paterno { get; set; }
public string Ap_Materno { get; set; }
public DateTime Fecha_Alta { get; set; }
public DateTime Fecha_Modificacion { get; set; }
public int UserAdmin_Modificacion { get; set; }
public bool Activo { get; set; }
public EDatos_Admin(int Id_Admin, string User_Name, char Password, string Nombre, string Ap_Paterno, string Ap_Materno, DateTime Fecha_Alta, DateTime Fecha_Modificacion, int UserAdmin_Modificacion, bool Activo)
{
this.Id_Admin = Id_Admin;
this.User_Name = User_Name;
this.Password = Password;
this.Nombre = Nombre;
this.Ap_Paterno = Ap_Paterno;
this.Ap_Materno = Ap_Materno;
this.Fecha_Alta = Fecha_Alta;
this.Fecha_Modificacion = Fecha_Modificacion;
this.UserAdmin_Modificacion = UserAdmin_Modificacion;
this.Activo = Activo;
}
public EDatos_Admin()
{
// TODO: Complete member initialization
}
}
And in my Bussines layer have this:
public EDatos_Admin SeleccionaAllDatos_Admin()
{
foreach (var n in contexto.SelectAllAdmin())
{
listDatosAdmin = new EDatos_Admin()
{
Id_Admin = n.Id_Admin,
User_Name = n.User_Name,
};
}
return listDatosAdmin;
}
In the datagridview only I want show me Id_Admin and User_Name but it doesn't. And when I review in debugging I can see the data but the datagridview doesn't work.
And I call the method SeleccionaAllDatos_Admin in my Bussines layer like this in the load form
dataGridView1.DataSource = new NDatos_Admin().SeleccionaAllDatos_Admin();
How can fixed?
Thanks
I'm trying to learn how to use LINQTOExcel to query a CSV file. Following the tutorial on the site I adapted their example to work with my data (filename is passed to it via an OpenDialog component):
var csv = new ExcelQueryFactory(filename);
var test = from c in csv.Worksheet<TestData>()
select c;
foreach(var t in test)
{
Console.WriteLine(t.Contract_Id);
}
I've got a separate TestData class/model which looks like this:
class TestData
{
public string Transaction_Id { get; set; }
public string Value_Date { get; set; }
public string Transmit_Date { get; set; }
public string Transmit_Time { get; set; }
public string Contract_Id { get; set; }
public string Contract_Amount { get; set; }
public string Contract_Rage { get; set; }
public string TestAmount { get; set; }
public string Employer_Code { get; set; }
public string Test_Acceptor { get; set; }
public string Institution_Id { get; set; }
}
But when I loop through, all of the values for each item are 'null'. Am I missing a step somewhere?
Example CSV Data:
transaction_id,value_date,transmit_date,transmit_time,contract_no,contract_amount,instalment,test_amount,employer_code,test_acceptor,institution_id
35454521,20111230,20120102,2:23:12,1442,1714.56,1,285.76,0,643650,a
The CSV file needs a header row that matches the property names:
Transaction_Id,Value_Date,Transmit_Date,Transmit_Time,Contract_Id,Contract_Amount,Contract_RageTestAmount,Employer_Code,Test_Acceptor,Institution_Id
35454521,20111230,20120102,2:23:12,1442,1714.56,1,285.76,0,643650