Making a switch to work against items in an array - c#

I'm using authorize.net AIM, the sample code they provide prints an ordered list of the response values. Rather than print out an ordered list to the screen where the customer would see all this information, how do I set up a switch to access certain indexs of the array and do something based on the text returned for the particular array index?
String post_response;
HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();
using (StreamReader responseStream = new StreamReader(objResponse.GetResponseStream()))
{
post_response = responseStream.ReadToEnd();
responseStream.Close();
}
// the response string is broken into an array
// The split character specified here must match the delimiting character specified above
Array response_array = post_response.Split('|');
// the results are output to the screen in the form of an html numbered list.
resultSpan.InnerHtml += "<OL> \n";
foreach (string value in response_array)
{
resultSpan.InnerHtml += "<LI>" + value + " </LI> \n";
}
resultSpan.InnerHtml += "</OL> \n";

Change the type of response_array to string[]:
string[] response_array = post_response.Split('|');
In C# you can switch on a string:
switch (response_array[0])
{
case "foo":
// do something...
break;
case "bar":
// do something else...
break;
default:
// Error?
break;
}

Related

Get Xml Data From URL

How can I get a list of items straight from the xml file that is on the host?
More precisely, I want to This xml file http://gamerpro.webd.pl/data/modlist.xml I pulled out a list of items and listened to the code
If (! File.Exists ("received list of items"))
{
Await client.DownloadFileTaskAsync (new Uri (url + "received item list"), dir + "received item list");
}
using System;
using System.Xml;
namespace ReadXMLfromURL
{
/// <summary>
/// Summary description for Class1.
/// </summary>
class Class1
{
static void Main(string[] args)
{
String URLString = "http://localhost/books.xml";
XmlTextReader reader = new XmlTextReader (URLString);
while (reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.Element: // The node is an element.
Console.Write("<" + reader.Name);
while (reader.MoveToNextAttribute()) // Read the attributes.
Console.Write(" " + reader.Name + "='" + reader.Value + "'");
Console.Write(">");
Console.WriteLine(">");
break;
case XmlNodeType.Text: //Display the text in each element.
Console.WriteLine (reader.Value);
break;
case XmlNodeType. EndElement: //Display the end of the element.
Console.Write("</" + reader.Name);
Console.WriteLine(">");
break;
}
}
}
}
}
You could do something like this
// Make your request
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, requestURL);
request.Headers.Add("Accept", "application/xml");
HttpResponseMessage response = client.SendAsync(request).Result;
// Parse your response
if (response.IsSuccessStatusCode)
{
using (Stream httpResponseStream = response.Content.ReadAsStreamAsync().Result)
{
XDocument responseXML = XDocument.Load(httpResponseStream);
// My Chosen element is the element you're looking for
IEnumerable<XElement> myElements = responseXML.Root.Elements("MyChosenElement");
foreach (XElement myEl in myElements)
{
// Access each element like this myEl.Child
// Do what you'd like with it
}
}
}

Reading in first line of csv file and saving to a list without using ',' split

