Paypal PDT with C# - c#

I'm trying to implement a shopping cart tracking system using pdt with C#.
the trouble i have is finding an example of the paypal succes postback, especially in case of multiple items !
Any help woul be appreciated (some code will be much better :D)!
Thanks

The code below parses PDT response:
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration;
using System.Globalization;
using System.Net;
using System.IO;
using System.Text;
namespace PayPal
{
public static class PaymentDataTransfer
{
private const string AppSetting_Identity = "PayPal.PaymentDataTransfer.Identity";
private const string AppSetting_ServiceUrl = "PayPal.PaymentDataTransfer.ServiceUrl";
public class TransactionStatus
{
public bool Success { get; set; }
public int ErrorCode { get; set; }
public NameValueCollection Parameters { get; set; }
public float PaymentGross { get; set; }
public string Currency { get; set; }
public string Invoice { get; set; }
public PayerInformation Payer { get; set; }
public CartItem[] CartItems;
}
public class PayerInformation
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
}
public class CartItem
{
public int Number { get; set; }
public string Name { get; set; }
public int Qunatity { get; set; }
public float GrossPrice { get; set; }
}
public static TransactionStatus GetTransactionStatus(string transactionToken)
{
return GetTransactionStatus(transactionToken, false);
}
public static TransactionStatus GetTransactionStatus(string transactionToken, bool sandbox)
{
#if ParsingTest
string response =
#"SUCCESS
mc_gross=1100.00
invoice=334354
protection_eligibility=Eligible
address_status=confirmed
item_number1=1
tax=0.00
item_number2=2
payer_id=DSFSDFSDFSDF
address_street=1+Main+St
payment_date=04%3A13%3A49+Oct+20%2C+2011+PDT
payment_status=Completed
charset=windows-1252
address_zip=95131
mc_shipping=0.00
mc_handling=0.00
first_name=Test
mc_fee=32.20
address_country_code=US
address_name=Test+User
custom=
payer_status=verified
business=yourbusiness%40business.com
address_country=United+States
num_cart_items=2
mc_handling1=0.00
mc_handling2=0.00
address_city=San+Jose
payer_email=payer_email%40business.com
mc_shipping1=0.00
mc_shipping2=0.00
txn_id=0SDFSDFSDFSDFD
payment_type=instant
last_name=User
address_state=CA
item_name1=First+test+item
receiver_email=yourbusiness%40business.com
item_name2=Second+test+item
payment_fee=32.20
quantity1=1
quantity2=1
receiver_id=SDFGDFGDFGDFDFG
txn_type=cart
mc_gross_1=1000.00
mc_currency=USD
mc_gross_2=100.00
residence_country=US
transaction_subject=Shopping+Cart
payment_gross=1100.00";
#else
string authToken = GetAppSetting(AppSetting_Identity, sandbox);
string serviceUrl = GetAppSetting(AppSetting_ServiceUrl, sandbox);
string query = string.Format("cmd=_notify-synch&tx={0}&at={1}", transactionToken, authToken);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(serviceUrl);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = query.Length;
using (var requestStreamWriter = new StreamWriter(request.GetRequestStream(), Encoding.ASCII))
{
requestStreamWriter.Write(query);
requestStreamWriter.Close();
}
string response;
// Do the request to PayPal and get the response
using(StreamReader stIn = new StreamReader(request.GetResponse().GetResponseStream()))
{
response = stIn.ReadToEnd();
stIn.Close();
}
#endif
string[] lines = response.Split(new []{"\n", "\r\n"}, StringSplitOptions.None); // splitting up by line breaks
var result = new TransactionStatus
{
Success = lines[0] == "SUCCESS",
Parameters = new NameValueCollection()
};
for(int i=1; i < lines.Length; i++)
{
string line = lines[i];
string[] keyValuePair = lines[i].Split(new [] {'='});
if(keyValuePair.Length == 2)
{
result.Parameters.Add(UrlDecode(keyValuePair[0]), UrlDecode(keyValuePair[1]));
}
else
{
const string errorCodePrefix = "Error:";
if(line.StartsWith(errorCodePrefix))
{
result.ErrorCode = Int32.Parse(line.Substring(errorCodePrefix.Length));
}
}
}
if(result.Success)
{
result.Invoice = result.Parameters["invoice"];
result.Payer = new PayerInformation
{
FirstName = result.Parameters["first_name"],
LastName = result.Parameters["last_name"],
Email = result.Parameters["payer_email"]
};
float paymentGross;
result.PaymentGross = float.TryParse(result.Parameters["mc_gross"],
NumberStyles.Float,
CultureInfo.InvariantCulture,
out paymentGross) ? paymentGross : 0.0f;
result.Currency = result.Parameters["mc_currency"];
int cartItemsNumber;
if (int.TryParse(result.Parameters["num_cart_items"], out cartItemsNumber) && cartItemsNumber > 0)
{
var cartItems = new List<CartItem>();
for(int i=1; i <= cartItemsNumber; i++)
{
cartItems.Add(new CartItem
{
Number = int.Parse(result.Parameters["item_number" + i], CultureInfo.InvariantCulture),
Name = result.Parameters["item_name" + i],
Qunatity = int.Parse(result.Parameters["quantity" + i], CultureInfo.InvariantCulture),
GrossPrice = float.Parse(result.Parameters["mc_gross_" + i], CultureInfo.InvariantCulture)
});
}
result.CartItems = cartItems.ToArray();
}
}
return result;
}
private static string UrlDecode(string encodedText)
{
return Uri.UnescapeDataString(encodedText.Replace("+", " "));
}
private static string GetAppSetting(string settingName, bool sandbox)
{
return ConfigurationManager.AppSettings[settingName + (sandbox ? "_sandbox" : string.Empty)];
}
}
}
The configuration part from web.config:
<appSettings>
.....
<!-- PayPal -->
<add key="PayPal.PaymentDataTransfer.Identity" value="....." />
<add key="PayPal.PaymentDataTransfer.Identity_sandbox" value="....." />
<add key="PayPal.PaymentDataTransfer.ServiceUrl" value="https://www.paypal.com/cgi-bin/webscr" />
<add key="PayPal.PaymentDataTransfer.ServiceUrl_sandbox" value="https://www.sandbox.paypal.com/cgi-bin/webscr" />
</appSettings>

