Pastel Partner SDK Create Invoice Issue - c#

I am trying to generate an invoice in Pastel Partner using the SDK from a C# application. I have followed the documentation to a tee but I keep on getting a return code of 17 (Invalid customer account code). I have verified that the customer exists.
public string GenerateInvoiceDocument(Order order)
{
var result = _sdk.SetDataPath($"{_directory}{_company}");
if (result == "0") _sdk.OpenDocumentFiles();
var customer = GetCustomer(order.CustomerNumber);
if (result == "0") {
var header = "|||OIL004|05/03/2017||N|0|Message no.1|Message no.2|Message no.3|Delivery no.1|Delivery no.2|Delivery no.3|Delivery no.4|Delivery no.5||00||05/03/1999|011-7402156|Johnny|011-7402157|1";
result =_sdk.DefineDocumentHeader(header);
}
for (var x = 0; x < order.InventoryCode.Count; x++)
{
if (result == "0")
{
var customerPrice = GetCustomerPrice(customer.Number, order.InventoryCode[x]);
result = _sdk.DefineDocumentLine(
GenerateDocumentLine(
0,
Convert.ToDouble(order.Quantity[x]),
customerPrice.Price[x],
customerPrice.IncPrice[x],
"",
customer.TaxCode.ToString().PastelZeroPad(2),
"",
"",
customerPrice.ItemCode,
order.InventoryCode[x],
"4",
"002",
""));
}
}
result = _sdk.ImportDocument(3);
_sdk.CloseDocumentFiles();
return result;
}

Seems like a bit of buggy behaviour from Pastel, the solution was to remove any calcs from the Pastel flow by doing them beforehand.
public string GenerateInvoiceDocument(Order order)
{
var customer = GetCustomer(order.CustomerNumber);
var header = GenerateCustomerDocumentHeader(customer, DateTime.Now.AddYears(-1), order.Number, "", "", "", "", "", "", "", "", "", "", DateTime.Now.AddYears(-1), "", "", "", 1);
var lines = new List<string>();
for (var x = 0; x < order.InventoryCode.Count; x++)
{
var customerPrice = GetCustomerPrice(order.CustomerNumber, order.InventoryCode[x]);
var newLine = GenerateDocumentLine(customerPrice.Price[x], (double)order.Quantity[x], customerPrice.Price[x], customerPrice.IncPrice[x], "0", customer.TaxCode.ToString(), "", "0", order.InventoryCode[x], order.InventoryDescription[x], "4", "001", "");
lines.Add(newLine);
}
var result = _sdk.SetDataPath($"{_directory}{_company}");
_sdk.OpenDocumentFiles();
result = _sdk.DefineDocumentHeader(header, true);
foreach (var line in lines)
{
result = _sdk.DefineDocumentLine(line);
}
result = _sdk.ImportDocument(3, 0);
_sdk.CloseDocumentFiles();
return result;
}

Related

How to check NewtonJson Jarray null/empty error when request data from an API and display DataSet to Excel in C#

