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();
Related
I am trying to loop through a list of generic objects call Condition<T> to read the generic field Value. I followed this question to be able to store the List<Condition<T>>. The issue I am running into now is that I can't use the Value field in my loop. What do I need to change in order to use the Value field?
Main
string url = "";
List<ConditionBase> Conditions = new List<ConditionBase>();
Conditions.Add(new Condition<int>(Field.Field1, 1, ConditionOperator.Equal))
Conditions.Add(new Condition<string>(Field.Field2, "test", ConditionOperator.NotEqual))
foreach (ConditionBase c in Conditions)
{
if (c.GetType() == typeof(string))
{
// c.Value throws an error
url += c.Field + " " + c.ConditionOperator + " '" + c.Value + "' and ";
}
else if (c.GetType() == typeof(DateTime))
{
// c.Value throws an error
url += c.Field + " " + c.ConditionOperator + " " + Helpers.FormatDate(c.Value) + " and ";
}
}
Condition Base
public interface ConditionBase
{
Field Field { get; set; }
ConditionOperator ConditionOperator { get; set; }
}
Condition
public class Condition<T> : ConditionBase
{
private Field _Field;
private T _Value;
private ConditionOperator _ConditionOperator;
public Condition(Field field, T value, ConditionOperator condition)
{
this._Field = field;
this._Value = value;
this._ConditionOperator = condition;
}
public Field Field
{
get
{
return this._Field;
}
set
{
if (this._Field != value)
{
this._Field = value;
}
}
}
public T Value
{
get
{
return this._Value;
}
set
{
if (!EqualityComparer<T>.Default.Equals(this._Value, value))
{
this._Value = value;
}
}
}
public ConditionOperator ConditionOperator
{
get
{
return this._ConditionOperator;
}
set
{
if (this._ConditionOperator != value)
{
this._ConditionOperator = value;
}
}
}
}
Enums
public enum Field{
Field1,
Field2
}
public enum ConditionOperator{
Equal,
NotEqual,
GreaterThan,
LessThan
}
Solution
This solution is based on the comments by #orhtej2 & the answer by #Igor.
Main - Test
static void Main(string[] args)
{
var x1 = new Condition<int>(new Field(), 123, ConditionOperator.Equal);
var x2 = new Condition<string>(new Field(), "test", ConditionOperator.Equal);
var x3 = new Condition<DateTime>(new Field(), new DateTime(2018,5,5), ConditionOperator.Equal);
var qqq = new List<ConditionBase>();
qqq.Add(x1);
qqq.Add(x2);
qqq.Add(x3);
foreach (ConditionBase c in qqq)
{
Console.WriteLine(c.GetValue());
}
Console.ReadLine();
}
Condition Base
public interface ConditionBase
{
Field Field { get; set; }
ConditionOperator ConditionOperator { get; set; }
string GetValue();
}
Condition
public class Condition<T> : ConditionBase
{
private Field _Field;
private T _Value;
private ConditionOperator _ConditionOperator;
public Condition(Field field, T value, ConditionOperator condition)
{
this._Field = field;
this._Value = value;
this._ConditionOperator = condition;
}
public Field Field
{
get
{
return this._Field;
}
set
{
if (this._Field != value)
{
this._Field = value;
}
}
}
public T Value
{
get
{
return this._Value;
}
set
{
if (!EqualityComparer<T>.Default.Equals(this._Value, value))
{
this._Value = value;
}
}
}
public ConditionOperator ConditionOperator
{
get
{
return this._ConditionOperator;
}
set
{
if (this._ConditionOperator != value)
{
this._ConditionOperator = value;
}
}
}
public string GetValue()
{
if (Value is string)
{
return "'" + Value.ToString() + "'";
}
else if (Value is DateTime)
{
return Helpers.FormatDate(Convert.ToDateTime(Value));
}
else
{
return Value.ToString();
}
}
}
Enums
public enum Field{
Field1,
Field2
}
public enum ConditionOperator{
Equal,
NotEqual,
GreaterThan,
LessThan
}
You have syntax errors in the code like the lacking public scope of your enums and ConditionOperator.Equal (not ConditionOperator.Equals) but that asside here is the fix.
Conditions should be of type List<ConditionBase>
Use OfType on the List to retrieve and cast the resulting type to Condition<string>. I assume that this was your intention with your added check c.GetType() == typeof(string)
string url = "";
List<ConditionBase> Conditions = new List<ConditionBase>();
Conditions.Add(new Condition<int>(Field.Field1, 1, ConditionOperator.Equal));
Conditions.Add(new Condition<string>(Field.Field2, "test", ConditionOperator.NotEqual));
foreach (var c in Conditions.OfType<Condition<string>>())
{
url += c.Field + " " + c.ConditionOperator + " '" + c.Value + "' and ";
}
If you want a generic property that you can access on all instances regardless of the generic type constraint then you would need to extend the base interface accordingly.
public interface ConditionBase
{
Field Field { get; set; }
ConditionOperator ConditionOperator { get; set; }
object FieldValue { get; }
}
public class Condition<T> : ConditionBase
{
/* I only included the added code in this type */
public object FieldValue
{
get { return (object) this.Value; }
}
}
string url = "";
List<ConditionBase> Conditions = new List<ConditionBase>();
Conditions.Add(new Condition<int>(Field.Field1, 1, ConditionOperator.Equal));
Conditions.Add(new Condition<string>(Field.Field2, "test", ConditionOperator.NotEqual));
foreach (var c in Conditions)
{
url += c.Field + " " + c.ConditionOperator + " '" + c.FieldValue + "' and ";
}
It seems you want to output your value to a string based on the changes in your question. Add a string formatter to your type.
/* I only included the added code in this type */
public class Condition<T> : ConditionBase
{
private Func<T, string> _formatValue;
public Condition(Field field, T value, ConditionOperator condition, Func<T, string> formatValue)
{
this._Field = field;
this._Value = value;
this._ConditionOperator = condition;
this._formatValue = formatValue;
}
public override string ToString()
{
return this._formatValue(this.Value);
}
}
string url = "";
List<ConditionBase> Conditions = new List<ConditionBase>();
Conditions.Add(new Condition<int>(Field.Field1, 1, ConditionOperator.Equal, (val)=> val.ToString()));
Conditions.Add(new Condition<string>(Field.Field2, "test", ConditionOperator.NotEqual, (val)=> val));
foreach (var c in Conditions)
{
url += c.Field + " " + c.ConditionOperator + " '" + c.ToString() + "' and ";
}
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; }
}
}
}
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);
I am implemented one method in my application when it run from visual studio OK fine, but when it run from task scheduler getting this error in Log file
System.Exception: Exception occurred in the Sync Process while fetching the suppliers list and method name is GetSuppliers. The Exception is Newtonsoft.Json.JsonReaderException: Unexpected character encountered while parsing value: C. Line 0, position 0. at Newtonsoft.Json.JsonTextReader.ParseValue() at Newtonsoft.Json.JsonTextReader.ReadInternal() at Newtonsoft.Json.JsonTextReader.Read() at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.ReadForType(JsonReader reader, JsonContract contract, Boolean hasConverter, Boolean inArray) at Newtonsoft.Json.Serialization
my method
public string GetSuppliers()
{
SqlConnection connect = null; var spdb = new Syncdbsource();
try
{
var hsp = new hspservice.MyServiceSoapClient("MyServiceSoap");
var sdetails = hsp.GetSupplier();
List<SupplierDetails> supplierslist = null; var countSuppliers = 0;
if (!string.IsNullOrEmpty(sdetails))
{ supplierslist = JsonConvert.DeserializeObject<List<SupplierDetails>>(sdetails); }
return countSuppliers + "Inserted";
}
catch (SocketException)
{
System.Threading.Thread.Sleep(25000);
try
{
var output = GetSuppliers();
return output;
}
catch (Exception ex)
{
var exception = new Exception(#"Exception occurred in the Sync Process while fetching the suppliers list and method name is GetSuppliers.
The Exception is " + Environment.NewLine + ex.Message);
var message = exception.Message;
SendMail.InsertIssue(message.Replace("'", "''"));
return "-1";
}
}
catch (Exception excp)
{
var exception = new Exception(#"Exception occurred in the Sync Process while fetching the suppliers list and method name is GetSuppliers.
The Exception is " + Environment.NewLine + excp);
SendMail.InsertIssue(exception.ToString().Replace("'", "''"));
}
finally
{
if (connect != null && connect.State == ConnectionState.Open)
{ connect.Dispose(); }
}
return string.Empty;
}
Json return string
[{"SUPPLIERID":"10148 ","SUPPLIERNAME":"ALLIED ELECTRONICS - LUD ","TNAMC":"ACCOUNTS RECEIVABLE ","TNAMB":" ","TNAME":"FORT WORTH ","TPSTC":"76113-2325","TCSTE":"TX","TCCTY":"USA","PHONE":"616-365-9960 ","FAX":"6163659895 "},{"SUPPLIERID":"10159 ","SUPPLIERNAME":"ALRO STEEL CO. ","TNAMC":"P.O. BOX 30382 ","TNAMB":" ","TNAME":"LANSING ","TPSTC":"48909-7882","TCSTE":"MI","TCCTY":"USA","PHONE":"616-248-7687 ","FAX":"6164522779 "}]
public class SupplierDetails
{
private string _supplierCode;
private string _supplierName;
private string _internalCompanyId;
private string _address1;
private string _address2;
private string _city;
private string _state;
private string _country;
private string _zipCode;
private string _fax;
private string _phone;
public string SUPPLIERID
{
get {
return !string.IsNullOrEmpty(_supplierCode) ? _supplierCode : "-";
}
set
{
_supplierCode = value.Trim();
}
}
public string SUPPLIERNAME
{
get {
return !string.IsNullOrEmpty(_supplierName) ? _supplierName : "-";
}
set
{
_supplierName = value.Trim();
}
}
public string CompanyID
{
get {
return !string.IsNullOrEmpty(_internalCompanyId) ? _internalCompanyId : "-";
}
set
{
_internalCompanyId = value.Trim();
}
}
public string TNAMC
{
get {
return !string.IsNullOrEmpty(_address1) ? _address1 : "-";
}
set
{
_address1 = value.Trim();
}
}
public string TNAMB
{
get {
return !string.IsNullOrEmpty(_address2) ? _address2 : "-";
}
set
{
_address2 = value.Trim();
}
}
public string TNAME
{
get {
return !string.IsNullOrEmpty(_city) ? _city : "-";
}
set
{
_city = value.Trim();
}
}
public string TCSTE
{
get {
return !string.IsNullOrEmpty(_state) ? _state : "-";
}
set
{
_state = value.Trim();
}
}
public string TCCTY
{
get {
return !string.IsNullOrEmpty(_country) ? _country : "-";
}
set
{
_country = value.Trim();
}
}
public string TPSTC
{
get {
return !string.IsNullOrEmpty(_zipCode) ? _zipCode : "-";
}
set
{
_zipCode = value.Trim();
}
}
public string PHONE
{
get
{
return !string.IsNullOrEmpty(_phone) ? _phone : "-";
}
set
{
_phone = value.Trim();
}
}
public string FAX
{
get
{
return !string.IsNullOrEmpty(_fax) ? _fax : "-";
}
set
{
_fax = value.Trim();
}
}
public SupplierDetails()
{
//
// TODO: Add constructor logic here
//
}
}
I put together the simplest implementation of what you presented that I could and found that this works:
string sdetails = "[{\"SUPPLIERID\":\"10148 \",\"SUPPLIERNAME\":\"ALLIED ELECTRONICS -LUD \",\"TNAMC\":\"ACCOUNTS RECEIVABLE \",\"TNAMB\":\" \",\"TNAME\":\"FORT WORTH \",\"TPSTC\":\"76113 - 2325\",\"TCSTE\":\"TX\",\"TCCTY\":\"USA\",\"PHONE\":\"616 - 365 - 9960 \",\"FAX\":\"6163659895 \"},{\"SUPPLIERID\":\"10159 \",\"SUPPLIERNAME\":\"ALRO STEEL CO. \",\"TNAMC\":\"P.O.BOX 30382 \",\"TNAMB\":\" \",\"TNAME\":\"LANSING \",\"TPSTC\":\"48909 - 7882\",\"TCSTE\":\"MI\",\"TCCTY\":\"USA\",\"PHONE\":\"616 - 248 - 7687 \",\"FAX\":\"6164522779 \"}]";
List<SupplierDetails> supplierslist = JsonConvert.DeserializeObject<List<SupplierDetails>>(sdetails);
Are you sure that the JSON string you have listed in your question is the entire response that you have in sdetails? Given that the error states that you have an error at character 0, I suspect you not receiving the JSON as you described.
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";
}