I have a csv file that I need to read in the first line and save it to a List. Only problem is there are commas in some of the text and it is splitting in the middle of a field when I need it not to. Unfortunately I cannot change the data inside so whats there needs to stay. I currently also write the data to csv so I was thinking maybe instead of using a comma I can use a different character. Does anyone know if this is possible? I have been researching but am not coming up with a proper answer. Here is my code below:
using System;
using System.CodeDom;
using System.IO;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace TestJSON
{
class Program
{
static void Main()
{
var data = JsonConvert.DeserializeObject<dynamic>(File.ReadAllText(
#"C:\Users\nphillips\workspace\2016R23\UITestAutomation\SeedDataGenerator\src\staticresources\seeddata.resource"));
string fileName = "";
var bundles = data.RecordSetBundles;
foreach (var bundle in bundles)
{
var records = bundle.Records;
foreach (var record in records)
{
var test = record.attributes;
foreach (var testagain in test)
{
// Getting the object Name Ex. Location, Item, etc.
var jprop = testagain as JProperty;
if (jprop != null)
{
fileName = jprop.First.ToString().Split('_')[2]+ ".csv";
}
break;
}
string header = "";
string value = "";
foreach (var child in record)
{
var theChild = child as JProperty;
if (theChild != null && !theChild.Name.Equals("attributes"))
{
header += child.Name + ",";
value += child.Value.ToString() + ",";
}
}
value += "+" + Environment.NewLine;
if (!File.Exists(fileName))
{
header += "+" + Environment.NewLine;
File.WriteAllText(fileName, header);
}
else
{
// Need to read in here
var readCSV = new StreamReader(fileName);
var splits = readCSV.ReadLine();
}
File.AppendAllText(fileName, value);
}
}
}
}
}
You need to know how the file is delimited. I would guess that this file is tab delimited, so split on that instead.
Assuming your line is called myCSVLine... I.E
string seperator = "\t";
string[] splitLine = myCSVLine.Split(seperator.ToCharArray());
splitLine would now have all of your strings, including ones with commas

Extract text from <1></1> (HTML/XML-Like but with Number Tag)

So I have a long string containing pointy brackets that I wish to extract text parts from.
string exampleString = "<1>text1</1><27>text27</27><3>text3</3>";
I want to be able to get this
1 = "text1"
27 = "text27"
3 = "text3"
How would I obtain this easily? I haven't been able to come up with a non-hacky way to do it.
Thanks.
Using basic XmlReader and some other tricks to do wrapper to create XML-like data, I would do something like this
string xmlString = "<1>text1</1><27>text27</27><3>text3</3>";
xmlString = "<Root>" + xmlString.Replace("<", "<o").Replace("<o/", "</o") + "</Root>";
string key = "";
List<KeyValuePair<string,string>> kvpList = new List<KeyValuePair<string,string>>(); //assuming the result is in the KVP format
using (XmlReader xmlReader = XmlReader.Create(new StringReader(xmlString))){
bool firstElement = true;
while (xmlReader.Read()) {
if (firstElement) { //throwing away root
firstElement = false;
continue;
}
if (xmlReader.NodeType == XmlNodeType.Element) {
key = xmlReader.Name.Substring(1); //cut of "o"
} else if (xmlReader.NodeType == XmlNodeType.Text) {
kvpList.Add(new KeyValuePair<string,string>(key, xmlReader.Value));
}
}
}
Edit:
The main trick is this line:
xmlString = "<Root>" + xmlString.Replace("<", "<o").Replace("<o/", "</o") + "</Root>"; //wrap to make this having single root, o is put to force the tagName started with known letter (comment edit suggested by Mr. chwarr)
Where you first replace all opening pointy brackets with itself + char, i.e.
<1>text1</1> -> <o1>text1<o/1> //first replacement, fix the number issue
and then reverse the sequence of all the opening point brackets + char + forward slash to opening point brackets + forward slash + char
<o1>text1<o/1> -> <o1>text1</o1> //second replacement, fix the ending tag issue
Using simple WinForm with RichTextBox to print out the result,
for (int i = 0; i < kvpList.Count; ++i) {
richTextBox1.AppendText(kvpList[i].Key + " = " + kvpList[i].Value + "\n");
}
Here is the result I get:
This is far from bulletproof, but you could use a combination of split and Regex matching:
string exampleString = "<1>text1</1><27>text27</27><3>text3</3>";
string[] results = exampleString.Split(new string[] { "><" }, StringSplitOptions.None);
Regex r = new Regex(#"^<?(\d+)>([^<]+)<");
foreach (string result in results)
{
Match m = r.Match(result);
if (m.Success)
{
string index = m.Groups[1].Value;
string value = m.Groups[2].Value;
}
}
The most non-bulletproof example I can think of is if your text contains a "<", that would pretty much break this.

StreamReader case sensitive

My program currently reads a text file and compares it with the value in a text box and then tells me how many matches, this currently works.
My query is that it is case sensitive. Is there any way to make it so it doesn't matter whether it is in upper or lower case?
This is my code below:
if (!String.IsNullOrEmpty(CustodianEAddress.Text))
{
for (AddressLength1 = 0; AddressLength1 < Length; AddressLength1++)
{
List<string> list1 = new List<string>();
using (StreamReader reader = new StreamReader(FileLocation))
{
string line1;
//max 500
string[] LineArray1 = new string[500];
while ((line1 = reader.ReadLine()) != null)
{
list1.Add(line1); // Add to list.
if (line1.IndexOf(cust1[AddressLength1].ToString()) != -1)
{
count1++;
LineArray1[count1] = line1;
}
}
reader.Close();
using (System.IO.StreamWriter filed =
new System.IO.StreamWriter(FileLocation, true))
{
filed.WriteLine("");
filed.WriteLine("The email address " +
cust1[AddressLength1].ToString() + " was found " + count1 +
" times within the recipient's inbox");
}
string count1a;
count1a = count1.ToString();
}
}
}
else
{
MessageBox.Show("Please Enter an Email Address");
}
So basically, I need to compare the value in cust1[AddressLength1] with any values found in an array which is in the text file.
String.Compare() takes in an optional parameter that let's you specify whether or not the equality check should be case sensitive.
Edited in response to code being posted
Compare and Index of both take in an optional enumeration, StringComparison. If you choose StringComparison.OrdinalIgnoreCase then case will be ignored.
Here's a quick way to compare two strings without checking case:
string a;
string b;
string.Compare(a, b, true);
The true here is passed as the value of the ignoreCase parameter, meaning that upper and lower-case letters will be compared as if they were all the same case.
EDIT:
I've cleaned up your code a bit, and also put in the compare function. I included comments where I changed stuff:
// Not needed: see below. List<string> list1 = new List<string>();
using (StreamReader reader = new StreamReader(FileLocation))
{
string line1;
//max 500
List<string> LineArray1 = new List<string>();
while ((line1 = reader.ReadLine()) != null)
{
// list1.Add(line1); // Add to list.
// By adding to the list, then searching it, you are searching the whole list for every single new line - you're searching through the same elements multiple times.
if (string.Compare(line1, cust1[AddressLength1].ToString(), true) == 0)
{
// You can just use LineArray1.Count for this instead. count1++;
LineArray1.Add(line1);
}
}
// Not needed: using() takes care of this. reader.Close();
using (System.IO.StreamWriter filed =
new System.IO.StreamWriter(FileLocation, true))
{
filed.WriteLine(); // You don't need an empty string for a newline.
filed.WriteLine("The email address " +
cust1[AddressLength1].ToString() + " was found " + LineArray1.Count +
" times within the recipient's inbox");
}
string count1a;
count1a = LineArray1.Count.ToString();
}
The fact you are reading from a file or not it does not matter, when compare
use the static string Comapare function:
public static int Compare(
string strA,
string strB,
bool ignoreCase
)
and pass true as a last parameter.

Bing Geocoding Help

I'm trying to use Bing's REST api to geocode. But my 'y' value is always null when I check my database. Any help would be appreciated.
private void Bing(geodata address)
{
try
{
string query;
//Create a new instance for holding geocoded data
currentdata newaddress = new currentdata();
newaddress.agency = address.agency;
newaddress.calltime = address.calltime;
newaddress.city = address.city;
newaddress.state = address.state;
newaddress.incidentType = address.incidentType;
newaddress.intersection = address.intersection.Replace("&", "and");
query = newaddress.intersection.ToString() + " " + newaddress.city.ToString() + " " + newaddress.state.ToString();
// query = query.Replace("&", "and");
//Geocoder returns data in XML format so we need to
//create a new instance of XMLTextReader and provide an url
XmlTextReader reader = new XmlTextReader
("http://dev.virtualearth.net/REST/v1/Locations/" + query + "?o=xml&key=MYBINGKEY");
//Specify the way how white space is handled
reader.WhitespaceHandling = WhitespaceHandling.Significant;
//Start reading geocoded data
while (reader.Read())
{
string node = reader.Name.ToString(); //current node in XML document
string value = reader.ReadString(); //value/inner text of current XML node
switch (node)
{
case "Name":
newaddress.intersection = value;
break;
case "Latitude":
newaddress.y = double.Parse(value);
break;
case "Longitude":
newaddress.x = double.Parse(value);
break;
default:
continue;
}
}
//Add geocoded address to our table
cD.currentdatas.InsertOnSubmit(newaddress);
cD.SubmitChanges();
}
catch
{
}
}
Does your location info contains a period (.), a comma (,), a colon (:) or a plus sign (+)? You should use the Unstructured URL syntax if this is the case. Info here:

Categories