How to Implement In-App Purchases in Windows 10 Apps? - c#

I want to integrate in-app purchasing in my windows universal app. I do the following thing before coding.
Make App on Windows Dev Center
Add products with details in IAPs section and submit to Store as you can see in Image
After that I use the following code in my app to get list of products of In-App purchasing and button to purchase product. I also used CurrentApp instead of CurrentAppSimulator in my code but it goes in exception.
private async void RenderStoreItems()
{
picItems.Clear();
try
{
//StoreManager mySM = new StoreManager();
ListingInformation li = await CurrentAppSimulator.LoadListingInformationAsync();
System.Diagnostics.Debug.WriteLine(li);
foreach (string key in li.ProductListings.Keys)
{
ProductListing pListing = li.ProductListings[key];
System.Diagnostics.Debug.WriteLine(key);
string status = CurrentAppSimulator.LicenseInformation.ProductLicenses[key].IsActive ? "Purchased" : pListing.FormattedPrice;
string imageLink = string.Empty;
picItems.Add(
new ProductItem
{
imgLink = key.Equals("BaazarMagzine101") ? "block-ads.png" : "block-ads.png",
Name = pListing.Name,
Status = status,
key = key,
BuyNowButtonVisible = CurrentAppSimulator.LicenseInformation.ProductLicenses[key].IsActive ? false : true
}
);
}
pics.ItemsSource = picItems;
}
catch (Exception e)
{
System.Diagnostics.Debug.WriteLine(e.ToString());
}
}
private async void ButtonBuyNow_Clicked(object sender, RoutedEventArgs e)
{
Button btn = sender as Button;
string key = btn.Tag.ToString();
if (!CurrentAppSimulator.LicenseInformation.ProductLicenses[key].IsActive)
{
ListingInformation li = await CurrentAppSimulator.LoadListingInformationAsync();
string pID = li.ProductListings[key].ProductId;
string receipt = await CurrentAppSimulator.RequestProductPurchaseAsync(pID, true);
System.Diagnostics.Debug.WriteLine(receipt);
// RenderStoreItems();
}
}
I also Associate my app with Store and my app package is same as in MS Dev Center App as you can see in Image
When I run my app and click on Buy button, I got this dialogue box as you can see in Image after that I did not get receipt data from Store.
If I'm doing wrong then Please give me proper guide to implement the In-app purchase and test that In-app purchase in my laptop device.

