Populate a 2 dimensional List From Directory.GetFiles - multidimensional-array

I currently am populating a dropdown list with the contents of all files in a directory using this code:
string[] filePaths = Directory.GetFiles(#ConfigurationManager.AppSettings["File_Path"]
.ToString(), "*.txt");
if (filePaths == null || filePaths.Length == 0)
{
ddlFiles.Items.Insert(0, new ListItem("NO TEXT FILES CURRENTLY AVAILABLE !"));
}
else
{
ddlFiles.DataSource = filePaths;
ddlFiles.DataBind();
ddlFiles.Items.Insert(0, new ListItem("PLEASE SELECT A TEXT FILE"));
}
The problem is that the dropdown will show the complete path to the files. I just want to show the file name and extension. I figure that I could use a two dimensional List, and load the path into one dimension. I could then just loop through that dimension and parse everything after the last "\" to get just the file name and write it back to the other dimension in that List. This would result in a List with two dimensions, one with paths and one with file names. I could then load the dropdown from the 2 dimensional List using the path for the DataValueField and the file name for the DataTextField.
My problem is that I can't get a 2 Dimensional List to load from Directory.GetFiles. Can someone post an example?
Also, how do I specifically address each dimension in the List to load the Value/Text attributes of the dropdown list?
Thank You in advance for your help!

