Xamarin iOS 8 Bundle Resource - Access to the path is denied - xamarin.ios

I've have a Xamarin iOS project with a file that I have marked as a bundle resource. The file is configured in the project like so:
<BundleResource Include="my\folder\file.xyz" />
I've have been using the following to access the file as a stream:
string ext = Path.GetExtension ("file.xyz");
string filenameNoExt = filename.Substring (0, filename.Length - ext.Length);
string path = Path.Combine ("my/folder", filenameNoExt);
var resourcePathname = NSBundle.MainBundle.PathForResource (path, ext.Substring (1, ext.Length - 1));
var fStream = new FileStream (resourcePathname, FileMode.Open);
It won't work on iOS 8. It worked without issue before iOS 8.
I get the following error:
Access to the path "/private/var/mobile/Containers/Bundle/Application/0E6DD32F-4E6F-4E54-B47E-A91060097E16/myapp.app/my/folder/file.xyz" is denied.
What, exactly, do I need to change to get this to work in iOS 8?

Provide also FileAccess.Read when you create the stream. Otherwise it will throw an UnauthorizedAccessException for read-only files.

Related

How to access Azure Linux web app path file

Trying to access file on path - wwwroot/templates/file.txt. It works using -_hostingEnvironment.ContentRootPath + "\templates\file.txt" on windows but same path says file does not exists.
What Am I missing
Trying to access file on path - wwwroot/templates/file.txt.
The following code snippet work for me, you can refer to it.
var filepath = Path.Combine(_hostingEnvironment.ContentRootPath, "templates", "file.txt");
var mes = "test message";
if (System.IO.File.Exists(filepath))
{
using (StreamReader file = new StreamReader(filepath))
{
mes = file.ReadLine();
}
}
ViewBag.fp = filepath;
ViewBag.mes = mes;
return View();
And please make sure the file is really existing under that folder on your server.
Test Result

Windows 10 App - File downloading

I am working with Windows 10 universal app and i want to download a file in that. The file link to Sharepoint server. I have passed token in headr to a web service and then service returned byte array to my WinJS.
Now i want to save the file, how can i do this? I tried several code samples but not working.
var folder = Windows.Storage.ApplicationData.current.localFolder;
folder.createFileAsync("document.docx", Windows.Storage.CreationCollisionOption.replaceExisting).then(function (file) {
return Windows.Storage.FileIO.writeTextAsync(file, result.response);
}).then(function () {
//saved
});
I am using above code and it is creating new file but no content is placed there. Please suggest what to do.
You never open the file for WriteAccess. I have included code from my working app. First do this command
StorageFile ageFile = await local.CreateFileAsync("Age.txt", CreationCollisionOption.FailIfExists);
then do this:
// Get the file.
var ageFile = await local.OpenStreamForWriteAsync("Age.txt",CreationCollisionOption.OpenIfExists);
// Read the data.
using (StreamWriter streamWriter = new StreamWriter(ageFile))
{
streamWriter.WriteLine(cmbAgeGroup.SelectedIndex + ";" + DateTime.Now);
streamWriter.Flush();
}
ageFile.Dispose();

Access denied using mvxfilestore, mvvmcross annd xamarin touch ios 8.1

My app just got reject from apple and i believe it might be caused by them changing to test with ios 8.1. However I cannot reproduce the error in any way. Their chrash report states the app chrashes on startup.
It seems that the exception(have the crash log) comes from
<Warning> Unhandled managed exception: Access to the path "/var/mobile/Documents/settings" is denied. (System.UnauthorizedAccessException)
which originates from
Cirrious.MvvmCross.Plugins.File.MvxFileStore.WriteFileCommon
I am using the mvvmcross 3.11 MvxFileStore plugin. Deployment target ios7, 8.1 ios sdk.
I have been surfing the web and some states Documents directory has moved in iOS 8 and this might cause the exception.
But I cant wrap my head around the fact that I cant reproduce this error.
Do anyone have a similar issue, a suggestion how to fix or an idea how to reproduce their crash.
Anything is appreciated.
Update:
From the post it is suggested to do the following fix
int SystemVersion = Convert.ToInt16(UIDevice.CurrentDevice.SystemVersion.Split('.')[0]);
if (SystemVersion >= 8)
{
var documents = NSFileManager.DefaultManager.GetUrls(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomain.User)[0].Path;
filename = Path.Combine(documents, sFile);
}
else
{
var documents = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); // iOS 7 and earlier
filename = Path.Combine(documents, sFile);
}
I have tried adding it to our project. We used the MvxFileStore to create the path to the settings file
var filestore = Mvx.Resolve<IMvxFileStore>();
string path = filestore.PathCombine(filestore.NativePath (string.Empty), FILENAME);
Now We de the following
var filestore = Mvx.Resolve<IMvxFileStore>();
string path = this.DocsDir() + "/" + FILENAME;
public string DocsDir ()
{
var version = int.Parse(UIDevice.CurrentDevice.SystemVersion.Split('.')[0]);
string docsDir = "";
if (version>=8) {
var docs = NSFileManager.DefaultManager.GetUrls (NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomain.User) [0];
docsDir = docs.Path;
Console.WriteLine("ios 8++ "+docsDir);
} else {
docsDir = Environment.GetFolderPath (Environment.SpecialFolder.MyDocuments);
Console.WriteLine("ios 7.1-- " + docsDir);
}
return docsDir;
}
I will resubmit our app and post the result.
Okay,
The fix we did by seperating ios 8 and the rest of ios and do different implementations depending on the ios worked.
Apple has approved our apps and all is love (y)