I'm trying to display the simple element of the array or value, below is my JSON string(an API from python pandas)
{
"msg": "success",
"state": 10000,
"data": {
"data": [
{
"index": 0,
"test_1": 110,
"test_2": "000001",
"test_3": "CN",
"test_4": "Bank",
"test_5": 893,
"test_6": 229
}
],
"schema": {
"fields": [
{
"type": "integer",
"name": "index"
},
{
"type": "string",
"name": "test_1"
},
{
"type": "string",
"name": "test_2"
},
{
"type": "number",
"name": "test_3"
},
{
"type": "number",
"name": "test_4"
},
{
"type": "number",
"name": "test_5"
},
{
"type": "string",
"name": "test_6"
}
],
"pandas_version": "0.20.0",
"primaryKey": [
"index"
]
}
}
}
Below code of C# is the query that I'm using, TestDataset.cs:
using System;
using System.IO;
using System.Net;
using Newtonsoft.Json.Linq;
using ExcelDna.Integration;
using Excel = Microsoft.Office.Interop.Excel;
namespace Test_Atune
{
public class Request
{
Excel.Application ExcelApp = (Excel.Application)ExcelDnaUtil.Application;
public object GetDatasetFromUrl(string root, string path, string headval, Excel.Range excelAddress)
{
string historicalData= "{}";
var webConnection = new WebClient();
webConnection.Headers.Add("Host", headval);
try
{
historicalData = webConnection.DownloadString(root+path);
}
catch (WebException ex)
{
string error_str = ex.Message;
if (ex.Status.ToString() == "ConnectFailure" || ex.Status.ToString() == "Timeout")
{
root = Constant.setURL_ROOT_COMMON(root);
try
{
historicalData= webConnection.DownloadString(root + path);
}
catch (WebException ex2)
{
return "";
}
}
}
finally
{
webConnection.Dispose();
}
JObject jsonFeed = JObject.Parse(historicalData);
Excel.Range range = excelAddress;
JObject B = new JObject();
JArray data = (JArray)jsonFeed["data"]["data"];
JArray columns = (JArray)jsonFeed["data"]["schema"]["fields"];
int rowNum = data.Count;
int colNum = columns.Count;
Excel.Range range_head = ExcelApp.Cells[range.Row + 1, range.Column];
range_head = range_head.get_Resize(1, colNum);
Excel.Range range_data = ExcelApp.Cells[range.Row + 2, range.Column];
range_data = range_data.get_Resize(rowNum, colNum);
// write header
object[,] headerData = new object[1, colNum];
for (int iCol = 0; iCol < colNum; iCol++)
{
headerData[0, iCol] = columns[iCol]["name"];
}
range_head.Value2 = headerData;
// write data
object[,] cellData = new object[rowNum, colNum];
int iRow = 0;
foreach (JObject jo in data)
{
var a = jo["test_code"];
for (int iCol = 0; iCol < colNum; iCol++)
{
if (columns[iCol]["test_1"].ToString() == "string")
{
cellData[iRow, iCol] = "'" + jo[columns[iCol]["name"].ToString()];
}
else
{
cellData[iRow, iCol] = jo[columns[iCol]["name"].ToString()];
}
}
iRow += 1;
}
range_data.Value2 = cellData;
return "Total" + rowNum.ToString() + "cells";
}
}
}
And below is the code of request.cs
using ExcelDna.Integration;
using Excel = Microsoft.Office.Interop.Excel;
namespace Test_Atune
{
public class Dataset
{
public static string baseurl = Constant.URL_ROOT_COMMON;
public static string headval = Constant.HEADVAL_COMMON;
public static Request request = new Request();
[ExcelFunction(Category = "test", IsMacroType = true, Description = "test dataset")]
public static object TEST_DATASET(
[ExcelArgument(Description = "test_code")] string test_1,
[ExcelArgument(Description = "YYYYMMDD")] string test_2,
[ExcelArgument(Description = "YYYYMMDD")] string test_3
)
{
string parstr = #"/test_dataset/?" +
#"test_1=" + test_1 +
#"&test_2=" + test_2 +
#"&test_3=" + test_3;
ExcelReference caller = (ExcelReference)XlCall.Excel(XlCall.xlfCaller);
Excel.Range rg = caller.ToPiaRange();
return ExcelAsyncUtil.Run("TEST_DATASET",
new object[] { parstr },
() => request.GetDatasetFromUrl(Constant.URL_ROOT_COMMON, parstr, headval, rg));
}
}
}
And I got the following error on JArray columns = (JArray)jsonFeed["data"]["schema"]["fields"];
System.NullReferenceException HResult=0x80004003 message=Object reference not set to an instance of an object.
I tried to debug and I got below results,
Name: historicalData, Value:"{}"; Name: jsonFeed,Vaule:Null; Name:B,Vaule:{{}}, Name:data, Value:"null"
I am very new to C#, is that an array,domain or url problem, or anything else? How can I do that? thank you so much for any advice.
Error: Object reference not set to an instance of an object. This means that the one or all of the data under ["data"] or ["data"]["schema"] or ["data"]["schema"]["fields"] does not exist.
I just tested your code and the following code works just fine based on the given json.
JArray columns = (JArray)jsonFeed["data"]["schema"]["fields"];
Suggestion: Use the debugger and see if the value of your jsonFeed is correct because thats the only thing that I cannot reproduce. If you are not able to use the debugger, log the parsed object by using .ToString() on the parsed object. (jsonFeed.ToString())
NOTE: There is an issue with your json. "test_3": CN, is suposed to be "test_3": "CN", with quotes on CN.

