C# User defined Array Size - c#

As seen below, I have:
A class (Viatura) that creates a Vehicle.
Another class (ArrayViatura) that creates an array of Vehicles and subsequent methods.
In the form, I have to let the user define the size of this array of vehicles (numericupdown1), before doing any other operations within the form.
How do I make this value become the array size?
Thanks in Advance!
Here's the Code:
Class Viatura
`namespace IP_GonçaloDias_G00
{
class Viatura
{
string cvMatrícula;
string cvMarca;
string cvModelo;
string cvAnoFabrico;
string cvTipoPropulsão;
string cvCilindrada;
string cvPotência;
double cvAceleração;
string cvConsumoMédio;
string cvCor;
int cvTipoVeículo;
string cvCaixa;
DateTime cvPrimeiraMatrícula;
int cvNúmeroRegistos;
double cvKMPercorridos;
string cvDescriçãoVeículo;
double cvPreçoAquisição;
double cvPreçoProposto;
double cvPreçoVenda;
DateTime cvDataVenda;
string cvNomeCliente;
public Viatura(string matricula, string marca, string modelo, string anofabrico, string tipopropulsao, string cilindrada, string potencia, double aceleracao, string consumomedio, string cor, int tipoveiculo, string caixa, DateTime primeiramatricula, int numeroregistos, double km, string descricaoveiculo, double precoaquisicao, double precoproposto, double precovenda, DateTime datavenda, string nomecliente)
{
string cvMatrícula=matricula;
string cvMarca=marca;
string cvModelo=modelo;
string cvAnoFabrico=anofabrico;
string cvTipoPropulsão=tipopropulsao;
string cvCilindrada=cilindrada;
string cvPotência=potencia;
double cvAceleração=aceleracao;
string cvConsumoMédio=consumomedio;
string cvCor=cor;
int cvTipoVeículo=tipoveiculo;
string cvCaixa=caixa;
DateTime cvPrimeiraMatrícula=primeiramatricula;
int cvNúmeroRegistos=numeroregistos;
double cvKMPercorridos=km;
string cvDescriçãoVeículo=descricaoveiculo;
double cvPreçoAquisição=precoaquisicao;
double cvPreçoProposto=precoproposto;
double cvPreçoVenda=precovenda;
DateTime cvDataVenda=datavenda;
string cvNomeCliente =nomecliente;
}
public string CVMatrícula
{
get { return cvMatrícula; }
set { cvMatrícula = value; }
}
public string CVMarca
{
get { return cvMarca; }
set { cvMarca = value; }
}
public string CVModelo
{
get { return cvModelo; }
set { cvModelo = value; }
}
public string CVAnoFabrico
{
get { return cvAnoFabrico; }
set { cvAnoFabrico = value; }
}
public string CVTipoPropulsão
{
get { return cvTipoPropulsão; }
set { cvTipoPropulsão = value; }
}
public string CVCilindrada
{
get { return cvCilindrada; }
set { cvCilindrada = value; }
}
public string CVPotência
{
get { return cvPotência; }
set { cvPotência = value; }
}
public double CvAceleração
{
get { return cvAceleração; }
set { cvAceleração = value; }
}
public string CVConsumoMédio
{
get { return cvConsumoMédio; }
set { cvConsumoMédio = value; }
}
public string CVCor
{
get { return cvCor; }
set { cvCor = value; }
}
public int CVTipoVeículo
{
get { return cvTipoVeículo; }
set { cvTipoVeículo = value; }
}
public string CVCaixa
{
get { return cvCaixa; }
set { cvCaixa = value; }
}
public DateTime CVPrimeiraMatrícula
{
get { return cvPrimeiraMatrícula; }
set { cvPrimeiraMatrícula = value; }
}
public int CVNúmeroRegistos
{
get { return cvNúmeroRegistos; }
set { cvNúmeroRegistos = value; }
}
public double CVKMPercorridos
{
get { return cvKMPercorridos; }
set { cvKMPercorridos = value; }
}
public string CVDescriçãoVeículo
{
get { return cvDescriçãoVeículo; }
set { cvDescriçãoVeículo = value; }
}
public double CVPreçoAquisição
{
get { return cvPreçoAquisição; }
set { cvPreçoAquisição = value; }
}
public double CVPreçoProposto
{
get { return cvPreçoProposto; }
set { cvPreçoProposto = value; }
}
public double CVPreçoVenda
{
get { return cvPreçoVenda; }
set { cvPreçoVenda = value; }
}
public DateTime CVDataVenda
{
get { return cvDataVenda; }
set { cvDataVenda = value; }
}
public string CVNomeCliente
{
get { return cvNomeCliente; }
set { cvNomeCliente = value; }
}
}
}`
The Class ArrayViatura
`namespace IP_GonçaloDias_G00
{
class ArrayViaturas
{
public Viatura[] viaturas;
private int numElementos;
private int pointer;
public ArrayViaturas(int nElem)
{
viaturas = new Viatura[nElem];
numElementos = 0;
pointer = 0;
}
public int NumElementos
{
set { numElementos = value; }
get { return numElementos; }
}
public int Pointer
{
set { pointer = value; }
get { return pointer; }
}
public void InserirViatura(string matricula, string marca, string modelo, string anofabrico, string tipopropulsao, string cilindrada, string potencia, double aceleracao, string consumomedio, string cor, int tipoveiculo, string caixa, DateTime primeiramatricula, int numeroregistos, double km, string descricaoveiculo, double precoaquisicao, double precoproposto, double precovenda, DateTime datavenda, string nomecliente)
{
viaturas[numElementos] = new Viatura(matricula, marca, modelo, anofabrico, tipopropulsao, cilindrada, potencia, aceleracao, consumomedio, cor, tipoveiculo, caixa, primeiramatricula, numeroregistos, km, descricaoveiculo, precoaquisicao, precoproposto, precovenda, datavenda, nomecliente);
numElementos++;
}
public string MostrarViatura(int index, string sep)
{
string str = viaturas[index].CVMatrícula + sep + viaturas[index].CVMarca + sep + viaturas[index].CVModelo + sep + viaturas[index].CVAnoFabrico +
sep + viaturas[index].CVTipoPropulsão + sep + viaturas[index].CVCilindrada + sep + viaturas[index].CVPotência +
sep + viaturas[index].CvAceleração.ToString("f2") + "KMh" + sep + viaturas[index].CVConsumoMédio + sep + viaturas[index].CVCor
+ sep + viaturas[index].CVTipoVeículo.ToString("f2") + sep + viaturas[index].CVCaixa + sep + viaturas[index].CVPrimeiraMatrícula.ToShortDateString()
+ sep + viaturas[index].CVNúmeroRegistos.ToString("f2") + sep + viaturas[index].CVKMPercorridos.ToString("f2") + sep + viaturas[index].CVDescriçãoVeículo +
sep + viaturas[index].CVPreçoAquisição.ToString("f2") + sep + viaturas[index].CVPreçoProposto.ToString("f2") + sep + viaturas[index].CVPreçoVenda.ToString("f2") +
sep + viaturas[index].CVNomeCliente;
return str;
}
public void EliminarViatura(int index)
{
for (int i = index; i < NumElementos - 1; i++)
{
viaturas[i] = viaturas[i + 1];
}
NumElementos--;
if (pointer == NumElementos)
pointer--;
}
}
}`
The Form Code
`namespace IP_GonçaloDias_G00
{
public partial class RegistoViaturas : Form
{
string cvMatrícula="";
string cvMarca = "";
string cvModelo = "";
string cvAnoFabrico = "";
string cvTipoPropulsão = "";
string cvCilindrada = "";
string cvPotência = "";
double cvAceleração = 0;
string cvConsumoMédio = "";
string cvCor = "";
int cvTipoVeículo = 0;
string cvCaixa = "";
DateTime cvPrimeiraMatrícula=DateTime.Now;
int cvNúmeroRegistos = 0;
double cvKMPercorridos = 0;
string cvDescriçãoVeículo = "";
double cvPreçoAquisição = 0;
double cvPreçoProposto = 0;
double cvPreçoVenda = 0;
DateTime cvDataVenda = DateTime.Now;
string cvNomeCliente = "";
public RegistoViaturas()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
this.Close();
}
private void button7_Click(object sender, EventArgs e)
{
int size= Convert.ToInt32(numericUpDown1.Value);
ArrayViaturas viaturas = new ArrayViaturas(size);
MessageBox.Show("O tamanho definido para o Array é: " + viaturas.viaturas.Length);
groupBox2.Enabled = true;
}
}
}`

