I am trying to split a string to get json object value - I have text values with numerous lines in the format:
new Car() { Id = 1, Year = 1926, Make = "Chrysler", Model = "Imperial", ImageUrl = "{"data":{"images":[{"thumb_url":"https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcRPe4CygIW-MuZL5jl77wlgXXK5_ANyC9l1X4QqLizCOkaVAlRe","image_url":"http://imperialclub.org/Yr/1926/photos/Phaeton2Big.jpg","width":1632,"height":1032}]},"error_code":0,"error":false,"message":"1 images(s) available"}" },
new Car() { Id = 2, Year = 1950, Make = "Hillman", Model = "Minx Magnificent", ImageUrl = "{"data":{"images":[{"thumb_url":"https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcScVsGEeRBh6xZYXr6Gm35Sk5ecSlk_ax3qZmoGRAtBbZC8vJZ9","image_url":"http://i.ebayimg.com/images/g/gcIAAOSwKadXPeLs/s-l300.jpg","width":300,"height":225}]},"error_code":0,"error":false,"message":"1 images(s) available"}" },
new Car() { Id = 3, Year = 1954, Make = "Chevrolet", Model = "Corvette", ImageUrl = "{"data":{"images":[{"thumb_url":"https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcSdZntu4tgWrZrxwqeuKlteCP9vJGnqUlmNq5JF1bBCf-EJy5r8","image_url":"http://momentcar.com/images/chevrolet-corvette-1954-1.jpg","width":1000,"height":600}]},"error_code":0,"error":false,"message":"1 images(s) available"}" },
What I would really like is to get them in the format:
new Car() { Id = 1, Year = 1926, Make = "Chrysler", Model = "Imperial", ImageUrl = "https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcRPe4CygIW-MuZL5jl77wlgXXK5_ANyC9l1X4QqLizCOkaVAlRe" },
new Car() { Id = 2, Year = 1950, Make = "Hillman", Model = "Minx Magnificent", ImageUrl = "https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcScVsGEeRBh6xZYXr6Gm35Sk5ecSlk_ax3qZmoGRAtBbZC8vJZ9" },
new Car() { Id = 3, Year = 1954, Make = "Chevrolet", Model = "Corvette", ImageUrl = "https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcSdZntu4tgWrZrxwqeuKlteCP9vJGnqUlmNq5JF1bBCf-EJy5r8" },
I know I can use JObject.Parse(data); to parse the json value - but just tring to get to it is becoming a bit of a nightmare. Is there a better way of doing this?
What I have so far:
static void Main(string[] args)
{
using (StreamWriter writer = new StreamWriter(#"c:\Data\temp\output.txt")) // file to write to
{
using (StreamReader reader = new StreamReader(#"c:\Data\temp\test.txt")) //file to read from
{
string line;
while (reader.ReadLine() != null)
{
line = reader.ReadLine();
string[] words = JsonSplitString(line);
string json = words[1];
writer.WriteLine("{0}", json);
}
}
}
}
static string[] JsonSplitString(string data)
{
return data.Split(new string[] { "ImageUrl" }, StringSplitOptions.None);
}
However I am getting a NullReferenceException - even though a string is being passed in to the JsonSplitString method.
You are calling reader.Readline() twice: once for the comparison and then again inside your loop. You are actually skipping every other line. And what is probably happening is that you are reaching the end of your file and then calling reader.Readline() again, which is null. Try this instead:
line = reader.ReadLine();
while (line != null)
{
string[] words = JsonSplitString(line);
string json = words[1];
writer.WriteLine("{0}", json);
line = reader.ReadLine();
}
using System;
using Newtonsoft.Json.Linq;
namespace JsonExperiments
{
class Program
{
static void Main(string[] args)
{
ExecuteEmployeeSearch();
Console.ReadLine();
}
static void ExecuteEmployeeSearch()
{
// mockup JSON that would be returned from API
string sampleJson = "{\"results\":[" +
"{\"employeename\":\"name1\",\"employeesupervisor\":\"supervisor1\"}," +
"{\"employeename\":\"name2\",\"employeesupervisor\":\"supervisor1\"}," +
"{\"employeename\":\"name3\",\"employeesupervisor\":[\"supervisor1\",\"supervisor2\"]}" +
"]}";
// Parse JSON into dynamic object, convenient!
JObject results = JObject.Parse(sampleJson);
// Process each employee
foreach (var result in results["results"])
{
// this can be a string or null
string employeeName = (string)result["employeename"];
// this can be a string or array, how can we tell which it is
JToken supervisor = result["employeesupervisor"];
string supervisorName = "";
if (supervisor is JValue)
{
supervisorName = (string)supervisor;
}
else if (supervisor is JArray)
{
// can pick one, or flatten array to a string
supervisorName = (string)((JArray)supervisor).First;
}
Console.WriteLine("Employee: {0}, Supervisor: {1}", employeeName, supervisorName);
}
}
}
}
Related
I've managed to create a payment using the C# .NET SDK, however it keeps showing up as 'unapplied' when I check in QBO.
I am providing the Invoice ID and tried to follow their developer API documentation but I been at this so long now that maybe I am missing something?
The following code creates the payment but doesn't 'receive' the payment towards the invoice, is there something I missed or need to do in order for the two to be linked together?
Payment payment = new Payment
{
ProcessPayment = false,
CustomerRef = new ReferenceType { name = customer.DisplayName, Value = customer.Id },
CurrencyRef = new ReferenceType { type = "Currency", Value = "CAD" },
TotalAmt = amount,
TotalAmtSpecified = true
};
if (method == PaymentTypes.Cash)
{
var paymentType = paymentMethods.FirstOrDefault(o => o.Id == "1");
if (paymentType != null)
{
payment.PaymentMethodRef = new ReferenceType()
{name = paymentType.Name, Value = paymentType.Id};
}
}
if (method == PaymentTypes.DebitCard)
{
var paymentType = paymentMethods.FirstOrDefault(o => o.Id == "9");
if (paymentType != null)
{
payment.PaymentMethodRef = new ReferenceType()
{ name = paymentType.Name, Value = paymentType.Id };
}
}
if (method == PaymentTypes.CreditCard)
{
var paymentType = paymentMethods.FirstOrDefault(o => o.Id == "8");
if (paymentType != null)
{
payment.PaymentMethodRef = new ReferenceType()
{ name = paymentType.Name, Value = paymentType.Id };
}
}
List<LinkedTxn> linkedTxns = new List<LinkedTxn>
{
new LinkedTxn()
{
TxnId = invoice.Id,
TxnType = TxnTypeEnum.Invoice.ToString()
},
};
foreach (Line line in invoice.Line)
{
//line.Amount = amount;
//line.AmountSpecified = true;
line.Received = amount;
line.ReceivedSpecified = true;
line.DetailType = LineDetailTypeEnum.PaymentLineDetail;
line.DetailTypeSpecified = true;
line.LinkedTxn = linkedTxns.ToArray();
}
payment.DepositToAccountRef = new ReferenceType() { Value = "5" };
payment.Line = invoice.Line;
payment.PaymentRefNum = reference;
DataService dataService = new DataService(serviceContext);
dataService.Add<Payment>(payment);
This is not an answer. However there's too much to add to the comments. I'm hoping this will be a helpful starting point (if not I'll remove it later).
Firstly I'd suggest refactoring your code and parameterise your variables. Doing so you should be able to preform repeatable testing in isolation.
When you preform the dataService.Add<Payment>(payment), store the response object as it may offer clues on how the request was processed. Alternatively if this is suppressing error messages, you might want to try an use Postman to send HTTP requests. This may help determine what's parameters are missing/ incorrect.
Avoid creating objects that are partially assigned it makes it a lot easier to read 7 work out which properties need to be assigned.
Also if you have a look at Full update a payment section on https://developer.intuit.com/app/developer/qbo/docs/api/accounting/all-entities/payment
the json payload has an additional Line with the property TxnType set to CreditMemo. I would assume you'll need to add something like ReceivePayment or CreditCardPayment?
To refactor your code consider:
// TODO - Set variables for testing purposes.
// This can be added as params to a method.
decimal amount = 100;
string reference = "";
string invoiceId = ""; // invoice.Id
string customerDisplayName = ""; //customer.DisplayName
string customerId = ""; //customer.Id
string paymentName = "Cash"; // paymentType.Name
string paymentId = "1"; // paymentType.Id
List<Line> lines = new List<Line>(); // invoice.Line
if(lines.Count() == 0)
{
// TODO: You might want to check there are lines?
throw new ArgumentException("No invoice.");
}
Line[] invoiceLines = lines.Select(m => new Line()
{
AnyIntuitObject = m.AnyIntuitObject,
Amount = m.Amount,
AmountSpecified = m.AmountSpecified,
CustomField = m.CustomField,
Id = m.Id,
LineNum = m.LineNum,
Description = m.Description,
DetailType = LineDetailTypeEnum.PaymentLineDetail, //m.DetailType,
DetailTypeSpecified = true, //m.DetailTypeSpecified,
LinkedTxn = new List<LinkedTxn>
{
new LinkedTxn()
{
TxnId = invoiceId,
TxnType = TxnTypeEnum.Invoice.ToString() // TODO: Should this be ReceivePayment?
},
}.ToArray(), //m.LinkedTxn,
LineEx = m.LineEx,
Received = amount, //m.Received,
ReceivedSpecified = true // m.ReceivedSpecified
}).ToArray();
Payment payment = new Payment
{
ProcessPayment = false,
CustomerRef = new ReferenceType { name = customerDisplayName, Value = customerId },
CurrencyRef = new ReferenceType { type = "Currency", Value = "CAD" },
TotalAmt = amount,
TotalAmtSpecified = true,
DepositToAccountRef = new ReferenceType() { Value = "5" },
Line = invoiceLines, // Variable is for debugging purposes - it should be inline or call a method.
PaymentRefNum = reference,
PaymentMethodRef = new ReferenceType()
{
name = paymentName,
Value = paymentId,
}
};
DataService dataService = new DataService(serviceContext);
Payment results = dataService.Add<Payment>(payment);
var json = JsonConvert.SerializeObject(results);
Console.Write(json); // TODO - Use break point/ or write response somewhere for clues.
I have a problem. I have 2 Android.Support.V4.App.Fragments
In the first Framgent I use this code:
AgentSpinnerAdapter = new ArrayAdapter<string>(Context, Android.Resource.Layout.SimpleSpinnerDropDownItem);
AgentSpinner.Adapter = AgentSpinnerAdapter;
foreach (string[] str in NamesArray)
{
string AgentId = str[0];
string Owner = str[1];
string Exchange = str[2];
string Remark = str[3];
AgentSpinnerAdapter.Add("Agent " + AgentId + " - " + Owner + " - " + Remark);
}
In the second Fragment I call this line:
dbValue = Fragment1.AgentSpinnerAdapter.GetItem(0);
But it says that AgentSpinnerAdapter is a nullreference, which is weird, because it get's filled. I have set the AgentSpinnerAdapter to Public static. Also in my MainActivity I first create Fragment1 and then Fragment2 like this:
Fragment1 = Fragment1.NewInstance();
Fragment2 = Fragment2.NewInstance();
What am I doing wrong?
UPDATE
Here is the full Fragment1.cs method
public void LoadAgentSpinner()
{
string json = "";
try
{
string html = string.Empty;
string url = "https://www.efy.nl/app/getagents.php";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
IgnoreBadCertificates();
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
using (Stream stream = response.GetResponseStream())
using (StreamReader reader = new StreamReader(stream))
{
json = reader.ReadToEnd();
}
}
catch (Exception ex1)
{
try
{
WebClient client = new WebClient();
NameValueCollection fields = new NameValueCollection();
fields.Add("error", ex1.GetBaseException().ToString());
string url = "https://www.mywebsite.com";
IgnoreBadCertificates();
byte[] respBytes = client.UploadValues(url, fields);
string resp = client.Encoding.GetString(respBytes);
SelectedQuantity.Text = "";
SelectedLimit.Text = "";
}
catch (Exception ex2)
{
string exFullName = (ex2.GetType().FullName);
string ExceptionString = (ex2.GetBaseException().ToString());
}
}
//Parse json content
var jObject = JObject.Parse(json);
//Create Array from everything inside Node:"Coins"
var agentPropery = jObject["Agents"] as JArray;
//Create List to save Coin Data
agentList = new List<agent>();
//Find every value in Array: coinPropery
foreach (var property in agentPropery)
{
//Convert every value in Array to string
var propertyList = JsonConvert.DeserializeObject<List<agent>>(property.ToString());
//Add all strings to List
agentList.AddRange(propertyList);
}
//Get all the values from Name, and convert it to an Array
string[][] NamesArray = agentList.OrderBy(i => i.AgentId)
.Select(i => new string[] { i.AgentId.ToString(), i.Owner, i.Exchange, i.Remark })
.Distinct()
.ToArray();
AgentSpinnerAdapter = new ArrayAdapter<string>(Context, Android.Resource.Layout.SimpleSpinnerDropDownItem);
AgentSpinner.Adapter = AgentSpinnerAdapter;
foreach (string[] str in NamesArray)
{
string AgentId = str[0];
string Owner = str[1];
string Exchange = str[2];
string Remark = str[3];
AgentSpinnerAdapter.Add("Agent " + AgentId + " - " + Owner + " - " + Remark); // format your string here
}
if(MainActivity.db.CheckExistTableSettings("Default Agent") == true)
{
string Value = MainActivity.db.SelectValueFromTableSettings("Default Agent");
int spinnerPosition = AgentSpinnerAdapter.GetPosition(Value);
AgentSpinner.SetSelection(spinnerPosition);
}
else
{
AgentSpinner.SetSelection(0);
}
}
In a few of my applications it's necessary to access the other fragments from my main Activity, so we do the following:
public class MainActivity : AppCompatActivity, BottomNavigationView.IOnNavigationItemSelectedListener
{
public static Dictionary<string, Fragment> FragmentList { get; set; }
private Fragment currentFragment = null;
private BottomNavigationView navigation;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.layout_mainactivity);
// create our fragments and initialise them early.
if (FragmentList == null)
{
FragmentList = new Dictionary<string, Fragment>
{
{ "main", MainFragment.NewInstance() },
{ "bugreport", BugReportFragment.NewInstance() },
{ "settings", SettingsFragment.NewInstance() }
};
}
navigation = FindViewById<BottomNavigationView>(Resource.Id.bottom_nav);
navigation.SetOnNavigationItemSelectedListener(this);
navigation.SelectedItemId = Resource.Id.navigation_main;
}
public bool OnNavigationItemSelected(IMenuItem item)
{
if (!popAction)
{
navigationResourceStack.Push(item.ItemId);
}
switch (item.ItemId)
{
case Resource.Id.navigation_main:
currentFragment = FragmentList["main"];
break;
case Resource.Id.navigation_settings:
currentFragment = FragmentList["settings"];
break;
case Resource.Id.navigation_bugreport:
currentFragment = FragmentList["bugreport"];
break;
}
if (currentFragment == null)
{
return false;
}
else
{
FragmentManager.BeginTransaction().Replace(Resource.Id.frame_content, currentFragment).Commit();
return true;
}
}
}
What this means is you could do something like MainActivity.FragmentList["main"] and then call any public method on the actual initialized class because a pointer to it is stored within the dictionary.
using System;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
namespace LearningJustCode
{
class Program
{
static void Main(string[] args)
{
Update();
}
static void Update()
{
var quote1 = new { Stock = "DELL", Quote = GetQuote("DELL") };
var quote2 = new { Stock = "MSFT", Quote = GetQuote("MSFT") };
var quote3 = new { Stock = "GOOG", Quote = GetQuote("GOOG") };
var quotes = new object[] { quote1, quote2, quote3 };
foreach (var item in quotes)
{
Console.WriteLine(item.Stock);
Console.WriteLine(item.Quote.ToString());
}
Console.ReadKey();
}
static string GetQuote(string stock)
{
try
{
return InnerGetQuote(stock);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return "N/A";
}
}
static string InnerGetQuote(string stock)
{
string url = #"http://www.webservicex.net/stockquote.asmx/GetQuote?symbol={0}";
var request = HttpWebRequest.Create(string.Format(url, stock));
using (var response = request.GetResponse())
{
using (var reader = new StreamReader(response.GetResponseStream(), Encoding.ASCII))
{
return reader.ReadToEnd();
}
}
}
}
}
I am getting an squiggley over item;Variable 'item' is only assigned to. This code has been slightly modified from Paul Kimmel's book C# Unleashed by Sams.
Your array needs to be of the type of your stock quote.
Your stock quote is an anonymous type, so we need to define the array anonymously as well. This can be done cleanly as:
var quotes = new[]{ new { Stock = "DELL", Quote = "123" },
new { Stock = "MSFT", Quote = "123" },
new { Stock = "GOOG", Quote = "123" }};
foreach (var item in quotes)
{
Console.WriteLine(item.Stock);
Console.WriteLine(item.Quote.ToString());
}
i guess the problem is in that line:
var quotes = new object[] { quote1, quote2, quote3 };
quotes is a object array, not an array of that anonymous type. the foreach also has just the object value. you could try to form the array within one line or within a lambda expression
A very dirty workaround is changing 'var' to 'dynamic'
var quote1 = new { Stock = "DELL", Quote = ("DELL") };
var quote2 = new { Stock = "MSFT", Quote = ("MSFT") };
var quote3 = new { Stock = "GOOG", Quote = ("GOOG") };
var quotes = new object[] { quote1, quote2, quote3 };
foreach (dynamic item in quotes)
{
var r = item.Stock;
}
a cleaner solution is leaving out 'object', so the compiler can generate an anonymous typed array
var quote1 = new { Stock = "DELL", Quote = ("DELL") };
var quote2 = new { Stock = "MSFT", Quote = ("MSFT") };
var quote3 = new { Stock = "GOOG", Quote = ("GOOG") };
var quotes = new [] { quote1, quote2, quote3 };
foreach (var item in quotes)
{
var r = item.Stock;
}
I'm trying to send a mail chimp campaign using asp.net, actually i created successfully the campaign and i can see it through my profile but also i want to send it through my code here is my code so if any one can help!!
private static void CreateCampaignAndSend(string apiKey, string listID)
{
Int32 TemplateID = 0;
string campaignID = string.Empty;
// compaign Create Options
var campaignCreateOpt = new campaignCreateOptions
{
list_id = listID,
subject = "subject",
from_email = "cbx#abc.com",
from_name = "abc",
template_id = TemplateID
};
// Content
var content = new Dictionary<string, string>
{
{"html", "Lots of cool stuff here."}
};
// Conditions
var csCondition = new List<campaignSegmentCondition>();
var csC = new campaignSegmentCondition {field = "interests-" + 123, op = "all", value = ""};
csCondition.Add(csC);
// Options
var csOptions = new campaignSegmentOptions {match = "all"};
// Type Options
var typeOptions = new Dictionary<string, string>
{
{"offset-units", "days"},
{"offset-time", "0"},
{"offset-dir", "after"}
};
// Create Campaigns
var campaignCreate = new campaignCreate(new campaignCreateInput(apiKey, EnumValues.campaign_type.plaintext, campaignCreateOpt, content, csOptions, typeOptions));
campaignCreateOutput ccOutput = campaignCreate.Execute();
campaignSendNow c=new campaignSendNow();
List<Api_Error> error = ccOutput.api_ErrorMessages; // Catching API Errors
if (error.Count <= 0)
{
campaignID = ccOutput.result;
}
else
{
foreach (Api_Error ae in error)
{
Console.WriteLine("\n ERROR Creating Campaign : ERRORCODE\t:" + ae.code + "\t ERROR\t:" + ae.error);
}
}
}
I downloaded an example application for using some web services with an online system.
I am not sure if all code below is needed but it is what I got and what I am trying to do is to use the search function.
I start by calling searchCustomer with an ID I have:
partnerRef.internalId = searchCustomer(customerID);
And the code for searchCustomer:
private string searchCustomer(string CustomerID)
{
string InternalID = "";
CustomerSearch custSearch = new CustomerSearch();
CustomerSearchBasic custSearchBasic = new CustomerSearchBasic();
String nameValue = CustomerID;
SearchStringField entityId = null;
entityId = new SearchStringField();
entityId.#operator = SearchStringFieldOperator.contains;
entityId.operatorSpecified = true;
entityId.searchValue = nameValue;
custSearchBasic.entityId = entityId;
String statusKeysValue = "";
SearchMultiSelectField status = null;
if (statusKeysValue != null && !statusKeysValue.Trim().Equals(""))
{
status = new SearchMultiSelectField();
status.#operator = SearchMultiSelectFieldOperator.anyOf;
status.operatorSpecified = true;
string[] nskeys = statusKeysValue.Split(new Char[] { ',' });
RecordRef[] recordRefs = new RecordRef[statusKeysValue.Length];
for (int i = 0; i < nskeys.Length; i++)
{
RecordRef recordRef = new RecordRef();
recordRef.internalId = nskeys[i];
recordRefs[i] = recordRef;
}
status.searchValue = recordRefs;
custSearchBasic.entityStatus = status;
}
custSearch.basic = custSearchBasic;
SearchResult response = _service.search(custSearch);
if (response.status.isSuccess)
{
processCustomerSearchResponse(response);
if (seachMoreResult.status.isSuccess)
{
processCustomerSearchResponse(seachMoreResult);
return InternalID;
}
else
{
_out.error(getStatusDetails(seachMoreResult.status));
}
}
else
{
_out.error(getStatusDetails(response.status));
}
return InternalID;
}
In the code above processCustomerSearchResponse gets called
processCustomerSearchResponse(response);
The code for this function is:
public string processCustomerSearchResponse(SearchResult response)
{
string InternalID = "";
Customer customer;
customer = (Customer)records[0];
InternalID = customer.internalId;
return InternalID;
}
What the original code did was to write some output in the console but I want to return the InternalID instead. When I debug the application InternalID in processCustomerSearchResponse contains the ID I want but I don't know how to pass it to searchCustomer so that function also returns the ID. When I debug searchCustomer InternalID is always null. I am not sure on how to edit the code under response.status.isSuccess
to return the InternalID, any ideas?
Thanks in advance.
When you call processCustomerSearchResponse(response);, you need to store the return value in memory.
Try modifying your code like this:
InternalID = processCustomerSearchResponse(response);