NEST compound queries which must all be satisfied

var availableToField = Infer.Field<Project>(f => f.Availablity.AvailableTo);
var availableFromField = Infer.Field<Project>(f => f.Availablity.AvailableFrom);
var nameField = Infer.Field<Project>(f => f.Contact.Name);
var active_date_to = new DateRangeQuery(){
Name = "toDate",
Boost = 1.1,
Field = "availablity.availableTo",
GreaterThan = DateTime.Now,
TimeZone = "+01:00",
Format = "yyyy-MM-ddTHH:mm:SS||dd.MM.yyyy"
};
var active_date_from = new DateRangeQuery(){
Name = "from",
Boost = 1.1,
Field = "availablity.availableFrom",
LessThanOrEqualTo = DateTime.Now,
TimeZone = "+01:00",
Format = "yyyy-MM-ddTHH:mm:SS||dd.MM.yyyy"
};
public ISearchResult<Project> Search(SearchCriteria criteria)
{var ret = _client.Search<Project>(s =>
s.Query(q =>
active_date_from &&
active_date_to &&
q.Match(d => d.Query(criteria.FreeText))
).From(criteria.CurrentPage).Size(criteria.Take)
.From(criteria.CurrentPage)
.Take(criteria.Take)
);
result.Total = ret.Total;
result.Page = criteria.CurrentPage;
result.PerPage = criteria.Take;
result.Results = ret.Documents;
return result;
}
what im trying to do is get the results matching the freetext but are also withing the pricerange..
somehow though what i get is an invalid NEST response build from a unsuccessful low level call on POST... and in consequence an empty query.
there are no compiling errors.
does anyone have an idea where i could have gone wrong or what im missing?
the other thing i tried was
var mustClauses = new List<QueryContainer>();
mustClauses.Add(active_date_from);
mustClauses.Add(active_date_to);
mustClauses.Add(new TermQuery
{
Field = "contact.name",
Value = criteria.FreeText
});
var searchRequest = new SearchRequest<Project>()
{
Size = 10,
From = 0,
Query = new BoolQuery
{
Must = mustClauses
}
};
var ret = _client.Search<Project>(searchRequest);
result.Total = ret.Total;
result.Page = criteria.CurrentPage;
result.PerPage = criteria.Take;
result.Results = ret.Documents;
which got me pretty much the same results.. (read: none)
is there something im missing?
edit:
however.. this:
var ret = _client.Search<Project>(s => s.Query(q => q.Match(m => m.Field(f => f.DisplayName).Query(criteria.FreeText))));
gives me exactly what i want (without the validation of the dates of course and only looking at one field)
In your first example, the match query is missing a field property which is needed for the query. Because of NEST's conditionless query behaviour, the query is not serialized as part of the request. The two date range queries are serialized however.
Here's a simple example that you may find useful to get the correct query you're looking for
void Main()
{
var pool = new SingleNodeConnectionPool(new Uri("http://localhost:9200"));
var defaultIndex = "projects";
var connectionSettings = new ConnectionSettings(pool, new InMemoryConnection())
.DefaultIndex(defaultIndex )
.PrettyJson()
.DisableDirectStreaming()
.OnRequestCompleted(response =>
{
if (response.RequestBodyInBytes != null)
{
Console.WriteLine(
$"{response.HttpMethod} {response.Uri} \n" +
$"{Encoding.UTF8.GetString(response.RequestBodyInBytes)}");
}
else
{
Console.WriteLine($"{response.HttpMethod} {response.Uri}");
}
Console.WriteLine();
if (response.ResponseBodyInBytes != null)
{
Console.WriteLine($"Status: {response.HttpStatusCode}\n" +
$"{Encoding.UTF8.GetString(response.ResponseBodyInBytes)}\n" +
$"{new string('-', 30)}\n");
}
else
{
Console.WriteLine($"Status: {response.HttpStatusCode}\n" +
$"{new string('-', 30)}\n");
}
});
var client = new ElasticClient(connectionSettings);
var availableToField = Infer.Field<Project>(f => f.Availablity.AvailableTo);
var availableFromField = Infer.Field<Project>(f => f.Availablity.AvailableFrom);
var nameField = Infer.Field<Project>(f => f.Contact.Name);
var active_date_to = new DateRangeQuery
{
Name = "toDate",
Boost = 1.1,
Field = availableToField,
GreaterThan = DateTime.Now,
TimeZone = "+01:00",
Format = "yyyy-MM-ddTHH:mm:SS||dd.MM.yyyy"
};
var active_date_from = new DateRangeQuery
{
Name = "from",
Boost = 1.1,
Field = availableFromField,
LessThanOrEqualTo = DateTime.Now,
TimeZone = "+01:00",
Format = "yyyy-MM-ddTHH:mm:SS||dd.MM.yyyy"
};
var ret = client.Search<Project>(s => s
.Query(q =>
active_date_from &&
active_date_to && q
.Match(d => d
.Query("free text")
)
)
.From(0)
.Size(10)
);
}
public class Project
{
public Availibility Availablity { get; set; }
public Contact Contact { get; set; }
}
public class Contact
{
public string Name { get; set; }
}
public class Availibility
{
public DateTime AvailableFrom { get; set; }
public DateTime AvailableTo { get; set; }
}
Your current query generates
POST http://localhost:9200/projects/project/_search?pretty=true
{
"from": 0,
"size": 10,
"query": {
"bool": {
"must": [
{
"range": {
"availablity.availableFrom": {
"lte": "2017-07-21T10:01:01.456794+10:00",
"time_zone": "+01:00",
"format": "yyyy-MM-ddTHH:mm:SS||dd.MM.yyyy",
"_name": "from",
"boost": 1.1
}
}
},
{
"range": {
"availablity.availableTo": {
"gt": "2017-07-21T10:01:01.456794+10:00",
"time_zone": "+01:00",
"format": "yyyy-MM-ddTHH:mm:SS||dd.MM.yyyy",
"_name": "toDate",
"boost": 1.1
}
}
}
]
}
}
}
If a nameField is added as the field for the match query you get
POST http://localhost:9200/projects/project/_search?pretty=true
{
"from": 0,
"size": 10,
"query": {
"bool": {
"must": [
{
"range": {
"availablity.availableFrom": {
"lte": "2017-07-21T10:02:23.896385+10:00",
"time_zone": "+01:00",
"format": "yyyy-MM-ddTHH:mm:SS||dd.MM.yyyy",
"_name": "from",
"boost": 1.1
}
}
},
{
"range": {
"availablity.availableTo": {
"gt": "2017-07-21T10:02:23.896385+10:00",
"time_zone": "+01:00",
"format": "yyyy-MM-ddTHH:mm:SS||dd.MM.yyyy",
"_name": "toDate",
"boost": 1.1
}
}
},
{
"match": {
"contact.name": {
"query": "free text"
}
}
}
]
}
}
}
Remove InMemoryConnection from ConnectionSettings if you actually want to execute the query against Elasticsearch and see the results.
The range query is a structured query where a document either matches or doesn't match the predicate. Because of this, it can be wrapped in a bool query filter clause which will forgo calculating a score for it and perform better. Because no scoring occurs, boost is not needed.
Putting this together
var availableToField = Infer.Field<Project>(f => f.Availablity.AvailableTo);
var availableFromField = Infer.Field<Project>(f => f.Availablity.AvailableFrom);
var nameField = Infer.Field<Project>(f => f.Contact.Name);
var active_date_to = new DateRangeQuery
{
Name = "toDate",
Field = availableToField,
GreaterThan = DateTime.Now,
TimeZone = "+01:00",
Format = "yyyy-MM-ddTHH:mm:SS||dd.MM.yyyy"
};
var active_date_from = new DateRangeQuery
{
Name = "from",
Field = availableFromField,
LessThanOrEqualTo = DateTime.Now,
TimeZone = "+01:00",
Format = "yyyy-MM-ddTHH:mm:SS||dd.MM.yyyy"
};
var ret = client.Search<Project>(s => s
.Query(q =>
+active_date_from &&
+active_date_to && q
.Match(d => d
.Field(nameField)
.Query("free text")
)
)
.From(0)
.Size(10)
);
You may also want to explore modelling available from and to as a date_range type

