Unexpected response from NSFileManager in Sketch Plugin - cocoa

I published a Sketch Plugin with some functionalities with a strong dependency in files management.
When execute, plugin needs to check if a folder exists, if not, create, and then manage several files inside this directory.
Some weeks ago, one user reported plugin was crashing in a new Sketch version.
Unexpected response from:
fileExistsAtPath return -folder does not exist- when actually exists in that path
createDirectoryAtPath return 'error' when trying to create a non-existing folder (I've tested both when folder exists and not)
Quick example:
Request
var document = context.document
var documentName = document.displayName()
var documentFolderPath = decodeURIComponent(document.fileURL()).replace('file:///','').replace(documentName,"")
print(documentName)
print(documentFolderPath)
var translationsFolderName = documentName.replace('.sketch','_translations')
var translationsFolderPath = documentFolderPath+translationsFolderName+'/'
print(translationsFolderName)
print(translationsFolderPath)
var fileManager = [NSFileManager defaultManager];
if(![fileManager fileExistsAtPath:translationsFolderPath isDirectory:'YES'])
{
print(translationsFolderPath+" folder does not exist")
if(![fileManager createDirectoryAtPath:translationsFolderPath withIntermediateDirectories:'YES' attributes:nil error:nil])
{
print(translationsFolderPath+" folder can't be created")
}
}
Response
test.sketch
Users/myuser/Documents/
test_translations
Users/myuser/Documents/test_translations/
Users/myuser/Documents/test_translations/ folder does not exist
Users/myuser/Documents/test_translations/ folder can't be created
Script executed in 0.034733s
Any idea?
Thanks!

Your file path is not rooted (doesn't start with /)

Related

search file from document directory in ios

I have enabled itune file sharing in my Application.
I have added pdf file in my application directory.
now I want to search that file using my app. and upload it on server.
also if there multiple file and folder I want to show in application. search folder and select specific file and upload it. please suggest best way for doing that.
Appriciate for help.
do
{
let dirPaths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0]
print(dirPaths)
let Pnames = try NSFileManager.defaultManager().contentsOfDirectoryAtPath(dirPaths) as [String]
var ProductImgs:Array<String> = Array<String>()
var ProductNames:Array<String> = Array<String>()
for name in Pnames
{
let fileName:String = name
if fileName.hasSuffix(".pdf")
{
PdfURLs.append(dirPaths.stringByAppendingString("/\(fileName)"))
PdfNames.append(fileName)
print(dirPaths.stringByAppendingString("/\(fileName)"))
}
}
}
catch
{
print(error)
}
If you are fine using third party libraries, it would be great to use Alamofire. It is an HTTP networking library written in Swift.
You can upload the file easily using this one,
let fileURL = NSBundle.mainBundle().URLForResource("Default", withExtension: "png")
Alamofire.upload(.POST, "https://httpbin.org/post", file: fileURL)
For a complete understanding of this library check out this link, https://github.com/Alamofire/Alamofire

DeleteAsync() broke my app

I've been playing around with DeleteAsync() to try and delete a folder called 'Images' inside Assets. I then want to recreate the folder so that it now contains no files.
My folder never deleted, its still in Assets with all its files, but when I re-run the app after the code below it crashes at StorageFolder appFolder = await StorageFolder.GetFolderFromPathAsync(path1);
My guess is that I misunderstood DeleteAsync() and removed some form of reference to the path without actually deleting the folder.
If I delete the 'Images' folder in the VS2015 Solution Explorer, then recreate it manually and add back in all the files manually, the app will run fine again.
Could someone help explain whats going on and if its possible to physically delete a known folder?
//Get the folder location.
string root = Windows.ApplicationModel.Package.Current.InstalledLocation.Path;
string path1 = root + #"\Assets";
string path2 = path1 + #"\Images";
StorageFolder appFolder = await StorageFolder.GetFolderFromPathAsync(path1);
StorageFolder appFolder1 = await StorageFolder.GetFolderFromPathAsync(path2);
//Delete a folder.
if (await appFolder.TryGetItemAsync(#"\Images") != null)
{
await appFolder1.DeleteAsync();
await appFolder.CreateFolderAsync("Images");
}

NotifyFilter of FileSystemWatcher not working

I have a windows service (and verified the code by creating a similar WinForms application) where the NotifyFilter doesn't work. As soon as I remove that line of code, the service works fine and I can see the event-handler fire in the WinForms application.
All I'm doing is dropping a text file into the input directory for the FileSystemWatcher to kick off the watcher_FileChanged delegate. When I have the _watcher.NotifyFilter = NotifyFilters.CreationTime; in there, it doesn't work. When I pull it out, it works fine.
Can anyone tell me if I'm doing something wrong with this filter?
Here is the FSW code for the OnStart event.
protected override void OnStart(string[] args)
{
_watcher = new FileSystemWatcher(#"C:\Projects\Data\Test1");
_watcher.Created += new FileSystemEventHandler(watcher_FileChanged);
_watcher.NotifyFilter = NotifyFilters.CreationTime;
_watcher.IncludeSubdirectories = false;
_watcher.EnableRaisingEvents = true;
_watcher.Error += new ErrorEventHandler(OnError);
}
private void watcher_FileChanged(object sender, FileSystemEventArgs e)
{
// Folder with new files - one or more files
string folder = #"C:\Projects\Data\Test1";
System.Console.WriteLine(#"C:\Projects\Data\Test1");
//Console.ReadKey(true);
// Folder to delete old files - one or more files
string output = #"C:\Temp\Test1\";
System.Console.WriteLine(#"C:\Temp\Test1\");
//Console.ReadKey(true);
// Create name to call new zip file by date
string outputFilename = Path.Combine(output, string.Format("Archive{0}.zip", DateTime.Now.ToString("MMddyyyy")));
System.Console.WriteLine(outputFilename);
//Console.ReadKey(true);
// Save new files into a zip file
using (ZipFile zip = new ZipFile())
{
// Add all files in directory
foreach (var file in Directory.GetFiles(folder))
{
zip.AddFile(file);
}
// Save to output filename
zip.Save(outputFilename);
}
DirectoryInfo source = new DirectoryInfo(output);
// Get info of each file into the output directory to see whether or not to delete
foreach (FileInfo fi in source.GetFiles())
{
if (fi.CreationTime < DateTime.Now.AddDays(-1))
fi.Delete();
}
}
I've been having trouble with this behavior too. If you step through the code (and if you look at MSDN documenation, you'll find that NotifyFilter starts off with a default value of:
NotifyFilters.FileName | NotifyFilters.DirectoryName | NotifyFilters.LastWrite
So when you say .NotifyFilter = NotifyFilters.CreationTime, you're wiping out those other values, which explains the difference in behavior. I'm not sure why NotifyFilters.CreationTime is not catching the new file... seems like it should, shouldn't it!
You can probably just use the default value for NotifyFilter if it's working for you. If you want to add NotifyFilters.CreationTime, I'd recommend doing something like this to add the new value and not replace the existing ones:
_watcher.NotifyFilter = _watcher.NotifyFilter | NotifyFilters.CreationTime;
I know this is an old post but File Creation time is not always reliable. I came across a problem where a Log file was being moved to an archive folder and a new file of the same name was created in it's place however the file creation date did not change, in fact the meta data was retained from the previous file (the one that was moved to the archive) .
Windows has this cache on certain attributes of a file, file creation date is included. You can read the article on here: https://support.microsoft.com/en-us/kb/172190.

how to programmatically kick off a ssis package in asp.net MVC3 to import excel files

I am having some trouble with a asp.net MVC3 web application that I am developing. I need an upload page which Allows the user to upload excel files and dump them to the file system. I got this to work fine. The next part is the part that I am having trouble with, After I upload the excel files I need to programmatically kick off a SSIS package which I have created already to import the excel files.
Here is what I have so far in code:
//
// POST: /Home/Update/
[HttpPost]
public ActionResult Update(HttpPostedFileBase file)
{
// Verify that the user selected a file
if (file != null && file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
// store the file inside ~/App_Data/uploads folder
var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
ViewBag.Message = "File Uploaded Successfully";
file.SaveAs(path);
}
//Start the SSIS here
try
{
Application app = new Application();
Package package = null;
package = app.LoadPackage( #"C:\Users\Chris\Documents\Visual Studio
2008\Projects\Integration Services Project1\Integration Services Project1
\bin\Package.dtsx", null);
// Execute Package
DTSExecResult results = package.Execute();
if(results == DTSExecResult.Failure)
{
foreach(DtsError local_DtsError in package.Errors)
{
ViewBag.Message("Package Execution results:{0}",
local_DtsError.Description.ToString());
}
}
}
catch(DtsException ex)
{
//ViewBag.Message("{0} Exception caught.", ex);
}
// redirect back to the index action to show the form once again
return RedirectToAction("Update");
}
When I run the code and upload an excel file I get a DtsException caught, which says:
Failed to open package file "C:\Users\Chris\Documents\Visual Studio 2008\Projects\Integration Services Project1\Integration Services Project1\bin\Package.dtsx" due to error 0x80070003 "The system cannot find the path specified.". This happens when loading a package and the file cannot be opened or loaded correctly into the XML document. This can be the result of either providing an incorrect file name was specified when calling LoadPackage or the XML file was specified and has an incorrect format.
I don't understand why it is giving me this because the file path is right I checked and it is exactly correct. I need some help fixing this issue I would greatly appreciate any help you guys can give.
Permissions I should think. Put the file somewhere where account running IIS can see it. Whereever you were planning on deploying it, would be good.

Custom Event Receiver - Copy To Folder

I am in the process of writing a custom event receiver. The basic flow is as follows:
Document is added to Library
Based on metadata of document, we check to see if a folder within another document library exists.
If the folder does not exist, it is created.
The newly added document is copied to the folder residing in another document library.
I have got myself to the point, where I can copy newly added files, from one document library to another when they are added. However I cannot figure out how to copy to a specific directory (by name) within a document library. Any help would be greatly received.
Here is my code so far:
SPFile sourceFile = properties.ListItem.File;
SPFile destFile; // Copy file from source library to destination
using (Stream stream = sourceFile.OpenBinaryStream())
{
var destLib = (SPDocumentLibrary) properties.ListItem.Web.Lists[listName];
destFile = destLib.RootFolder.Files.Add(sourceFile.Name, stream);
stream.Close();
}
// Update item properties
SPListItem destItem = destFile.Item;
SPListItem sourceItem = sourceFile.Item;
// Copy meta data
destItem["Title"] = sourceItem["Title"];
//...
//... destItem["FieldX"] = sourceItem["FieldX"];
//...
destItem.UpdateOverwriteVersion();
Answer
//Ensure folder here
var destFolder = destLib.RootFolder.SubFolders["name"];
destFile = destFolder.Files.Add(sourceFile.Name, stream);

Resources