How to parse script data in c# and serialize the same - c#

public class PageParser
{
public List<Websitedata> PageParserMethod()
{
var websitedata = new List<Websitedata>();
HtmlWeb web = new HtmlWeb();
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
HtmlDocument doc = web.Load("https://www.sullivanautomotivegroup.net/");
var metaTags = doc.DocumentNode.SelectNodes("//meta");
var foundAppropriateMetaTag = false;
if (metaTags != null)
{
foreach (var tag in metaTags)
{
if (tag.Attributes["name"] != null && tag.Attributes["content"] != null)
{
foundAppropriateMetaTag = true;
var name = tag.Attributes["name"].Value;
var content = tag.Attributes["content"].Value;
//items.Add(new { name, content });
Websitedata info = new Websitedata();
info.name = name;
info.content = content;
websitedata.Add(info);
}
}
}
//var linksOnPage = doc.DocumentNode.Descendants.SelectNodes("//link");
var linksOnPage = from lnks in doc.DocumentNode.Descendants()
where lnks.Name == "a" &&
lnks.Attributes["href"] != null &&
lnks.InnerText.Trim().Length > 0
select new
{
Url = lnks.Attributes["href"].Value,
Text = lnks.InnerText,
};
if (linksOnPage != null)
{
foreach (var tag in linksOnPage)
{
foundAppropriateMetaTag = true;
var rel = tag.Text;
var href = tag.Url;
Websitedata info = new Websitedata();
info.rel = rel;
info.href = href;
websitedata.Add(info);
//items.Add(new { rel, href });
}
}
var scriptGoogleTagManager = doc.DocumentNode.SelectNodes("//script").Where(x => x.InnerHtml.Contains("www.googletagmanager.com"));
if (scriptGoogleTagManager != null)
{
foreach (var tag in scriptGoogleTagManager)
{
{
var abc = tag.InnerText;
//items.Add(new { abc });
Websitedata info = new Websitedata();
info.GoogleTag = abc;
websitedata.Add(info);
}
}
}
var FacebookPixel = doc.DocumentNode.SelectNodes("//script").Where(x => x.InnerHtml.Contains("connect.facebook.net"));
if (FacebookPixel != null)
{
foreach (var tag in FacebookPixel)
{
{
var abc = tag.InnerText;
//items.Add(new { abc });
Websitedata info = new Websitedata();
info.FacebookPixel = abc;
websitedata.Add(info);
}
}
}
var newrelic = doc.DocumentNode.SelectNodes("//script").Where(x => x.InnerHtml.Contains("newrelic"));
if (newrelic != null)
{
foreach (var tag in newrelic)
{
{
var abc = tag.InnerText;
//items.Add(new { abc });
Websitedata info = new Websitedata();
info.NewRelic = abc;
websitedata.Add(info);
}
}
}
var adobelinks = doc.DocumentNode.SelectNodes("//script").Where(x => x.InnerHtml.Contains("adobe"));
if (adobelinks != null)
{
foreach (var tag in adobelinks)
{
{
var abc = tag.InnerText;
//items.Add(new { abc });
Websitedata info = new Websitedata();
info.NewRelic = abc;
websitedata.Add(info);
}
}
}
//www.google-analytics.com
var googleAnalytics = doc.DocumentNode.SelectNodes("//script").Where(x => x.InnerHtml.Contains("www.google-analytics.com/analytics.js"));
if (googleAnalytics != null)
{
foreach (var tag in googleAnalytics)
{
{
foundAppropriateMetaTag = true;
var abc = tag.InnerText;
//items.Add(new { abc });
Websitedata info = new Websitedata();
info.FacebookPixel = abc;
websitedata.Add(info);
}
}
}
return websitedata;
}
}
public class Websitedata
{
public string name { get; set; }
public string content { get; set; }
public string rel { get; set; }
public string href { get; set; }
public string GoogleTag { get; set; }
public string FacebookPixel { get; set; }
public string NewRelic { get; set; }
}
Hi, I have used Html agility pack to parse contents of a website but have no idea how to parse retrieved contents of scripts and serialize the same to retrieve useful information. I want to store all the contents received from website to a class.I am stuck in the problem and unable to find any solution. kindly help me!!!