I believe this book has some good examples.
http://www.amazon.com/Beginning-ASP-NET-E-Commerce-2005-ebook/dp/B001JEPVVE/ref=sr_1_2?ie=UTF8&s=digital-text&qid=1268249356&sr=8-2

Related

How to loop API pages and compare values for changing markers on map using xamarin.forms.maps iOS C#

I want to check each page values from the API and against the values to change the color of the map marker.
This is my API: http://194.141.118.43:3001/?id=0 where id is from 0 to 16
I want:
if from ?id=0 AL = 1 the marker should be green
if from ?id=0 AL = 2 the marker should be yellow
if from ?id=0 AL = 3 the marker should be orange
if from ?id=0 AL = 4 the marker should be red
So I want to check for all 17 stations (from ?id=0 to ?id=16)
I am currently checking the property Alertlevelwebsite in this method with this API: http://194.141.118.43:3001/stations, But now I have to check all the values from this address for each pin and I have to put a color for the largest value for each pin.
http://194.141.118.43:3001/?id=0 (from 0 to 16)
I use this example from xamarin.forms.maps - https://learn.microsoft.com/en-us/samples/xamarin/xamarin-forms-samples/workingwithmaps/ and in CustomMapRenderer class I try to change the colors in this method:
protected override MKAnnotationView GetViewForAnnotation(MKMapView mapView, IMKAnnotation annotation)
{
MKAnnotationView annotationView = null;
if (annotation is MKUserLocation)
return null;
var customPin = GetCustomPin(annotation as MKPointAnnotation);
//Get Value
c_annotation = annotation;
if (customPin == null)
{
throw new Exception("Custom pin not found");
}
annotationView = mapView.DequeueReusableAnnotation(customPin.Name);
if (annotationView == null)
{
annotationView = new CustomMKAnnotationView(annotation, customPin.Name);
annotationView.CalloutOffset = new CGPoint(0, 0);
((CustomMKAnnotationView)annotationView).Name = customPin.Name;
((CustomMKAnnotationView)annotationView).Url = customPin.Url;
((CustomMKAnnotationView)annotationView).Address = customPin.Address;
//Add First Line
((CustomMKAnnotationView)annotationView).AlertLevel = customPin.AlertLevel;
if (customPin.AlertLevel == 1)
{
annotationView.Image = UIImage.FromFile("green.png");
}
else if (customPin.AlertLevel == 2)
{
annotationView.Image = UIImage.FromFile("yellow.png");
}
else if (customPin.AlertLevel == 3)
{
annotationView.Image = UIImage.FromFile("orange.png");
}
else if (customPin.AlertLevel == 4)
{
annotationView.Image = UIImage.FromFile("red.png");
}
//Add Second Line
((CustomMKAnnotationView)annotationView).CodeNum = customPin.CodeNum;
((CustomMKAnnotationView)annotationView).MapCode = customPin.MapCode;
//Here I add the RequestUri for stations
string GenerateRequestUriStations(string endpoint)
{
string requestUri = endpoint;
requestUri += $"stations";
return requestUri;
}
//Here I need the loop from 0 to 16 every page and change the pin icons like above if statement
string GenerateRequestUri(string endpoint)
{
string requestUri = endpoint;
requestUri += $"?id=0";
return requestUri;
}
//This is the value who I need to compare result.WaterData.Ardaforecast but does not allow me to write result.WaterData.Ardaforecast and does not allow me to foreach here .. I don't know why ?
var reusult = _restServiceData.GetWaterDataForecast(GenerateRequestUriStations(Constants.EndPoint), GenerateRequestUri(Constants.EndPoint));
}
annotationView.CanShowCallout = true;
configureDetailView(annotationView);
return annotationView;
}
In the comments above the code I mean that when I write:
var reusult = _restServiceData.GetWaterDataForecast(GenerateRequestUriStations(Constants.EndPoint), GenerateRequestUri(Constants.EndPoint));
foreach (var item in IAsyncResult)
{
}
When I try to write result. automatic puts me IAsyncResult.. I don't know why.. ?
Can I get an example of how to loop all the pages and change colors on the markers ?
My GetDataFromAPI look like this:
public IEnumerable<AlertLevel> GetDataFromAPI(int mapCode)
{
var listAlert = new List<AlertLevel>();
var reusult = _restServiceData.GetWaterDataForecast(GenerateRequestUriStations(Constants.EndPoint), GenerateRequestUri(Constants.EndPoint, mapCode));
foreach (var item in reusult.WaterData.Ardaforecast[0].Items)
{
var currentData = new AlertLevel()
{
dateForecast = item.DateTimeForecast,
levelForecast = item.AlertLevelForecast
};
listAlert.Add(currentData);
}
return listAlert;
}
My GetWaterDataForecast look like this:
using System;
using System.Diagnostics;
using System.Net.Http;
using System.Threading.Tasks;
using MaritsaTundzhaForecast.Models;
using Newtonsoft.Json;
namespace MaritsaTundzhaForecast.Services
{
public class RestServiceData
{
HttpClient _client1;
HttpClient _client2;
public RestServiceData()
{
_client1 = new HttpClient();
_client2 = new HttpClient();
}
public WaterBindingData GetWaterDataForecast(string query, string query2)
{
WaterDataJson waterData = new WaterDataJson();
WaterStationsJson waterStations = new WaterStationsJson();
WaterBindingData result = new WaterBindingData();
try
{
var task = Task.Run(() => _client1.GetAsync(query));
task.Wait();
var response = task.Result;
var task2 = Task.Run(() => _client2.GetAsync(query2));
task2.Wait();
var response2 = task2.Result;
if (response.IsSuccessStatusCode && response2.IsSuccessStatusCode)
{
var content = response.Content.ReadAsStringAsync().Result;
var content2 = response2.Content.ReadAsStringAsync().Result;
var json = content2.Replace("\"ardaforecast\":[[", "\"ardaforecast\":[ {\"items\": [")
.Replace("}],{\"fieldCount\"", "}],\"details\":{\"fieldCount\"")
.Replace("}]}", "}}]}");
waterData = JsonConvert.DeserializeObject<WaterDataJson>(json);
waterStations = JsonConvert.DeserializeObject<WaterStationsJson>(content);
result.WaterData = waterData;
result.WaterStation = waterStations;
}
}
catch (Exception ex)
{
Debug.WriteLine("\t\tERROR {0}", ex.Message);
}
return result;
}
}
}
My WaterBindingData look like:
using System;
namespace MaritsaTundzhaForecast.Models
{
public class WaterBindingData
{
public WaterDataJson WaterData { get; set; }
public WaterStationsJson WaterStation { get; set; }
}
}
My WaterDataJson and WaterStations look like:
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
namespace MaritsaTundzhaForecast
{
public class WaterDataJson
{
public List<ForecastBody> Ardaforecast { get; set; }
}
public class ForecastBody
{
public ForecastItem[] Items { get; set; }
public ForecastDetails Details { get; set; }
}
public class ForecastItem
{
[JsonProperty("Dt")]
public DateTime DateTimeForecast { get; set; }
[JsonProperty("AL")]
public int AlertLevelForecast { get; set; }
}
public class ForecastDetails
{
public int fieldCount { get; set; }
public int affectedRows { get; set; }
public int insertId { get; set; }
public int serverStatus { get; set; }
public int warningCount { get; set; }
public int changedRows { get; set; }
public string message { get; set; }
public bool protocol41 { get; set; }
}
}
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
namespace MaritsaTundzhaForecast.Models
{
public class WaterStationsJson
{
public List<ForecastStations> Stations { get; set; }
}
public class ForecastStations
{
[JsonProperty("Map_code")]
public int MapCode { get; set; }
[JsonProperty("NAME_IME")]
public string NameEN { get; set; }
[JsonProperty("NAME_CYR")]
public string NameBG { get; set; }
[JsonProperty("Alertlevelwebsite")]
public int AlertLevelStation { get; set; }
[JsonProperty("CODENUM")]
public int CodeNum { get; set; }
}
}