Assuming that the size is defined in TextBox1:
int size = 20;
int.TryParse(TextBox1.Text, out size);
public ArrayColab colaborators = new ArrayColab(size);
But note that its not a good idea to get the array size directly from user but you can define the array size yourself after detemening the user's need.
If the size is defined in NumericUpDown then:
public ArrayColab colaborators = new ArrayColab(NumericUpDown1.Value);

Related

no argument given that corresponds to required format parameter error

i have ran into some problems with my insert function.
i am trying to make my the string listing_ID an auto increment int with no input needed, however when coding for the button submit i included all the inputs for all the other values but not listing_ID , this gave me the error below. below are all the images and these are the codes for the insert function.
public class Carlisting
{
private string _listID = "";
private string _car_model = "";
private string _brand_name = "";
private string _car_description = "";
private string _car_condition = "";
private string _price = "";
private string _inspection_date = "";
string _connStr = ConfigurationManager.ConnectionStrings["roadbnb.mdf"].ConnectionString;
public Carlisting(string listID, string car_model, string brand_name, string car_description, string car_condition, string price, string inspection_date)
{
_listID = listID;
_car_model = car_model;
_brand_name = brand_name;
_car_description = car_description;
_car_condition = car_condition;
_price = price;
_inspection_date = inspection_date;
}
public Carlisting()
{
}
public string listing_ID
{
get { return _listID; }
set { _listID = value; }
}
public string car_model
{
get { return _car_model; }
set { _brand_name = value; }
}
public string brand_name
{
get { return _brand_name; }
set { _brand_name = value; }
}
public string car_description
{
get { return _car_description; }
set { _car_description = value; }
}
public string car_condition
{
get { return _car_condition; }
set { _car_condition = value; }
}
public string price
{
get { return _price; }
set { _price = value; }
}
public string inspection_date
{
get { return _inspection_date; }
set { _inspection_date = value; }
}
protected void btn_submit_Click(object sender, EventArgs e)
{
int result = 0;
Carlisting car = new Carlisting(tb_model.Text, tb_brand.Text, tb_description.Text, dl_condition.Text, tb_price.Text, tb_date.Text);
result = car.ListingInsert();
if (result > 0)
{
Response.Write("<script>alert('You have succesfully added listing , PLease wait for approval');</script>");
}
else
{
Response.Write("<script>alert('Error : PLease contact helpdesk');</script>");
}
}
public int ListingInsert()
{
int result = 0;
string queryStr = "INSERT INTO Carlisting(car_model, brand_name, car_description, car_condition , price, inspection_date)"
+"VALUES (#car_model, #brand_name, #car_description, #car_condition, #price, #inspection_date)";
SqlConnection conn = new SqlConnection(_connStr);
SqlCommand cmd = new SqlCommand(queryStr, conn);
cmd.Parameters.AddWithValue("#car_model", this.car_model);
cmd.Parameters.AddWithValue("#brand_Name", this.brand_name);
cmd.Parameters.AddWithValue("#car_description", this.car_description);
cmd.Parameters.AddWithValue("#car_condition", this.car_condition);
cmd.Parameters.AddWithValue("#price", this.price);
cmd.Parameters.AddWithValue("#inspection_date", this.inspection_date);
conn.Open();
result += cmd.ExecuteNonQuery();
conn.Close();
return result;
}
Does anyone know how should fix it in order to get the results i wan? Thank you in advance
As per your screenshot, you are getting compilation error. To Fix it, create another constructor. Currently your code want to invoke constructor which does not take listId as parameter.
public Carlisting(string listID, string car_model, string brand_name, string car_description, string car_condition, string price, string inspection_date)
: this(car_model, brand_name, car_description, car_condition, price, inspection_date)
{
_listID = listID;
}
public Carlisting(string car_model, string brand_name, string car_description, string car_condition, string price, string inspection_date)
{
_car_model = car_model;
_brand_name = brand_name;
_car_description = car_description;
_car_condition = car_condition;
_price = price;
_inspection_date = inspection_date;
}
With above the 1st constructor invokes the another constructor with other required parameters. And for your code, the 2nd constructor will be invoked and you won't have compilation error.

Huge List<T> processing and Pdf generate

I have a pdf file as Byte[] and I'm using iTextSharp to modify the file and embed a specific details in it.
in the List I have min. 25K objects, and I need to generate 25K pdf files.
I'm using Parallel.ForEach but it takes 16.40 mins to be done in Total.
I used ToLookUp method like this:
var valuesToLookupWith = Recipients.ToLookup(item => item.ID);
List<int> Ids = Recipients.Select(item => item.ID).ToList();
Partitioner<int> partitioner = Partitioner.Create(Ids, EnumerablePartitionerOptions.NoBuffering);
Parallel.ForEach(partitioner, new ParallelOptions { MaxDegreeOfParallelism = 6 } ,(id) =>
{
var item = valuesToLookupWith[id].ToList().FirstOrDefault();
item.Attachment = AttachmentEngine.GeneratePdfFromPdfFile((fileAsByteArray,id, "www.xyz.ca"));
...
});
and I used ForEach and also it takes approx. > 25 minutes.
foreach (int id in Ids)
{
var item = valuesToLookupWith[id].ToList().FirstOrDefault();
item.Attachment = AttachmentEngine.GeneratePdfFromPdfFile(fileAsByteArray,id, "www.xyz.ca");
...
}
any suggested way to speedup the process please?
FYI I'm not writing anything on the disk, all is done in memory as Byte[] and then I'm writing the values back to the Db.
and also all the time spent - mentioned in the question is only the time spent for Parallel.ForEach / ForEach statements.
Db calls is not an issue for me at all, I'm making only two calls to the Db , one when I load list of recipients from it and another call when writing values back to the Db
public static byte[] GeneratePdfFromPdfFile(byte[] file, int id, string landingPage)
{
try
{
using (var ms = new MemoryStream())
{
//Create an iTextSharp Document which is an abstraction of a PDF but **NOT** a PDF
var doc = new iTextSharp.text.Document();
//Create a writer that's bound to our PDF abstraction and our stream
var writer = PdfWriter.GetInstance(doc, ms);
//Open the document for writing
doc.Open();
PdfContentByte cb = writer.DirectContent;
// doc.NewPage();
//var srHtml = new StringReader(source);
////parse html code to xml
//iTextSharp.tool.xml.XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, srHtml);
PdfReader reader = new PdfReader(file);
for (int pageNumber = 1; pageNumber < reader.NumberOfPages + 1; pageNumber++)
{
doc.SetPageSize(reader.GetPageSizeWithRotation(1));
doc.NewPage();
//Insert to Destination on the first page
PdfImportedPage page = writer.GetImportedPage(reader, pageNumber);
int rotation = reader.GetPageRotation(pageNumber);
if (rotation == 90 || rotation == 270)
{
cb.AddTemplate(page, 0, -1f, 1f, 0, 0, reader.GetPageSizeWithRotation(pageNumber).Height);
}
else
{
cb.AddTemplate(page, 1f, 0, 0, 1f, 0, 0);
}
}
// Add a new page to the pdf file
doc.NewPage();
// set pdf open action to open the link embedded in the file.
string _embeddedURL = "http://" + landingPage + "/Default.aspx?code=" + GetCampaignRecipientCode(id) + "&m=" + eventCode18;
PdfAction act = new PdfAction(_embeddedURL);
writer.SetOpenAction(act);
doc.Close();
return ms.ToArray();
}
}
catch { return null; }
}
Recipient Class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CampaignLauncherLibrary
{
public class CampaignRecipientLib
{
private int _id;
private int _crid;
private string _crcode;
private int _cmpId;
private string _cmpStatus;
private string _email;
private string _firstName;
private string _lastName;
private string _language;
private string _cmpDefaultlanguage;
private bool _isdoubleBarrle;
private DateTime? _scheduled;
private string _offset;
private string _emailTo;
private string _emailFrom;
private string _emailBody;
private string _emailSubject;
private byte[] _emailAttachment;
private string _emailReplyTo;
private string _attachmentName;
private bool _readytobesent;
private bool _pickupready;
private TimeSpan _Toffset;
private int? _cmprIDnextRecipient;
private string _CampaignGroupCode;
private bool _Reschedule;
private List<int> _Campaigns;
private List<int> _SentCampaigns;
private bool _restrictToWorkHours;
private TimeSpan? _whStart;
private TimeSpan? _whEnd;
private string _emailName;
public CampaignRecipientLib()
{
}
public CampaignRecipientLib(CampaignRecipientLib _recipient)
{
ID = _recipient.ID;
CampaignId = _recipient.CampaignId;
CampaignStatus = _recipient.CampaignStatus;
CMPRID = _recipient.CMPRID;
CMPRCode = Guid.NewGuid().ToString("N");
Email = _recipient.Email;
FirstName = _recipient.FirstName;
LastName = _recipient.LastName;
Language = _recipient.Language;
DefaultLanguage = _recipient.DefaultLanguage;
IsdoubleBarrle = _recipient.IsdoubleBarrle;
Scheduled = _recipient.Scheduled;
Offset = _recipient.Offset;
EmailTo = _recipient.EmailTo;
EmailFrom = _recipient.EmailFrom;
EmailBody = _recipient.EmailBody;
EmailSubject = _recipient.EmailSubject;
EmailAttachment = _recipient.EmailAttachment;
EmailReplyTo = _recipient.EmailReplyTo;
AttachmentName = _recipient.AttachmentName;
ReadyTobeSent = _recipient.ReadyTobeSent;
PickupReady = _recipient.PickupReady;
IDnextRecipient = _recipient.IDnextRecipient;
CampaignGroupCode = _recipient.CampaignGroupCode;
Reschedule = _recipient.Reschedule;
Campaigns = _recipient.Campaigns;
SentCampaigns = _recipient.SentCampaigns;
EmailName = _recipient.EmailName;
Toffset = _recipient.Toffset;
}
public void AssingRandomCampaign()
{
int result = 0;
List<int> cmp = _Campaigns;
List<int> sentcmp = _SentCampaigns;
if (cmp.Where(x => !sentcmp.Distinct().Contains(x)).ToList().Count > 0)
{
cmp = cmp.Where(x => !sentcmp.Distinct().Contains(x)).ToList();
result = cmp.Shuffle().Take(1).ToList()[0];
}
else
{
int N = 0;
if (sentcmp.Count == 2) N = 1;
else if (sentcmp.Count == 3) N = 2;
else N = sentcmp.Count % 2 == 0 ? 2 : 3;
List<int> lastN = sentcmp.Skip(Math.Max(0, sentcmp.Count) - N).ToList();
cmp = cmp.Where(predicate: x => !lastN.Contains(x)).ToList();
sentcmp = sentcmp.Where(predicate: x => cmp.Contains(x)).ToList();
List<int> grpOccurrences = sentcmp.GroupBy(i => i).OrderByDescending(item => item.Count()).SelectMany(i => i).Distinct().ToList();
result = grpOccurrences.Shuffle().PickRandom(1).ToList()[0];
}
if (result > 0)
{
_SentCampaigns.Add(result);
CampaignId = result;
}
}
public bool reAdjustScheduleDate()
{
try
{
Scheduled = Utilities.FixDate(Scheduled.Value, RestrictToWorkHours, Offset, WhStart, WhEnd);
}
catch (Exception ex)
{
return false;
}
return true;
}
public TimeSpan Toffset
{
get { return _Toffset; }
set { _Toffset = value; }
}
public string EmailName
{
get { return _emailName; }
set { _emailName = value; }
}
public int? IDnextRecipient
{
get { return _cmprIDnextRecipient; }
set { _cmprIDnextRecipient = value; }
}
public string CampaignGroupCode
{
get { return _CampaignGroupCode; }
set { _CampaignGroupCode = value; }
}
public bool RestrictToWorkHours
{
get { return _restrictToWorkHours; }
set { _restrictToWorkHours = value; }
}
public TimeSpan? WhStart
{
get { return _whStart; }
set { _whStart = value; }
}
public TimeSpan? WhEnd
{
get { return _whEnd; }
set { _whEnd = value; }
}
public bool Reschedule
{
get { return _Reschedule; }
set { _Reschedule = value; }
}
public List<int> Campaigns
{
get { return _Campaigns; }
set { _Campaigns = value; }
}
public List<int> SentCampaigns
{
get { return _SentCampaigns; }
set { _SentCampaigns = value; }
}
public int ID
{
get { return _id; }
set { _id = value; }
}
public int CMPRID
{
get { return _crid; }
set { _crid = value; }
}
public string CMPRCode
{
get { return _crcode; }
set { _crcode = value; }
}
public int CampaignId
{
get { return _cmpId; }
set { _cmpId = value; }
}
public string CampaignStatus
{
get { return _cmpStatus; }
set { _cmpStatus = value; }
}
public string Email
{
get { return _email; }
set { _email = value; }
}
public string FirstName
{
get { return _firstName; }
set { _firstName = value; }
}
public string LastName
{
get { return _lastName; }
set { _lastName = value; }
}
public string Language
{
get { return _language; }
set { _language = value; }
}
public string DefaultLanguage
{
get { return _cmpDefaultlanguage; }
set { _cmpDefaultlanguage = value; }
}
public bool IsdoubleBarrle
{
get { return _isdoubleBarrle; }
set { _isdoubleBarrle = value; }
}
public DateTime? Scheduled
{
get { return _scheduled; }
set { _scheduled = value; }
}
public string EmailTo
{
get { return _emailTo; }
set { _emailTo = value; }
}
public string Offset
{
get { return _offset; }
set { _offset = value; }
}
public string EmailFrom
{
get { return _emailFrom; }
set { _emailFrom = value; }
}
public string EmailBody
{
get { return _emailBody; }
set { _emailBody = value; }
}
public string EmailSubject
{
get { return _emailSubject; }
set { _emailSubject = value; }
}
public byte[] EmailAttachment
{
get { return _emailAttachment; }
set { _emailAttachment = value; }
}
public string EmailReplyTo
{
get { return _emailReplyTo; }
set { _emailReplyTo = value; }
}
public string AttachmentName
{
get { return _attachmentName; }
set { _attachmentName = value; }
}
public bool ReadyTobeSent
{
get { return _readytobesent; }
set { _readytobesent = value; }
}
public bool PickupReady
{
get { return _pickupready; }
set { _pickupready = value; }
}
}
}

sort text file by property (e.g. .last_name)

I've searched StackOverflow for an answer to this, but can't find a clear answer.
I've this Player Class (Yes i've posted the class before)
namespace Tennis_Match
{
class Player
{
private string first_name;
private string middle_name;
private string last_name;
private DateTime dob;
private string nat;
private char gender;
public string First_name { get { return first_name; } set { first_name = value; } }
public string Middle_name { get {return middle_name; } set { middle_name = value; } }
public string Last_name { get { return last_name; } set { last_name = value; } }
public DateTime Dob { get { return dob; } set { dob = value; } }
public string Nat { get { return nat; } set { nat = value; } }
public char Gender { get { return gender; } set { gender = value; } }
public Player(string first_name, string last_name, string middle_name, DateTime dob, string nat, char gender)
{
this.first_name = first_name;
this.last_name = last_name;
this.middle_name = middle_name;
this.dob = dob;
this.nat = nat;
this.gender = gender;
}
public override string ToString()
{
return first_name + " " + middle_name + " " + last_name + " " + dob + " "+ nat + " " + gender;
}
public static int CalculateAge(DateTime dob)
{
int years = DateTime.Now.Year - dob.Year;
if ((dob.Month > DateTime.Now.Month) || (dob.Month == DateTime.Now.Month && dob.Day > DateTime.Now.Day))
years--;
return years;
}
private List<string> content = new List<string>();
public string FileName { get; set; }
public string Delimiter { get; set; }
private void Load()
{
TextFieldParser par = new TextFieldParser(FileName);
par.TextFieldType = FieldType.Delimited;
par.SetDelimiters(Delimiter);
while (!par.EndOfData)
{
string[] fields = par.ReadFields();
foreach (string field in fields)
{
Console.WriteLine(field);
}
}
par.Close();
}
public void RunReadCSVFile(string fn, string delim = "|")
{
FileName = fn;
Delimiter = delim;
Load();
}
public string GetLine(string fileName, int line)
{
using (var sr = new StreamReader(fileName))
{
for (int i = 1; i < line; i++)
sr.ReadLine();
return sr.ReadLine();
}
}
}
}
Then I've another class tournament. I want to sort a textfile by among other Last_name. I've got an idea that i might need to use IComparable to sort the file.
The file is structured like this:
1|Mariuss|Luka|Thygesen|1986-07-25|NAURU|NR
First you have nothing to sort. So add to class
static List<Player> players = new List<Player>();
Next you need to add items to List in following function
private void Load()
{
TextFieldParser par = new TextFieldParser(FileName);
par.TextFieldType = FieldType.Delimited;
par.SetDelimiters(Delimiter);
while (!par.EndOfData)
{
string[] fields = par.ReadFields();
foreach (string field in fields)
{
Console.WriteLine(field);
}
//-----------------------------Add -----------------------
Player newPlayer = new Player(fields[0], fields[1], fields[2], DateTime.Parse(fields[3]), fields[4], fields[5][0]);
players.Add(newPlayer);
}
par.Close();
}
Now you have something to sort. So add a sort method (or CompareTo())
public void Sort()
{
players = players.OrderBy(x => new { x.last_name, x.first_name, x.middle_name }).ToList();
}

