Unexpected character encountered while parsing value: c. Path '', line 0, position 0 - c#

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.

Related

JsonObject<List<string>> can't add any data

I tried writing to db using Pomelo.EntityFramework.Mysql with the following code, but it failed. (I know that this is not the fault of Pomelo.EntityFramework.)
public class Element
{
[Key]
public string Id { get; set; }
public JsonObject<List<string>> Tags { get; set; }
}
and
Element element = new Element();
element.ElementId = Guid.NewGuid().ToString();
element.Tags = new List<string>() { "user" };
element.Tags.Object.Add("newtag");
jsonobject only converts "user" to json.(["user"])
What did I make a mistake?
EDIT
i try rewrite code of Pomelo.JsonObject
just changed this code.
public string Json
{
get { return SerializeObject(Object); }
set
{
try
{
Object = string.IsNullOrWhiteSpace(value)
? default(T)
: DeserializeObject<T>(value);
_originalValue = value;
}
catch
{
Object = null;
_originalValue = string.Empty;
}
}
}
from
public string Json
{
get { return _originalValue; }
set
{
try
{
Object = string.IsNullOrWhiteSpace(value)
? default(T)
: DeserializeObject<T>(value);
_originalValue = value;
}
catch
{
Object = null;
_originalValue = string.Empty;
}
}
}
Now it works perfectly.

Reading Generic Value from List of Generic Objects

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 ";
}

Specified cast is not valid C# Entity Framework

