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;
}
}
Related
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; }
}
}
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;
}
}
}
I used HttpWebRequest to get the content from a website.
The problem is that I got a response in json and I don't really know how to use, convert and implement that data in my program.
Current code:
namespace Web_Scraper
{
class Program
{
static void Main(string[] args)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://steamcommunity.com/market/priceoverview/?currency=3&appid=440&market_hash_name=Genuine%20Purity%20Fist");
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader stream = new StreamReader(response.GetResponseStream());
string final_response = stream.ReadToEnd();
Console.WriteLine("Genuine Purity Fist");
Console.WriteLine(final_response);
Console.ReadKey();
}
}
}
Response:
{"success":true,"lowest_price":"1,05\u20ac","volume":"26","median_price":"1,06\u20ac"}
json2csharp code:
public class RootObject
{
public bool success { get; set; }
public string lowest_price { get; set; }
public string volume { get; set; }
public string median_price { get; set; }
}
Hey you could downloade Json.NET and parse your json string like this:
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://steamcommunity.com/market/priceoverview/?currency=3&appid=440&market_hash_name=Genuine%20Purity%20Fist");
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader stream = new StreamReader(response.GetResponseStream());
var final_response = stream.ReadToEnd();
// Converts the unicode to string correctValue.
string correctValue = "Euro";
StringBuilder sb = new StringBuilder(final_response);
if (sb.ToString().Contains("\\u20ac"))
{
sb.Replace("\\u20ac", correctValue);
}
dynamic items = JObject.Parse(sb.ToString());
bool success = items.success;
string lowest = items.lowest_price;
string volume = items.volume;
string median = items.median_price;
// Create a test object of RootObject class and display it's values in cw.
RootObject r = new RootObject(success, lowest, volume, median);
Console.WriteLine("TEST OBJECT VALUES: Success: " + r.success + ", lPrice: " + r.lowest_price + ", vol: " + r.volume + ", mPrice: " + r.median_price + "\n");
// Calculation example
double num1 = Convert.ToDouble(r.FixComma(r.lowest_price,correctValue));
double num2 = Convert.ToDouble(r.FixComma(r.median_price, correctValue));
double result = num1 + num2;
Console.WriteLine("Result: " + result+"\n");
Console.WriteLine("Genuine Purity Fist");
Console.WriteLine(final_response);
Console.ReadKey();
}
}
public class RootObject
{
public bool success { get; set; }
public string lowest_price { get; set; }
public string volume { get; set; }
public string median_price { get; set; }
public RootObject(bool success, string lowest_price, string volume, string median_price)
{
this.success = success;
this.lowest_price = lowest_price;
this.volume = volume;
this.median_price = median_price;
}
public string FixComma(string value,string currency)
{
string correctValue = ".";
string correctValue2 = "";
StringBuilder sb = new StringBuilder(value);
if (sb.ToString().Contains(","))
{
sb.Replace(",", correctValue);
}
if (sb.ToString().Contains(currency))
{
sb.Replace(currency, correctValue2);
}
return sb.ToString();
}
}
}
Here is a link that explains how to downloade Json.NET https://www.nuget.org/packages/newtonsoft.json/.
One option is to use the JavaScriptSerializer class in the System.Web.Script.Serialization namespace.
For example:
RootObject obj = new JavaScriptSerializer().Deserialize<RootObject>(final_response);
Other options might be:
Do it yourself using reflection or manual parsing.
Third-party libraries like this one.
I would use JSON.NET for this. It provides a powerful and flexible way to deserialize and consume the data (and lets you change your mind about how to do it fairly easily later). It's also available as a NuGet package.
The simplest way would be to deserialize it into a dynamic or Object instance:
var object = JsonConvert.Deserialize<Object>(final_response);
var isSuccessful = object.success; // true or false
// ...
(You can replace object with dynamic too.)
If you want to deserialize to a class, create one:
class PriceData {
public bool success { get; set; }
public string lowest_price { get; set; }
public string volume { get; set; }
public string median_price { get; set; }
}
Then call .Deserialize<PriceData>(final_response) instead.
If you don't like lowercase-named or underscore-named variables (which is not the common style in C#), you can override the deserialization to specify which field to use for which C# property:
class PriceData {
[JsonProperty("success")]
public bool Success { get; set; }
[JsonProperty("lowest_price")]
public string LowestPrice { get; set; }
[JsonProperty("volume")]
public string Volume { get; set; }
[JsonProperty("median_price")]
public string MedianPrice { get; set; }
}
I am looking to deserialize data and place it into a generic class from a response from Azure.
<ServiceResources xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/windowsazure">
<ServiceResource>
<Name>Airport1</Name>
<Type>Microsoft.SqlAzure.FirewallRule</Type>
<State>Normal</State>
<SelfLink>https://management.core.windows.net:xxx/xxx/services/sqlservers/servers/xxx/firewallrules/Airport1</SelfLink>
<ParentLink>https://management.core.windows.net:xxxx/services/sqlservers/servers/xxx</ParentLink>
<StartIPAddress>000.000.000.000</StartIPAddress>
<EndIPAddress>2000.000.000.000</EndIPAddress>
</ServiceResource>
There are several objects I need to deserialze into my class.
[Serializable, XmlRoot(ElementName = "ServiceResource", Namespace = "http://schemas.microsoft.com/windowsazure/")]
public class ServiceResource
{
[XmlElement("Name")]
public string Name { get; set; }
[XmlElement("Type")]
public string Type { get; set; }
[XmlElement("State")]
public string State { get; set; }
[XmlElement("SelfLink")]
public string SelfLink { get; set; }
[XmlElement("ParentLink")]
public string ParentLink { get; set; }
[XmlElement("StartIPAddress")]
public string StartIPAddress { get; set; }
[XmlElement("EndIPAddress")]
public string EndIPAddress { get; set; }
}
I have tried several different ventures into this and can't nail it. I have used the xmlSerializer but hit blocks on that.
using (var responseStreamReader = new StreamReader(webResponse.GetResponseStream()))
{
XmlSerializer serializer = new XmlSerializer(typeof(ServiceResource));
ServiceResource deserialized = (ServiceResource)serializer.Deserialize(responseStreamReader);
}
Any help would be gratefully accepted.
Answer
The Azure REST Api is returning a list of ServiceResource in the XML. So you need to encapsulate that into a class. Here is an example.
[XmlRoot(
ElementName = "ServiceResources",
Namespace = "http://schemas.microsoft.com/windowsazure")]
public class ServiceResources
{
public ServiceResources()
{
Items = new List<ServiceResource>();
}
[XmlElement("ServiceResource")]
public List<ServiceResource> Items { get; set; }
}
public class ServiceResource
{
[XmlElement("Name")]
public string Name { get; set; }
[XmlElement("Type")]
public string Type { get; set; }
[XmlElement("State")]
public string State { get; set; }
[XmlElement("SelfLink")]
public string SelfLink { get; set; }
[XmlElement("ParentLink")]
public string ParentLink { get; set; }
[XmlElement("StartIPAddress")]
public string StartIPAddress { get; set; }
[XmlElement("EndIPAddress")]
public string EndIPAddress { get; set; }
}
With those two classes, you can now do the following.
var response = request.GetResponse();
var message = string.Empty;
using (var responseStreamReader = new StreamReader(response.GetResponseStream()))
{
message = responseStreamReader.ReadToEnd();
}
var textReader = new StringReader(message);
var serializer = new XmlSerializer(typeof(ServiceResources));
var serviceResources =
serializer.Deserialize(textReader) as ServiceResources;
Demo Console App
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
namespace DeserializeAzureXmlResponse
{
class Program
{
private static string certificateThumbprint = "19DAED4D4ABBE0D400DC33A6D99D00D7BBB24472";
private static string subscriptionId = "14929cfc-3501-48cf-a5c9-b24a7daaf694";
static string sqlServerName = "mvp2015";
static string managementUri = "https://management.core.windows.net";
static string sqlServerApi = "services/sqlservers/servers";
static string firewallRules = "firewallrules";
static void Main(string[] args)
{
var restUri = CreateRestUri();
var clientCert = GetX509FromPersonalStore();
var request = (HttpWebRequest)HttpWebRequest.Create(restUri);
request.Headers.Add("x-ms-version", "2012-03-01");
request.ClientCertificates.Add(clientCert);
var response = request.GetResponse();
var message = string.Empty;
using (var responseStreamReader = new StreamReader(response.GetResponseStream()))
{
message = responseStreamReader.ReadToEnd();
}
var textReader = new StringReader(message);
var serializer = new XmlSerializer(typeof(ServiceResources));
var serviceResources = serializer.Deserialize(textReader) as ServiceResources;
foreach (var sr in serviceResources.Items)
{
Console.WriteLine("Name".PadRight(20) + sr.Name);
Console.WriteLine("Type".PadRight(20) + sr.Type);
Console.WriteLine("State".PadRight(20) + sr.State);
Console.WriteLine("SelfLink".PadRight(20) + sr.SelfLink);
Console.WriteLine("ParentLink".PadRight(20) + sr.ParentLink);
Console.WriteLine("StartIP".PadRight(20) + sr.StartIPAddress);
Console.WriteLine("EndIP".PadRight(20) + sr.EndIPAddress);
Console.WriteLine("+++++++++++");
}
Console.ReadLine();
}
static Uri CreateRestUri()
{
// https://management.core.windows.net/{subscriptionID}/services/sqlservers/servers/{server}/firewallrules/
var builder = new StringBuilder();
builder.Append(managementUri + "/");
builder.Append(subscriptionId + "/");
builder.Append(sqlServerApi + "/");
builder.Append(sqlServerName + "/");
builder.Append(firewallRules + "/");
var uri = new Uri(builder.ToString());
return uri;
}
static X509Certificate GetX509FromPersonalStore()
{
// To view the personal store, press `Win + R` and then type `certmgr.msc`
var store = new X509Store(StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadOnly);
var certificates = store.Certificates.Find(X509FindType.FindByThumbprint, certificateThumbprint, true);
var certificate = certificates[0];
store.Close();
return certificate;
}
}
[XmlRoot(
ElementName = "ServiceResources",
Namespace = "http://schemas.microsoft.com/windowsazure")]
public class ServiceResources
{
public ServiceResources()
{
Items = new List<ServiceResource>();
}
[XmlElement("ServiceResource")]
public List<ServiceResource> Items { get; set; }
}
public class ServiceResource
{
[XmlElement("Name")]
public string Name { get; set; }
[XmlElement("Type")]
public string Type { get; set; }
[XmlElement("State")]
public string State { get; set; }
[XmlElement("SelfLink")]
public string SelfLink { get; set; }
[XmlElement("ParentLink")]
public string ParentLink { get; set; }
[XmlElement("StartIPAddress")]
public string StartIPAddress { get; set; }
[XmlElement("EndIPAddress")]
public string EndIPAddress { get; set; }
}
}
Output
Name My-House
Type Microsoft.SqlAzure.FirewallRule
State Normal
SelfLink https://management.core.windows.net/14929cfc-35
ParentLink https://management.core.windows.net/14929cfc-35
StartIP 123.435.234.643
EndIP 123.435.234.643
+++++++++++
Name AllowAllWindowsAzureIps
Type Microsoft.SqlAzure.FirewallRule
State Normal
SelfLink https://management.core.windows.net/14929cfc-35
ParentLink https://management.core.windows.net/14929cfc-35
StartIP 0.0.0.0
EndIP 0.0.0.0
+++++++++++
See Also
Is it possible to deserialize XML into List<T>?
List Firewall Rules
I am assuming you are trying to deserialize the whole object graph. Given xml has root node ServiceResources which contains ServiceResource. You have two options, you can mimic the whole xml into classes and desrialize; or just get the inner node of ServiceResource and deserialize that part.
If you use first option, then you would need to store ServiceResource inside another class which has mapped collections property with XmlElement name set to "ServiceResource", e.g.:
[XmlType(Namespace="http://schemas.microsoft.com/windowsazure")]
[XmlRoot(Namespace="http://schemas.microsoft.com/windowsazure")]
public class ServiceResource
{
public string Name { get; set; }
public string Type { get; set; }
public string State { get; set; }
public string SelfLink { get; set; }
public string ParentLink { get; set; }
public string StartIPAddress { get; set; }
public string EndIPAddress { get; set; }
}
[XmlType(Namespace="http://schemas.microsoft.com/windowsazure")]
[XmlRoot(Namespace="http://schemas.microsoft.com/windowsazure")]
public class ServiceResources
{
[XmlElement("ServiceResource")]
public List<ServiceResource> ServiceResource { get; set; }
}
With that you should be able to deserialize directly. Container class has the collections mapped to the ServiceResource element, which will load all of the nodes for service resource. Note: deserialization target type is now "ServiceResources" not the inner type "ServiceResource"
using (var responseStreamReader = new StreamReader(webResponse.GetResponseStream()))
{
XmlSerializer serializer = new XmlSerializer(typeof(ServiceResources));
ServiceResources deserialized = (ServiceResources)serializer.Deserialize(responseStreamReader);
//you can access each item in loop
foreach(var res in deserialized.ServiceResource)
{
//access items e.g.
var name = res.Name;
}
}
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