How to parse JSON object using C#

I want to post data to the database where I am fetching the data in a JSON format.
Here is the following JSON string:
"[{"cph_id":"67/123/7894","phone_no":"0000623019"},
{"cph_id":"69/213/1234","phone_no":"0000623019"}]"
I have also created the following classes:
public class RootObject
{
public List<dlregistrationdata> data { get; set; }
}
public class dlregistrationdata
{
public string cph_id[] { get; set; }
public string phone_no[] { get; set; }
}
I try to deserialize using the following command:
try
{
var obj = JsonConvert.DeserializeObject<List<dlregistrationdata>>(result);
var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://172.61.25.30/CPRestApi/api/user/register");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
if (email != null)
{
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
dynamic arr = new JObject();
for (int i = 0; i < obj.Count; i++)
{
arr.cph_id = obj[i].cph_id;
arr.user_name = email;
arr.user_phone_number = obj[i].phone_no;
arr.user_password = password;
arr.status = 1;
arr.name = name;
}
streamWriter.Write(arr);
}
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
if (httpResponse.StatusCode == System.Net.HttpStatusCode.Created)
{
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result1 = streamReader.ReadToEnd();
}
return RedirectToLocal("Index");
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
ViewBag.ErrorMessage = "User Already Registered";
ModelState.AddModelError("", "User Already Registered");
return View(model);
}
But I am getting the error:
"converting value "67/123/7894" to type 'System.String[]'. Path '[0].cph_id', line 1, position 24"
Any help will be highly appreciated.
Thank You!
Changes made in model class:
public class dlregistrationdata
{
public string cph_id { get; set; }
public string phone_no { get; set; }
}
public class RequestRegistrationAPI {
public string user_name { get; set; }
public string user_password { get; set; }
public string user_phone_number { get; set; }
public string name { get; set; }
public int status { get; set; }
public string[] cph_id { get; set; }
}
Changes made in code:
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
List<string> cphid = new List<string>();
string phone_no = "";
foreach (dlregistrationdata data in obj)
{
cphid.Add(data.cph_id);
phone_no = data.phone_no;
}
RequestRegistrationAPI request = new RequestRegistrationAPI();
request.user_name = email;
request.user_password = password;
request.user_phone_number = phone_no;
request.name = name;
request.cph_id = cphid.ToArray();
request.status = 1;
streamWriter.Write(JsonConvert.SerializeObject(request));
}
This works perfectly for me.
change classes to :
public class dlregistrationdata
{
public string cph_id { get; set; }
public string phone_no { get; set; }
}
now change code to :
var obj = JsonConvert.DeserializeObject<List<dlregistrationdata>>(result);
var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://172.61.25.30/CPRestApi/api/user/register");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
if (email != null)
{
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
dynamic arr = new JObject();
for (int i = 0; i < obj.Count; i++)
{
arr.cph_id = obj[i].cph_id;
arr.user_name = email;
arr.user_phone_number = obj[i].phone_no;
arr.user_password = password;
arr.status = 1;
arr.name = name;
}
streamWriter.Write(arr);
}
}