Related

Pagedlist Pagination without Parameters MVC

I am using Pagedlist for Pagination in my MVC project. Pagination is working for most of the cases without ViewModels.
But when I use a ViewModel PagedList generating Pagination links but without any parameter value to querystring page.
Here is my ViewModel
public class SearchResult
{
public int ItemID { get; set; }
public string ItemTitle { get; set; }
public int? AuthorID { get; set; }
public string AuthorName { get; set; }
public int? IssueDate { get; set; }
}
And ActionResult Method
public ActionResult Date(int? page)
{
try
{
string query;
if (Request.RequestContext.RouteData.Values["query"] != null)
{
using (dreposEntities db = new dreposEntities())
{
query = Request.RequestContext.RouteData.Values["query"].ToString();
int issueYear = int.Parse(query);
ViewBag.Query = issueYear;
var dateFilter = db.itemstreams.Where(q => q.issuedate == issueYear).ToList();
List<SearchResult> resultList = new List<SearchResult>();
if (dateFilter.Any())
{
foreach (var c in dateFilter)
{
SearchResult obj = new SearchResult
{
ItemID = c.id,
ItemTitle = c.title,
IssueDate = c.issuedate,
};
resultList.Add(obj);
}
}
ViewBag.SearchQuery = query;
return View(resultList.OrderBy(d=>d.IssueDate).ToPagedList(page ?? 1, 10));
}
}
else
{
using (dreposEntities db = new dreposEntities())
{
List<SearchResult> resultList = new List<SearchResult>();
var files = db.itemstreams.Where(s=>s.status==1).ToList();
if (files.Any())
{
foreach (var f in files)
{
SearchResult obj = new SearchResult
{
ItemID = f.id,
ItemTitle = f.title,
IssueDate = f.issuedate,
};
resultList.Add(obj);
}
}
return View(resultList.OrderBy(d=>d.IssueDate).ToPagedList(page ?? 1, 10));
}
}
}
catch (Exception e)
{
return View();
}
}
What above code is showing in View is attached in below email
And in View/Razor
<div class="pull-right">
#Html.PagedListPager(Model, page => Url.Action("Date", new { page }), new PagedListRenderOptions() { Display = PagedListDisplayMode.IfNeeded })
</div>

How Can I Create One xml file with Multiple XML douments inside from a text file