Hi I have been getting this Specified cast is not valid in my code but when I connect to my backup database I do not get the Specified cast is not valid error. I am not sure what is going on.
Again, this code works perfectly on one database and gives me the error on the other.
My Controller
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data.Linq.SqlClient;
using System.Text.RegularExpressions;
using MvcPaging;
using lookups.Models;
using lookups.Helpers;
namespace lookups.Controllers
{
public class MPController : Controller
{
// GET: /Lookups/
public LpAppsDataDataContext db = new LpAppsDataDataContext();
public const int DefaultPageSize = 30;
//get MP Data
if (countSpace == 1 && v.Count(char.IsLetter) > 3)
{
if (SqlString.CheckStringForComma(v))
{
mpq = db.mps
.Where(c => c.NAME_LAST.ToLower().Contains(SqlString.GetSplitCommaString(v.ToLower(), 0))).OrderBy(c => c.NAME_LAST).ThenBy(f => f.NAME_FIRST);
}
else
{
mpq = db.mps
.Where(c => c.NAME_LAST.ToLower().Contains(SqlString.GetSplitString(v.ToLower(), 1)) || c.NAME_LAST.Contains(SqlString.GetSplitString(v.ToLower(), 0))).OrderBy(c => c.NAME_LAST).ThenBy(f => f.NAME_FIRST);
}
}
else
{
mpq = db.mps
.Where(c => c.NAME_L
ViewBag.count = mpq.Count();
}
}
else { ViewBag.count = 0; }
#ViewBag.col = "Unclaimed Pensions";
return View(mpq.ToPagedList(currentPageIndex, DefaultPageSize));
}
}
}
My Model
[global::System.Data.Linq.Mapping.TableAttribute(Name = "dbo.mp")]
public partial class mp
{
private string _COMPANY;
private string _STATE;
private System.Nullable<System.DateTime> _DOPT;
private string _SP_STATE;
private string _PRT_NAME;
private string _NAME_LAST;
private string _NAME_FIRST;
private string _LASTADDRESS;
private System.Nullable<double> _ID;
private System.Nullable<System.DateTime> _DATE;
private string _PLAN_TYPE;
public mp()
{
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage = "_COMPANY", DbType = "NVarChar(255)")]
public string COMPANY
{
get
{
return this._COMPANY;
}
set
{
if ((this._COMPANY != value))
{
this._COMPANY = value;
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage = "_STATE", DbType = "NVarChar(255)")]
public string STATE
{
get
{
return this._STATE;
}
set
{
if ((this._STATE != value))
{
this._STATE = value;
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage = "_DOPT", DbType = "DateTime")]
public System.Nullable<System.DateTime> DOPT
{
get
{
return this._DOPT;
}
set
{
if ((this._DOPT != value))
{
this._DOPT = value;
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage = "_SP_STATE", DbType = "NVarChar(255)")]
public string SP_STATE
{
get
{
return this._SP_STATE;
}
set
{
if ((this._SP_STATE != value))
{
this._SP_STATE = value;
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage = "_PRT_NAME", DbType = "NVarChar(255)")]
public string PRT_NAME
{
get
{
return this._PRT_NAME;
}
set
{
if ((this._PRT_NAME != value))
{
this._PRT_NAME = value;
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage = "_NAME_LAST", DbType = "NVarChar(255)")]
public string NAME_LAST
{
get
{
return this._NAME_LAST;
}
set
{
if ((this._NAME_LAST != value))
{
this._NAME_LAST = value;
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage = "_NAME_FIRST", DbType = "NVarChar(255)")]
public string NAME_FIRST
{
get
{
return this._NAME_FIRST;
}
set
{
if ((this._NAME_FIRST != value))
{
this._NAME_FIRST = value;
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage = "_LASTADDRESS", DbType = "NVarChar(255)")]
public string LASTADDRESS
{
get
{
return this._LASTADDRESS;
}
set
{
if ((this._LASTADDRESS != value))
{
this._LASTADDRESS = value;
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage = "_ID", DbType = "Float")]
public System.Nullable<double> ID
{
get
{
return this._ID;
}
set
{
if ((this._ID != value))
{
this._ID = value;
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage = "_DATE", DbType = "DateTime")]
public System.Nullable<System.DateTime> DATE
{
get
{
return this._DATE;
}
set
{
if ((this._DATE != value))
{
this._DATE = value;
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage = "_PLAN_TYPE", DbType = "NVarChar(255)")]
public string PLAN_TYPE
{
get
{
return this._PLAN_TYPE;
}
set
{
if ((this._PLAN_TYPE != value))
{
this._PLAN_TYPE = value;
}
}
}
}
StackTrace
Line 257: #ViewBag.col = "Unclaimed Pensions";
Line 258:
Line 259: return View(mpq.ToPagedList(currentPageIndex, DefaultPageSize));
Line 260: }
Line 261:
Stack Trace:
[InvalidCastException: Specified cast is not valid.]
System.Data.SqlClient.SqlBuffer.get_Double() +51
System.Data.SqlClient.SqlDataReader.GetDouble(Int32 i) +62
Read_mp(ObjectMaterializer`1 ) +2057
System.Data.Linq.SqlClient.ObjectReader`2.MoveNext() +32
System.Collections.Generic.List`1.InsertRange(Int32 index, IEnumerable`1 collection) +392
System.Collections.Generic.List`1.AddRange(IEnumerable`1 collection) +10
MvcPaging.PagedList`1..ctor(IQueryable`1 source, Int32 index, Int32 pageSize, Nullable`1 totalCount) +2014
MvcPaging.PagingExtensions.ToPagedList(IQueryable`1 source, Int32 pageIndex, Int32 pageSize, Nullable`1 totalCount) +134
lookups.Controllers.MPController.Mp(Nullable`1 page, String sortOrder) in
Compare the backup database with the database that doesn't work, specifically the ID column. Make sure they match both the Type (Float) and ability to be Nullable (NULL).
The exception being thrown indicates that one of the columns (that is of type "double") doesn't match the model.
The ID column on the "mp" table is the only double column in your model.
In SQL Server Developer 2019, I used the sys tables to create a SQL script to determine what SQL Server thinks are the types per columns.
select
obj.name as [Table]
, col.name as [Column]
, case
when type.[precision] > 0 and type.scale = 0 then type.name + '(' + CONVERT(nvarchar(8), type.precision) + ')'
when type.[precision] > 0 and type.scale > 0 then type.name + '(' + CONVERT(nvarchar(8), type.precision) + ',' + CONVERT(nvarchar(8), type.scale) + ')'
else type.name end as [FullType]
from
sys.objects as [obj]
inner join sys.columns as [col]
on obj.object_id = col.object_id
inner JOIN sys.types as [type]
on col.system_type_id = type.system_type_id
where
obj.type = N'U'
I could then use script in a common table expressions (CTE) or other similar structure to filter on specific columns.

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();

Displaying all items in another class

My problem is that I have a List<> variable connected to another class, and I want to get all the items from that List<> and put it into a string.
In the result string, i'd like to see callNum, copyNum, content, author, year, title
Here is where I'm trying to put it into a string
public class CItemControl
{
//declare a list variable
private List<CItem> mItems;
private CItem mNewItem;
//a method that instantiates the list
public CItemControl()
{
mItems = new List<CItem>();
}
//attribute to get all items
public List<CItem> Items
{
get { return mItems; }
}
public CItem NewItem
{
get { return mNewItem; }
}
//method to add item to the CItem list
public void AddItem(int callNum, int copyNum, string content, string author, string year)
{
mNewItem = new CItem(callNum, copyNum, content, author, year);
mItems.Add(mNewItem);
}
//method to return all items to a string
public CItem ListAllItems()
{
string allItems;
}
Here is the class where I'm trying to get the items from. There will be variables added later.
class CItem
{
//declare attributes
private string mTitle;
private string mAuthor;
private string mContent;
private string mYear;
private int mCopyNum;
private int mCallNum;
private bool mHold = false;
private bool mBorrowed = false;
private bool mShelf = false;
//overload a constructor
public CItem(int CallNum, int CopyNum, string Content, string Author, string Year)
{
callNum = CallNum;
copyNum = CopyNum;
content = Content;
author = Author;
year = Year;
}
//create the default constructor
public CItem()
{
callNum = 0;
copyNum = 0;
content = "";
author = "";
year = "";
}
//set attributes
public int callNum
{
get { return mCallNum; }
set { mCallNum = value; }
}
public string content
{
get { return mContent; }
set { mContent = value; }
}
public string author
{
get { return mAuthor; }
set { mAuthor = value; }
}
public string year
{
get { return mYear; }
set { mYear = value; }
}
public string title
{
get { return mTitle; }
set { mTitle = value; }
}
public int copyNum
{
get { return mCopyNum; }
set { mCopyNum = value; }
}
public bool hold
{
get { return mHold; }
}
public bool borrowed
{
get { return mBorrowed; }
}
public bool shelf
{
get { return mShelf; }
}
//display information for users
public string displayInfo()
{
return "Call Number: " + callNum + ". Copy Number: " + copyNum + ". Title: " + title +
". Author: " + author + ". Year Published: " + year + ". Content: " + content;
}
//new method to display status of item
public string displayStatus()
{
if (borrowed == true)
return "Item is currently being borrowed.";
if (shelf == true && hold == false)
return "Item is available for borrowing.";
else
return "Item is on hold";
}
Any help is much appreciated!
Thanks in advance.
ListAllItems shall look something like this
public string ListAllItems()
{
var sb = new StringBuilder(); // var is of type StringBuilder
mItems.ForEach(item => sb.Append(item.displayInfo());
return sb.ToString();
}
return String.Join("; ", allItems.Select(item => item.displayInfo()));
You don't provide a lot of informations on how and what informations you want in your result string.
Can't you achieve this objective with a simple loop ?
using System.Text;
(...)
public string ListAllItems()
{
StringBuilder allItems = new StringBuilder();
foreach(CItem itm in Items){
allItems.AppendLine(itm.displayInfo());
}
return allItems.ToString();
}
Stringbuilder is optional but is faster than string concatenation.
I don't normally like to add formatter methods to property bags like this. If you want the flexibility to change have many formatting implementations, you might want to make a seperate class do the formatting.
public interface IFormatter<in T>
{
string Format(T obj);
}
public class CItemFormatter : IFormatter<CItem>
{
public string Format(CItem item)
{
//formatting logic
}
}

Categories