powershell cmdlet in visual studio 2017, deserialization method

I have got a problem with undestanding powershell cmdlet.
Task is, to deserialize a xml file. I have got a folder with a lot of xml files, I would like to read in an filter certain information using the deserializiation method. My supervisor mentioned that I should use powershell cmdlet... but I haven't heard anything of it before. So what is the benefit? And how do I create such a cmdlet.
That is my code so far:
using System;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
using System.Collections.Generic;
using System.Text;
using System.Management.Automation;
namespace EdocX
{
[Cmdlet(VerbsCommon.Get, "test", SupportsShouldProcess = true)]
public class program : Cmdlet
{
public static string dirPath = #"N:\EGS_SDRE\OB\19_Schnittstellen_eDocX_ITAS\06_Matching EdocX-Objektbrief\01_exemplarische_XMLs_fuer_den_Import\RWA-Anlage"
public static List<string> dirs = new List<string>(Directory.GetFiles(dirPath, "*.xml"));
public static (string[], string[], string[,], string[,], string[,]) deserializeobject(string filename)
{
// Liste Prüfgrundlagen
List<string> pg = new List<string>();
pg.Add("GaVO");
pg.Add("VkVO");
pg.Add("VStättVO");
pg.Add("SPrüfV");
pg.Add("BetrVO");
pg.Add("BbgSGPrüfV");
pg.Add("BremAnlPrüfV");
pg.Add("PVO");
pg.Add("TPrüfVO");
pg.Add("BauPrüfVO M-V");
pg.Add("DVO-NBauO");
pg.Add("PrüfVO NRW");
pg.Add("HTechAnlV RP");
pg.Add("TPrüfVO");
pg.Add("SächsTechPrüfVO");
pg.Add("TAnlVO");
pg.Add("PrüfVO");
pg.Add("ThürTechPrüfVO");
// Auftraggeber - Var
string[] Auftraggeber;
string Name_AG = "";
string Stadt_AG = "";
string PLZ_AG = "";
string Straße_AG = "";
string Hausnummer_AG = "";
string Region_AG = "";
string PARNR_AG = "";
// Aufstellungsort - Var
string[] Aufstellungsort;
string Name_AO = "";
string Stadt_AO = "";
string PLZ_AO = "";
string Straße_AO = "";
string Hausnummer_AO = "";
string Region_AO = "";
string Land_AO = "";
// Anlage - Var
string[,] Anlagen;
string Materialnummer = "";
string EQnummer = "";
string Anlagentyp = "RWA-Anlage";
string[] InterneBezeichnung;
string[] Hersteller;
// Vorgang rückgemeldet - Var
string[,] Vorgang_rückgemeldet;
string Typ_VR = "Prüfung";
string Dienstleister = "TÜV SÜD Industrie Service GmbH";
string Durchführungsdatum = "";
string Maengel = "";
string Bemerkungstexte = "";
string Pruefgrundlage_VR = "";
// Vorgang zukünftig - Var
string[,] Vorgang_zukünftig;
string Typ_VZ = "Prüfung";
string Fälligkeit = "";
string Pruefgrundlage_VZ = "";
//****************************************************************************************************
//********************************************SERIALIZATION*******************************************
// new instance of XMLSerializer --> specifiying type
var serializer = new XmlSerializer(typeof(Document));
// read the XML document
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
var encoding = Encoding.GetEncoding("Windows-1252");
using (var sr = new StreamReader(filename, encoding, true))
using (var reader = XmlReader.Create(sr))
{
// restore the object's state using the deserialize method
var i = (Document)serializer.Deserialize(reader);
//---------------------------------------Auftraggeber-----------------------------------------------
int count_Z1ZRMPA = i.IDOC.Z1ZRMDB.Z1ZRMPA.Count;
for (int c = 0; c < count_Z1ZRMPA; c++)
{
if (i.IDOC.Z1ZRMDB.Z1ZRMPA[c].TITLE == "Auftraggeber")
{
Name_AG = i.IDOC.Z1ZRMDB.Z1ZRMPA[c].NAME1 + i.IDOC.Z1ZRMDB.Z1ZRMPA[c].NAME2;
Stadt_AG = i.IDOC.Z1ZRMDB.Z1ZRMPA[c].CITY1;
PLZ_AG = i.IDOC.Z1ZRMDB.Z1ZRMPA[c].POST_CODE1;
Straße_AG = i.IDOC.Z1ZRMDB.Z1ZRMPA[c].STREET;
Hausnummer_AG = i.IDOC.Z1ZRMDB.Z1ZRMPA[c].HOUSE_NUM1;
Region_AG = i.IDOC.Z1ZRMDB.Z1ZRMPA[c].REGION;
PARNR_AG = i.IDOC.Z1ZRMDB.Z1ZRMPA[c].PARNR;
}
//---------------------------------------Aufstellungsort----------------------------------------
if (i.IDOC.Z1ZRMDB.Z1ZRMPA[c].TITLE == "Aufstellungsort")
{
Name_AO = i.IDOC.Z1ZRMDB.Z1ZRMPA[c].NAME1 + i.IDOC.Z1ZRMDB.Z1ZRMPA[c].NAME2;
Stadt_AO = i.IDOC.Z1ZRMDB.Z1ZRMPA[c].CITY1;
PLZ_AO = i.IDOC.Z1ZRMDB.Z1ZRMPA[c].POST_CODE1;
Straße_AO = i.IDOC.Z1ZRMDB.Z1ZRMPA[c].STREET;
Hausnummer_AO = i.IDOC.Z1ZRMDB.Z1ZRMPA[c].HOUSE_NUM1;
Region_AO = i.IDOC.Z1ZRMDB.Z1ZRMPA[c].REGION;
Land_AO = i.IDOC.Z1ZRMDB.Z1ZRMPA[c].COUNTRY;
}
}
//---------------------------------------Anlage----------------------------------------------------
Materialnummer = i.IDOC.Z1ZRMDB.MABEZ;
EQnummer = i.IDOC.Z1ZRMDB.OBJNR;
int count_ANLAGEPRFTXT = i.IDOC.Z1ZRMDB.PRFBER.PRFERG.ANLAGE.PRFTXT.Count;
int AnzahlAnlagen = count_ANLAGEPRFTXT - 1;
InterneBezeichnung = new string[AnzahlAnlagen];
Hersteller = new string[AnzahlAnlagen];
for (int c = 1; c < count_ANLAGEPRFTXT; c++)
{
InterneBezeichnung[c - 1] = i.IDOC.Z1ZRMDB.PRFBER.PRFERG.ANLAGE.PRFTXT[c].ENTRBEREICH;
Hersteller[c - 1] = i.IDOC.Z1ZRMDB.PRFBER.PRFERG.ANLAGE.PRFTXT[c].HERSTELLER;
}
//---------------------------------------Vorgang rückgemeldet-------------------------------------
Durchführungsdatum = i.IDOC.Z1ZRMDB.PRFBER.DATEN.Pruefungszeitraum;
int count_PRFTXT = i.IDOC.Z1ZRMDB.PRFBER.PRFERG.PRFTXT.Count;
for (int c = 0; c < count_PRFTXT; c++)
{
if (i.IDOC.Z1ZRMDB.PRFBER.PRFERG.PRFTXT[c].KATEGORIE == "Grundlage")
{
string Pruefgrundlage = i.IDOC.Z1ZRMDB.PRFBER.PRFERG.PRFTXT[c].Value;
int count_pg = pg.Count;
for (int cc = 0; cc < count_pg; cc++)
{
if (Pruefgrundlage.Contains(pg[cc]) == true)
{
Pruefgrundlage_VR = pg[cc];
}
}
}
if (i.IDOC.Z1ZRMDB.PRFBER.PRFERG.PRFTXT[c].ROWTYPE == "Zwischenüberschrift" && i.IDOC.Z1ZRMDB.PRFBER.PRFERG.PRFTXT[c].PATTERN == "#KATEGORIE[../#KATEGORIE='Mangel' and ../#GEWICHT[not(contains(.,'Beseitigt'))]]")
{
string Maengelabruf = i.IDOC.Z1ZRMDB.PRFBER.PRFERG.PRFTXT[c].Value;
if (Maengelabruf == "Mängel")
{
Maengel = "Mängel_ja";
}
else
{
Maengel = "Mängel_nein";
}
}
if (i.IDOC.Z1ZRMDB.PRFBER.PRFERG.PRFTXT[c].ROWTYPE == "Mangel" && i.IDOC.Z1ZRMDB.PRFBER.PRFERG.PRFTXT[c].PATTERN == "#KATEGORIE[../#KATEGORIE='Mangel' and ../#GEWICHT[not(contains(.,'Beseitigt'))]]")
{
string Bemerkungstext = i.IDOC.Z1ZRMDB.PRFBER.PRFERG.PRFTXT[c].Value;
Bemerkungstexte += " " + Bemerkungstext;
}
}
//---------------------------------------Vorgang zukünftig--------------------------------------
int count_Z1ZRMAU = i.IDOC.Z1ZRMDB.Z1ZRMAU.Count;
for (int c = 0; c < count_Z1ZRMAU; c++)
{
if (i.IDOC.Z1ZRMDB.Z1ZRMAU[c].MNAME == "Nächste Wiederkehrende Prüfung")
{
Fälligkeit = i.IDOC.Z1ZRMDB.Z1ZRMAU[c].MWERT;
}
}
for (int c = 0; c < count_PRFTXT; c++)
{
if (i.IDOC.Z1ZRMDB.PRFBER.PRFERG.PRFTXT[c].KATEGORIE == "Grundlage")
{
string Pruefgrundlage = i.IDOC.Z1ZRMDB.PRFBER.PRFERG.PRFTXT[c].Value;
int count_pg = pg.Count;
for (int cc = 0; cc < count_pg; cc++)
{
if (Pruefgrundlage.Contains(pg[cc]) == true)
{
Pruefgrundlage_VZ = pg[cc];
}
}
}
}
Auftraggeber = new string[7];
Aufstellungsort = new string[7];
Anlagen = new string[AnzahlAnlagen, 5];
Vorgang_rückgemeldet = new string[AnzahlAnlagen, 6];
Vorgang_zukünftig = new string[AnzahlAnlagen, 3];
}
Auftraggeber[0] = Name_AG;
Auftraggeber[1] = Stadt_AG;
Auftraggeber[2] = PLZ_AG;
Auftraggeber[3] = Straße_AG;
Auftraggeber[4] = Hausnummer_AG;
Auftraggeber[5] = Region_AG;
Auftraggeber[6] = PARNR_AG;
Aufstellungsort[0] = Name_AO;
Aufstellungsort[1] = Stadt_AO;
Aufstellungsort[2] = PLZ_AO;
Aufstellungsort[3] = Straße_AO;
Aufstellungsort[4] = Hausnummer_AO;
Aufstellungsort[5] = Region_AO;
Aufstellungsort[6] = Land_AO;
for (int j = 0; j < Anlagen.GetLength(0); j++)
{
Anlagen[j, 0] = Materialnummer;
Anlagen[j, 1] = EQnummer;
Anlagen[j, 2] = Anlagentyp;
Anlagen[j, 3] = InterneBezeichnung[j];
Anlagen[j, 4] = Hersteller[j];
Vorgang_rückgemeldet[j, 0] = Typ_VR;
Vorgang_rückgemeldet[j, 1] = Dienstleister;
Vorgang_rückgemeldet[j, 2] = Durchführungsdatum;
Vorgang_rückgemeldet[j, 3] = Maengel;
Vorgang_rückgemeldet[j, 4] = Bemerkungstexte;
Vorgang_rückgemeldet[j, 5] = Pruefgrundlage_VR;
Vorgang_zukünftig[j, 0] = Typ_VZ;
Vorgang_zukünftig[j, 1] = Fälligkeit;
Vorgang_zukünftig[j, 2] = Pruefgrundlage_VZ;
}
return (Auftraggeber, Aufstellungsort, Anlagen, Vorgang_rückgemeldet, Vorgang_zukünftig);
}
}
}
And here the class to simulate the xml structure:
using System;
using System.Xml;
using System.Xml.Serialization;
using System.Collections.Generic;
namespace EdocX
{//ZRM01 Root Environment
[Serializable()]
[XmlRoot(ElementName = "ZRM01")]
public partial class Document
{
[XmlElement()]
public ZRM01IDOC IDOC { get; set; }
}
//IDOC
[Serializable()]
public partial class ZRM01IDOC
{
[XmlElement()]
public ZRM01IDOCZ1ZRMDB Z1ZRMDB { get; set; }
}
//IDOC Elements
[Serializable()]
public partial class ZRM01IDOCZ1ZRMDB
{
public string MABEZ { get; set; } // Materialnummer
public string OBJNR { get; set; } // Equipmentnummer
[XmlElement("Z1ZRMPA")]
public List<ZRM01IDOCZ1ZRMDBZ1ZRMPA> Z1ZRMPA = new List<ZRM01IDOCZ1ZRMDBZ1ZRMPA>(); //{ get; set; }
[XmlElement("Z1ZRMAU")]
public List<ZRM01IDOCZ1ZRMDBZ1ZRMAU> Z1ZRMAU = new List<ZRM01IDOCZ1ZRMDBZ1ZRMAU>();
[XmlElement()]
public ZRM01IDOCZ1ZRMDBPRFBER PRFBER { get; set; }
}
//Z1ZRMPA --> Mandant / Gebäude
[Serializable()]
public partial class ZRM01IDOCZ1ZRMDBZ1ZRMPA
{
[XmlAttribute()]
public string TITLE { get; set; } // "Auftraggeber" "Aufstellungsort"
[XmlElement()]
public string PARNR { get; set; } // Parnr. (Mandant)
[XmlElement()]
public string NAME1 { get; set; } // Name
[XmlElement()]
public string NAME2 { get; set; } // Name
[XmlElement()]
public string CITY1 { get; set; } // Stadt
[XmlElement()]
public string POST_CODE1 { get; set; } // PLZ
[XmlElement()]
public string STREET { get; set; } // Straße
[XmlElement()]
public string HOUSE_NUM1 { get; set; } // Hausnummer
[XmlElement()]
public string REGION { get; set; } // Region
[XmlElement()]
public string COUNTRY { get; set; } // Land
}
//Z1ZRMAU
[Serializable()]
public partial class ZRM01IDOCZ1ZRMDBZ1ZRMAU
{
[XmlElement()]
public string MNAME { get; set; } // "Nächste Wiederkehrende Prüfung"
[XmlElement()]
public string MWERT { get; set; } // Fälligkeit
}
//PRFBER Elemts
[Serializable()]
public partial class ZRM01IDOCZ1ZRMDBPRFBER
{
[XmlElement()]
public ZRM01IDOCZ1ZRMDBPRFBERPRFERG PRFERG { get; set; }
[XmlElement()]
public ZRM01IDOCZ1ZRMDBPRFBERDATEN DATEN { get; set; }
}
//DATEN
[Serializable()]
public partial class ZRM01IDOCZ1ZRMDBPRFBERDATEN
{
[XmlElement()]
public string Pruefungszeitraum { get; set; } //Durchführungsdatum
}
//PRFERG Elements
[Serializable()]
public partial class ZRM01IDOCZ1ZRMDBPRFBERPRFERG
{
[XmlElement()]
public ZRM01IDOCZ1ZRMDBPRFBERPRFERGANLAGE ANLAGE { get; set; }
[XmlElement("PRFTXT")]
public List<ZRM01IDOCZ1ZRMDBPRFBERPRFERGPRFTXT> PRFTXT = new List<ZRM01IDOCZ1ZRMDBPRFBERPRFERGPRFTXT>();
}
//ANLAGE
[Serializable()]
public partial class ZRM01IDOCZ1ZRMDBPRFBERPRFERGANLAGE
{
[XmlElement("PRFTXT")]
public List<ZRM01IDOCZ1ZRMDBPRFBERPRFERGANLAGEPRFTXT> PRFTXT = new List<ZRM01IDOCZ1ZRMDBPRFBERPRFERGANLAGEPRFTXT>();
}
//PRFTXT
[Serializable()]
public partial class ZRM01IDOCZ1ZRMDBPRFBERPRFERGANLAGEPRFTXT
{
[XmlAttribute()]
public string REF { get; set; } // Anzahl Anlagen
[XmlAttribute()]
public string HERSTELLER { get; set; } // Hersteller Anlage
[XmlAttribute()]
public string ENTRBEREICH { get; set; } // Interne Bezeichnung Anlage
}
//PRFTXT
[Serializable()]
public partial class ZRM01IDOCZ1ZRMDBPRFBERPRFERGPRFTXT
{
[XmlAttribute()]
public string KATEGORIE { get; set; } // A"Grundlage" < ... >
[XmlText()]
public string Value { get; set; }
[XmlAttribute()]
public string ROWTYPE { get; set; } // "Zwischenüberschrift" (für Mangel ja/nein) "Mangel" (für Bemerkungstext)
[XmlAttribute()]
public string PATTERN { get; set; } // "#KATEGORIE[../#KATEGORIE='Mangel' and ../#GEWICHT[not(contains(.,'Beseitigt'))]]" < Mängel > bzw < ... >
}
}
I'm very thankful for help!