How to add \r\n\ in json Using c#

I do have a hard code json,I have to send that in http request using post,
This is the json
{
"RequestHeader": {
"UserName": " ",
"Password": " "
},
"RequestBody": {
"ChannelType": 1,
"BillAccountNumber": "1075-001",
"BillAccountType": null,
"PaymentAmount": 15.05,
"FeeAmount": 3.50,
"ABA": "111993776",
"BankAccount": "1234567899",
"EmailAddress": "jonah#doe.org",
"AccountHolder": "JonahDoe",
"WaiveFee": false,
"Recurring": false,
"CustomData": null
}
}
When i am passing this i am getting the right response
But when i am using the other it is not giving the response what i need, The only difference in first one my hard coded have \r\n and the 2nd one below don't have.
{
"RequestHeader": {
"UserName": " ",
"Password": " "
},
"RequestBody": {
"ChannelType": 1,
"BillAccountNumber": "1075-001",
"BillAccountType": null,
"PaymentAmount": 15.05,
"FeeAmount": 3.5,
"ABA": "111993776",
"BankAccount": "1234567899",
"EmailAddress": "jonah#doe.org",
"AccountHolder": "Jonah Doe",
"WaiveFee": false,
"Recurring": false,
"CustomData": null
}
}
Can some body tell me what is the problem.
Code IS:
class Program
{
static void Main(string[] args)
{
var RequestBody = new RequestBody
{
ChannelType = 1,
BillAccountNumber = "1075-001",
BillAccountType = null,
PaymentAmount = 15.05,
FeeAmount = 3.50,
ABA = "111993776",
BankAccount = "1234567899",
EmailAddress = "jonah#doe.org",
AccountHolder = "Jonah Doe",
WaiveFee = false,
Recurring = false,
CustomData = null
};
var RequestHeader = new RequestHeader
{
UserName = "myUname",
Password = "MyPass"
};
var Request = new Request
{
RequestBody = RequestBody,
RequestHeader = RequestHeader,
};
var ApiCredentials = new ApiCredentials
{
Request = Request
};
var httpWReq = (HttpWebRequest)WebRequest.Create("https://gw1.cwplab.com/api/Gateway/AuthorizeCheck");
httpWReq.ContentType = "application/json";
//httpWReq.Credentials = new NetworkCredential(" ", " ");
string data = "{\r\n\"RequestHeader\":{\r\n\"UserName\":\" \",\r\n\"Password\":\" \"\r\n},\r\n\"RequestBody\":{\r\n \"ChannelType\":1,\r\n \"BillAccountNumber\":\"1075-001\",\r\n \"BillAccountType\":null,\r\n \"PaymentAmount\":15.05,\r\n \"FeeAmount\":3.50,\r\n \"ABA\":\"111993776\",\r\n \"BankAccount\":\"1234567899\",\r\n \"EmailAddress\":\"jonah#doe.org\",\r\n \"AccountHolder\":\"Jonah Doe\",\r\n \"WaiveFee\":false,\r\n \"Recurring\":false,\r\n \"CustomData\":null\r\n}\r\n}\r\n";//Request.ToJSON();
string data1 = Newtonsoft.Json.JsonConvert.SerializeObject(Request);
httpWReq.ContentLength = data.Length;
httpWReq.Method = "POST";
using (StreamWriter stream = new StreamWriter(httpWReq.GetRequestStream()))
{
stream.Write(data);
//stream.Flush();
//stream.Close();
};
dynamic httpResponse = (HttpWebResponse)httpWReq.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
Console.WriteLine(result);
Console.ReadKey();
}
}
}
There is a difference in the JSON. I suspect your server doesn't accept the second json (you say you get the wrong response). \r\n are not mandatory, it is just for the reader.
"FeeAmount": 3.5,
"FeeAmount": 3.50,
And
"AccountHolder": "Jonah Doe",
"AccountHolder": "JonahDoe",

