java.io.File's .createNewFile() doesn't create a file - file

class FileClassOne {
public static void main(String args[]) {
File myDir = new File(File.separator);
System.out.println("myDir.getAbsolutePath() = " + myDir.getAbsolutePath());
System.out.println("myDir.isDirectory() = " + myDir.isDirectory());
System.out.println("myDir.isFile() = " + myDir.isFile());
System.out.println();
myDir = new File(File.separator+"Java"+File.separator+"FilePartOne");
System.out.println("myDir.getAbsolutePath() = " + myDir.getAbsolutePath());
System.out.println("myDir.isDirectory() = " + myDir.isDirectory());
System.out.println("myDir.isFile() = " + myDir.isFile());
System.out.println();
File myFile = new File(myDir, "Temp.txt");
System.out.println("myFile.getAbsolutePath() = " + myFile.getAbsolutePath());
System.out.println("myFile.isDirectory() = " + myFile.isDirectory());
System.out.println("myFile.isFile() = " + myFile.isFile());
System.out.println("myFile.exists() = " + myFile.exists());
try {
myFile.createNewFile();
} catch (IOException e) {
System.out.println(e.getMessage());
}
Output:
myDir.getAbsolutePath() = C:\
myDir.isDirectory() = true
myDir.isFile() = false
myDir.getAbsolutePath() = C:\Java\FilePartOne
myDir.isDirectory() = false
myDir.isFile() = false
myFile.getAbsolutePath() = C:\Java\FilePartOne\Temp.txt
myFile.isDirectory() = false
myFile.isFile() = false
myFile.exists() = false
The system cannot find the path specified
This code if from an online tutorial that works in the video and it's copied verbatim. IDE is eclipse.

I would say its likely because of missing directories along the path "C:\Java\FilePartOne".
The statement:
myFile.createNewFile();
Will attempt to create a file on a given path, not create any missing directories. You therefore get the error "The system cannot find the path specified" if any directories are missing when executing the statement.
A quick way to fix this would be to either create the missing folders yourself or add the code below just before myFile.createNewFile();.
myFile.getParentFile().mkdirs();

Related

Possible to download JPA repository in Vaadin as CSV file?

Assume that we have defined a entity and it's connected to a database. Now we can access the database by using a repository.
#Autowired
private DataLoggRepository dataLoggRepository;
If I want to get all the rows from the database and download it. Then I can write this code:
List<DataLogg> dataLoggers = dataLoggRepository.findAll();
Now, how can I donwload the object dataLoggers as a CSV file in Vaadin in a proper way?
Here you can see how to create a link to download a file:
Anchor csvLink = new Anchor(new StreamResource("file.csv",
() -> {
String csvString = ...// create the csv
return new ByteArrayInputStream(csvString.getBytes());
}), "Download CSV");
csvLink.getElement().setAttribute("download", true);
To create the CSV you have various options like OpenCSV or directly create the CSV from the SQL query.
Here is a working example
// Download all data
Anchor download = new Anchor(); // Add this to the layout
loggerId.addValueChangeListener(e-> {
String fileName = String.valueOf(loggerId.getValue()) + ".csv";
List<DataLogg> selectedLogger = dataLoggRepository.findByLoggerId(loggerId.getValue());
download.setHref(getStreamResource(fileName, selectedLogger));
});
download.getElement().setAttribute("download",true);
download.add(new Button("Download", new Icon(VaadinIcon.DOWNLOAD_ALT)));
Function
public StreamResource getStreamResource(String filename, List<DataLogg> selectedLogger) {
// Create a large CSV file in a form of StringBuilder and then convert it all to bytes
StringWriter stringWriter = new StringWriter();
stringWriter.write("id, dateTime, DO0, DO1, DO2, DO3, AI0, AI1, AI2, AI3, loggerId, samplingTime\n");
for (int i = 0; i < selectedLogger.size(); ++ i) {
DataLogg dataLogg = selectedLogger.get(i);
String row = dataLogg.getId() + "," +
dataLogg.getDateTime() + "," +
dataLogg.getDO0() + "," +
dataLogg.getDO1() + "," +
dataLogg.getDO2() + "," +
dataLogg.getDO3() + "," +
dataLogg.getAI0() + "," +
dataLogg.getAI1() + "," +
dataLogg.getAI2() + "," +
dataLogg.getAI3() + "," +
dataLogg.getLoggerId() + "," +
dataLogg.getSamplingTime() + "\n";
stringWriter.write(row);
}
// Try to download
try {
byte[] buffer = stringWriter.toString().getBytes("UTF-8");
return new StreamResource(filename, () -> new ByteArrayInputStream(buffer));
} catch (UnsupportedEncodingException e) {
byte[] buffer = new byte[] {0};
return new StreamResource(filename, () -> new ByteArrayInputStream(buffer));
}
}

BrowserMob Proxy is not opening 2nd page in chrome (Internet connection goes off after landing to 2nd page)

I'm running Windows 10 virtual machine on ubuntu, and on VM I have following versions :-
Eclipse neon, Selenium Webdriver 3.0.1, Mozilla Firefox 51.0.1, Google Chrome 55, geckoDriver v0.11.1, Chromedriver v2.27, BrowserMob Proxy jar 2.1.4, jackson-all-1.7.3.jar, harlib-1.1.2.jar
I wanted to read browser traffics in selenium and for that i opted for BrowserMob proxy. I have 2 page of communication on the browser like Authenticates url, Lands on the 1st page clicks a dropdown menu (link) and lands on the 2nd page
When the second page opens the page does not load but the calls are going behind. What i noticed is in the VM when the second page loads internet connectivity goes off at that page only (internet sign stops blinking).
When i Reboot both the VM & the host machine and then execute the code. It loads the page at first attempt after fresh reboot of the system then again, if i execute the same code same problem persists.
But the traffic data is getting logged in the file. The same code if i try to execute in geckodriver(Firefox) then the page is getting loaded but traffic is not getting captured.capturing only specific urls from the log data
I have stuck in both the ways. Please find below the code :-
class 1 :-
public class BrowserMobExample{
public static String sFileName = System.getProperty("user.dir") + "\\CaptureNetworkTraffic\\BrowserMob.har";
WebDriver driver = null;
BrowserMobProxy proxy = null;
#BeforeTest
public void setUp() throws Exception {
// start the proxy
proxy = new BrowserMobProxyServer();
proxy.start(0);
//get the Selenium proxy object - org.openqa.selenium.Proxy;
Proxy seleniumProxy = ClientUtil.createSeleniumProxy(proxy);
// configure it as a desired capability
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability(CapabilityType.PROXY, seleniumProxy);
//set chromedriver system property
System.setProperty("webdriver.chrome.driver", "path to chromedriver");
driver = new ChromeDriver(capabilities);
/*System.setProperty("webdriver.gecko.driver", "path to geckodriver");
driver = new FirefoxDriver(capabilities);*/
// enable more detailed HAR capture, if desired (see CaptureType for the complete list)
proxy.enableHarCaptureTypes(CaptureType.REQUEST_HEADERS, CaptureType.RESPONSE_HEADERS);
proxy.newHar("label_for_har");
driver.manage().window().maximize();
driver.get("http://username:pswd#url.com");
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
Robot rb = new Robot();
rb.keyPress(KeyEvent.VK_ENTER);
//do something on page
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
WebElement citySelect = driver.findElement(By.xpath("dropdown_xpath"));
Select dropdown= new Select(select_a_dropdown_menuitem);
dropdown.selectByVisibleText("Text_displayed");
//driver.navigate().refresh();
}
#Test
public void testCaseOne() throws AWTException {
/*driver.manage().window().maximize();
driver.get("http://username:pswd#url.com");
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
Robot rb = new Robot();
rb.keyPress(KeyEvent.VK_ENTER);
//do something on page
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
WebElement citySelect = driver.findElement(By.xpath("dropdown_xpath"));
Select dropdown= new Select(select_a_dropdown_menuitem);
dropdown.selectByVisibleText("Text_displayed");
//driver.navigate().refresh();*/
}
#AfterTest
public void tearDown() {
// get the HAR data
Har har = proxy.getHar();
// Write HAR Data in a File
File harFile = new File(sFileName);
try {
har.writeTo(harFile);
ReadHAR reading = new ReadHAR();
reading.main(null);
} catch (IOException ex) {
System.out.println (ex.toString());
System.out.println("Could not find file " + sFileName);
}
/*if (driver != null) {
proxy.stop();
//driver.quit();
}*/
}
}
class 2 :-
public class ReadHAR {
public static void main(String[] args) {
String filename = new String();
filename = BrowserMobExample.sFileName;
// System.out.println("This is the file location " + filename);
File f = new File(filename);
HarFileReader r = new HarFileReader();
HarFileWriter w = new HarFileWriter();
try
{
System.out.println("Reading " + filename);
HarLog log = r.readHarFile(f);
// Access all elements as objects
HarBrowser browser = log.getBrowser();
HarEntries entries = log.getEntries();
// Used for loops
List<HarPage> pages = log.getPages().getPages();
List<HarEntry> hentry = entries.getEntries();
String string1 = "p_still_media";
String string2 = "m_still_media";
String string3 = "T-Map";
/* for (HarPage page : pages)
{
System.out.println("page start time: "
+ ISO8601DateFormatter.format(page.getStartedDateTime()));
System.out.println("page id: " + page.getId());
System.out.println("page title: " + page.getTitle());
}*/
File varTmpDir = new File(System.getProperty("user.dir") + "\\CaptureNetworkTraffic\\results.txt");
boolean exists = varTmpDir.exists();
System.out.println(" result.txt : " +exists);
System.out.println(" file path:"+ varTmpDir);
if(exists){
varTmpDir.delete();
}
File result = new File(System.getProperty("user.dir") + "\\CaptureNetworkTraffic\\results.txt");
// result.createNewFile();
result.setWritable(true);
//FileWriter fw = new FileWriter(result, false);
// PrintWriter out = new PrintWriter(fw);
//Output "response" code of entries.
for (HarEntry entry : hentry)
{
// System.out.println("IP is : " + entry.getServerIPAddress());
if(entry.getRequest().getUrl().contains(string2)/* & entry.getResponse().getStatus() !=200*/){
System.out.println(" Url is : " + entry.getRequest().getUrl() + " response code: " + entry.getResponse().getStatus()); //Output url of request
// Files.newBufferedWriter(result, StandardOpenOption.APPEND);
// out.write(" Url is : " + entry.getRequest().getUrl() + " response code: " + entry.getResponse().getStatus());
// BufferedWriter bw = new BufferedWriter(fw);
System.out.println("IP is :- "+entry.getServerIPAddress());
FileWriter fw = new FileWriter(result, true);
BufferedWriter out = new BufferedWriter(fw);
out.write(" Url is : " + entry.getRequest().getUrl() + " response code: " + entry.getResponse().getStatus());
out.newLine();
out.close();
fw.close();
}
else if(entry.getRequest().getUrl().contains(string3) /*& entry.getResponse().getStatus() !=200*/){
// System.out.println("request code: " + entry.getRequest().getMethod()); //Output request type
System.out.println(" Url is: " + entry.getRequest().getUrl() + " response code: " + entry.getResponse().getStatus()); //Output url of request
// out.write(" Url is : " + entry.getRequest().getUrl() + " response code: " + entry.getResponse().getStatus());
FileWriter fw = new FileWriter(result, true);
BufferedWriter out = new BufferedWriter(fw);
out.write(" Url is : " + entry.getRequest().getUrl() + " response code: " + entry.getResponse().getStatus());
out.newLine();
out.close();
fw.close();
}
else if(entry.getRequest().getUrl().contains(string1) /*& entry.getResponse().getStatus() !=200*/){
// System.out.println("request code: " + entry.getRequest().getMethod()); //Output request type
System.out.println(" Url is: " + entry.getRequest().getUrl() + " response code: " + entry.getResponse().getStatus()); //Output url of request
//out.write(" Url is : " + entry.getRequest().getUrl() + " response code: " + entry.getResponse().getStatus());
// out.close();
//System.out.println(" response code: " + entry.getResponse().getStatus()); // Output the
FileWriter fw = new FileWriter(result, true);
BufferedWriter out = new BufferedWriter(fw);
out.write(" Url is : " + entry.getRequest().getUrl() + " response code: " + entry.getResponse().getStatus());
out.newLine();
out.close();
fw.close();
}
}
/*
// Once you are done manipulating the objects, write back to a file
System.out.println("Writing " + "fileName" + ".test");
File f2 = new File("fileName" + ".test");
w.writeHarFile(log, f2);
*/
}
catch (JsonParseException e)
{
e.printStackTrace();
//fail("Parsing error during test");
}
catch (IOException e)
{
e.printStackTrace();
//fail("IO exception during test");
}
}
}
With ChromeDriver logs are getting generated but the page is not loading. With firefox page is loading but logs are not captured (I think for geckodriver browsermob proxy is not compatible or this feature isn't available yet)
Am i missing anything or what is the issue ? Stuck on this since more than a week. Tried the above on ubuntu to but facing the same issue.
Any help on this issue is much appreciated.

Using "shared logic" across multiple Typewriter templates?

We have multiple Typewriter .tst templates in our project, and would like to share some common logic/methods between them. Is there a way to do this?
You can use T4 templates to generate the Typewriter templates. Put the code inside a reusable T4 template (*.ttinclude) and create tt-files to pass parameters to the rendering method of this base template.
(I use a Visual Studio extension for File nesting.)
Each tt-file looks something like this;
<## template debug="true" hostSpecific="true" #>
<## output extension=".tst" #>
<## include file="..\ModelsTemplate.ttinclude" #>
<# this.ModelsTemplate_Render("UserSettings"); #>
...and my ttinclude file looks like this (it is a bit project specific, but I included it all so that anyone who wants to try it out can easily get something working);
<## IntelliSenseLanguage processor="tangibleT4Editor" language="C#" #>
<#+
void ModelsTemplate_Render(string #subnamespace) {
ModelsTemplate_Render("MyApp.ViewData", #subnamespace);
}
void ModelsTemplate_Render(string #mainnamespace, string #subnamespace) {
string renderedMainNamespace = #mainnamespace;
#>
// <auto-generated>
// This code was generated by a tool.
// Template: <#= Host.TemplateFile #>
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
${
// Enable extension methods by adding using Typewriter.Extensions.*
using Typewriter.Extensions.Types;
using System.Text.RegularExpressions;
Template(Settings settings)
{
settings.IncludeProject("MyApp.ViewData");
}
static string DebugInfo = "";
string PrintDebugInfo(File f){
if (string.IsNullOrEmpty(DebugInfo)) {
return "";
}
return "/*" + Environment.NewLine + "Template debug info: " + DebugInfo + Environment.NewLine + "*/";
}
string BaseClassFullPath(Class baseClass)
{
//DebugInfo = DebugInfo + Environment.NewLine + "baseClass.FullName:" + baseClass.FullName;
var result = baseClass.Name;
// Until we find a better way to handle implementations of generic base classes...
result = result.Replace("<bool?>", "<boolean>");
result = result.Replace("<int?>", "<number>");
result = result.Replace("<long?>", "<number>");
result = result.Replace("<decimal?>", "<number>");
result = result.Replace("<double?>", "<number>");
result = result.Replace("<System.Double>", "<number>");
result = result.Replace("<System.Double?>", "<number>");
result = result.Replace("<System.DateTime?>", "<Date>");
return result;
}
string NullableFilter(string typeName)
{
return typeName.Replace("?", "");
}
string TypeFilteredPath(Type type)
{
//DebugInfo = DebugInfo + Environment.NewLine + "type:" + type.FullName + " - genericType:" + type.Unwrap().FullName;
return NullableFilter(type.Name);
}
string TypeFiltered(Type type)
{
if (type.IsEnumerable)
{
var genericType = type.Unwrap();
if (!genericType.FullName.StartsWith("System"))
{
return TypeFilteredPath(genericType)+"[]";
}
}
return TypeFilteredPath(type);
}
string PropertyTypeFiltered(Property prop)
{
return TypeFiltered(prop.Type);
}
string ImplementedInterfaces(Class c){
if (!c.Interfaces.Any()){
return string.Empty;
}
return "implements " + string.Join(", ", c.Interfaces.Select(x => x.FullName));
}
string ExtendedInterfaces(Interface i){
if (!i.Interfaces.Any()){
return string.Empty;
}
return "extends " + string.Join(", ", i.Interfaces.Select(x => x.FullName));
}
string DescriptionAttributeValue(Attribute a){
if (!a.FullName.Contains("DescriptionAttribute")){
return string.Empty;
}
return a.Value;
}
string GetPropertyDefinitionWithScope(Property p){
var definition = GetPropertyDefinition(p);
if (definition != "")
return "public " + definition;
else
return definition;
}
string GetPropertyDefinition(Property p){
var ignoreAttribute = p.Attributes.SingleOrDefault(x => x.FullName.Contains("TypeScriptIgnoreMemberAttribute"));
if (ignoreAttribute != null)
return "";
var typeAttribute = p.Attributes.SingleOrDefault(x => x.FullName.Contains("TypeScriptTypeAttribute"));
if (typeAttribute != null) {
return p.name + ": " + typeAttribute.Value + ";";
}
return p.name + ": " + TypeFiltered(p.Type) + ";";
}
string WriteImports(Class theClass){
//return "import { ViewDataEntity } from '../common/ViewDataEntity';";
var list = new List<string>();
var typesToImport = theClass.Properties.Select(x => x.Type.Unwrap()).Where(x => x.Namespace.Contains("MyApp.ViewData.")).ToList();
if (theClass.BaseClass?.Namespace.Contains("MyApp.ViewData.") == true)
typesToImport.Add(theClass.BaseClass);
foreach (var impType in typesToImport)
{
var modules = impType.Namespace.Replace("MyApp.ViewData.", "").Split('.').ToList();
string modPart = string.Join("/", modules.Select(x => CamelCase(x)));
list.Add($"import {{ {impType.Name} }} from '../{modPart}/{impType.Name}';");
}
return string.Join(Environment.NewLine, list.Distinct());
}
string CamelCase(string value){
return value.First().ToString().ToLower() + value.Substring(1);
}
}//namespace <#= renderedMainNamespace #>.<#= #subnamespace #> {
$Classes(c => c.Namespace.StartsWith("<#= #mainnamespace #>.<#= #subnamespace #>"))[
$WriteImports
export class $Name$TypeParameters $BaseClass[extends $BaseClassFullPath ] $ImplementedInterfaces {$Properties[
$GetPropertyDefinitionWithScope]
}]
$Interfaces(<#= #mainnamespace #>.<#= #subnamespace #>.*)[
export interface $Name $ExtendedInterfaces {
$Properties[
$GetPropertyDefinition]
}]
$Enums(<#= #mainnamespace #>.<#= #subnamespace #>.*)[
export class $Name {
$Values[// $Value - "$Attributes[$Value]"
static $Name = "$Name";
]
}]
$PrintDebugInfo
//}<#+
}
#>
Unfortunately there's no way to share code in tst templates. Support for this will probably come in a future version though.

Get appointments from all Outlook calendars

I'm trying to read appointments from Outlook calendar using ExchangeServiceBinding but my solution takes appointments only from "default" outlook calendar and don't read from "sub calendars/custom calendars". Do you know how to define rest of the calendars or do you know better solution which contains all calendars?
Critical part is that solution shouldn't contain MAPI because of next use in web service.
My current code:
private static List<List<string>> ReadCalendarEvents(string email)
{
List<List<string>> calendarEvents = new List<List<string>>();
// Specify the request version.
esb.RequestServerVersionValue = new RequestServerVersion();
esb.RequestServerVersionValue.Version = ExchangeVersionType.Exchange2007;
// Form the FindItem request.
FindItemType findItemRequest = new FindItemType();
CalendarViewType calendarView = new CalendarViewType();
calendarView.StartDate = DateTime.Now.AddDays(-7);
calendarView.EndDate = DateTime.Now.AddDays(200);
calendarView.MaxEntriesReturned = 1000;
calendarView.MaxEntriesReturnedSpecified = true;
findItemRequest.Item = calendarView;
// Define which item properties are returned in the response.
ItemResponseShapeType itemProperties = new ItemResponseShapeType();
// Use the Default shape for the response.
//itemProperties.BaseShape = DefaultShapeNamesType.IdOnly;
itemProperties.BaseShape = DefaultShapeNamesType.AllProperties;
findItemRequest.ItemShape = itemProperties;
DistinguishedFolderIdType[] folderIDArray = new DistinguishedFolderIdType[1];
folderIDArray[0] = new DistinguishedFolderIdType();
folderIDArray[0].Id = DistinguishedFolderIdNameType.calendar;
//
folderIDArray[0].Mailbox = new EmailAddressType();
folderIDArray[0].Mailbox.EmailAddress = email;
findItemRequest.ParentFolderIds = folderIDArray;
// Define the traversal type.
findItemRequest.Traversal = ItemQueryTraversalType.Shallow;
try
{
// Send the FindItem request and get the response.
FindItemResponseType findItemResponse = esb.FindItem(findItemRequest);
// Access the response message.
ArrayOfResponseMessagesType responseMessages = findItemResponse.ResponseMessages;
ResponseMessageType[] rmta = responseMessages.Items;
int folderNumber = 0;
foreach (ResponseMessageType rmt in rmta)
{
// One FindItemResponseMessageType per folder searched.
FindItemResponseMessageType firmt = rmt as FindItemResponseMessageType;
if (firmt.RootFolder == null)
continue;
FindItemParentType fipt = firmt.RootFolder;
object obj = fipt.Item;
// FindItem contains an array of items.
if (obj is ArrayOfRealItemsType)
{
ArrayOfRealItemsType items =
(obj as ArrayOfRealItemsType);
if (items.Items == null)
{
folderNumber++;
}
else
{
foreach (ItemType it in items.Items)
{
if (it is CalendarItemType)
{
CalendarItemType cal = (CalendarItemType)it;
List<string> ce = new List<string>();
ce.Add(cal.Location);
ce.Add(cal.Start.ToShortDateString() + " " + cal.Start.ToShortTimeString());
ce.Add(cal.End.ToShortDateString() + " " + cal.End.ToShortTimeString());
ce.Add(cal.Subject);
if (cal.Organizer != null)
{
ce.Add(cal.Organizer.Item.Name);
}
calendarEvents.Add(ce);
Console.WriteLine(cal.Subject + " " + cal.Start.ToShortDateString() + " " + cal.Start.ToShortTimeString() + " " + cal.Location);
}
}
folderNumber++;
}
}
}
}
catch (Exception e)
{
throw;
}
finally
{
}
return calendarEvents;
}
In EWS you need to query one folder at a time, for non default folders you will first need to find the FolderId before you can then query the appointments (or items) within a Folder. To find all the Calendar folders in a Mailbox you need to use the FindFolder operation and create a restriction to limit the result to folder with a FolderClass of IPF.Appointment eg
// Create the request and specify the travesal type.
FindFolderType findFolderRequest = new FindFolderType();
findFolderRequest.Traversal = FolderQueryTraversalType.Deep;
// Define the properties that are returned in the response.
FolderResponseShapeType responseShape = new FolderResponseShapeType();
responseShape.BaseShape = DefaultShapeNamesType.Default;
findFolderRequest.FolderShape = responseShape;
// Identify which folders to search.
DistinguishedFolderIdType[] folderIDArray = new DistinguishedFolderIdType[1];
folderIDArray[0] = new DistinguishedFolderIdType();
folderIDArray[0].Id = DistinguishedFolderIdNameType.msgfolderroot;
IsEqualToType iet = new IsEqualToType();
PathToUnindexedFieldType FolderClass = new PathToUnindexedFieldType();
FolderClass.FieldURI = UnindexedFieldURIType.folderFolderClass;
iet.Item = FolderClass;
FieldURIOrConstantType constantType = new FieldURIOrConstantType();
ConstantValueType constantValueType = new ConstantValueType();
constantValueType.Value = "IPF.Appointment";
constantType.Item = constantValueType;
iet.FieldURIOrConstant = constantType;
// Add the folders to search to the request.
RestrictionType restriction = new RestrictionType();
restriction.Item = iet;
findFolderRequest.Restriction = restriction;
findFolderRequest.ParentFolderIds = folderIDArray;
try
{
// Send the request and get the response.
FindFolderResponseType findFolderResponse = esb.FindFolder(findFolderRequest);
// Get the response messages.
ResponseMessageType[] rmta = findFolderResponse.ResponseMessages.Items;
foreach (ResponseMessageType rmt in rmta)
{
// Cast to the correct response message type.
if (((FindFolderResponseMessageType)rmt).ResponseClass == ResponseClassType.Success) {
foreach (FolderType folder in ((FindFolderResponseMessageType)rmt).RootFolder.Folders) {
Console.WriteLine(folder.DisplayName);
}
}
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
You also might want to look at using the EWS Managed API which will save you greatly time and the amount of code you need to write
Cheers
Glen

PhoneGap, File copy error: Code = 1,

file copy error, detail information:
2012-06-12 09:21:38.557 mead_debug[10314:fb03] [INFO] parent_entry := /Users/laiqinyi/Library/Application Support/iPhone Simulator/4.3.2/Applications/5EFBD6D1-66EB-4DEC-8AE7-D386729744E9/Documents/dest/
2012-06-12 09:22:34.640 mead_debug[10314:fb03] [INFO] upload error source undefined
2012-06-12 09:22:34.641 mead_debug[10314:fb03] [INFO] upload error target undefined
I follow the API instruction, and do not think there are some thing wrong with this "copyTo" code.
In addition, there are folder "Documents/dest" and file "Documents/readme.txt"
http://docs.phonegap.com/en/1.8.0/cordova_file_file.md.html#File
**var FileSystem = {
copy : function(src, dest){
var parentEntry = new DirectoryEntry({fullPath:("/dest")});
console.log("parent_entry := " + FileSystem.root_path+"/dest");
function gotFS(fileSystem) {
fileSystem.root.getFile("readme.txt", null, gotFileEntry, fail);
}
function gotFileEntry(fileEntry) {
fileEntry.copyTo(parentEntry, "file.copy", function(e){console.log("copy okay");}, fail);
}
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail);
}
}**
copy : function(fromUrl, toPath, toName){
console.log("copyFile - From: [" + fromUrl + "] To: " + toPath + " Name: " + toName);
// Set up some storage
var destPath = '';
var destName = '';
doMoveFile(fromUrl);
// Called when file needs to be moved / after capture
function doMoveFile(fileUrl){
//console.log("doMoveFile - fileUrl: " + JSON.stringify(fileUrl));
// Remember the source file name just in case it was not passed so reuse it, and for logging
var destName = fileUrl.name;
var destPath = fileUrl;
// Resolve the file system
window.resolveLocalFileSystemURI(fileUrl,resFSSuccess, resFSError);
// Called upon successful File System resolution
function resFSSuccess(entry){
//console.log("resFSSuccess Success - entry: " + JSON.stringify(entry));
// Request a file system
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0,
requestFileSystemSuccess, requestFileSystemError);
// Called upon successful File System request
function requestFileSystemSuccess(fileSys){
// Get the source directory
fileSys.root.getDirectory(toPath, {create: true, exclusive:false}, getDestDirSuccess, getDestDirError);
// Called upon successful Get Of Destination Directory
function getDestDirSuccess(directory){
// Get the destination file name, set it if it is blank or not passed by the App
toName = (toName) ? toName : destName;
// Remember the full path name for the console log
fullDestPath = directory.fullPath + '/' + toName;
// Make the move
entry.copyTo(directory, toName, moveSuccess, moveError);
function moveSuccess(){
console.log("Successful copy of " + destPath + " to " + fullDestPath);
};
function moveError(error){
console.log("copyError code: " + JSON.stringify(error));
};
}
// Get Destination Dir Failure
function getDestDirError(error){
console.log("getDestDirError code: " + JSON.stringify(error));
};
}
// File System Request Failure
function requestFileSystemError(error){
console.log("requestFileSystemError code: " + JSON.stringify(error));
};
}
// Note File System failure
function resFSError(error){
console.log("resFSError code: " + JSON.stringify(error));
};
}
}

Resources