I am a C# beginner programmer. I have a text file, which is my source, with multiple rows of data. I want to create one xml file with multiple xml documents inside the file. The xml documents are generated from the rows of data in the text file. I can only get one xml document to generate in the A0x.xml file that is created. My code only reads the first row of data and generates one xml document instead to multiple xml documents. Below are 8 rows from the M24EX.txt file. Please help!!
A0ASMSS3110004624190 EA00008FB239980940001RAIR A30 0120505 18094133644FT
A0ASMSS5340011122822 HD00001FB239981000001RAIR A6C 0120503 18100124741FT
A0ASMSS5365002870093 EA00003FB239981000002RAIR A6C 0120503 18100125431FT
A0ASMS 5365001671717 EA00005FB239981010001REY2550A6C 0120503133 18101075536SF
A0ASMS 5365001671717 EA00011FB239981010002RGE A6C 0120505129 18101105015FT
A0AFLZ 6625013922071 EA00001FB239981070001RGRN D6C 0120505110 18107150014FT
A0AFLZ 6650013204283 EA00003FB239981070002NGRN D6C 0120504777 18107151015FT
A0ASMSS1650009937278 EA00006FB239981080001RAIR A6C 0120505 18108082906FT
And the code:
Public class Program
{
public static void Main(string[] arg)
{
XDocument A0x = new XDocument();
var IdCode = "511";
var CtrlNbr = "0001";
var PurposeCode = "00";
var TypeCode = "A0";
var EntyIdCode = "OB";
var IdCodeQlfr = "10";
var EntyIdCode1 = "FR";
var DocNbr = "TN";
var AssignNbr = "1";
var NSN = "FS";
var DD = "74";
var AgncyQlfrCode = "DF";
var LstQlfrCode = "0";
DateTime saveUtcNow = DateTime.UtcNow;
DateTime saveNow = DateTime.Now;
var field = new ParseTextFile().Parse();
var tagBuilder = new TagBuilder();
var parent = tagBuilder.BuildParent("File");
var subParent = tagBuilder.BuildParent("T_Requisition_511");
var ParentST = tagBuilder.BuildParent("S_Transaction_Set_Header");
var ST01 = tagBuilder.BuildChild("E_Transaction_Set_Identifier_Code", IdCode);
var ST02 = tagBuilder.BuildChild("E_Transaction_Set_Control_Number", CtrlNbr);
var ParentBR = tagBuilder.BuildParent("S_Beginning_Segment_for_Material_Management");
var BR01 = tagBuilder.BuildChild("E_Transaction_Set_Purpose_Code", PurposeCode);
var BR02 = tagBuilder.BuildChild("E_Transaction_Type_Code", TypeCode);
var BR03 = tagBuilder.BuildChild("E_Date", saveUtcNow.ToString("yyyyMMdd"));
var BR09 = tagBuilder.BuildChild("E_Time", saveUtcNow.ToString("hhmmss"));
var ParentN1 = tagBuilder.BuildParent("L_Name");
var ParentS = tagBuilder.BuildParent("S_Name");
var N101 = tagBuilder.BuildChild("E_Entity_Identifier_Code", EntyIdCode);
var N103 = tagBuilder.BuildChild("E_Identification_Code_Qualifier", IdCodeQlfr);
var N104 = tagBuilder.BuildChild("E_Identification_Code", field.SRAN);
var N106 = tagBuilder.BuildChild("E_Entity_Identifier_Code_1", EntyIdCode1);
var ParentLX = tagBuilder.BuildParent("L_Assigned_Number");
var ParentAN = tagBuilder.BuildParent("S_Assigned_Number");
var LX01 = tagBuilder.BuildChild("E_Assigned_Number", AssignNbr);
var ParentN9 = tagBuilder.BuildParent("S_Reference_Identification");
var N901 = tagBuilder.BuildChild("E_Reference_Identification_Qualifier", DocNbr);
var N902 = tagBuilder.BuildChild("E_Reference_Identification", field.DocumentNumber);
var ParentPO1 = tagBuilder.BuildParent("S_Baseline_Item_Data");
var PO102 = tagBuilder.BuildChild("E_Quantity_Ordered", Convert.ToString(field.Quantity));
var PO103 = tagBuilder.BuildChild("E_Unit_or_Basis_for_Measurement_Code", field.UnitofIssue);
var PO106 = tagBuilder.BuildChild("E_Product_Service_ID_Qualifier", NSN);
var PO107 = tagBuilder.BuildChild("E_Product_Service_ID", field.StockNumber);
var ParentSE = tagBuilder.BuildParent("S_Transaction_Set_Trailer");
var SE01 = tagBuilder.BuildChild("E_Number_of_Included_Segments", new CountSegmentTags().CountSgmts().ToString());
var SE02 = tagBuilder.BuildChild("E_Transaction_Set_Control_Number", CtrlNbr);
parent.Add(subParent);
subParent.Add(ParentST);
ParentST.Add(ST01);
ParentST.Add(ST02);
subParent.Add(ParentBR);
ParentBR.Add(BR01);
ParentBR.Add(BR02);
ParentBR.Add(BR03);
ParentBR.Add(BR09);
subParent.Add(ParentN1);
ParentN1.Add(ParentS);
ParentS.Add(N101);
ParentS.Add(N103);
ParentS.Add(N104);
ParentS.Add(N106);
subParent.Add(ParentLX);
ParentLX.Add(ParentAN);
ParentAN.Add(LX01);
ParentLX.Add(ParentN9);
ParentN9.Add(N901);
ParentN9.Add(N902);
ParentLX.Add(ParentPO1);
ParentPO1.Add(PO102);
ParentPO1.Add(PO103);
ParentPO1.Add(PO106);
ParentPO1.Add(PO107);
ParentSE.Add(SE01);
ParentSE.Add(SE02);
A0x.Add(parent);
A0x.Declaration = new XDeclaration("1.0", "utf-8", "true");
A0x.Save("M24EX.xml");
}
public class TagBuilder
{
public XElement BuildParent(string name)
{
return new XElement(name);
}
public XElement BuildChild(string name, string value)
{
var tag = new XElement(name);
tag.Add(value);
return tag;
}
}
public void Read()
{
int counter = 0;
string line;
StreamReader file = new StreamReader("M24EX.txt");
while ((line = file.ReadLine()) != null)
if (line.StartsWith("A0")) // only pull "A0x" records
{
counter++;
Console.WriteLine("{0}:{1}", counter, line);
}
file.Close();
}
public class ParseTextFile
{
public TransactionFields Parse()
{
StreamReader file = new StreamReader("M24Ex.txt");
string line;
int counter = 0;
var field = new TransactionFields();
while ((line = file.ReadLine()) != null)
if (line.StartsWith("A0"))
{
//Assigns field to the Transaction field names
field.DocumentIdentifier = line.Substring(0, 3).Trim(); // Tric
field.RoutingIdentifier = line.Substring(4, 3).Trim();
field.MediaStatusCode = line.Substring(7, 1).Trim();
field.StockNumber = line.Substring(7, 15).Trim();
field.UnitofIssue = line.Substring(22, 2).Trim();
field.Quantity = Convert.ToInt32(line.Substring(24, 5));
field.DocumentNumber = line.Substring(29, 14).Trim();
field.SRAN = line.Substring(29, 6).Trim();
field.DemandCode = line.Substring(44, 1).Trim();
field.SupplementaryAddress = line.Substring(45, 6).Trim();
field.SignalCode = line.Substring(51, 1).Trim();
field.FundCode = line.Substring(52, 2).Trim();
field.DistributionCode = line.Substring(54, 3).Trim();
field.ProjectCode = line.Substring(57, 3).Trim();
field.Priority = line.Substring(60, 2).Trim();
field.ReqDeliveryDate = line.Substring(62, 3).Trim();
field.AdviceCode = line.Substring(65, 2).Trim();
field.DateReceiptofReq = line.Substring(67, 3).Trim();
field.PurposeCode = line.Substring(70, 1).Trim();
field.ConditionCode = line.Substring(71, 1).Trim();
field.MgmtCode = line.Substring(72, 1).Trim();
}
file.Close();
return field;
}
}
public class ConvertXmlToText
{
public void ConvertXmlDoc()
{
string onlyContent = string.Empty;
XmlDocument xdoc = new XmlDocument();
xdoc.Load("A0x.xml");
var file = xdoc.SelectNodes("File/T_Requisition_511");
for (int i = 0; i < file.Count; i++)
{
onlyContent += string.Format("\n", i);
foreach (XmlNode node in file[i].ChildNodes)
onlyContent += string.Format("{0},", node.InnerText);
}
File.WriteAllText("A0x.txt", onlyContent);
}
}
public class TransactionFields
{
public string DocumentIdentifier { get; set; }
public string RoutingIdentifier { get; set; }
public string MediaStatusCode { get; set; }
public string StockNumber { get; set; }
public string UnitofIssue { get; set; }
public int Quantity { get; set; }
public string DocumentNumber { get; set; }
public string SRAN { get; set; }
public string DemandCode { get; set; }
public string SupplementaryAddress { get; set; }
public string SignalCode { get; set; }
public string FundCode { get; set; }
public string DistributionCode { get; set; }
public string ProjectCode { get; set; }
public string Priority { get; set; }
public double UnitPrice { get; set; }
public string Date { get; set; }
public string Time { get; set; }
}

Assign Value in List using lambda expression

I have following classes:
public class ProviderQualificationTimeViewModel
{
public string SessionId { get; set; }
public List<ProviderQualificationDetail> ProviderQualificationDetails { get; set; }
}
public class ProviderQualificationDetail
{
public string ProviderName { get; set; }
public string ProviderQualificationTime { get; set; }
public string TotalServiceableOffers { get; set; }
}
Basically, I want to create a new object if condition is true else I want to update ProviderQualificationDetail.ProviderQualificationTime where ProviderQualificationDetail.ProviderName == providerName
Is it possible using lambda expression?
List<ProviderQualificationDetail> providerQualificationDetail = new List<ProviderQualificationDetail>();
foreach (ProviderModel providers in allProviders)
{
if(!providerQualificationDetail.Any(p=>p.ProviderName.Contains(providerName)))
{
ProviderQualificationDetail ProviderQualificationDetail = new ProviderQualificationDetail();
ProviderQualificationDetail.ProviderName = providerName;
ProviderQualificationDetail.ProviderQualificationTime = Math.Round(processingTime).ToString();
ProviderQualificationDetail.TotalServiceableOffers = "Not serviceable";
providerQualificationDetail.Add(ProviderQualificationDetail);
}
else
{
//Lambda expression here
}
}
like this in else part:
foreach (var item in providerQualificationDetail.Where(x => x.ProviderName== providerName))
{
item.ProviderQualificationTime = Math.Round(processingTime).ToString();
}
Or
providerQualificationDetail.Where(x => x.ProviderName == ProviderName).Select(c =>
{
c.ProviderQualificationTime = "new time ";
return providerQualificationDetail;
}).ToList();
Or
providerQualificationDetail.ForEach(x =>
{
if(x.ProviderName == ProviderName)
x.ProviderQualificationTime = "new time";
});
Try this....
List<ProviderQualificationDetail> providerQualificationDetail = new List<ProviderQualificationDetail>();
foreach (ProviderModel providers in allProviders)
{
if(!providerQualificationDetail.Any(p=>p.ProviderName.Contains(providerName)))
{
ProviderQualificationDetail ProviderQualificationDetail = new ProviderQualificationDetail();
ProviderQualificationDetail.ProviderName = providerName;
ProviderQualificationDetail.ProviderQualificationTime = Math.Round(processingTime).ToString();
ProviderQualificationDetail.TotalServiceableOffers = "Not serviceable";
providerQualificationDetail.Add(ProviderQualificationDetail);
}
else
{
var qualificationDetail = providerQualificationDetail.SingleOrDefault(p => p.ProviderName.Equals(providerName));
//Assing your values here
//example;
qualificationDetail.ProviderName = NewProviderName.ToString();
providerQualificationDetail.SaveChanges();
}
}

set content-available using moon apns

referring to this link : http://www.objc.io/issue-5/multitasking.html i can now send a silent push notification on ios by setting content-available=1
i'm using moon apns on c# to send the push notification but i can not find this property to send a silent push (i'm using a development certificate)
below is my code :
string p12File = "test.p12";
string p12FilePassword = "1234";
bool sandbox = false;
var push = new PushNotification(sandbox, p12File, p12FilePassword);
NotificationPayload payload1;
payload1 = new NotificationPayload(testDeviceToken, message, 0, "Silence.m4R");
payload1.AddCustom("message", "HIDDEN");
var notificationList = new List<NotificationPayload>() { payload1 };
var rejected = push.SendToApple(notificationList);
foreach (var item in rejected)
{
return false;
}
any idea how can send this using moon apns :
{
"aps" : {
"content-available" : 1
},
"content-id" : 42
}
System;
using System.Collections.Generic;
using System.Text;
using Newtonsoft.Json.Linq;
namespace MoonAPNS
{
public class NotificationPayload
{
public NotificationAlert Alert { get; set; }
public string DeviceToken { get; set; }
public int? Badge { get; set; }
public string Sound { get; set; }
internal int PayloadId { get; set; }
public int Content_available { get; set; }
public Dictionary<string, object[]> CustomItems
{
get;
private set;
}
public NotificationPayload(string deviceToken)
{
DeviceToken = deviceToken;
Alert = new NotificationAlert();
CustomItems = new Dictionary<string, object[]>();
}
public NotificationPayload(string deviceToken, string alert)
{
DeviceToken = deviceToken;
Alert = new NotificationAlert() { Body = alert };
CustomItems = new Dictionary<string, object[]>();
}
public NotificationPayload(string deviceToken, string alert, int badge)
{
DeviceToken = deviceToken;
Alert = new NotificationAlert() { Body = alert };
Badge = badge;
CustomItems = new Dictionary<string, object[]>();
}
public NotificationPayload(string deviceToken, string alert, int badge, string sound)
{
DeviceToken = deviceToken;
Alert = new NotificationAlert() { Body = alert };
Badge = badge;
Sound = sound;
CustomItems = new Dictionary<string, object[]>();
}
public NotificationPayload(string deviceToken, string alert, int badge, string sound,int content_available)
{
DeviceToken = deviceToken;
Alert = new NotificationAlert() { Body = alert };
Badge = badge;
Sound = sound;
Content_available = content_available;
CustomItems = new Dictionary();
}
public void AddCustom(string key, params object[] values)
{
if (values != null)
this.CustomItems.Add(key, values);
}
public string ToJson()
{
JObject json = new JObject();
JObject aps = new JObject();
if (!this.Alert.IsEmpty)
{
if (!string.IsNullOrEmpty(this.Alert.Body)
&& string.IsNullOrEmpty(this.Alert.LocalizedKey)
&& string.IsNullOrEmpty(this.Alert.ActionLocalizedKey)
&& (this.Alert.LocalizedArgs == null || this.Alert.LocalizedArgs.Count <= 0))
{
aps["alert"] = new JValue(this.Alert.Body);
}
else
{
JObject jsonAlert = new JObject();
if (!string.IsNullOrEmpty(this.Alert.LocalizedKey))
jsonAlert["loc-key"] = new JValue(this.Alert.LocalizedKey);
if (this.Alert.LocalizedArgs != null && this.Alert.LocalizedArgs.Count > 0)
jsonAlert["loc-args"] = new JArray(this.Alert.LocalizedArgs.ToArray());
if (!string.IsNullOrEmpty(this.Alert.Body))
jsonAlert["body"] = new JValue(this.Alert.Body);
if (!string.IsNullOrEmpty(this.Alert.ActionLocalizedKey))
jsonAlert["action-loc-key"] = new JValue(this.Alert.ActionLocalizedKey);
aps["alert"] = jsonAlert;
}
}
if (this.Badge.HasValue)
aps["badge"] = new JValue(this.Badge.Value);
if (!string.IsNullOrEmpty(this.Sound))
aps["sound"] = new JValue(this.Sound);
if (this.Content_available == 1)
aps["content-available"] = new JValue(this.Content_available);
json["aps"] = aps;
foreach (string key in this.CustomItems.Keys)
{
if (this.CustomItems[key].Length == 1)
json[key] = new JValue(this.CustomItems[key][0]);
else if (this.CustomItems[key].Length > 1)
json[key] = new JArray(this.CustomItems[key]);
}
string rawString = json.ToString(Newtonsoft.Json.Formatting.None, null);
StringBuilder encodedString = new StringBuilder();
foreach (char c in rawString)
{
if ((int)c < 32 || (int)c > 127)
encodedString.Append("\\u" + String.Format("{0:x4}", Convert.ToUInt32(c)));
else
encodedString.Append(c);
}
return rawString;// encodedString.ToString();
}
public override string ToString()
{
return ToJson();
}
}

Why is my JSON Response not being Deserialized on my Client into the same Generic List Type as the Origin IEnumerable Type on the Web API server?

If I understand Ufuk Hacıoğulları here
I can simplify this code:
using (var webResponse = (HttpWebResponse)webRequest.GetResponse())
{
if (webResponse.StatusCode == HttpStatusCode.OK)
{
var reader = new StreamReader(webResponse.GetResponseStream());
string s = reader.ReadToEnd();
var arr = JsonConvert.DeserializeObject<JArray>(s);
if (arr.Count <= 0) break;
foreach (JObject obj in arr)
{
id = obj.Value<int?>("Id") ?? 0;
var _deptId = obj.Value<int?>("deptId") ?? 0;
var _subdeptId = obj.Value<int?>("subdeptId") ?? 0;
var _deptIdSubdeptId = Convert.ToDouble(String.Format("{0}.{1}", _deptId, _subdeptId));
var _subdeptName = obj.Value<string>("subdeptName") ?? "";
subDeptList.subDepartments.Add(new HHSUtils.Subdepartment
{
Id = id,
deptIdSubdeptId = (float)_deptIdSubdeptId,
subDeptName = _subdeptName
});
} // foreach
} // if ((webResponse.StatusCode == HttpStatusCode.OK)
} // using HttpWebResponse
...if I were to "use custom types instead of JArray or JObject types"
If I understand what he's saying, I could replace this line:
var arr = JsonConvert.DeserializeObject<JArray>(s);
...with something like:
var subDeptList = new SubdeptsList();
. . .
var arr = JsonConvert.DeserializeObject<Subdepartment>(s);
foreach (HHSUtils.Subdepartment obj in arr)
{
subDeptList.subDepartments.Add(obj);
}
Yet doing so fails with, "Exception: Cannot deserialize JSON array into type 'HHS.HHSUtils+Subdepartment'."
What the server passes is an IEnumerable which is defined there as:
public class Redemption
{
[Key]
public long Id { get; set; }
[Required]
public string RedemptionId { get; set; }
[Required]
public string RedemptionName { get; set; }
[Required]
public string RedemptionItemId { get; set; }
[Required]
public double RedemptionAmount { get; set; }
public string RedemptionDept { get; set; }
public string RedemptionSubDept { get; set; }
}
And it converts that data to JSON when passing it back; in the client, I'm attempting to convert the sent JSON back to this:
public class Redemption
{
public long Id { get; set; }
public string RedemptionId { get; set; }
public string RedemptionItemId { get; set; }
public string RedemptionName { get; set; }
public double RedemptionAmount { get; set; }
public string RedemptionDept { get; set; }
public string RedemptionSubDept { get; set; }
}
...with the code shown above. The only mismatch I can see (besides the class member "decorations" (Key, Required) the Redemption has on the server, which are missing on the client), is that on the server the generic list is an IEnumerable, whereas on the client it's a List:
public class SubdeptsList
{
public List<Subdepartment> subDepartments = new List<Subdepartment>();
}
So how can I more directly transfer the JSON object to my client, rather than use the JArray/JObject? Is it really feasible?
This is what I ended up with; Ufuk's suggestion has led to much more streamlined/elegant code:
// the old way:
using (var webResponse = (HttpWebResponse)webRequest.GetResponse())
{
if (webResponse.StatusCode == HttpStatusCode.OK)
{
var reader = new StreamReader(webResponse.GetResponseStream());
string s = reader.ReadToEnd();
var arr = JsonConvert.DeserializeObject<JArray>(s);
if (arr.Count <= 0) break;
foreach (JObject obj in arr)
{
id = obj.Value<int?>("Id") ?? 0;
var _redemptionId = obj.Value<string>("RedemptionId") ?? "";
var _redemptionItemId = obj.Value<string>("RedemptionItemId") ?? "";
var _redemptionName = obj.Value<string>("RedemptionName") ?? "";
double _redemptionAmount = obj.Value<double?>("RedemptionAmount") ?? 0.0;
var _redemptionDept = obj.Value<string>("RedemptionDept") ?? "";
var _redemptionSubdept = obj.Value<string>("RedemptionSubDept") ?? "";
redemptionsList.redemptions.Add(new Redemption
{
Id = id,
RedemptionId = _redemptionId,
RedemptionItemId = _redemptionItemId,
RedemptionName = _redemptionName,
RedemptionAmount = _redemptionAmount,
RedemptionDept = _redemptionDept,
RedemptionSubDept = _redemptionSubdept
});
} // foreach
} // if ((webResponse.StatusCode == HttpStatusCode.OK)
} // using HttpWebResponse
And now the new and improved way:
using (var webResponse = (HttpWebResponse)webRequest.GetResponse())
{
if (webResponse.StatusCode == HttpStatusCode.OK)
{
var reader = new StreamReader(webResponse.GetResponseStream());
string jsonizedRedemptions = reader.ReadToEnd();
List<Redemption> redemptions = JsonConvert.DeserializeObject<List<Redemption>>(jsonizedRedemptions);
if (redemptions.Count <= 0) break;
foreach (Redemption redemption in redemptions)
{
redemptionsList.redemptions.Add(redemption);
}
} // if ((webResponse.StatusCode == HttpStatusCode.OK)
} // using HttpWebResponse

Categories

Resources