Method listDuplicates() error - c#-3.0

Can somebody help me with this problem here. I'm a newbie . I'm trying to find file duplicates or files with the same content in a directory and write texfile to display duplicates but now it says input string was not in a correct format
public static List<FileInfo> files = new List<FileInfo>();
public static void ListDrive(string drive)
{
try
{
DirectoryInfo di = new DirectoryInfo(drive);
foreach (FileInfo fi in di.GetFiles())
{
files.Add(fi);
}
}
catch (UnauthorizedAccessException)
{ }
}
//Find duplicates
public static void ListDuplicates()
{
var duplicatedFiles = files.GroupBy(x => new { x.Length }).Where(t => t.Count() > 1).ToList();
Console.WriteLine("Total items: {0}", files.Count);
Console.WriteLine("Probably duplicates {0} ", duplicatedFiles.Count());
StreamWriter duplicatesFoundLog = new StreamWriter("log.txt");
foreach (var filter in duplicatedFiles)
{
duplicatesFoundLog.WriteLine("Probably duplicated item: Name: { 0}, Length: { 1}",
filter.Key.Length);
var items = files.Where(x => x.Length == filter.Key.Length).ToList();
int c = 1;
foreach (var suspected in items)
{
duplicatesFoundLog.WriteLine("{3},{ 0}- { 1}, Creation date { 2}",
suspected.Name, suspected.FullName, suspected.CreationTime, c);
c++;
}
duplicatesFoundLog.WriteLine();
}
duplicatesFoundLog.Flush();
duplicatesFoundLog.Close();
}
Here is my client method that invokes the two methods
try
{
Console.WriteLine("Enter the path");
string path = Console.ReadLine();
ListDrive(path);
ListDuplicates();
Console.ReadLine();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
Console.ReadLine();
}
Your help will be high appreciated...