I also had this issue and the problem was in the WindowsStoreProxy.xml file.
Solution in short
By default in the WindowsStoreProxy.xml the IsTrial is set to true and in that mode in-app purchases do not seem to work. When I changed it to false it started to work for me.
Solution a little bit longer
So first of all here we are talking about the simulation of an In-App Purchase in development time (by using the CurrentAppSimulator class). In that case you need a WindowsStoreProxy.xml file. It’s described here
Now the window you showed is opened by the CurrentAppSimulator.RequestProductPurchaseAsync line. It basically controls the return value of a Windows Runtime native method (which is very strange for me… I think it’s not intentional by Microsoft… something else should be done there), but if you let it return S_OK that basically is the case when the user paid for the in-App Purchase.
When it returns nothing then with very high probability something in the WindowsStoreProxy.xml is wrong. I suggest you to create your own WindowsStoreProxy.xml and read it with the CurrentAppSimulator.ReloadSimulatorAsync method like this:
var file = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync(#"Testing\WindowsStoreProxy.xml");
await CurrentAppSimulator.ReloadSimulatorAsync(file);
For me using the default one from C:\Users\<username>\AppData\Local\Packages\<app package folder>\LocalState\Microsoft\Windows Store\ApiData\WindowsStoreProxy.xml
did not work, but a single change already solved the problem: I changed this part
<LicenseInformation>
<App>
<IsActive>true</IsActive>
<IsTrial>true</IsTrial>
</App>
</LicenseInformation>
To this:
<LicenseInformation>
<App>
<IsActive>true</IsActive>
<IsTrial>false</IsTrial>
</App>
</LicenseInformation>
(So IsTrial was set to false...)
Now at this point I also would like to mention that this was a little bit strange, since in in the default WindowsStoreProxy.xml there was no Product defined for my In-App Purchase. So for my “RemoveAds” a proper WindowsStoreProxy.xml would be something like this:
<?xml version="1.0" encoding="utf-16" ?>
<CurrentApp>
<ListingInformation>
<App>
<AppId>00000000-0000-0000-0000-000000000000</AppId>
<LinkUri>http://apps.microsoft.com/webpdp/app/00000000-0000-0000-0000-000000000000</LinkUri>
<CurrentMarket>en-US</CurrentMarket>
<AgeRating>3</AgeRating>
<MarketData xml:lang="en-US">
<Name>AppName</Name>
<Description>AppDescription</Description>
<Price>1.00</Price>
<CurrencySymbol>$</CurrencySymbol>
<CurrencyCode>USD</CurrencyCode>
</MarketData>
</App>
<Product ProductId="RemoveAds" LicenseDuration="1" ProductType="Durable">
<MarketData xml:lang="en-US">
<Name>RemoveAds</Name>
<Price>1.00</Price>
<CurrencySymbol>$</CurrencySymbol>
<CurrencyCode>USD</CurrencyCode>
</MarketData>
</Product>
</ListingInformation>
<LicenseInformation>
<App>
<IsActive>true</IsActive>
<IsTrial>false</IsTrial>
</App>
<Product ProductId="1">
<IsActive>true</IsActive>
</Product>
</LicenseInformation>
<ConsumableInformation>
<Product ProductId="RemoveAds" TransactionId="10000000-0000-0000-0000-000000000000" Status="Active" />
</ConsumableInformation>
</CurrentApp>
Another thing I would like to point out is that the CurrentAppSimulator.RequestProductPurchaseAsync with two parameter is obsolete. Leave the true parameter out and you get PurchaseResults instance as the result, which contains the receipt in the ReceiptXML property.

WindowsStoreProxy.xml to c# code and serialize to xml file
public static CurrentApp LoadCurrentApp(string productKey = "Premium", bool isActive = false, bool isTrial = false)
{
CurrentApp currentApp = new CurrentApp();
currentApp.ListingInformation = new ListingInformation()
{
App = new App()
{
AgeRating = "3",
AppId = BasicAppInfo.AppId,
CurrentMarket = "en-us",
LinkUri = "",
MarketData = new MarketData()
{
Name = "In-app purchases",
Description = "AppDescription",
Price = "5.99",
CurrencySymbol = "$",
CurrencyCode = "USD",
}
},
Product = new Product()
{
ProductId = productKey,
MarketData = new MarketData()
{
Lang = "en-us",
Name = productKey,
Description = "AppDescription",
Price = "5.99",
CurrencySymbol = "$",
CurrencyCode = "USD",
}
}
};
currentApp.LicenseInformation = new LicenseInformation()
{
App = new App()
{
IsActive = isActive.ToString(),
IsTrial = isTrial.ToString(),
},
Product = new Product()
{
ProductId = productKey,
IsActive = isActive.ToString(),
}
};
return currentApp;
}
Base xml model
[XmlRoot(ElementName = "MarketData")]
public class MarketData
{
[XmlElement(ElementName = "Name")]
public string Name { get; set; }
[XmlElement(ElementName = "Description")]
public string Description { get; set; }
[XmlElement(ElementName = "Price")]
public string Price { get; set; }
[XmlElement(ElementName = "CurrencySymbol")]
public string CurrencySymbol { get; set; }
[XmlElement(ElementName = "CurrencyCode")]
public string CurrencyCode { get; set; }
[XmlAttribute(AttributeName = "lang", Namespace = "http://www.w3.org/XML/1998/namespace")]
public string Lang { get; set; }
}
[XmlRoot(ElementName = "App")]
public class App
{
[XmlElement(ElementName = "AppId")]
public string AppId { get; set; }
[XmlElement(ElementName = "LinkUri")]
public string LinkUri { get; set; }
[XmlElement(ElementName = "CurrentMarket")]
public string CurrentMarket { get; set; }
[XmlElement(ElementName = "AgeRating")]
public string AgeRating { get; set; }
[XmlElement(ElementName = "MarketData")]
public MarketData MarketData { get; set; }
[XmlElement(ElementName = "IsActive")]
public string IsActive { get; set; }
[XmlElement(ElementName = "IsTrial")]
public string IsTrial { get; set; }
}
[XmlRoot(ElementName = "Product")]
public class Product
{
[XmlElement(ElementName = "MarketData")]
public MarketData MarketData { get; set; }
[XmlAttribute(AttributeName = "ProductId")]
public string ProductId { get; set; }
[XmlElement(ElementName = "IsActive")]
public string IsActive { get; set; }
}
[XmlRoot(ElementName = "ListingInformation")]
public class ListingInformation
{
[XmlElement(ElementName = "App")]
public App App { get; set; }
[XmlElement(ElementName = "Product")]
public Product Product { get; set; }
}
[XmlRoot(ElementName = "LicenseInformation")]
public class LicenseInformation
{
[XmlElement(ElementName = "App")]
public App App { get; set; }
[XmlElement(ElementName = "Product")]
public Product Product { get; set; }
}
[XmlRoot(ElementName = "CurrentApp")]
public class CurrentApp
{
[XmlElement(ElementName = "ListingInformation")]
public ListingInformation ListingInformation { get; set; }
[XmlElement(ElementName = "LicenseInformation")]
public LicenseInformation LicenseInformation { get; set; }
}
Get XmlFile
public async static Task<StorageFile> GetWindowsStoreProxyXmlAsync(string productKey, bool isActive = false, bool isTrial = false)
{
StorageFile xmlFile = null;
var currentApp = LoadCurrentApp(productKey, isActive, isTrial);
var xml = StorageHelper.SerializeToXML<CurrentApp>(currentApp);
if (!string.IsNullOrEmpty(xml))
{
xmlFile = await StorageHelper.LocalFolder.CreateFileAsync("MarketData.xml", CreationCollisionOption.ReplaceExisting);
await FileIO.WriteTextAsync(xmlFile, xml);
}
return xmlFile;
}

Related

Update UnitAmount of Stripe Checkout Price

I'm using Stripe Checkout and would like to update the UnitAmount of a Price.
However, the Update Price API doesn't allow UnitPrice. This is the code from Stripe's API Documentation:
StripeConfiguration.ApiKey = "{MY_API_KEY}";
var options = new PriceUpdateOptions
{
Metadata = new Dictionary<string, string>
{
{ "order_id", "6735" },
},
};
var service = new PriceService();
service.Update("gold", options);
And these are the properties in PriceUpdateOptions:
[JsonProperty("active")]
public bool? Active { get; set; }
[JsonProperty("lookup_key")]
public string LookupKey { get; set; }
[JsonProperty("metadata")]
public Dictionary<string, string> Metadata { get; set; }
public string Nickname { get; set; }
[JsonProperty("recurring")]
public PriceRecurringOptions Recurring { get; set; }
[JsonProperty("transfer_lookup_key")]
public bool? TransferLookupKey { get; set; }
Looking at the properties, UnitAmount doesn't seem to be editable once Price has been created.
I would like to do something like:
public void UpdateStripePrice(Product updatedProductResponse, ProductViewModel updatedProduct)
{
StripeConfiguration.ApiKey = "{MY_API_KEY}";
var options = new PriceUpdateOptions
{
Product = updatedProductResponse.Id,
UnitAmount = (long)updatedProduct.Price * 100,
};
var service = new PriceService();
service.Update(updatedProduct.StripePriceId, options);
}
I'm also unable to find a way of removing a Price, and "updating" it by recreating it.

Formatting issue with a class generated xml in ASP.Net C#

My below my code which generate an xml and return the generated xml but the current format is not the structure expected:
My Class:
public class response
{
[StringLength(64)]
public string reference { get; set; }
public int responseCode { get; set; }
[StringLength(140)]
public string responseMessage { get; set; }
[StringLength(32)]
public string transactionId { get; set; }
public List<account> accounts { get; set; }
}
public class account
{
[StringLength(64)]
public string account_number { get; set; }
}
rs = "<?xml version='1.0' encoding='UTF-8'?><USSDResponse><Status>true</Status><StatusMessage>Account details returned for 08069262257</StatusMessage><SessionID>31853F5C-A1C1-2A6F-E054-8E1F65C33B15</SessionID><AccountNumber><AccountNo>0003893369</AccountNo><AccountStatus>ACCOUNT OPEN REGULAR</AccountStatus><AvailableBalance>17674.69</AvailableBalance><AccountName>IYEKE IKECHUKWU I.</AccountName><AccountCurrency>NGN</AccountCurrency><ProductName>CURRENT STAFF</ProductName></AccountNumber><AccountNumber><AccountNo>0064612613</AccountNo><AccountStatus>ACCOUNT OPEN REGULAR</AccountStatus><AvailableBalance>201132.18</AvailableBalance><AccountName>IKECHUKWU ISRAEL IYEKE</AccountName><AccountCurrency>NGN</AccountCurrency><ProductName>HIDA</ProductName></AccountNumber></USSDResponse>";
x.LoadXml(rs);
status = x.GetElementsByTagName("Status")[0].InnerText;
SessionID = x.GetElementsByTagName("SessionID")[0].InnerText;
if (status != null && status == "true")
{
var accts = x.GetElementsByTagName("AccountNo");
var names = x.GetElementsByTagName("ProductName");
if (accts.Count >= 2)
{
//var AcctNo = new accounts();
foreach (XmlElement a in accts)
{
var acctNo = a.InnerText.Substring(0, 10);
accounts.Add(new account { account_number = acctNo });
}
o.accounts = accounts;
o.reference = reference;
o.responseCode = 6;
o.responseMessage = "Please you can only purchase airtime in naira only and no kobo inclusive.";
o.transactionId = "Nil";
logger.Info($"Wrong amount: {amountString} including kobo entered by the user for mobile number: {msisdn}");
return o;
}
}
Result:
<response xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<reference>565695769-8490890112091</reference>
<responseCode>6</responseCode>
<responseMessage>Please you can only purchase airtime in naira only and no kobo inclusive.</responseMessage>
<transactionId>Nil</transactionId>
<accounts>
<account><account_number>0003893369</account_number></account>
<account><account_number>0064612613</account_number></account>
</accounts>
</response>
My above code generate an xml and return the generated xml but the current format is not the structure expected:But I want the result to be exactly with the removal of tag <account_number></account_number>:
<response xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<reference>565695769-8490890112091</reference>
<responseCode>6</responseCode>
<responseMessage>Please you can only purchase airtime in naira only and no kobo inclusive.</responseMessage>
<transactionId>Nil</transactionId>
<accounts>
<account>0003893369</account>
<account>0064612613</account>
</accounts>
</response>
Modify your class structure as below,
public class Accounts {
public Accounts ()
{
Account = new List<string>();
}
public List<string> Account { get; set; }
}
public class Response {
...
public Accounts Accounts { get; set; }
}

Parsing JSON using LINQ

Hello I am facing a very simple problem but it is not getting Solved. Here is my class design
public class Program
{
public string ProgramName { get; set; }
public string ProgramTime { get; set; }
public string ProgramDetails { get; set; }
}
public class Listing
{
public string ChannelName { get; set; }
public string NowShowing { get; set; }
public string NowShowingTime { get; set; }
public string NowShowingDescription { get; set; }
public string NowShowingPicture { get; set; }
public List<Program> Programs { get; set; }
}
public class RootObject
{
public string status { get; set; }
public string about { get; set; }
public List<Listing> listings { get; set; }
}
I am parsing using the following code.
JObject json = JsonConvert.DeserializeObject(e.Result) as JObject;
Listing ls = new Listing
{
ChannelName = (string)json["listings"].Children()["ChannelName"],
NowShowing = (string)json["listings"].Children()["NowShowing"],
Programs = new Program
{
ProgramName = (string)json["listings"]["Program"]["ProgramName"]
}
};
Help me solve my lame approach. My concerns are parsing the items correctly and also how to add them to the nested list "Programs". The second one is more crucial.
Sample Json input-
{
"listings": [
{
"ChannelName": "NTV BANGLA",
"NowShowing": "Ei Shomoy (R)",
"NowShowingTime": "12:10",
"NowShowingDescription": "Ei Shomoy is a daily talk show ........",
"Programs": [
{
"ProgramName": "Ainer Chokhe (R)",
"ProgramTime": "13:00",
"ProgramDetails": "Human Rights and law based program Ainer Chokhe,"
},
{
"ProgramName": "Shonkhobash",
"ProgramTime": "15:10",
"ProgramDetails": "Drama serial Shonkhobash, script by Bipasha Hayat and"
}
]
},
{
"ChannelName": "CHANNEL i",
"NowShowing": "Taroka Kothon (Live)",
"NowShowingTime": "12:30",
"NowShowingDescription": "City Cell Taroka Kothon Live is a talk show ",
"Programs": [
{
"ProgramName": "Channel i Top News",
"ProgramTime": "13:00",
"ProgramDetails": "Mutual Trust Bank top news (Shirsho Shongbad)"
},
{
"ProgramName": "Ebong Cinemar Gaan",
"ProgramTime": "13:10",
"ProgramDetails": "Ebong Cinemar Gaan, a musical show based on "
}
]
}
]
}
EDIT1
var customers = JsonConvert.DeserializeObject<RootObject>(e.Result);
Listing ls = new Listing
{
ChannelName = customers.listings.First().ChannelName,
NowShowing=customers.listings.First().NowShowing,
Programs=??
};
if e.Result is string with your JSON try this
var jss = new JavaScriptSerializer();
var o = jss.Deserialize<RootObject>(e.Result);
UPDATE
possibly you need something like this
var customers = JsonConvert.DeserializeObject<RootObject>(e.Result);
Listing ls = new Listing
{
ChannelName = customers.listings.First().ChannelName,
NowShowing=customers.listings.First().NowShowing,
Programs=customers.listings.First().Programs
};
UPDATE2
if you want based on existing you can try comething like this
var customers = JsonConvert.DeserializeObject<RootObject>(e.Result);
Listing ls = new Listing
{
ChannelName = customers.listings.First().ChannelName,
NowShowing=customers.listings.First().NowShowing,
Programs=customers.listings.First().Programs.Select(p=>new Program{
ProgramName=p.ProgramName,
ProgramTime=p.ProgramTime,
ProgramDetails = p.ProgramDetails
}).ToList()
};
UPDATE3
or if you whant simply random you can try something like this
var customers = JsonConvert.DeserializeObject<RootObject>(e.Result);
Listing ls = new Listing
{
ChannelName = customers.listings.First().ChannelName,
NowShowing=customers.listings.First().NowShowing,
Programs=Enumerable.Range(1,10).Select(p=>new Program{
ProgramName="generated name",
ProgramTime="generated time",
ProgramDetails = "generated details"
}).ToList()
};
Use DataContractJsonSerializer to parse json string in windows phone.
MemoryStream memoryStream = new MemoryStream(Encoding.Unicode.GetBytes(e.Result));
DataContractJsonSerializer dataContractJsonSerializer = new DataContractJsonSerializer(typeof(List<RootObject>));
RootObject itemDataList = dataContractJsonSerializer.ReadObject(memoryStream) as RootObject;
ChannelName = itemDataList.listings.First().ChannelName;

RavenDB query with Linq and enum

Given this document class:
public class Tea
{
public String Id { get; set; }
public String Name { get; set; }
public TeaType Type { get; set; }
public Double WaterTemp { get; set; }
public Int32 SleepTime { get; set; }
}
public enum TeaType
{
Black,
Green,
Yellow,
Oolong
}
I store a new Tea with the following code:
using (var ds = new DocumentStore { Url = "http://localhost:8080/" }.Initialize())
using (var session = ds.OpenSession("RavenDBFirstSteps"))
{
Tea tea = new Tea() { Name = "Earl Grey", Type = TeaType.Black, WaterTemp = 99d, SleepTime = 3 };
session.Store(tea);
session.SaveChanges();
Console.WriteLine(tea.Id);
}
The tea will be successfully saved, but when I try to query all black teas with linq, I am getting no results:
using (var ds = new DocumentStore { Url = "http://localhost:8080/" }.Initialize())
using (var session = ds.OpenSession("RavenDBFirstSteps"))
{
var dbTeas = from teas in session.Query<Tea>()
where teas.Type == TeaType.Black
select teas;
foreach (var dbTea in dbTeas)
{
Console.WriteLine(dbTea.Id + ": " + dbTea.Name);
}
}
I also tried to save the Enum as Integer with the following command:
ds.Conventions.SaveEnumsAsIntegers = true;
But, the result is the same. All works when I use the Name or the WaterTemp. Does RavenDB supports Enums in this way or I am totally wrong?
It seemed that I got the answer. It is always not recommended to use properties with a name like Type, which can be a reserved keyword.
I renamed Type and everything works, so the answer is:
public class Tea
{
public String Id { get; set; }
public String Name { get; set; }
public TeaType TeaType { get; set; }
public Double WaterTemp { get; set; }
public Int32 SleepTime { get; set; }
}

XML Parsing to c# objects

I am trying to do a XML parser which will extract data from a website using REST service, the protocol for communication is HTTP, the data I get is in XML format, and I get to the data I need after several requests to different addresses on the server. I need to parse this data to c# objects so I can operate with them lately.
The information on the server is on 5 levels( I am willing to make work only 4 of them for know)
1-List of vendors
2-List of groups
3-List of subgroups
4-List of products
5-List of full information about products
After I get to 4th level I need to check if the product is in my database or if it has different details so I can add or update it.
With "GET" request to a server I get XML with this structure:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<vendors>
<vendor>
<id>someID</id>
<name>someName</name>
</vendor>
<vendor>
<id>someId1</id>
<name>somename1</name>
</vendor>
</vendors>
XML structure for groups is the same :
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<groups vendor_id="43153185318">
<group>
<id>someID</id>
<name>someName</name>
</group>
<group>
<id>someId1</id>
<name>somename1</name>
</group>
The XML structure is analogical for subgroups and products, except that for products I have more elements like catalog_num, price etc.
I made the classes as follows :
public class VendorList
{
public List<Vendor> vendor_list { get; set; }
public VendorList()
{
vendor_list = new List<Vendor>();
}
}
public class Vendor
{
public string id { get; set; }
public string name { get; set; }
public List<Group> groups_list { get; set; }
public Vendor()
{
id = "N/A";
name = "N/A";
groups_list = new List<Group>();
}
}
public class Group
{
public string id { get; set; }
public string name { get; set; }
public List<SubGroup> subgroup_list { get; set; }
public Group()
{
id = "N/A";
name = "N/A";
subgroup_list = new List<SubGroup>();
}
}
public class SubGroup
{
public string id { get; set; }
public string name { get; set; }
public List<Product> product_list { get; set; }
public SubGroup()
{
id = "N/A";
name = "N/A";
product_list = new List<Product>();
}
}
public class Product
{
public string available { get; set; }
public string catalog_num { get; set; }
public string code { get; set; }
public string currency { get; set; }
public string description { get; set; }
public string haracteristics { get; set; }
public string product_id { get; set; }
public string model { get; set; }
public string name { get; set; }
public string price { get; set; }
public string price_dds { get; set; }
public string picture_url { get; set; }
public Product()
{
available = "N/A";
catalog_num = "N/A";
code = "N/A";
currency = "N/A";
description = "N/A";
haracteristics = "N/A";
product_id = "N/A";
model = "N/A";
name = "N/A";
price = "N/A";
price_dds = "N/A";
picture_url = "N/A";
}
}
and the Parser method like this :
public static void FillVendor(string url)
{
string result = GetXMLstream(url);
var vendors = new VendorList();
XmlDocument doc = new XmlDocument();
doc.Load(new StringReader(result));
doc.Save(#"D:/proba/proba.xml");
XDocument d = XDocument.Load(#"D:/proba/proba.xml");
vendors.vendor_list = (from c in d.Descendants("vendor")
select new Vendor()
{
id = c.Element("id").Value,
name = c.Element("name").Value
}).ToList<Vendor>();
foreach (Vendor v in vendors.vendor_list)
{
FillGroups(v.id);
}
}
public static void FillGroups(string vendorID)
{
string url = "main address" + vendorID;
string result = GetXMLstream(url);
var group = new Vendor();
XmlDocument doc = new XmlDocument();
doc.Load(new StringReader(result));
doc.Save(#"D:/proba/proba1.xml");
XDocument d = XDocument.Load(#"D:/proba/proba1.xml");
group.groups_list = (from g in d.Descendants("group")
select new Group()
{
id = g.Element("id").Value,
name = g.Element("name").Value
}).ToList<Group>();
foreach (Group g in group.groups_list)
{
FillSubGroup(vendorID, g.id);
}
}
public static void FillSubGroup(string vendorID, string groupID)
{
string url = "main address" + vendorID+"/"+groupID;
string result = GetXMLstream(url);
var subgroup = new Group();
XmlDocument doc = new XmlDocument();
doc.Load(new StringReader(result));
doc.Save(#"D:/proba/proba2.xml");
XDocument d = XDocument.Load(#"D:/proba/proba2.xml");
subgroup.subgroup_list = (from g in d.Descendants("subgroup")
select new SubGroup()
{
id = g.Element("id").Value,
name = g.Element("name").Value
}).ToList<SubGroup>();
foreach (SubGroup sb in subgroup.subgroup_list)
{
FillProduct(vendorID, groupID, sb.id);
}
}
public static void FillProduct(string vendorID,string groupID,string subgroupID)
{
string url = "main address" + vendorID + "/" + groupID+"/"+subgroupID;
string result = GetXMLstream(url);
var product = new SubGroup();
XmlDocument doc = new XmlDocument();
doc.Load(new StringReader(result));
doc.Save(#"D:/proba/proba2.xml");
XDocument d = XDocument.Load(#"D:/proba/proba2.xml");
product.product_list = (from g in d.Descendants("subgroup")
select new Product()
{
available = g.Element("available").Value,
catalog_num = g.Element("catalog_num").Value,
code = g.Element("code").Value,
currency = g.Element("currency").Value,
description = g.Element("description").Value,
haracteristics = g.Element("haracteristics").Value,
product_id = g.Element("id").Value,
model = g.Element("model").Value,
name = g.Element("name").Value,
price = g.Element("price").Value,
price_dds = g.Element("price_dds").Value,
picture_url = g.Element("small_picture").Value,
}).ToList<Product>();
}
But after finishing parsing I try to check if my Lists are populated with objects, but I get an error which says that they are null "NullReferenceException"
So my question is did I make classes properly and is my parsing method right ( you can suggest how to parse the xml without creating a file on my computer) and if I didn't where is my mistake and how should I make it work properly?
Thanks in advance!
modify this line add 's'( vendor -> vendors)
-> vendors.vendor_list = (from c in d.Descendants("vendor")
and the same case for group -> groups
Instead of making the classes yourself.
Create a properly formatted XML Schema either manually or with Visual Studio and then from that XSD File you've created generate your C# Classes.

Categories

Resources