JSON SelectTokens expression

I have a JSON file (below). My goal is to, fill a dictionary with unit_ids (f.e. in this JSON unit_ids are: 153470, 153471 and 178903) and corresponding classtype_id (f.e. in this JSON corresponding classtype_id are: CW,CW, null). (unit_ids are uniqe)
So f.e. my dictionary might be: {[153470, CW],[153471, CW],[178903, null]}.
But there is a problem, in my current approach, because of the possibility of: "unit_id":null like f.e. in this file: "178903": null.
Dictionary<string, string> unit_id_translate = new Dictionary<string, string>();
var unitIdsTypes = JObject.Parse(unit_ids_json).SelectTokens("*.['classtype_id']");
var unitIdsNumbers = JObject.Parse(unit_ids_json);
List<String> tempForUID = new List<String>();
List<String> tempForVAL = new List<String>();
foreach (var unitIdType in unitIdsTypes)
{
tempForVAL.Add(unitIdType.ToString());
}
foreach (var unitIdNumber in unitIdsNumbers)
{
foreach (var tmp44 in unitIdNumber)
{
var trimmedNr = unitIdNumber.Cast<JProperty>().Select(o => o.Name);
foreach (var unitIdNr in trimmedNr)
{
tempForUID.Add(unitIdNr);
}
break;
}
}
for (int i = 0; i < tempForUID.Count(); i++)
{
unit_id_translate.Add(tempForUID.ElementAt(i), tempForVAL.ElementAt(i));
}
I need help, because my solution crashes (out of range exception) - there is more unit_ids than classtype_id - because of the null value.
What I can do to fix this ?
{
"153470": {
"topics": {
"en": ""
},
"classtype_id": "CW",
"learning_outcomes": {
"en": ""
},
"course_id": "06-DRSOLI0",
"course_name": {
"en": "Distributed operating systems"
},
"id": 153470,
"teaching_methods": {
"en": ""
}
},
"153471": {
"topics": {
"en": ""
},
"classtype_id": "CW",
"learning_outcomes": {
"en": ""
},
"course_id": "06-DPROLI0",
"course_name": {
"en": "Team project"
},
"id": 153471,
"teaching_methods": {
"en": ""
}
},
"178903": null,
}
You can do this easily with Enumerable.ToDictionary():
var unit_id_translate = JObject.Parse(unit_ids_json)
.Properties()
.ToDictionary(p => p.Name, p => (string)p.Value.SelectToken("classtype_id"));
Then
Console.WriteLine(JsonConvert.SerializeObject(unit_id_translate));
produces {"153470":"CW","153471":"CW","178903":null}.