Please eliminate the space, for example change { 0} to {0}. If you do this for all locations the error should go away.
If you want spaces, make the code "{3}, {0}- {1}, Creation date {2}". i.e. Add the space before the opening {, not after. The format items need have no space after the first opening brace to be interpreted as a formatting item correctly.

Related

Read content of repeating sections with apache POI

I Have a word document with a repeating section, containing other content controls.
In java project, I have a function that gets all sdts (content controls) from a word document in apache POI, in a List List.
When I inspect my repeating section in that list, I can get the text inside all content controls (inside my repeating section) but is apears as a long paragraph instead of other sdt nodes.
Is there a way to inspect content of repeating section sdt with Apache POI ? I can't find anything about it in the doc
function that gets all sdts
private static List
extractSDTsFromBodyElements(List<IBodyElement> elements) {
List<AbstractXWPFSDT> sdts = new ArrayList<AbstractXWPFSDT>();
for (IBodyElement e : elements) {
if (e instanceof XWPFSDT) {
XWPFSDT sdt = (XWPFSDT) e;
sdts.add(sdt);
} else if (e instanceof XWPFParagraph) {
XWPFParagraph p = (XWPFParagraph) e;
for (IRunElement e2 : p.getIRuns()) {
if (e2 instanceof XWPFSDT) {
XWPFSDT sdt = (XWPFSDT) e2;
sdts.add(sdt);
}
}
}
}
return sdts;
}
The XWPF part of apache poi is rudimentary until now and highly in development. In XWPFSDT is this mentioned also: "Experimental class to offer rudimentary read-only processing of of StructuredDocumentTags/ContentControl". So until now your code only gets the surrounding XWPFSDT of the repeating content control but not the inner controls. One could have seen that by having some debugging outputs in the code. See my System.out.println(...).
So to really get all XWPFSDTs we must go other ways using the underlaying XMLdirectly.
Lets have a complete example.
Look at this Worddocument:
As you see there is a single control to input the group name, then a repeating content control around three controls to input name, amount and date and then a single control to input the employee. All controls which shall be read have titles set. So whether the title is set, is the criterion whether a control is important for reading or not.
The following code now can read all controls and their content:
import java.io.FileInputStream;
import org.apache.poi.xwpf.usermodel.*;
import java.util.List;
import java.util.ArrayList;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.*;
import org.apache.xmlbeans.XmlCursor;
import javax.xml.namespace.QName;
public class ReadWordForm {
/*
private static List<AbstractXWPFSDT> extractSDTsFromBodyElements(List<IBodyElement> elements) {
List<AbstractXWPFSDT> sdts = new ArrayList<AbstractXWPFSDT>();
for (IBodyElement e : elements) {
if (e instanceof XWPFSDT) {
XWPFSDT sdt = (XWPFSDT) e;
System.out.println("block: " + sdt);
sdts.add(sdt);
} else if (e instanceof XWPFParagraph) {
XWPFParagraph p = (XWPFParagraph) e;
for (IRunElement e2 : p.getIRuns()) {
if (e2 instanceof XWPFSDT) {
XWPFSDT sdt = (XWPFSDT) e2;
System.out.println("inline: " + sdt);
sdts.add(sdt);
}
}
}
}
return sdts;
}
*/
private static List<XWPFSDT> extractSDTsFromBody(XWPFDocument document) {
XWPFSDT sdt;
XmlCursor xmlcursor = document.getDocument().getBody().newCursor();
QName qnameSdt = new QName("http://schemas.openxmlformats.org/wordprocessingml/2006/main", "sdt", "w");
List<XWPFSDT> allsdts = new ArrayList<XWPFSDT>();
while (xmlcursor.hasNextToken()) {
XmlCursor.TokenType tokentype = xmlcursor.toNextToken();
if (tokentype.isStart()) {
if (qnameSdt.equals(xmlcursor.getName())) {
if (xmlcursor.getObject() instanceof CTSdtRun) {
sdt = new XWPFSDT((CTSdtRun)xmlcursor.getObject(), document);
//System.out.println("inline: " + sdt);
allsdts.add(sdt);
} else if (xmlcursor.getObject() instanceof CTSdtBlock) {
sdt = new XWPFSDT((CTSdtBlock)xmlcursor.getObject(), document);
//System.out.println("block: " + sdt);
allsdts.add(sdt);
}
}
}
}
return allsdts;
}
public static void main(String[] args) throws Exception {
XWPFDocument document = new XWPFDocument(new FileInputStream("WordDataCollectingForm.docx"));
/*
List<IBodyElement> bodyelements = document.getBodyElements();
List<AbstractXWPFSDT> sdts = extractSDTsFromBodyElements(bodyelements);
*/
List<XWPFSDT> allsdts = extractSDTsFromBody(document);
for (XWPFSDT sdt : allsdts) {
//System.out.println(sdt);
String title = sdt.getTitle();
String content = sdt.getContent().getText();
if (!(title == null) && !(title.isEmpty())) {
System.out.println(title + ": " + content);
} else {
System.out.println("====sdt without title====");
}
}
document.close();
}
}

Export Metadata from a Custom Tab from file properties for a list of files in sub folders

The Problem:
On my Windows file server I have around 1,000,000 SolidWorks files that have metadata in the file properties under a custom tab (see image below) that I would like to export to a single CSV file.
These files are located in sub-tree of folders, and mixed with other file types.
The Solution:
A script is needed to only target specific file types (extensions) in a sub-tree of folders, that exports the metadata from the custom tab to a CSV File, where i can then clean up and import the data into an SQL database.
I am not sure the best way to achieve this I was thinking along the lines of PowerShell, any help to get going would be greatly appreciated.
If you use a .NET language like C# or Visual Basic, you can use the SolidWorks API and the Document Manager libraries (you'll need to get a license, free with your subscription from the Customer Portal) to extract this information without opening the files. It's quite fast. As for only looking at certain files, that's straight forward with .NET IO.Path.GetExtension.
Below is a working example of what I think you're looking for.
You will need the Document Manager dll, which is on the SolidWorks API SDK, which is included in the installation media. Then you can referencene SolidWorks.Interop.swdocumentmgr.dll.
You will also need a Document Manager Serial Number which you can request through the SolidWorks Customer Portal free of charge with your SolidWorks Subscription. Once you have that number, replace the lic string value below with the entire serial number, in quotes.
To define which Custom Properties to read from the SolidWorks files, just change the list propertiesToRead to include any values you need to retrieve. These are NOT case sensitive.
You you run this, you will be prompted to enter a directory path. This is also where the Output.csv file will be created.
At the bottom is a screen-shot of sample results.
using SolidWorks.Interop.swdocumentmgr;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace WriteProperties
{
class Program
{
static ISwDMApplication4 docManager;
static List<string> propertiesToRead = new List<string>() { "Number", "Description", "Revision", "Material", "Finish", "Weight" };
const string lic = "YOU CAN GET THIS NUMBER FROM THE CUSTOMER PORTAL WITH YOUR SOLIDWORKS SUBSCRIPTION AT NO COST";
static char[] charactersToQuote = { ',', '"', '\n' };
const string QUOTE = "\"";
const string QUOTEFORMATTED = "\"\"";
static void Main(string[] args)
{
string directoryPath = GetDirectory(args);
if (string.IsNullOrEmpty(directoryPath)) return;
if (!LoadDocManager()) return;
string outputPath = Path.Combine(directoryPath, "Output.csv");
StringBuilder sb = new StringBuilder();
sb.AppendLine("File Name," + string.Join(",", propertiesToRead));
int counter = 0;
foreach (string filePath in Directory.EnumerateFiles(directoryPath, "*.sld*", SearchOption.AllDirectories))
{
SwDMDocument21 dmDocument = GetDocument(filePath);
if (dmDocument == null) continue;
WriteProperties(sb, dmDocument, filePath);
counter++;
}
File.WriteAllText(outputPath, sb.ToString());
Console.WriteLine("{0} files read and saved to {1}", counter, outputPath);
Console.ReadLine();
}
static string GetDirectory(string[] args)
{
if (args != null && args.Count() > 0 && Directory.Exists(args[0])) return args[0];
Console.WriteLine("Directory to read:");
string filePath = Console.ReadLine();
if (Directory.Exists(filePath)) return filePath;
Console.WriteLine("Directory does not exists: {0}", filePath);
return string.Empty;
}
static bool LoadDocManager()
{
if (docManager != null) return true;
try
{
SwDMClassFactory factory = new SwDMClassFactory();
if (factory == null) throw new NullReferenceException(nameof(SwDMClassFactory));
docManager = (SwDMApplication4)factory.GetApplication(lic);
if (docManager == null) throw new NullReferenceException(nameof(SwDMApplication4));
return true;
}
catch (Exception ex)
{
Console.WriteLine("Document Manager failed to load: {0}", ex.Message);
Console.ReadLine();
return false;
}
}
static SwDMDocument21 GetDocument(string filePath)
{
SwDmDocumentType documentType = GetDocType(filePath);
if (documentType == SwDmDocumentType.swDmDocumentUnknown) return null;
SwDmDocumentOpenError result = SwDmDocumentOpenError.swDmDocumentOpenErrorNone;
SwDMDocument21 dmDocument = (SwDMDocument21)docManager.GetDocument(filePath, documentType, true, out result);
if (result == SwDmDocumentOpenError.swDmDocumentOpenErrorNone || result == SwDmDocumentOpenError.swDmDocumentOpenErrorFileReadOnly) return dmDocument;
if (dmDocument != null) dmDocument.CloseDoc();
return null;
}
static SwDmDocumentType GetDocType(string filePath)
{
if (filePath.Contains("~$")) return SwDmDocumentType.swDmDocumentUnknown;
switch (Path.GetExtension(filePath).ToLower())
{
case ".sldprt": return SwDmDocumentType.swDmDocumentPart;
case ".sldasm": return SwDmDocumentType.swDmDocumentAssembly;
case ".slddrw": return SwDmDocumentType.swDmDocumentDrawing;
default: return SwDmDocumentType.swDmDocumentUnknown;
}
}
static void WriteProperties(StringBuilder sb, SwDMDocument21 dmDocument, string filePath)
{
Console.WriteLine("Reading {0}", filePath);
List<string> propertiesInFile = new List<string>();
if (dmDocument.GetCustomPropertyCount() > 0) propertiesInFile.AddRange(dmDocument.GetCustomPropertyNames());
string csvLine = filePath;
foreach (string property in propertiesToRead)
{
string propertyValue = "";
if (propertiesInFile.Any(s => string.Compare(s, property, true) == 0))
{
SwDmCustomInfoType propertyType = SwDmCustomInfoType.swDmCustomInfoText;
string resolvedValue;
propertyValue = dmDocument.GetCustomPropertyValues(property, out propertyType, out resolvedValue);
}
csvLine = csvLine + "," + FixChars(propertyValue);
}
sb.AppendLine(csvLine);
dmDocument.CloseDoc();
}
static string FixChars(string s)
{
if (s.Contains(QUOTE)) s = s.Replace(QUOTE, QUOTEFORMATTED);
if (s.IndexOfAny(charactersToQuote) > -1) s = QUOTE + s + QUOTE;
return s;
}
}
}
Here is a sample output

android cardview only show the last result the right amount of times

i'm new to android and java.
i made a cardview and populated it with a simple loop like so:
private ArrayList<DataObject> getTheData(){
ArrayList res = new ArrayList<DataObject>();
for (int index = 0; index < 5; index++){
DataObject obj = new DataObject("shit","happen");
res.add(index,obj);
}
return res;
}
it worked. now i created a database and want to populate it with this data. so i have this:
public ArrayList<DataObject> getData() {
SQLiteDatabase db = this.getReadableDatabase();
ArrayList res = null;
try {
res = new ArrayList<DataObject>();
String selectQuery = "SELECT * FROM quotes a LEFT JOIN authors b ON b.author_id=a.quote_author";
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
Log.d("CHECKDB",cursor.getString(cursor.getColumnIndex("first_name")) + " " + cursor.getString(cursor.getColumnIndex("last_name")));
Log.d("CHECKDB2",cursor.getString(cursor.getColumnIndex("quote_text")));
DataObject obj = new DataObject(
cursor.getString(cursor.getColumnIndex("first_name")) + " " + cursor.getString(cursor.getColumnIndex("last_name")),
cursor.getString(cursor.getColumnIndex("quote_text"))
);
res.add(obj);
} while (cursor.moveToNext());
}
}
} catch (SQLiteException se) {
Log.e(getClass().getSimpleName(), "Could not create or Open the database");
} finally {
if (db != null)
db.close();
}
return res;
}
the log show all the results, but when i run the app i get the last result the right amount of times. in this case 4 quotes in my database, so i see 4 but the last one 4 times.
please , since i'm new to it, good explanations will be appreciated.
the issue was that my dataobject attributes were set to static