XmlException When Parsing Valid XML

I have a WPF application that calls an API and creates an System.Xml.Linq.XDocument using XDocument.Parse(string). I am running into a problem where an XmlException ("Root element is missing") is thrown when I try to do this, but my XML is completely valid. I tried syntax-checking it by calling the API in my browser and checking its syntax, calling the API in my application and Console.WriteLineing the response, and using various XML syntax validators (all of which returned no errors).
A sample XML response from the API is as follows:
<?xml version="1.0" encoding="UTF-8"?>
<response>
<event title="Event 1" id="75823347" icon="www.example.com/images/event1-icon.png" uri="www.example.com/rsvp/event1" mode="none" price="10.00" cover="www.example.com/event1-cover.png" enddate="2016-06-01 14:00:00" startdate="2016-06-01 12:00:00" address="1 Example St, Example City State 12345" location="Example Place" description="This is an event" shortdescription="This is an event" theme="auto" color="#FF000000"/>
</response>
This is my application's code:
public static WebRequest CreateRequest(string baseUrl, string httpMethod, Dictionary<string, string> requestValues) {
var requestItems = requestValues == null ? null : requestValues.Select(pair => string.Format("&{0}={1}", pair.Key, pair.Value));
var requestString = "";
if (requestItems != null)
foreach (var s in requestItems)
requestString += s;
var request = WebRequest.CreateHttp(baseUrl + CredentialRequestString + requestString);
request.Method = httpMethod.ToUpper();
request.ContentType = "application/x-www-form-urlencoded";
request.Credentials = CredentialCache.DefaultCredentials;
return request;
}
public static WebRequest CreateRequest(string apiEndpoint, string endpointParam, int apiVersion, string httpMethod, Dictionary<string, string> requestValues) {
return CreateRequest(string.Format("http://www.example.com/api/v{0}/{1}/{2}", apiVersion, apiEndpoint, endpointParam), httpMethod, requestValues);
}
public static async Task<string> GetResponseFromServer(WebRequest request) {
string s;
using (var response = await request.GetResponseAsync()) {
using (var responseStream = response.GetResponseStream()) {
using (var streamReader = new StreamReader(responseStream)) {
s = streamReader.ReadToEnd();
}
}
}
return s;
}
public static async Task<List<Event>> GetEvents() {
var response = await GetResponseFromServer(CreateRequest("events", "", 1, "GET", null));
Console.WriteLine(response); //validation
var data = XDocument.Parse(response).Root; //XmlException: Root element is mising
return new List<Event>(data.Elements("event").Select(e => Event.FromXml(e.Value)));
}
Why is this happening?
The following code works
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
var data = XDocument.Load(FILENAME);
Event _event = Event.FromXml(data.Descendants("event").FirstOrDefault());
}
}
public class Event
{
public string title { get ; set; }
public string icon {get; set; }
public string uri { get; set; }
public string mode { get;set; }
public decimal price { get; set; }
public string cover { get; set; }
public DateTime enddate { get; set; }
public DateTime startdate { get; set; }
public string address { get; set; }
public string location { get; set; }
public string description { get; set; }
public string shortdescription { get; set; }
public string theme { get; set; }
public uint color { get; set; }
public static Event FromXml(XElement data)
{
Event _event = new Event();
_event.title = (string)data.Attribute("title");
_event.icon = (string)data.Attribute("icon");
_event.uri = (string)data.Attribute("uri");
_event.mode = (string)data.Attribute("mode");
_event.price = (decimal)data.Attribute("price");
_event.cover = (string)data.Attribute("cover");
_event.enddate = (DateTime)data.Attribute("enddate");
_event.startdate = (DateTime)data.Attribute("startdate");
_event.address = (string)data.Attribute("address");
_event.location = (string)data.Attribute("location");
_event.description = (string)data.Attribute("description");
_event.shortdescription = (string)data.Attribute("shortdescription");
_event.theme = (string)data.Attribute("theme");
_event.color = uint.Parse(data.Attribute("color").Value.Substring(1), System.Globalization.NumberStyles.HexNumber) ;
return _event;
}
}
}

