I need to validate a selected Xml file using Xdocument without Xsd.
I have a file named "Cheker" and the file to check.
for example i need to compare the hierarchy ,and how much elements by name from the checker file.
if i have in the "checker" file 3 page i need to chek there is no more in the selected file.
I tried with a array but is to much complicated like this
thanks!!
XElement pageElement = metadataFile.Root.Element("Pages");
int cntPage = ((IEnumerable<XElement>)pageElement.Elements()).Count();
if (cntPage < 1 || cntPage > 3) errorDetails += "Number of Pages wrong!!";
Elements() already returns IEnumerabl<XElement>. So the explicit cast on the second line of your code is unnecessary :
int cntPage = pageElement.Elements().Count();
Which style to use is a matter of preference here, but the entire code snippet can be re-written to be as follow :
int cntPage = metadataFile.Root
.Element("Pages")
.Elements()
.Count();
if (cntPage < 1 || cntPage > 3)
errorDetails += "Number of Pages wrong!!";
Related
Inside a string array -"files", 10 file paths are stored.
For example, I show 2 of them,
[0] C:\\Users\\17\\Documents\\FS\\D\\mdN_2903.dat
[1] C:\\Users\\17\\Documents\\FS\\D\\mdNBP_29032.dat
I want to validate using their filename (before the numbering & extension .dat) as well the number of files counted in c#.net
I tried to use it like this, but it didn't passed even though the files are present
if(Array.Exists(files,e => e.Contains("mdN_") && e.Contains("mdNBP_") && e.count()==10)) { // All 10 files are present }
Is there any other way to implement this in c#, please explain?
Without testing it. If your file array always has 2 has mdN and mdNBP and the same order with up to 10 files, you can do something like this:
if (files[0].Contains("mdN") && files[1].Contains("mdNBP") && files.Length == 10)
{
Console.WriteLine("all good");
}
You can also use linq just example, it can be done differnt ways, here the order does not matter, it just check if you files contian the mentioned values:
if (files.Any(e => e.Contains("mdN") && e.Contains("mdNBP") && files.Length == 10))
{
Console.WriteLine("all good");
}
If you have more files, then you can for loop the file array and check against a list of what it should contain.
I was facing this problem earlier today, and since I could not find a satisfactory solution, I decided to change my class design, and have seperate properties such as Tag 1, Tag 2, Tag 3 etc.
My main problem is the fact that I need to bind a grid to an object that contains a list among other properties and I need to show each item in the list as a separate column which I am unable to do. Hence I am resorting to declaring variables separately. Original question is here...
Now, I'm facing one of the most common design problem that probably every programmer has at some point of time. Here is the code to demonstrate it,
for (int i = 0; i < tags.Length; ++i) // Length not known here.
{
if(i==0){
tag1 = tags[0];
}
else if(i == 1){
tag2 = tags[1];
}
else if(i == 2){
tag3 = tags[2];
}
....
}
Here tags is a string array.
I was wondering if there is a more elegant way to do this. Another thing to note is that the efficiency of this loop decreases as it progresses, since with more iterations it has to check more conditions. If we could remove a condition after it had become true once it would speed up each iteration since we know that each condition will become true only once in all the iterations
Moved answer about DataGridView and using ComponentModel to the correct question:
Displaying a list of object containing a list in a grid view
Briefing
The DataGridView controll supports the ComponentModel namespace so that you can create classes that appear to have properties that don't exist. It is the same mechanism the PropertyGrid uses.
The sample code is in this answer of that question:
https://stackoverflow.com/a/13078735/195417
OLD ANSWER
This was my previous answer, when I didn't realize the real question was about the DataGridView control.
Isn't this the same as setting the values directly:
this.tag1 = tags[0];
this.tag2 = tags[1];
this.tag3 = tags[2];
EDIT: as you sayd you don't know how many variables will be needed, then you need only one, and that is a list:
var list = new List<string>();
for (int i = 0; i < tags.Length; ++i)
{
list.add(tags[i]);
}
If all you want is to copy all values, you can even do this:
var list = new List<string>(tags);
Tell me whether this is what you want or not... maybe I have misunderstood the question.
The whole loop is pointless. But unless the tags array length is always going to be the same, you have to be sure not to go out of bounds...
if(tags.Length >= 1) this.tag1 = tags[0];
if(tags.Length >= 2) this.tag2 = tags[1];
if(tags.Length >= 3) this.tag3 = tags[2];
if(tags.Length >= 4) this.tag4 = tags[3];
if(tags.Length >= 5) this.tag5 = tags[4];
... so on for however many this.tag# you have.
This is essentially the same:
for(int index = 0; index < tags.Length[]; index++){
switch(index){
case 0:
tag1 = tags[0];
break;
// And so on
}
}
I need to load a long string from the internet and I have done that. Now I need to find the H1 header tag and print the contents.
What is the shortest or the easiest way to do that?
for (int x = 0; x < tempString.Length; x++)
{
if (write == 2)
{
name =name + tempString[x];
lenght++;
}
if (tempString[x] == '<' && tempString[x] == 'h' && tempString[x] == '1' )
write = 1;
if (write == 1 && tempString[x] == '>')
write = 2;
if (tempString[x] == '-' && write == 1)
write = 0;
}
I know it's a bit how shall I say odd. But it's all I have.
Use the HTML Agility Pack - Pretty much anything else you try is just going to cause you a headache.
HtmlAgility sample:
var html = "<html><head></head><body><h1>hello</h1></body></html>";
HtmlDocument d = new HtmlDocument();
d.LoadHtml(html);
var h1Contents = d.DocumentNode.SelectSingleNode("//h1").InnerText;
If you want to do it in flat C#, and you're only looking at 1 tag:
int first_tag = str.IndexOf("<H1>");
int last_tag = str.IndexOf("</H1>");
string text = str.SubString((first_tag + 4), (last_tag - first_tag));
Use an HTML library!
Otherwise try:
String.IndexOf(String x )
http://msdn.microsoft.com/en-us/library/k8b1470s.aspx
you can use that to get the first index of the start and end tags. you can then just read between those indices.
The System.String class has methods like IndexOf(String) - Reports the zero-based index of the first occurence of the specified string.
So in your case, you could pass in "<H1>". Then you could get a substring starting at that point, and then call this method again looking for "</H1>" again.
Or if you want, it might be easier to use Regular Expressions in .NET. Those are found in the System.Tet.RegularExpressions namespace. Those are definitely more complicated. But I'm sure you could practice using some small samples and learn the power of the dark side! (errr....) the power of regular expressions! :)
[edit] Now that I see other's answers, I definitely agree with others. If you need do anything more complicated than getting one item in an HTML formatted string use an html parser.
all of the above work fine i just can't use any external libaries
this works well for me
for (int x = 0; x < tempString.Length; x++)
{
if (tempString[x] == '-' && write == 2)
{ write = 0; }
if (write == 2)
{
title =title + tempString[x];
lenght++;
}
if (tempString[x] == '<' && tempString[x+1] == 'h' && tempString[x+2] == '1' )
{ write = 1; }
if (write == 1 && tempString[x] == '>')
{ write = 2; }
}
I am reading in multiple files in with millions of lines and I am creating a list of all line numbers that have a specific issue. For example if a specific field is left blank or contains an invalid value.
So my question is what would be the most efficient date type to keep track of a list of numbers that could be upwards of a million number of rows. Would using String Builder, Lists, or something else be more efficient?
My end goal is to out put a message like "Specific field is blank on 1-32, 40, 45, 47, 49-51, etc. So in the case of a String Builder, I would check the previous value and if it is is only 1 more I would change it from 1 to 1-2 and if it was more than one would separate it by a comma. With the List, I would just add each number to the list and then combine then once the file has been completely read. However in this case I could have multiple list containing millions of numbers.
Here is the current code I am using to combine a list of numbers using String Builder:
string currentLine = sbCurrentLineNumbers.ToString();
string currentLineSub;
StringBuilder subCurrentLine = new StringBuilder();
StringBuilder subCurrentLineSub = new StringBuilder();
int indexLastSpace = currentLine.LastIndexOf(' ');
int indexLastDash = currentLine.LastIndexOf('-');
int currentStringInt = 0;
if (sbCurrentLineNumbers.Length == 0)
{
sbCurrentLineNumbers.Append(lineCount);
}
else if (indexLastSpace == -1 && indexLastDash == -1)
{
currentStringInt = Convert.ToInt32(currentLine);
if (currentStringInt == lineCount - 1)
sbCurrentLineNumbers.Append("-" + lineCount);
else
{
sbCurrentLineNumbers.Append(", " + lineCount);
commaCounter++;
}
}
else if (indexLastSpace > indexLastDash)
{
currentLineSub = currentLine.Substring(indexLastSpace);
currentStringInt = Convert.ToInt32(currentLineSub);
if (currentStringInt == lineCount - 1)
sbCurrentLineNumbers.Append("-" + lineCount);
else
{
sbCurrentLineNumbers.Append(", " + lineCount);
commaCounter++;
}
}
else if (indexLastSpace < indexLastDash)
{
currentLineSub = currentLine.Substring(indexLastDash + 1);
currentStringInt = Convert.ToInt32(currentLineSub);
string charOld = currentLineSub;
string charNew = lineCount.ToString();
if (currentStringInt == lineCount - 1)
sbCurrentLineNumbers.Replace(charOld, charNew);
else
{
sbCurrentLineNumbers.Append(", " + lineCount);
commaCounter++;
}
}
My end goal is to out put a message like "Specific field is blank on 1-32, 40, 45, 47, 49-51
If that's the end goal, no point in going through an intermediary representation such as a List<int> - just go with a StringBuilder. You will save on memory and CPU that way.
StringBuilder serves your purpose so stick with that, if you ever need the line numbers you can easily change the code then.
Depends on how you can / want to break the code up.
Given you are reading it in line order, not sure you need a list at all.
Your current desired output implies that you can't output anything until the file is completely scanned. The size of the file suggests a one pass`analysis phase would be a good idea as well, given you are going to use buffered input as opposed to reading the entire thing into memory.
I'd be tempted with an enum to describe the issue e.g Field??? is blank and then use that as the key a dictionary of string builders.
As a first thought anyway
Is your output supposed to be human readable? If so, you'll hit the limit of what is reasonable to read, long before you have any performance/memory issues from your data structure. Use whatever is easiest for you to work with.
If the output is supposed to be machine readable, then that output might suggest an appropriate data structure.
As others have pointed out, I would probably use StringBuilder. The List may have to resize many times; the new implementation of StringBuilder does not have to resize.
I'm currently coding a project that can take up to 200 entries of a specific product, as determined by user input. Basically, my GUI loads, and I use jQuery to dynamically build the entries whenever there is a change to the amount field. When using jQuery, I simply give each of them ids in the form of variable1, variable2, ...., variableX (where X is the amount of entries indicated). Small snippet of code to clarify:
for(var i = 1;i <= amount_selected; i++) {
$('table_name tr:last').after('<tr><td><input type="text" id="variable' + i + '"></td></tr>');
}
Now when I try to move to the back end, I'm trying to reference these variable names by putting them in a list. I went ahead and put them in a list of HtmlInputText, to call the Variable names from the list itself. (This would save having to call all (up to 200) methods manually, which is really not an option).
So what I did (in C#) was:
List<HtmlInputText> listvar = new List<HtmlInputText>();
for(int i = 1; i <= amount_selected; i++) {
string j = "variable" + Convert.ToString(i);
HtmlInputText x = j;
listvar.Add((x));
samplemethod(listvar[i]);
}
But it's not working at all. Does anyone have any ideas as to how this would be done, without doing so manually? I know my logic might be completely off, but hopefully this illustrates at least what I'm attempting to do.
I'm assuming these inputs are in a form? If you're submitting then you can access the text boxes from the Request object:
List<string> results = new List<string>();
for (int i = 1; i <= amount_selected; i++)
{
string s = String.Format("{0}", Request.Form["variable" + Convert.ToString(i)]);
results.Add(s);
}
you could do $("#variable" + Convert.ToString(i)).val()