I don't think you need multi-dimensional arrays here.. You can just separate "Value" and "Text". That is, data binding supports value and text, using "DataValueField" and "DataTextField", you could just use those. Means, first you get a list of pairs, and then bind them to the value/text of the item, like this:
var filePaths = Directory.GetFiles(#ConfigurationManager.AppSettings["File_Path"].ToString(), "*.txt")
.Select(path => new
{
Path = path,
Name = Path.GetFileName(path)
}).ToArray();
if (filePaths == null || filePaths.Length == 0)
{
ddlFiles.Items.Insert(0, new ListItem("NO TEXT FILES CURRENTLY AVAILABLE !"));
}
else
{
ddlFiles.DataSource = filePaths;
ddlFiles.DataValueField = "Path";
ddlFiles.DataTextField = "Name";
ddlFiles.DataBind();
ddlFiles.Items.Insert(0, new ListItem("PLEASE SELECT A TEXT FILE"));
}

Related

How to add any symbols after prefix_?

is there any solution? e.g. I have data in Map with key favorites_ prefix and values _suffix (for example: favorites_jeans, favorites_suit,...,). I want to by dint of loop get that values and set in List, because of it I must give keys of map, right?
I want to know how can I get values of myMap["favorites_*"] (* - after the favorites_ any symbols).
List<String> favoritesStrings = ['favorite_name','favorite_jeans',];
Map<String,dynamic> myMap = {
favoritesStrings[0]:'0',
favoritesStrings[1]:'1',
'someKey':'2',
'anotherKey':'3',
};
favoritesStrings.forEach((favorite)=>print(myMap[favorite]));//prints 0 1
As per what I understood, you want to fetch value from map using "favorites_" + a dynamic value from list as key.
You just have to use String templates and use $ to insert suffix variable to build key dynamically:
List<String> suffixList = ["jeans", "suit", "shirt"];
for(String suffix in suffixList) {
var item = myMap["favorites_$suffix"];
// Do something with item
}
Hope it helps

Can not convert from object to list exception

List<myJavaClass> smallListnew = (List<myJavaClass>) i1.next();
Above line causing error says object can not be type casted to type List<myJavaClass>.
Below is some description code:
List<myJavaClass> i1=bigList.iterator();
Big list contains many small list in the following way:
//here unique list contains some Long values without the duplicates that were being compared with the refreshJobCountList.
Iterator<Long> i=uniqueRefJobId.iterator();
while (i.hasNext()) {
Long refreshJobID = i.next();
List<myJavaClass> smallList = new ArrayList<>();
for (myJavaClass details : refreshJobCountList) {
if (refreshJobID.equals(details.getRefreshJobId())) {
myJavaClass new_obj=new myJavaClass();
new_obj.setCount(details.getCount());
new_obj.setJobRunId(details.getJobRunId());
new_obj.setRefreshJobId(details.getRefreshJobId());
smallList.add(new_obj);
}
}
bigList.addAll(smallList);
}
Instead of typecasting the array. Add the elements of the small list to a bigger list. Use .allAll() to add the entire list.

How use a variable name to point different data types with the same name?

I have 2 List one stores the name of filterable columns(of type DropDown) and another store the values to load in those filterable columns.
List<string> filterableFields = new List<string>() { "A_B", "C_D", "E_F" };
List<string> AB, CD , EF;
Now at the run time I get the data from web service and I have written a function to to extract values for these filterable fields and store the values to 2nd List.
private void prepareListForFilterableColumns(XDocument records)
{
foreach (var currentField in filterableFields)
{
var values = (from xml in records.Descendants(z + "row")
let val = (string)xml.Attribute("ows_" + currentField.Replace("_", "_x0020_"))
where val != ""
orderby val
select val
).Distinct();
switch (currentField)
{
case "A_B": AB = values.ToList(); break;
case "C_D": CD = values.ToList(); break;
}
}
}
Now I was thinking that instead of hard coding the assignment in swtich case block, If I could just use the first List name "A_B" and replace "_" from it to point to my 2nd List and assign values.ToList() to it.
I understand that c# is a static language, So not sure if we can achieve this, but IF I can it will make my function generic.
Thanks a lot in advance for time and help.
Vishal
You could use a dictionary of lists of strings instead of 3 lists to store the values.
Dictionary<string, List<string>> val lists = new Dictionary<string,List<string>>();
And make the keys of the dictionary equal to the filterables: "AB", "CD",..
then, instead of AB you would use valLists["AB"] and could then reference reach list based on a string key.
The other option would be to use reflection but that would be slower and unnecessarily a bit more complicated.

how do i get section target page number in pdf file using iTextSharp?

I have a pdf file which contains Index Page that includes section with target page.
I could get the section name(Section 1.1, Section 5.2) but i can not get the target page number...
For ex:
http://www.mikesdotnetting.com/Article/84/iTextSharp-Links-and-Bookmarks
Here is my code:
string FileName = AppDomain.CurrentDomain.BaseDirectory + "TestPDF.pdf";
PdfReader pdfreader = new PdfReader(FileName);
PdfDictionary PageDictionary = pdfreader.GetPageN(9);
PdfArray Annots = PageDictionary.GetAsArray(PdfName.ANNOTS);
if ((Annots == null) || (Annots.Length == 0))
return;
foreach (PdfObject oAnnot in Annots.ArrayList)
{
PdfDictionary AnnotationDictionary = (PdfDictionary)PdfReader.GetPdfObject(oAnnot);
if (AnnotationDictionary.Keys.Contains(PdfName.A))
{
PdfDictionary oALink = AnnotationDictionary.GetAsDict(PdfName.A);
if (oALink.Get(PdfName.S).Equals(PdfName.GOTO))
{
if (oALink.Keys.Contains(PdfName.D))
{
PdfObject objs = oALink.Get(PdfName.D);
if (objs.IsString())
{
string SectionName = objs.ToString(); // here i could see the section name...
}
}
}
}
}
How do i get the target page number?
also I couldn't access the Section name for some pdf ex: http://wwwimages.adobe.com/www.adobe.com/content/dam/Adobe/en/devnet/pdf/pdfs/adobe_supplement_iso32000.pdf
In this PDF 9th page contains a section I could not get the section.
so please give me solution....
There's two possible types of Link Annotations, either A or Dest. The A is the more powerful type but is often overkill. The Dest type just specifies an indirect reference to a page along with some fitting and zooming options.
The Dest value can be a couple of different things but is usually (as far as I've ever seen) a named string destination. You can look up named destinations in the document's name destination dictionary. So before your main loop add this so that it can be referenced later:
//Get all existing named destinations
Dictionary<string, PdfObject> dests = pdfreader.GetNamedDestinationFromStrings();
Once you've got the Dest as a string you can look that object up as a key in the above dictionary.
PdfArray thisDest = (PdfArray)dests[AnnotationDictionary.GetAsString(PdfName.DEST).ToString()];
The first item in the array returned is the indirect reference that you're used to. (Actually, the first item could be an integer representing a page number in a remote document so you might have to check for that.)
PdfIndirectReference a = (PdfIndirectReference)thisDest[0];
PdfObject thisPage = PdfReader.GetPdfObject(a);
Below is code that puts most of the above together, omitting some of the code that you already have. A and Dest are mutually exclusive per the spec so no annotation should ever have both specified.
//Get all existing named desitnations
Dictionary<string, PdfObject> dests = pdfreader.GetNamedDestinationFromStrings();
foreach (PdfObject oAnnot in Annots.ArrayList) {
PdfDictionary AnnotationDictionary = (PdfDictionary)PdfReader.GetPdfObject(oAnnot);
if (AnnotationDictionary.Get(PdfName.SUBTYPE).Equals(PdfName.LINK)) {
if (AnnotationDictionary.Contains(PdfName.A)) {
//...Do normal A stuff here
} else if (AnnotationDictionary.Contains(PdfName.DEST)) {
if (AnnotationDictionary.Get(PdfName.DEST).IsString()) {//Named-based destination
if (dests.ContainsKey(AnnotationDictionary.GetAsString(PdfName.DEST).ToString())) {//See if it exists in the global name dictionary
PdfArray thisDest = (PdfArray)dests[AnnotationDictionary.GetAsString(PdfName.DEST).ToString()];//Get the destination
PdfIndirectReference a = (PdfIndirectReference)thisDest[0];//TODO, this could actually be an integer for the case of Remote Destinations
PdfObject thisPage = PdfReader.GetPdfObject(a);//Get the actual PDF object
}
} else if(AnnotationDictionary.Get(PdfName.DEST).IsArray()) {
//Technically possible, I think the array matches the code directly above but I don't have a sample PDF
}
}
}
}

Filehelpers ExcelStorage.ExtractRecords fails when first cell is empty

When the first cell of an excel sheet to import using ExcelStorage.ExtractRecords is empty, the process fail. Ie. If the data starts at col 1, row 2, if the cell (2,1) has an empty value, the method fails.
Does anybody know how to work-around this? I've tried adding a FieldNullValue attribute to the mapping class with no luck.
Here is a sample project that show the code with problems
Hope somebody can help me or point in some direction.
Thank you!
It looks like you have stumbled upon an issue in FileHelpers.
What is happening is that the ExcelStorage.ExtractRecords method uses an empty cell check to see if it has reached the end of the sheet. This can be seen in the ExcelStorage.cs source code:
while (CellAsString(cRow, mStartColumn) != String.Empty)
{
try
{
recordNumber++;
Notify(mNotifyHandler, mProgressMode, recordNumber, -1);
colValues = RowValues(cRow, mStartColumn, RecordFieldCount);
object record = ValuesToRecord(colValues);
res.Add(record);
}
catch (Exception ex)
{
// Code removed for this example
}
}
So if the start column of any row is empty then it assumes that the file is done.
Some options to get around this:
Don't put any empty cells in the first column position.
Don't use excel as your file format -- convert to CSV first.
See if you can get a patch from the developer or patch the source yourself.
The first two are workarounds (and not really good ones). The third option might be the best but what is the end of file condition? Probably an entire row that is empty would be a good enough check (but even that might not work in all cases all of the time).
Thanks to the help of Tuzo, I could figure out a way of working this around.
I added a method to ExcelStorage class to change the while end condition. Instead of looking at the first cell for empty value, I look at all cells in the current row to be empty. If that's the case, return false to the while. This is the change to the while part of ExtractRecords:
while (!IsEof(cRow, mStartColumn, RecordFieldCount))
instead of
while (CellAsString(cRow, mStartColumn) != String.Empty)
IsEof is a method to check the whole row to be empty:
private bool IsEof(int row, int startCol, int numberOfCols)
{
bool isEmpty = true;
string cellValue = string.Empty;
for (int i = startCol; i <= numberOfCols; i++)
{
cellValue = CellAsString(row, i);
if (cellValue != string.Empty)
{
isEmpty = false;
break;
}
}
return isEmpty;
}
Of course if the user leaves an empty row between two data rows the rows after that one will not be processed, but I think is a good thing to keep working on this.
Thanks
I needed to be able to skip blank lines, so I've added the following code to the FileHelpers library. I've taken Sebastian's IsEof code and renamed the method to IsRowEmpty and changed the loop in ExtractRecords from ...
while (CellAsString(cRow, mStartColumn) != String.Empty)
to ...
while (!IsRowEmpty(cRow, mStartColumn, RecordFieldCount) || !IsRowEmpty(cRow+1, mStartColumn, RecordFieldCount))
I then changed this ...
colValues = RowValues(cRow, mStartColumn, RecordFieldCount);
object record = ValuesToRecord(colValues);
res.Add(record);
to this ...
bool addRow = true;
if (Attribute.GetCustomAttribute(RecordType, typeof(IgnoreEmptyLinesAttribute)) != null && IsRowEmpty(cRow, mStartColumn, RecordFieldCount))
{
addRow = false;
}
if (addRow)
{
colValues = RowValues(cRow, mStartColumn, RecordFieldCount);
object record = ValuesToRecord(colValues);
res.Add(record);
}
What this gives me is the ability to skip single empty rows. The file will be read until two successive empty rows are found

Resources