How do i assign a value to a public const string variable?

I have this class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Web.Script.Serialization;
using System.Json;
using System.Runtime.Serialization.Json;
using System.Web.Helpers;
namespace Automatic_Record
{
class Youtube_Video_Information
{
public const string ytKey = "";
public int Width { get; set; }
public int Height { get; set; }
public int Duration { get; set; }
public string Title { get; set; }
public string ThumbUrl { get; set; }
public string BigThumbUrl { get; set; }
public string Description { get; set; }
public string VideoDuration { get; set; }
public string Url { get; set; }
public DateTime UploadDate { get; set; }
public bool YouTubeImport(string VideoID)
{
try
{
WebClient myDownloader = new WebClient();
myDownloader.Encoding = System.Text.Encoding.UTF8;
string jsonResponse = myDownloader.DownloadString("https://www.googleapis.com/youtube/v3/videos?id=" + VideoID + "&key=" + ytKey + "&part=snippet");
JavaScriptSerializer jss = new JavaScriptSerializer();
var dynamicObject = Json.Decode(jsonResponse);
var item = dynamicObject.items[0].snippet;
Title = item.title;
ThumbUrl = item.thumbnails.#default.url;
BigThumbUrl = item.thumbnails.high.url;
Description = item.description;
UploadDate = Convert.ToDateTime(item.publishedAt);
jsonResponse = myDownloader.DownloadString("https://www.googleapis.com/youtube/v3/videos?id=" + VideoID + "&key=" + ytKey + "&part=contentDetails");
dynamicObject = Json.Decode(jsonResponse);
string tmp = dynamicObject.items[0].contentDetails.duration;
Duration = Convert.ToInt32(System.Xml.XmlConvert.ToTimeSpan(tmp).TotalSeconds);
Url = "http://www.youtube.com/watch?v=" + VideoID;
return true;
}
catch (Exception ex)
{
return false;
}
}
public bool VimeoImport(string VideoID)
{
try
{
WebClient myDownloader = new WebClient();
myDownloader.Encoding = System.Text.Encoding.UTF8;
string jsonResponse = myDownloader.DownloadString("http://vimeo.com/api/v2/video/" + VideoID + ".json");
JavaScriptSerializer jss = new JavaScriptSerializer();
var dynamicObject = Json.Decode(jsonResponse);
var item = dynamicObject[0];
Title = item.title;
Description = item.description;
Url = item.url;
ThumbUrl = item.thumbnail_small;
BigThumbUrl = item.thumbnail_large;
UploadDate = Convert.ToDateTime(item.upload_date);
Width = Convert.ToInt32(item.width);
Height = Convert.ToInt32(item.height);
Duration = Convert.ToInt32(item.duration);
return true;
}
catch (Exception ex)
{
return false;
}
}
}
}
In form1 constructor i did:
Youtube_Video_Information.ytKey = "myapikey";
Youtube_Video_Information yvi = new Youtube_Video_Information();
yvi.YouTubeImport("ee-myvideoid");
The problem is that i'm getting error on:
Youtube_Video_Information.ytKey
Error 3 The left-hand side of an assignment must be a variable, property or indexer
How can i solve the error ?
How do i assign a value to a public const string variable?
You cannot. Const values cannot have a value assigned in runtime. If you need to be able to assign value in runtime, pass the value to a constructor call and make the member readonly.
class Youtube_Video_Information
{
public readonly string ytKey;
public Youtube_Video_Information(string ytKey)
{
this.ytKey = ytKey;
}
}

Categories

Resources