|
I'm fairly new to Serialization, most of my work has been direct DB or Simple Serialize an object using json. I'm trying to read an XML document using an XmlSerializer. I've done this in the past from an XSD but there is none for this application. and Im lost
The XML file looks like this
<? xml version="1.0" encoding="utf-8"?>
<DTAXDOC>
<DATA>
<KEY FIELDID = "1" > Hello World</ KEY>
</DATA>
</DTAXDOC>
And this is my simple sample app
using System;
using System.IO;
using System.Xml.Serialization;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var ser = new XmlSerializer(typeof(POCO.DTAxType));
var returned = (DTAxType)ser.Deserialize(new FileStream("D:\\HelloWorld.txt", FileMode.Open));
}
}
[Serializable]
[XmlRoot("DTAXDOC", Namespace = "", IsNullable = false)]
public class DTAxType
{
[XmlElement("DATA")]
public KeyType[] Data { set; get; }
}
[Serializable]
[XmlType("DATA")]
public class KeyType
{
[XmlAttribute("FIELDID")]
public int FieldId { set; get; }
public string Value { set; get; }
}
}
When I run the app I get nothing but an empty object
Am I a complete idiot or missing something simple. In the finished solution The Data variable should be a List of KeyType.
Thanks in advance for any help.
|
|
|
|
|
Assuming the extra spaces in your sample XML aren't actually present in your file, there are two problems.
First, the KeyType element is too high. You've declared that it's taken from the DATA node, but it's actually a descendant of that node.
Second, the Value property needs to be decorated with the [XmlText] attribute.
[Serializable]
[XmlRoot("DTAXDOC", Namespace = "", IsNullable = false)]
public class DTAxType
{
[XmlElement("DATA")]
public DataType[] Data { set; get; }
}
[Serializable]
[XmlType("DATA")]
public class DataType
{
[XmlElement("KEY")]
public KeyType[] Key { set; get; }
}
[Serializable]
[XmlType("KEY")]
public class KeyType
{
[XmlAttribute("FIELDID")]
public int FieldId { set; get; }
[XmlText]
public string Value { set; get; }
}
With those changes in place, your sample XML deserializes to:
new DTAxType
{
Data = new[]
{
new DataType
{
Key = new[]
{
new KeyType
{
FieldId = 1,
Value = "Hello World"
}
}
}
}
}
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Perfect thanks. for the help
|
|
|
|
|
I'm working on a program that is behaving differently when I debug than when I run it. Everyone I've described it to says it sounds like a data race is happening, but if I've done any of the kinds of things that can possibly lead to data races, I've done it without realizing.
It won't compile on its own, but this is the function that is behaving unexpectedly:
static public Dictionary<ComplexNumber, int> getFactorization(ComplexNumber x)
{
ComplexNumber xGaussian = new ComplexNumber(x.getRealPart().getNumerator() *
x.getImaginaryPart().getDenominator(), x.getImaginaryPart().getNumerator() *
x.getRealPart().getDenominator());
Dictionary<int, int> denominatorCancellerFactors =
getFactorization(x.getRealPart().getDenominator() *
x.getImaginaryPart().getDenominator());
Dictionary<ComplexNumber, int> factors = new Dictionary<ComplexNumber, int>();
foreach (int factor in denominatorCancellerFactors.Keys)
factors.Add(new ComplexNumber(new Fraction(1, factor), new Fraction(0, 1)),
denominatorCancellerFactors[factor]);
int sumOfRealAndImaginary = 2;
while (true)
{
Console.WriteLine(sumOfRealAndImaginary);
int realPart = sumOfRealAndImaginary / 2;
int imaginaryPart = sumOfRealAndImaginary - realPart;
for (int i = 0; realPart - i >= 0;)
{
if ((realPart - i) * (realPart - i) +
(imaginaryPart + i) * (imaginaryPart + i) >
xGaussian.getRealPart().getNumerator() *
xGaussian.getRealPart().getNumerator() +
xGaussian.getImaginaryPart().getNumerator() *
xGaussian.getImaginaryPart().getNumerator())
{
if (factors.ContainsKey(xGaussian))
factors[xGaussian] += 1;
else
factors.Add(xGaussian, 1);
return factors;
}
ComplexNumber factor =
new ComplexNumber(realPart - i, imaginaryPart + i);
ComplexNumber quotient = (ComplexNumber)(xGaussian / factor);
quotient.getRealPart().reduce();
quotient.getImaginaryPart().reduce();
if (quotient.getRealPart().getDenominator() == 1 &&
quotient.getImaginaryPart().getDenominator() == 1)
{
if (factors.ContainsKey(factor))
factors[factor] += 1;
else
factors.Add(factor, 1);
xGaussian = (ComplexNumber)(xGaussian / factor);
continue;
}
factor = new ComplexNumber(realPart - i, -imaginaryPart - i);
quotient = (ComplexNumber)(xGaussian / factor);
quotient.getRealPart().reduce();
quotient.getImaginaryPart().reduce();
if (quotient.getRealPart().getDenominator() == 1 &&
quotient.getImaginaryPart().getDenominator() == 1)
{
if (factors.ContainsKey(factor))
factors[factor] += 1;
else
factors.Add(factor, 1);
xGaussian = (ComplexNumber)(xGaussian / factor);
continue;
}
++i;
}
++sumOfRealAndImaginary;
}
}
The ComplexNumber type is designed to behave the way complex numbers do in math (though limited to real and imaginary parts that are rational) so I'll type the value of a ComplexNumber object the same way as I would a complex number in math.
Note how sumOfRealAndImaginary is initialized to 2, and the only place it's changed is where it's incremented at the bottom of the while loop. In debug mode, when I pass getFactorization() the value 3+4i and step through the code at a sufficiently moderate speed, it returns at a time when sumOfRealAndImaginary = 3 . This is what I expect. However, when I run the program, also with 3+4i as the function argument, it doesn't return until sumOfRealAndImaginary = 126 , as can be seen from the WriteLine() call at the top of the while loop. In particular, the first if statement in the while loop, whose code block includes the function's return statement, takes many more passes to evaluate to true when running than when debugging. It should evaluate to true not only for the expected sumOfRealAndImaginary value of 3, but also for every value larger than that. Also, when I step through the code sufficiently quickly in debug mode, that if statement keeps evaluating to false until I slow down, at which point it evaluates to true on the next pass. So it would seem that whether the if statement evaluates correctly depends on how quickly the code is executed. What could cause this behavior?
Unfortunately, any compilable test program I can figure out how to make for getFactorization() would include the majority of the original program, so...here is a text file of the code for the whole thing, for if the problem depends on the other parts of my code that getFactorization() refers to, and in case people need to test it themselves firsthand. A command line input of (3+4i)^2 will cause getFactorization() to be called with an argument of 3+4i.
modified 5-Oct-17 12:53pm.
|
|
|
|
|
It happens because of reduce in Fraction (more accurately, because it gets called at some later time, instead of directly at construction). Likely (though this is hard to test) because single-stepping actually calls it (since the debugger calls ToString on locals to display them, and ToString does a reduce). Calling reduce late causes problems, like changing the hash value of objects or whatever, though GetHashCode does call reduce already. Nevertheless something goes wrong because of this, which I could fix by stopping all those random reduces and just reducing in the constructor.
I recommend making all of those types immutable, and reducing in the constructor of Fraction.
Bonus: I also recommend not using | to combine hash codes (which is very biased towards producing set bits in the result). The "basic choices" are XOR and addition, there are fancier combiners such as unchecked(x + 31 * y) . Choose basically whatever, just not OR. You don't need to call GetHashCode on an int.
Also your GCD-by-factorization is extreme overkill, just use the Euclidean algorithm.
modified 5-Oct-17 17:12pm.
|
|
|
|
|
Quote: Likely (though this is hard to test) because single-stepping actually calls it (since the debugger calls ToString on locals to display them, and ToString does a reduce).
I had noticed that what displays when I hover the cursor over a variable in debug mode is whatever the result of calling ToString on its value would be. I would have expected the IDE to effectively make a copy of the variable value and apply ToString to that so as not to impose any side effects a ToString override might have on the execution of the program itself. Is it, perhaps, very unusual to override ToString in a way that has side effects? The reason I did it here, for what it's worth, is so that Fraction objects only get reduced at times when they "need" to be, but you may be right that this causes problems. It's certainly worth it for me to try your suggestion and see if it fixes the problem. I would have thought reduce being called more often than I intended would be harmless as far as getFactorization and most other things are concerned, though. I'll have to think about whether it makes sense that it would cause the behavior I'm seeing, or if there's still an element to this that I don't understand.
Quote: Bonus: I also recommend not using | to combine hash codes (which is very biased towards producing set bits in the result).
Heh. I only used | in GetHashCode because at the time, all I was really interested in was the Equals overload, and | is what the MSDN documentation on the topic used. I'll look into ways to do it that are more proper at some point.
|
|
|
|
|
To be honest I don't fully understand what happened there either, it looks as though reducing multiple times (or never, in cases where it shouldn't be necessary) should be mostly harmless (except for overflow, which doesn't seem to happen in this test case).. but when I changed it to reducing in the constructor it behaved as expected, so I ended up blaming that anyway.
|
|
|
|
|
I made the change too and things are now working as expected (including for inputs that used to misbehave much worse than the one I described). It bothers me a little that I'm now doing more work reducing than is theoretically necessary, but I suppose viewing it as a relatively expensive operation will be less true if I implement a more efficient algorithm for it, as you point out is possible.
|
|
|
|
|
You could perhaps skip some unnecessary reductions in a more explicit way, though most of the ways to do that make it possible to hold an unreduced fraction and use it in ways that it isn't meant to be used. I'm think of approaches such as returning unreduced fractions from arithmetic operators, and having reduce return a new fraction. If you made reduced and unreduced fractions separate types, you could still maintain a safe interface, but it also complicates everything. I can't really think of a solution that is just all around a Great Solution, perhaps someone else has more inspiration?
TBH I would probably resort to just using plain ints in most of the math routines, so that from the outside all fractions are nice and reduced and no weird problems arise, but internally the cost of unnecessary reductions is not paid. Not a Great Solution since it breaks through the abstraction but I could live with that because it is contained. This approach probably allows the most optimization since everything is super explicit, so if that's the focus it may be reasonable.
With the Euclidean algorithm the cost of reducing is typically one or two divisions (a handful at worst) and a couple of branches, not ideal but probably not a huge deal, I don't know. Not as big a deal as factorization at least.
|
|
|
|
|
An experiment I ran:
using System;
namespace Test
{
class Foo
{
public int a = 2;
public override string ToString()
{
a = 3;
return a.ToString();
}
}
class Solver
{
public static void Main()
{
Foo x = new Foo();
Console.WriteLine(x.a);
}
}
}
This does indeed print 2 when run, but 3 when debugged, so the debugger definitely calls ToString directly on the object in the given code. While there are other details to fill in about what was happening in my program, this is one thing cleared up.
|
|
|
|
|
Hello everyone, first post here, so if you see errors on posting/explaining, make me know to fix it...
What i want to make it's form that parse an INTRANET webpage and bring me data back to show it on labels....
I have tried with HtlmAgilityPack, but it doesn't parse anything of that web, cause its intranet, and i'm doing something that don't fit well. It returns me an error like "specific node can't be null"...
Something like this:
public class Program
{
public static void Main()
{
var html = @"http://html-agility-pack.net/"; HERE GOES MY INTRANET URL, AND NOT THIS.
HtmlWeb web = new HtmlWeb();
var htmlDoc = web.Load(html);
var node = htmlDoc.DocumentNode.SelectSingleNode("//td/span");
}
}
Something like this:
https://imgur.com/uk4Wztd[^]
When click in the button, bring me the especific data.
|
|
|
|
|
Member 13447810 wrote: What i want to make it's form that parse an INTRANET webpage and bring me data back to show it on labels.... That makes no sense at all in my limited mind.
You have a webpage, shown in a browser. And now you want a WinForm to fetch those values?
Member 13447810 wrote: I have tried with HtlmAgilityPack, but it doesn't parse anything of that web, cause its intranet, and i'm doing something that don't fit well. Works as well with internet as well as intranet; there is no difference between those two on that level.
Bastard Programmer from Hell
If you can't read my code, try converting it here[^]
|
|
|
|
|
Eddy Vluggen wrote: That makes no sense at all in my limited mind.
You have a webpage, shown in a browser. And now you want a WinForm to fetch those values?
The problem is that people working here shouldn't use internet, but they do. So, we need to take them off of the browser, then putting it on a Winform will make it easier to block them from internet.
Any idea?
|
|
|
|
|
Install a firewall.
Building a new GUI does not make sense if you just want to limit access.
Bastard Programmer from Hell
If you can't read my code, try converting it here[^]
|
|
|
|
|
i have these data in sql table
Hide Copy Code
02 Dec 2013 Monday xxx 1 11:38:00 18:00:00
02 Dec 2013 Monday xxx 1 11:22:00 no time out
02 Dec 2013 Monday xxx 1 11:26:00 19:21:00
02 Dec 2013 Monday xxx 1 11:47:00 20:11:00
02 Dec 2013 Monday xxx 1 12:18:00 no time out
02 Dec 2013 Monday xxx 1 13:54:00 21:40:00
02 Dec 2013 Monday xxx 1 11:22:00 19:23:00
02 Dec 2013 Monday xxx 1 11:26:00 19:32:00
02 Dec 2013 Monday xxx 1 11:44:00 21:39:00
02 Dec 2013 Monday xxx 1 12:13:00 20:11:00
02 Dec 2013 Monday xxx 1 12:21:00 no time out
02 Dec 2013 Monday xxx 1 12:22:00 no time out
02 Dec 2013 Monday xxx 1 12:28:00 no time out
02 Dec 2013 Monday xxx 1 12:29:00 18:46:00
02 Dec 2013 Monday xxx 1 12:47:00 no time out
02 Dec 2013 Monday xxx 1 13:53:00 21:29:00
02 Dec 2013 Monday xxx 1 11:47:00 no time out
02 Dec 2013 Monday xxx 1 14:41:00 no time out
02 Dec 2013 Monday xxx 1 15:09:00 22:11:00
02 Dec 2013 Monday xxx 1 12:39:00 no time out
i want show this data like this
Hide Copy Code
Name 1-Dec 2-Dec 3-Dec
IN OUT IN OUT IN OUT
|
|
|
|
|
|
Hi i have 3 dropdowns the primary one is filled via jquery ajax request and it fills 2nd dropdown based on seletion and 3rd one is filled after 2nd's selection.
It was previously used Dropdown selected change event which AutoPostBack and gets data from server and page get refresh again and again. Instead of doing this i replace selection change events with jquery ajax calls and its seems fine but now when i click on my search button to fetch data based on selection it loses all dropdown's previous state and reset to default as on fresh page load. Whereas, my repeater remains the data which i had bound on button click. Any help regarding this issue???
|
|
|
|
|
Please use the ASP.NET forum for ASP.NET questions.
|
|
|
|
|
dear friends,
I'm new in Json, I need some help
here's the data:
{
"CardCode": "C001",
"PostingDate": "2017-05-17",
"DocDueDate": "2017-05-17",
"TaxDate": "2017-05-17",
"SalesPersonCode": "-1",
"DocumentNumberingPOS":"2",
"PrimaryNumberingPOS":"A002",
"lines": [{
"ItemCode": "ITEM0001",
"WarehouseCode": "PST-000",
"Quantity": "1",
"Price": "50000"
}, {
"ItemCode": "ITEM0002",
"WarehouseCode": "PST-000",
"Quantity": "1",
"Price": "10000"
}
]
}
and this is the result
{
"errorCode": "0",
"message": "Data has beed added",
"value": "23"
}
I've try to create the code in C#, but still nothing happen, and I don't know how to show the result in text box, and for the login to url, there's username: username and password: password,
here's my code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Net;
using Newtonsoft.Json;
namespace JsonTest
{
public partial class Form1 : Form
{
private string respon;
private static void PostJson(string url, template postParameters)
{
string postData = JsonConvert.SerializeObject(postParameters);
byte[] bytes = Encoding.UTF8.GetBytes(postData);
var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.Method = "POST";
httpWebRequest.ContentLength = bytes.Length;
httpWebRequest.ContentType = "application/json";
string autorization = "username" + ":" + "password";
byte[] binaryAuthorization = System.Text.Encoding.UTF8.GetBytes(autorization);
autorization = Convert.ToBase64String(binaryAuthorization);
autorization = "Basic " + autorization;
httpWebRequest.Headers.Add("AUTHORIZATION", autorization);
using (Stream requestStream = httpWebRequest.GetRequestStream())
{
requestStream.Write(bytes, 0, bytes.Count());
}
var httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
if (httpWebResponse.StatusCode != HttpStatusCode.OK)
{
string message = String.Format("POST failed. Received HTTP {0}", httpWebResponse.StatusCode);
throw new ApplicationException(message);
}
}
private static void Result(string url, template postParameters)
{
//string respon;
string postData = JsonConvert.SerializeObject(postParameters);
byte[] bytes = Encoding.UTF8.GetBytes(postData);
System.Net.WebRequest request = System.Net.HttpWebRequest.Create("http:xxxxxxxx/api/CustomerSalesOrder"); // This only for your testing
var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.Method = "GET";
httpWebRequest.ContentLength = bytes.Length;
httpWebRequest.ContentType = "application/json";
string autorization = "admin" + ":" + "admin";
byte[] binaryAuthorization = System.Text.Encoding.UTF8.GetBytes(autorization);
autorization = Convert.ToBase64String(binaryAuthorization);
autorization = "Basic " + autorization;
httpWebRequest.Headers.Add("AUTHORIZATION", autorization); //System.Net.WebRequest request = System.Net.HttpWebRequest.Create("(ServerLocal)/WSLokalRest/Peserta/peserta/" + txtNoKartu.Text); Get This from your Client (live)
try
{
System.Net.WebResponse response1 = request.GetResponse();
System.IO.Stream stream = response1.GetResponseStream();
System.IO.StreamReader reader = new System.IO.StreamReader(stream);
string contents = reader.ReadToEnd();
respon = contents;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
PostJson("http:xxxxxxx/api/CustomerSalesOrder", new template{ });
var template = new template
{
CardCode = "C001",
PostingDate = "2017-05-17",
DocDueDate = "2017-05-17",
TaxDate = "2017-05-17",
SalesPersonCode = "-1",
DocumentNumberingPOS = "2",
PrimaryNumberingPOS = "A002",
};
template.Lines.Add(new template_item
{
ItemCode = "ITEM0001",
WarehouseCode = "PST-000",
Quantity = "1",
Price = "50000",
});
template.Lines.Add(new template_item
{
ItemCode = "ITEM0002",
WarehouseCode = "PST-000",
Quantity = "1",
Price = "10000"
});
txtRespon.Text = respon;
}
}
public class template
{
public string CardCode { get; set; }
public string PostingDate { get; set; }
public string DocDueDate { get; set; }
public string TaxDate { get; set; }
public string SalesPersonCode { get; set; }
public string DocumentNumberingPOS { get; set; }
public string PrimaryNumberingPOS { get; set; }
public static List<template_item> Lines = new List<template_item>();
}
public class template_item
{
public string ItemCode { get; set; }
public string WarehouseCode { get; set; }
public string Quantity { get; set; }
public string Price { get; set; }
}
}
Does anyone could help me ?
Thank you for your help
Regards,
Steve Henry
|
|
|
|
|
|
That is lousy advice, as a newbie he may want a discussion on how to achieve his requirements.
Redirecting his inquiry from c# to web forum or quick answers may be valid because of the context of the question but to redirect everything to quick answers for a "speedy" response is not valid.
Never underestimate the power of human stupidity
RAH
|
|
|
|
|
This is the first post for him in Codeproject, may be he is not aware of quick answers section thats why gave a headsup.
since the question is related to json, he might get quick response in QA.
|
|
|
|
|
I agree with Mycroft, there is nothing wrong with the OP's question being here. And no guarantee that he will get a faster answer in QA.
|
|
|
|
|
You have not explained what is wrong with the result, or where you think your code is going wrong. Also, it would really help if you use proper indentation of your code, and the code button to add <pre></pre> tags around your code to make it readable, thus:
public class template_item
{
public string ItemCode { get; set; }
public string WarehouseCode { get; set; }
public string Quantity { get; set; }
public string Price { get; set; }
}
|
|
|
|
|
Hello everyone, I kindly ask for an orientation in my code, which is done in C # with Android Debug Bridge (ADB) commands that run at a DOS prompt.
The command basically reads the serial number from my tablet and transfers it to a textBox. Until then, no problem. However I need to copy this serial number from this textBox and transfer it to a new ADB command in DOS to read the battery data. Below is the code for better understanding, the first block is to get the serial number and transfer it to textBox1:
{
System.Diagnostics.Process process = new System.Diagnostics.Process();
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
startInfo.UseShellExecute = false;
startInfo.RedirectStandardOutput = true;
startInfo.FileName = "adb.exe";
startInfo.Arguments = "get-serialno";
process.StartInfo = startInfo;
process.Start();
string output1 = process.StandardOutput.ReadToEnd();
textBox1.Text = output1;
process.WaitForExit();
}
And the second block is the code that will direct the commands to the serial number:
startInfo.FileName = "adb.exe";
startInfo.Arguments = "-s " + textBox1.Text + " shell dumpsys battery";
process.StartInfo = startInfo;
process.Start();
string output = process.StandardOutput.ReadToEnd();
richTextBox1.Text = output;
process.WaitForExit();
But I can not get it to recognize the variable in the argument line. I've tried to concatenate, without success ... where am I going wrong? What I've already tried, in the searches I've done:
startInfo.Arguments = String.Format(@"/c adb -s ""{0}"" shell dumpsys battery", output1);
startInfo.Arguments = "/c adb -s \"" + output1 + "\" shell dumpsys battery";
startInfo.Arguments = $@"/c adb -s ""{output1}"" shell dumpsys battery";
Thanks a lot!
|
|
|
|
|