Upload a file to a document library in SharePoint 2010 programmatically in client-server application

I am using below code to upload the file in SharePoint 2010 Library
String fileToUpload = #"C:\YourFile.txt";
String sharePointSite = "http://yoursite.com/sites/Research/";
String documentLibraryName = "Shared Documents";
using (SPSite oSite = new SPSite(sharePointSite))
{
using (SPWeb oWeb = oSite.OpenWeb())
{
if (!System.IO.File.Exists(fileToUpload))
throw new FileNotFoundException("File not found.", fileToUpload);
SPFolder myLibrary = oWeb.Folders[documentLibraryName];
// Prepare to upload
Boolean replaceExistingFiles = true;
String fileName = System.IO.Path.GetFileName(fileToUpload);
FileStream fileStream = File.OpenRead(fileToUpload);
// Upload document
SPFile spfile = myLibrary.Files.Add(fileName, fileStream, replaceExistingFiles);
// Commit
myLibrary.Update();
}
}
This worked well through my machine. But when I deploy it on server and used the below snippet to upload file in library from my machine, it gives error. It is not getting the file location (C:\YourFile.txt) from local(client) machine.
When you run on the server your code runs under a different account (apppool identity) which does not have the permission to read C drive.
I dont know why would you want to read and upload a file from the same server, looks like you are simply testing Sharepoint Object Model then it is ok
If you are expecting some other app or service to keep an updated file for Sharepoint , it should be moved to the web directory i.e \wwwroot\wss\VirtualDirectories\80 and then use your code to read and update your doc lib (myLibrary) as you are doing.
Are you running this in a console app or "in SharePoint"?
Could it be that the account running the code doesnt have read permissions in C:\?

How can I get the WebRole site root path from RoleEntryPoint.OnStart()?

As part of starting up a WebRole on Windows Azure I would like to access files on the website being started and I would like to do this in RoleEntryPoint.OnStart(). This will for instance enable me to influence ASP.NET config before the ASP.NET AppDomain is loaded.
When running locally with Azure SDK 1.3 and VS2010 the sample code below do the trick, but the code has the stench of hack around it and it does not do the trick when deploying to Azure.
XNamespace srvDefNs = "http://schemas.microsoft.com/ServiceHosting/2008/10/ServiceDefinition";
DirectoryInfo di = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory);
string roleRoot = di.Parent.Parent.FullName;
XDocument roleModel = XDocument.Load(Path.Combine(roleRoot, "RoleModel.xml"));
var propertyElements = roleModel.Descendants(srvDefNs + "Property");
XElement sitePhysicalPathPropertyElement = propertyElements.Attributes("name").Where(nameAttr => nameAttr.Value == "SitePhysicalPath").Single().Parent;
string pathToWebsite = sitePhysicalPathPropertyElement.Attribute("value").Value;
How can I get the WebRole site root path from RoleEntryPoint.OnStart() in a way that work in both dev and on Azure?
This seem to work in both dev and on Windows Azure:
private IEnumerable<string> WebSiteDirectories
{
get
{
string roleRootDir = Environment.GetEnvironmentVariable("RdRoleRoot");
string appRootDir = Path.GetDirectoryName(AppDomain.CurrentDomain.BaseDirectory);
XDocument roleModelDoc = XDocument.Load(Path.Combine(roleRootDir, "RoleModel.xml"));
var siteElements = roleModelDoc.Root.Element(_roleModelNs + "Sites").Elements(_roleModelNs + "Site");
return
from siteElement in siteElements
where siteElement.Attribute("name") != null
&& siteElement.Attribute("name").Value == "Web"
&& siteElement.Attribute("physicalDirectory") != null
select Path.Combine(appRootDir, siteElement.Attribute("physicalDirectory").Value);
}
}
If anyone use this to manipulate files in the ASP.NET app, you should know that the files written by RoleEntryPoint.OnStart() will have ACL settings that prevent the ASP.NET application from updating them.
If you need to write to such files from ASP.NET this code show how you can change file permissions so this is possible:
SecurityIdentifier sid = new SecurityIdentifier(WellKnownSidType.WorldSid, null);
IdentityReference act = sid.Translate(typeof(NTAccount));
FileSecurity sec = File.GetAccessControl(testFilePath);
sec.AddAccessRule(new FileSystemAccessRule(act, FileSystemRights.FullControl, AccessControlType.Allow));
File.SetAccessControl(testFilePath, sec);
Take a look at:
Environment.GetEnvironmentVariable("RoleRoot")
Does that give you what you're looking for?

Resources