|
|
string date1 = $"{DateTime.Now:MM/dd/yyyy}";
"(I) am amazed to see myself here rather than there ... now rather than then".
― Blaise Pascal
|
|
|
|
|
That looks interesting.
Actually my final output model is string for the date.
I'm gonna look into this.
If it ain't broke don't fix it
|
|
|
|
|
I have an XML file that I'm pulling data in and out of some lines are nothing more than crlf
<KEY FIELDID="451">
</KEY>
The property in the POCO class is structured like this
[XmlText]
public string Value { set; get; }
I can serialize the file and 451 comes back empty or when I save it saves as empty
<KEY FIELDID="451" />
I can update it to "\r\n" and it puts it back in the saved file.
var returned = MyType.Load("D:\\Sample.xml");
returned.AddUpdate(451,"\r\n");
MyType.Save(returned,"D:\\Output.xml");
Other Records with \r\n in them with additional data work with no problems
|
|
|
|
|
Not sure what you are talking about.
You have a 'element' which has a name of 'KEY'. The value of that element is some whitespace.
The element also has an 'attribute'. And the attribute name is 'FIELDID' with a value of '451'.
The element and attribute are not the same.
Without knowing the actual usage of the element (not attribute) I cannot speak to the value of it but certainly if you want a specific value then you must set it.
End of line characters shouldn't be in an attribute at all, so presumably you are referring to the element.
But an element that has nothing but whitespace, especially when it is named 'KEY' should be irrelevant and not needed.
So in summary.
1. If you want to change the value of the element then set it.
2. If you want to change the value of the attribute then set that (different than 1) and do not attempt to be end of line characters in it.
|
|
|
|
|
Let me try this again then. The item in question is not a whitespace it is a crlf which is needed by a separate app. (Yea I know, don't ask)
The XML file has a series of Key Elements each element has a FieldID and a value
<KEY FIELDID="72">TX</KEY>
I have my serializer working great except for the instances where the value is a crlf
<KEY FIELDID="451">
</KEY>
In this instance the serializer strips out the crlf and returns an null value.
I have other Keys that have data like
<pre> <KEY FIELDID="510">This one works
Really well
</KEY>
I'm having trouble understanding why the one with just a crlf comes back null and the multi line works fine. My Ultimate question is there a parameter/markup I need to add so that the crlf line works like the multi line.
I am reasonably new to XML most of my career I've worked heavily with Databases and only ever had to read output from a service and save it as xml. so this is out side of my wheelhouse.
|
|
|
|
|
XML and white-space don't generally work well together:
2.10 White Space Handling | Extensible Markup Language (XML) 1.1[^]
Unfortunately, the usual workarounds don't seem to apply to XML deserialization. Adding xml:space="preserve" , or passing in an XmlReader set to not ignore white-space, makes no difference to the result.
The only way I can see for you to preserve the white-space in an empty node is to use a CDATA element:
<KEY FIELDID="1"><![CDATA[</KEY>
[Serializable]
[XmlType("KEY")]
public class KeyType
{
[XmlAttribute("FIELDID")]
public int FieldId { set; get; }
[XmlText]
public string Value { set; get; }
[XmlElement("")]
public XmlCDataSection Content
{
get
{
return new XmlDocument().CreateCDataSection(Value);
}
set
{
if (value == null)
{
Value = null;
}
else
{
Value = value.Value;
}
}
}
}
c# - How do you serialize a string as CDATA using XmlSerializer? - Stack Overflow[^]
NB: ALL white-space within the CDATA element will be returned. So if your XML is:
<DATA>
<KEY FIELDID="1"><![CDATA[</KEY>
</DATA> your content will include the white-space at the start of the next line. If you wanted just the line break, the closing ]]> would need to be the first thing on the line, with no indentation.
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Well crap that is not the answer I was looking for. again its not whitespace it is literally a crlf. Perhaps XML treats it the same. Just wanted to make sure I was clear. Our current reader / writer is almost 200 lines of code that is unbelievably slow. If I can get over that one hurdle I can replace it with 10 poco classes and this method
public static MyType Load(string filename)
{
var ser = new XmlSerializer(typeof(MyType));
var returned = (MyType)ser.Deserialize(new FileStream(filename, FileMode.Open));
return returned;
}
Guess its time to get the other Guy to test my output and see if it breaks his app, if not I'm good. I was trying to open an existing file and save it as an exact match with the exception of
<Key FIELDID="123"></Key>
becoming
<Key FIELDID="123"/>
Thanks again for all your help.
If I have to keep the crlf in the file and find a way I'll post it here
I can't be the only moron to ever need to do this
|
|
|
|
|
C. David Johnson wrote: its not whitespace it is literally a crlf
CrLf is white-space!
Whitespace character - Wikipedia[^]
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
C. David Johnson wrote: Well crap that is not the answer I was looking for
Presumably you are not passing the xml data but rather a string.
So once you have the string use string (not xml) insertion to add the whitespace.
And ALSO add a comment both in the xml handling code and the string insertion code to explain why you are doing that.
|
|
|
|
|
FIELDID is an "attribute" and you need to tag it as such; e.g.
[System.Xml.Serialization.XmlAttributeAttribute()]
public ushort FIELDID { get; set; }
"(I) am amazed to see myself here rather than there ... now rather than then".
― Blaise Pascal
|
|
|
|
|
Hi,
In this value, 1.0, I want to compare the 0 value. While the code works if the value is 1.5, I am able to compare 5, i am not able to do the same with 0.
This works:: Convert.ToDouble(1.5).ToString().Split('.')[1]; I get a 5 value.
But this does not work :Convert.ToDouble(1.0).ToString().Split('.')[1]; I get an error message, out of bounds.
any ideas?
thanks.
|
|
|
|
|
You need to use a format string which produces a fixed number of decimal places - for example, "F3" .
Standard Numeric Format Strings | Microsoft Docs[^]
You'll also need to use the invariant culture, in case the current culture uses a different decimal separator.
string s = value.ToString("F3", CultureInfo.InvariantCulture).Split('.')[1];
But if you explain what you're actually trying to achieve, there's probably a better way to do it.
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Don't use compound statements like the above, and assume that they will do what you want. As you can see they often do not. In your case (double)1.0.ToString() produces the simple string "1". Which, if you had split the statement into its constituent parts you would have seen immediately.
I am not sure what actual problem you are trying to solve here but I suspect there are much simpler mathematical ways to do it.
|
|
|
|
|
I laugh and laugh and laugh, I got chipped by a junior recently for doing exactly that, he proudly proclaimed he could write it in a single pass, when I pointed out it was difficult to debug ha had trouble understanding why.
I when pointed out the commented input string where a stupid f***ing bastard of a system of steaming pile of dog crap allows the user t enter 7.2m ot 3.1T to represent millions and thousands - Murex I hate you!
Never underestimate the power of human stupidity
RAH
|
|
|
|
|
Hi,
you shouldn't use strings to solve numeric problems. Your problem arrises when ToString() returns just "1" and not "1.0". You could of course enforce the latter by specifying the string format you want, but that is not the right way, use the appropriate conversions or functions instead.
It seems you want the fractional part of a real (float or double or even decimal) number; I don't know any function that offers that straight away. One way to get that is by first getting the integer part (e.g. with Math.Floor or Math.Truncate ) then take the difference. Another way could be to cast to integer, but then you might run into overflow situations.
If negative inputs are allowed, be careful to first specify what you want, and then check your code for it.
|
|
|
|
|
I just ran into a similar issue. We store data in an XML file and doubles trim the trailing zeros
so you may have to do something like
Convert.ToDouble(1.0).ToString("0.00").Split('.')[1]
|
|
|
|
|
Your code is basically what Richard D already offered (minus the Culture stuff) and it wouldn't work in large parts of the world, as not all people use a period for the decimal point.
Furthermore you are calling multiple methods and generating several objects that aren't really necessary to perform a rather simple math operation.
|
|
|
|
|
Granted there are a number of things you would do differently if your code is used internationally. Normally I pass and use the base types (double, int...) and let the UI worry about the display and format.
And sure I would never do multiple method calls in a single line. When you split you always make sure the ordinal is there before trying to pull it.
|
|
|
|
|
Why don't you just get and compare the "remainders"? e.g.
int remainder1 = (int) (1.0 % 1);
int remainder2 = (int) (1.5 % 1);
"(I) am amazed to see myself here rather than there ... now rather than then".
― Blaise Pascal
|
|
|
|
|
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.
|
|
|
|