Get variables for ipn option_name_1_1 C#

I have a paypal shopping cart button that has 3 option dropdowns. The first is Style - Tee, Sweat, Hood - this one has a price tied to each, then there are two others Size and Color. This is a C# ASP.NET app. If I look at the whole response that the listener gets ( all the variables) the style is the 'option_name1_1' and it returns "Style" as it should. But in the list 'option_selection_1_1' = "Sweat", which is what I selected, but it doesn't show anything when I call that value. This is the code that puts the response to the user.
if (strResponse.StartsWith("SUCCESS"))
{
PDTHolder pdt = PDTHolder.Parse(strResponse);
Label1.Text =
string.Format("" + pdt.PayerFirstName + " " + pdt.PayerLastName + " for your payment of " + pdt.GrossTotal + " " + pdt.Currency + " option:"+pdt.OptionName+" : "+pdt.OptionOne+":"+pdt.OptionName2+ " :" + pdt.OptionTwo+"!",
pdt.PayerFirstName, pdt.PayerLastName,
pdt.PayerEmail, pdt.GrossTotal, pdt.Currency);
This is the class the the listener uses to parse the response.
public class PDTHolder
{
public PDTHolder()
{
}
private double grosstotal;
public double GrossTotal
{
get { return grosstotal; }
set { grosstotal = value; }
}
private int invoicenumber;
public int InvoiceNumber
{
get { return invoicenumber; }
set { invoicenumber = value; }
}
private string paymentstatus;
public string PaymentStatus
{
get {return paymentstatus; }
set { paymentstatus = value; }
}
private string payerfirstname;
public string PayerFirstName {
get { return payerfirstname; }
set { payerfirstname = value; }
}
private double paymentfee;
public double PaymentFee {
get { return paymentfee; }
set { paymentfee = value; }
}
private string businessemail;
public string BusinessEmail {
get { return businessemail; }
set { businessemail = value; }
}
private string payeremail;
public string PayerEmail {
get { return payeremail; }
set { payeremail = value; }
}
private string txtoken;
public string TxToken {
get { return txtoken; }
set { txtoken = value; }
}
private string payerlastname;
public string PayerLastName {
get { return payerlastname; }
set { payerlastname = value; }
}
private string receiveremail;
public string ReceiverEmail {
get { return receiveremail; }
set { receiveremail = value; }
}
private string itemname;
public string ItemName {
get { return itemname; }
set { itemname = value; }
}
private string currency;
public string Currency {
get { return currency; }
set {currency = value; }
}
private string transactionid;
public string TransactionId {
get { return transactionid; }
set { transactionid = value; }
}
private string subscriberid;
public string SubscriberId {
get { return subscriberid; }
set { subscriberid = value; }
}
private string custom;
public string Custom {
get { return custom; }
set { custom = value; }
}
private string optionone;
public string OptionOne{
get{ return optionone;}
set{optionone = value;}
}
private string optionname;
public string OptionName
{
get { return optionname; }
set { optionname = value; }
}
private string optiontwo;
public string OptionTwo{
get{ return optiontwo;}
set{optiontwo = value;}
}
private string optionname2;
public string OptionName2
{
get { return optionname2; }
set { optionname2 = value; }
}
private double price;
public static PDTHolder Parse(string postData)
{
String sKey, sValue;
PDTHolder ph = new PDTHolder();
try
{
//split response into string array using whitespace delimeter
String[] StringArray = postData.Split('\n');
// NOTE:
/*
* loop is set to start at 1 rather than 0 because first
string in array will be single word SUCCESS or FAIL
Only used to verify post data
*/
// use split to split array we already have using "=" as delimiter
int i;
for (i = 1; i < StringArray.Length - 1; i++)
{
String[] StringArray1 = StringArray[i].Split('=');
sKey = StringArray1[0];
sValue = HttpUtility.UrlDecode(StringArray1[1]);
// set string vars to hold variable names using a switch
switch (sKey)
{
case "mc_gross":
ph.GrossTotal = Convert.ToDouble(sValue);
break;
case "invoice":
ph.InvoiceNumber = Convert.ToInt32(sValue);
break;
case "payment_status":
ph.PaymentStatus = Convert.ToString(sValue);
break;
case "first_name":
ph.PayerFirstName = Convert.ToString(sValue);
break;
case "mc_fee":
ph.PaymentFee = Convert.ToDouble(sValue);
break;
case "business":
ph.BusinessEmail = Convert.ToString(sValue);
break;
case "payer_email":
ph.PayerEmail = Convert.ToString(sValue);
break;
case "Tx Token":
ph.TxToken = Convert.ToString(sValue);
break;
case "last_name":
ph.PayerLastName = Convert.ToString(sValue);
break;
case "receiver_email":
ph.ReceiverEmail = Convert.ToString(sValue);
break;
case "item_name":
ph.ItemName = Convert.ToString(sValue);
break;
case "mc_currency":
ph.Currency = Convert.ToString(sValue);
break;
case "txn_id":
ph.TransactionId = Convert.ToString(sValue);
break;
case "custom":
ph.Custom = Convert.ToString(sValue);
break;
case "subscr_id":
ph.SubscriberId = Convert.ToString(sValue);
break;
case "option_selection1_1":
ph.OptionOne = Convert.ToString(sValue);
break;
case "option_name1_1":
ph.OptionName = Convert.ToString(sValue);
break;
case "option_selection1_2":
ph.OptionTwo = Convert.ToString(sValue);
break;
case "option_name1_2":
ph.OptionName2 = Convert.ToString(sValue);
break;
}
}
return ph;
}
catch (Exception ex)
{
throw ex;
}
}
}
Here is a snipet from my IPN: I hope it helps:
for (var iloop = 1; iloop <= Convert.ToInt32(inTransaction["num_cart_items"]); iloop++)
{
var currentitem = new PurchasedItem(ID, inTransaction["item_name" + iloop],
inTransaction["mc_gross_" + iloop], inTransaction["tax" + iloop],
inTransaction["quantity" + iloop], inTransaction["item_number" + iloop],
inTransaction["mc_shipping" + iloop], inTransaction["mc_handling" + iloop],
new Dictionary<string, string>());
foreach (var argument in inTransaction)
{
var match = Regex.Match(argument.ToString(), #"option_name(\d)_" + iloop);
if (!match.Success) continue;
var buildselection = "option_selection" + match.Groups[1].Value + "_" + iloop;
var key = inTransaction[argument.ToString()];
var value = inTransaction[buildselection];
currentitem.AddAdditionalInfo(new KeyValuePair<string, string>(key, value));
}
PurchasedItem.Add(currentitem);
}
WireAllComponents();

Binding to New Member Display; BuildComboList

I am trying to build a combo list for a program to fill the combobox with a list of applications. it keeps throwing up "Cannot bind to the new display member. Parameter name: newDisplayMember"
private void BuildComboList()
{
Applicant defaultApplicant = new Applicant();
applicationList = defaultApplicant.GetList();
applicantList.DataSource = applicationList;
applicantList.DisplayMember = "DisplayName";
applicantList.ValueMember = "DisplayValue";
}
Applicant Class
public class Applicant
{
//Members
private int applicant_ID;
private string applicant_fname;
private string applicant_lname;
private string applicant_phone;
private string applicant_address1;
private string applicant_address2;
private string applicant_city;
private string applicant_state;
private string applicant_zip;
private string applicant_email;
//properties
public int Applicant_ID
{
get { return applicant_ID; }
set { applicant_ID = value; }
}
public string Applicant_fname
{
get { return applicant_fname; }
set { applicant_fname = value; }
}
public string Applicant_lname
{
get { return applicant_lname; }
set { applicant_lname = value; }
}
public string Applicant_phone
{
get { return applicant_phone; }
set { applicant_phone = value; }
}
public string Applicant_address1
{
get { return applicant_address1; }
set { applicant_address1 = value; }
}
public string Applicant_address2
{
get { return applicant_address2; }
set { applicant_address2 = value; }
}
public string Applicant_city
{
get { return applicant_city; }
set { applicant_city = value; }
}
public string Applicant_state
{
get { return applicant_state; }
set { applicant_state = value; }
}
public string Applicant_zip
{
get { return applicant_zip; }
set { applicant_zip = value; }
}
public string Applicant_email
{
get { return applicant_email; }
set { applicant_email = value; }
}
//Constructors
private void DefaultValues()
{
applicant_ID = 0;
applicant_fname = "";
applicant_lname = "";
applicant_phone = "";
applicant_address1 = "";
applicant_address2 = "";
applicant_city = "";
applicant_state = "";
applicant_zip = "";
applicant_email = "";
}
private void Rec2Members(ApplicantRecord record)//defined in ApplicantDL
{
applicant_ID = record.applicant_ID;
applicant_fname = record.applicant_fname;
applicant_lname = record.applicant_lname;
applicant_phone = record.applicant_phone;
applicant_address1 = record.applicant_address1;
applicant_address2 = record.applicant_address2;
applicant_city = record.applicant_city;
applicant_state = record.applicant_state;
applicant_zip = record.applicant_zip;
applicant_email = record.applicant_email;
}
public ApplicantRecord ToRecord()
{
ApplicantRecord record = new ApplicantRecord();
record.applicant_ID = applicant_ID;
record.applicant_fname = applicant_fname;
record.applicant_lname = applicant_lname;
record.applicant_phone = applicant_phone;
record.applicant_address1 = applicant_address1;
record.applicant_address2 = applicant_address2;
record.applicant_city = applicant_city;
record.applicant_state = applicant_state;
record.applicant_zip = applicant_zip;
record.applicant_email = applicant_email;
return record;
}
public List<ApplicantRecord> GetList()
{
return Approval_Form.ApplicantRecord.ApplicantDL.GetList();
}
public void Insert()
{
applicant_ID = Approval_Form.ApplicantRecord.ApplicantDL.Insert(applicant_fname, applicant_lname, applicant_phone, applicant_address1, applicant_address2, applicant_city, applicant_state, applicant_zip, applicant_email);
}
public void Select(int applicant_ID)
{
ApplicantRecord record = Approval_Form.ApplicantRecord.ApplicantDL.Select(applicant_ID);
Rec2Members(record);
}
public void Update()
{
if (applicant_ID != 0)
{
Approval_Form.ApplicantRecord.ApplicantDL.Update(applicant_ID, applicant_fname, applicant_lname, applicant_phone, applicant_address1, applicant_address2, applicant_city, applicant_state, applicant_zip, applicant_email);
}
}
}
I think it should be:
private void BuildComboList()
{
Applicant defaultApplicant = new Applicant();
applicationList = defaultApplicant.GetList();
applicantList.DataSource = applicationList;
applicantList.DisplayMember = "Applicant_fname";
applicantList.ValueMember = "Applicant_ID";
}
You can change the applicant class further as follows:
Add two properties.
public string DisplayName
{
get { return (applicant_fname + " " + applicant_lname; }
}
public string DisplayValue
{
get { return (applicant_ID.ToString(); }
}
Keep data binding as:
private void BuildComboList()
{
Applicant defaultApplicant = new Applicant();
applicationList = defaultApplicant.GetList();
applicantList.DataSource = applicationList;
applicantList.DisplayMember = "DisplayName";
applicantList.ValueMember = "DisplayValue";
}

Categories