How I count all the number of records in a RecordStore

I have a LWUIT app that should display the number of records in a LWUIT list.
To get all the records I use a method called getRecordData() that returns all records as a String array, it works fine.
But how do I count the number of these records?
import java.util.*;
import com.sun.lwuit.events.*;
import javax.microedition.midlet.*;
import com.sun.lwuit.*;
import com.sun.lwuit.plaf.*;
import javax.microedition.rms.RecordStore;
import javax.microedition.rms .*;
public class number_of_records extends MIDlet {
private RecordStore recordStore;
// Refresh2( ) method for getting the time now
public String Refresh2()
{
java.util.Calendar calendar = java.util.Calendar.getInstance();
Date myDate = new Date();
calendar.setTime(myDate);
StringBuffer time = new StringBuffer();
time.append(calendar.get(java.util.Calendar.HOUR_OF_DAY)).append(':');
time.append(calendar.get(java.util.Calendar.MINUTE)) ;
// time.append(calendar.get(java.util.Calendar.SECOND));
String tt = time.toString();
return tt;
}
// return all records of recordStore RecordStore
public String [] getRecordData( )
{
String[] str = null;
int counter = 0;
try
{
RecordEnumeration enumeration = recordStore.enumerateRecords(null, null, false);
str = new String[recordStore.getNumRecords()];
while(enumeration.hasNextElement())
{
try
{
str[counter] = (new String(enumeration.nextRecord()));
counter ++;
}
catch(javax.microedition.rms.RecordStoreException e)
{
}
}
}
catch(javax.microedition.rms.RecordStoreNotOpenException e)
{
}
catch(java.lang.NullPointerException n)
{
}
return str;
}
public void startApp()
{
com.sun.lwuit.Display.init(this);
final Button addition = new Button("add a goal");
final com.sun.lwuit.TextField tf = new com.sun.lwuit.TextField();
final com.sun.lwuit.List mylist = new com.sun.lwuit.List();
final Button All = new Button("All Goals");
final com.sun.lwuit.Form ff = new com.sun.lwuit.Form();
final com.sun.lwuit.Form g = new com.sun.lwuit.Form();
ff.getStyle().setBgColor(0X99CCFF);
All.getStyle().setBgColor(0X0066CC);
Style g_style5 = g.getSelectedStyle() ;
g.addComponent(tf);
g.addComponent(addition);
addition.getStyle().setBgColor(0X0066CC);
g.addComponent(All);
g.getStyle().setBgColor(0X99CCFF);
addition.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
//
String s =tf.getText();
if( s!=null && s.length() > 0)
{
try
{
// Store the time in the String k
String k = Refresh2();
// The record and the time stored in KK String
String kk =tf.getText()+"-"+k;
// Add an item (the kk String) to mylist List.
mylist.addItem(kk);
byte bytestream[] = kk.getBytes() ;
// Add a record to recordStore.
int i = recordStore.addRecord(bytestream, 0, bytestream.length);
}
catch(Exception ex) { }
// Inform the User that he added the a record.
Dialog validDialog = new Dialog(" ");
Style Dialogstyle = validDialog.getSelectedStyle() ;
validDialog.setScrollable(false);
validDialog.getDialogStyle().setBgColor(0x0066CC);
validDialog.setTimeout(1000); // set timeout milliseconds
TextArea textArea = new TextArea("...."); //pass the alert text here
textArea.setFocusable(false);
textArea.setText("A goal has been added"+"" );
validDialog.addComponent(textArea);
validDialog.show(0, 10, 10, 10, true);
}
// Information to user that he/she didn’t add a record
else if((s==null || s.length()<= 0))
{
Dialog validDialo = new Dialog(" ");
validDialo.setScrollable(false);
validDialo.getDialogStyle().setBgColor(0x0066CC);
validDialo.setTimeout(5000); // set timeout milliseconds
TextArea textArea = new TextArea("...."); //pass the alert text here
textArea.setFocusable(false);
textArea.setText("please enter scorer name or number");
validDialo.addComponent(textArea);
validDialo.show(50, 50, 50, 50, true);
}
}
});
/*Action here for displaying all records of recordStore RecordStore in a new form */
All.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
try
{
recordStore = RecordStore.openRecordStore("My Record Store", true);
}
catch(Exception ex) {}
try
{
com.sun.lwuit.Label l = new com.sun.lwuit.Label(" Team Goals") ;
ff.addComponent(l);
// Store the records of recordStore in string array
String [] record= getRecordData();
int j1;
String valueToBeInserted2="";
int k=getRecordData().length;
for( j1=0;j1< getRecordData().length;j1++)
{
valueToBeInserted2=valueToBeInserted2 + " " + record[j1];
if(j1==getRecordData().length)
{
mylist.addItem(record[j1]);
int m = getRecordData().length;
// Counting the number of records
String goals =""+getRecordData().length;
/* I tried to use for…loop to count them by length of the recordStore and render it.
This list also should display the number of records on the form.
But it didn’t !!!
*/
mylist.addItem(goals);
}
}
ff.addComponent(mylist);
}
catch(java.lang.IllegalArgumentException e)
{
}
finally
{
ff.show();
}
}
}
);
g.show();
}
public void pauseApp()
{
}
public void destroyApp(boolean unconditional) {
}
}
I Wrote this code but it gives NullPointerException at recordStore.enumerateRecords (null, null,true);
So I think the problem here.
please help.
myButton.addActionListener( new ActionListener()
{
public void actionPerformed(ActionEvet av)
{
try
{
RecordEnumeration enumeration = recordStore.enumerateRecords (null, null,true);
int o =recordStore.getNumRecords () ;
}
catch(Exception e)
{
}
}
});
what you need is enumeration.numRecords(); i reckon recordStore.getNumRecords() should work also, since this is what you are using the populate the array, you could even use the length of the array itself. These options are all in the code, it would be better to explore a bit more and also check the documentation to resolve trivial problems.
you could use the length of the array or set a RecordListener to your recordstore and increase a counter when added a record to recordstore.
here is the solution of my problem , I do a for loop to get the number of
elements of the array.
the counter should be the length of array
count.addActionListener( new ActionListener()
{
public void actionPerformed(ActionEvent av)
{
try
{
recordStore = RecordStore.openRecordStore("recordStore", true);
}
catch(Exception e)
{ }
try
{
RecordEnumeration enumeration = recordStore.enumerateRecords (null, null,true);
}
catch(Exception e)
{
}
String record[] = getRecordData();
int j;
j = record.length-1;
Dialog validDialog = new Dialog(" ");
Style Dialogstyle = validDialog.getSelectedStyle() ;
validDialog.setScrollable(false);
validDialog.getDialogStyle().setBgColor(0x0066CC);
validDialog.setTimeout(1000); // set timeout milliseconds
TextArea textArea = new TextArea("....");
textArea.setFocusable(false);
textArea.setText("Number Counted"+j );
validDialog.addComponent(textArea);
validDialog.show(0, 10, 10, 10, true);
}});

<epubreder in mono touch using C#>

i want epubreder source code in mono touch c# for iPad i got it in Xcode but need to convert in c#...
problem of conversion is that i want to parse the container.xml to get the .opf file path and again parse the .opf file....
can any one please help me out to solve this problem...
public void parseXMLFileAt(string strUrl)
{
try
{
NSMutableDictionary dict=new NSMutableDictionary();
XmlTextReader reader = new XmlTextReader("/Users/krunal/Desktop/container.xml");
string strAttribute="";
while (reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.Element:
Hashtable attributes = new Hashtable();
string strURI= reader.NamespaceURI;
string strName= reader.Name;
if (reader.HasAttributes)
{
for (int i = 0; i < reader.AttributeCount; i++)
{
reader.MoveToAttribute(i);
attributes.Add(reader.Name,reader.Value);
}
}
parser(_parser,strUrl,strURI,strName,dict);
enter code here
StartElement(strURI,strName,strName,attributes);
break;
default:
break;
}
}
}
catch (XmlException e)
{
Console.WriteLine("error occured: " + e.Message);
}
}
Thanks in advance