Add new json object to existing json object in C#

I want to add a new playlist with songs to an existing json file.
I'm using Newtonsoft Json.NET to create a Json file like this:
dynamic GroupObj = new JObject();
GroupObj.Playlist = new JArray() as dynamic;
dynamic PlayListObj = new JObject();
PlayListObj.UniqueId = "";
PlayListObj.Title = "Playlist name";
GroupObj.Playlist.Add(PlayListObj);
PlayListObj.Songs = new JArray() as dynamic;
dynamic SongObj = new JObject();
SongObj.UniqueId = "";
SongObj.Title = "song name";
PlayListObj.Songs.Add(SongObj);
data = GroupObj.ToString();
That outputs this:
{
"Playlist": [
{
"UniqueId": "",
"Title": "Playlist name",
"Songs": [
{
"UniqueId": "",
"Title": "song name",
}
]
}
]
}
How would I modify the Json.NET to add new Objects to the existing Object to get to something like this:
{
"Playlist": [
{
"UniqueId": "",
"Title": "Playlist name",
"Songs": [
{
"UniqueId": "",
"Title": "song name",
}
]
},
{
"UniqueId": "",
"Title": "Playlist name",
"Songs": [
{
"UniqueId": "",
"Title": "song name",
"Lyrics": "song lyrics",
"Location": "location"
}
]
}
]
}
Nevermind, I made a solution by rewriting the whole file. Probably not very resource friendly but for a school project, it works. Thanks
string data;
JsonValue val = JsonValue.Parse("{\"some json data\": some value,}");
JsonArray Pl = val.GetObject().GetNamedArray("Playlist");
for (uint x = 0; x != Pl.Count; x++)//go through each playlist
{
var Pl_title = Pl.GetObjectAt(x).GetNamedString("Title"); //get playlist name
if (Pl_title != txtPlaylistName.Text)//dont do anything if playlist exists
{
var Pl_id = Pl.GetObjectAt(x).GetNamedString("UniqueId");
var Pl_loc = Pl.GetObjectAt(x).GetNamedString("Location");
var Pl_img = Pl.GetObjectAt(x).GetNamedString("ImagePath");
//re-create the playlist
dynamic PlayListObj = new JObject();
PlayListObj.UniqueId = Pl_id;
PlayListObj.Title = Pl_title;
PlayListObj.Location = Pl_loc;
PlayListObj.ImagePath = Pl_img;
GroupObj.Playlist.Add(PlayListObj);
PlayListObj.Songs = new JArray() as dynamic;
JsonArray Sng = Pl.GetObjectAt(x).GetNamedArray("Songs");
for (uint y = 0; y != Sng.Count; y++)
{
var Sng_id = Sng.GetObjectAt(y).GetNamedString("UniqueId");
var Sng_title = Sng.GetObjectAt(y).GetNamedString("Title");
var Sng_lyr = Sng.GetObjectAt(y).GetNamedString("Lyrics");
var Sng_loc = Sng.GetObjectAt(y).GetNamedString("Location");
//re-create the songs in the playlist
dynamic SongObj = new JObject();
SongObj.UniqueId = Sng_id;
SongObj.Title = Sng_title;
SongObj.Lyrics = Sng_lyr;
SongObj.Location = Sng_loc;
PlayListObj.Songs.Add(SongObj);
}
}
else
txtBerror.Text = "The name: " + txtPlaylistName.Text + " already exists.";
}
if (txtPlaylistName.Text != string.Empty)
{
//re-create the playlist
dynamic newPlayListObj = new JObject();
newPlayListObj.UniqueId = "PL " + txtPlaylistName.Text;
newPlayListObj.Title = txtPlaylistName.Text;
newPlayListObj.Location = "";
newPlayListObj.ImagePath = "";
GroupObj.Playlist.Add(newPlayListObj);
newPlayListObj.Songs = new JArray() as dynamic;
for (int a = 0; a != 3; a++)//number of songs
{
dynamic SongObj = new JObject();
SongObj.UniqueId = "Sng " + "file name";
SongObj.Title = "file name";
SongObj.Lyrics = "";
SongObj.Location = "";
newPlayListObj.Songs.Add(SongObj);
}
}
else
txtBerror.Text = "Enter a playlist name";
data = GroupObj.ToString();
await Windows.Storage.FileIO.WriteTextAsync(newFile, data);//write to the file

Categories

Resources