How to include resources to application for windows phone? - visual-studio

I have a problem: I created new c# project for windows phone (in VS 2013) and set test file property as "Copy if newer", but I cannot see file in emulator's Local folder. What do I do wrong?
More detailed:
Create app:
File->New->Project->Templates->Visual C#->Store Apps->Windows Phone Apps->Blank App (Windows Phone)
set test file property
run on emulator (there is a button for this) and list files with code:
async void listFolder()
{
StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;
Stack<StorageFolder> stack = new Stack<StorageFolder>();
stack.Push(local);
StorageFolder current;
string path;
byte[] bytes;
StorageFile logFile = await local.CreateFileAsync("log.txt", CreationCollisionOption.ReplaceExisting);
using (var s = await logFile.OpenStreamForWriteAsync())
{
while (stack.Count > 0)
{
current = stack.Pop();
foreach (StorageFolder f in await current.GetFoldersAsync())
{
stack.Push(f);
}
path = current.Path;
bytes = Encoding.UTF8.GetBytes(current.Path + "\n");
s.Write(bytes, 0, bytes.Length);
foreach (StorageFile f in await current.GetFilesAsync())
{
bytes = Encoding.UTF8.GetBytes(f.Path + "\n");
s.Write(bytes, 0, bytes.Length);
}
s.Flush();
}
}
}
Check file with Windows Phone Power Tools. Local folder contains log.txt only. Log contains Local directory and log file. No TestText.txt
How do I include file to application and access it on emulator?
Limitations:
I do need to held data on local storage (no web links, no cloud)

If you want to access files that come with your package, then you need to use Package.InstalledLocation, you won't find those files in ApplicationData.LocalFolder.
Note that files included in Package are read-only and you won't be able to write them.
Some more information you will also find at this answer.

Related

UWP open pdf fails when publish

i have this methods working fine when i'm on debug and on my pc:
public void ShowPdf(byte[] pdfInfo)
{
...
Device.BeginInvokeOnMainThread(async () =>
{
var intentHelper = DependencyService.Get<IIntentHelper>();
intentHelper.File(pdfInfo);
});
}
And the dependency service like that:
[assembly: Xamarin.Forms.Dependency(typeof(IntentHelperUWP))]
namespace myApp.UWP
{
class IntentHelperUWP : IIntentHelper
{
public async Task FileAsync2(byte[] array)
{
var baseUrl = DependencyService.Get<IBaseUrl>().Get();
StorageFolder storageFolder = ApplicationData.Current.LocalFolder;
StorageFile pdfFile = await storageFolder.CreateFileAsync("test.pdf", CreationCollisionOption.ReplaceExisting);
//write data to created file
await FileIO.WriteBytesAsync(pdfFile, array);
//get asets folder
StorageFolder appInstalledFolder = Windows.ApplicationModel.Package.Current.InstalledLocation;
StorageFolder assetsFolder = await appInstalledFolder.GetFolderAsync("Assets");
//move file from local folder to assets
await pdfFile.MoveAsync(assetsFolder, "test.pdf", NameCollisionOption.ReplaceExisting);
Device.BeginInvokeOnMainThread(async () =>
{
Windows.System.LauncherOptions options = new Windows.System.LauncherOptions();
options.DisplayApplicationPicker = true;
options.ContentType = "application/pdf";
Windows.System.Launcher.LaunchFileAsync(pdfFile);
});
}
Why it's working fine in debug with visual studio but not when i publish? i tried to publish release and debug, look if the pdf is set to content and copy all in properties, but every time i publish and test, the button to download pdf does nothing, but in my debug open the Adode reader with the PDF. Some hints of what i can do or test?
Once packaged the install folder is read only. You cannot copy the file into the assets folder. This is the same in UWP, iOS, and Android.
You’ll need to launch it from the app data location you create it in rather than trying to move it into the installed package.
It works when debugging without publishing because the unpackaged app has full access to its working directory.

How to list all children in Google Drive's appfolder and read file contents with Xamarin / c#?

I'm trying to work with text files in the apps folder.
Here's my GoogleApiClient constructor:
googleApiClient = new GoogleApiClient.Builder(this)
.AddApi(DriveClass.API)
.AddScope(DriveClass.ScopeFile)
.AddScope(DriveClass.ScopeAppfolder)
.UseDefaultAccount()
.AddConnectionCallbacks(this)
.EnableAutoManage(this, this)
.Build();
I'm connecting with:
googleApiClient.Connect()
And after:
OnConnected()
I need to list all files inside the app folder. Here's what I got so far:
IDriveFolder appFolder = DriveClass.DriveApi.GetAppFolder(googleApiClient);
IDriveApiMetadataBufferResult result = await appFolder.ListChildrenAsync(googleApiClient);
Which is giving me the files metadata.
But after that, I don't know how to read them, edit them or save new files. They are text files created with my app's previous version (native).
I'm following the google docs for drive but the Xamarin API is a lot different and has no docs or examples. Here's the API I'm using: https://components.xamarin.com/view/googleplayservices-drive
Edit:
Here is an example to read file contents from the guide:
DriveFile file = ...
file.open(mGoogleApiClient, DriveFile.MODE_READ_ONLY, null)
.setResultCallback(contentsOpenedCallback);
First I can't find anywhere in the guide what "DriveFile file = ..." means. How do I get this instance? DriveFile seems to be a static class in this API.
I tried:
IDriveFile file = DriveClass.DriveApi.GetFile(googleApiClient, metadata.DriveId);
This has two problems, first it complains that GetFile is deprecated but doesn't say how to do it properly. Second, the file doesn't have an "open" method.
Any help is appreciated.
The Xamarin binding library wraps the Java Drive library (https://developers.google.com/drive/), so all the guides/examples for the Android-based Drive API work if you keep in mind the Binding's Java to C# transformations:
get/set methods -> properties
fields -> properties
listeners -> events
static nested class -> nested class
inner class -> nested class with an instance constructor
So you can list the AppFolder's directory and files by recursively using the Metadata when the drive item is a folder.
Get Directory/File Tree Example:
await Task.Run(() =>
{
async void GetFolderMetaData(IDriveFolder folder, int depth)
{
var folderMetaData = await folder.ListChildrenAsync(_googleApiClient);
foreach (var driveItem in folderMetaData.MetadataBuffer)
{
Log.Debug(TAG, $"{(driveItem.IsFolder ? "(D)" : "(F)")}:{"".PadLeft(depth, '.')}{driveItem.Title}");
if (driveItem.IsFolder)
GetFolderMetaData(driveItem.DriveId.AsDriveFolder(), depth + 1);
}
}
GetFolderMetaData(DriveClass.DriveApi.GetAppFolder(_googleApiClient), 0);
});
Output:
[SushiHangover.FlightAvionics] (D):AppDataFolder
[SushiHangover.FlightAvionics] (F):.FlightInstrumentationData1.json
[SushiHangover.FlightAvionics] (F):.FlightInstrumentationData2.json
[SushiHangover.FlightAvionics] (F):.FlightInstrumentationData3.json
[SushiHangover.FlightAvionics] (F):AppConfiguration.json
Write a (Text) File Example:
using (var contentResults = await DriveClass.DriveApi.NewDriveContentsAsync(_googleApiClient))
using (var writer = new OutputStreamWriter(contentResults.DriveContents.OutputStream))
using (var changeSet = new MetadataChangeSet.Builder()
.SetTitle("AppConfiguration.txt")
.SetMimeType("text/plain")
.Build())
{
writer.Write("StackOverflow Rocks\n");
writer.Write("StackOverflow Rocks\n");
writer.Close();
await DriveClass.DriveApi.GetAppFolder(_googleApiClient).CreateFileAsync(_googleApiClient, changeSet, contentResults.DriveContents);
}
Note: Substitute a IDriveFolder for DriveClass.DriveApi.GetAppFolder to save a file in a subfolder of the AppFolder.
Read a (text) File Example:
Note: driveItem in the following example is an existing text/plain-based MetaData object that is found by recursing through the Drive contents (see Get Directory/File list above) or via creating a query (Query.Builder) and executing it via DriveClass.DriveApi.QueryAsync.
var fileContexts = new StringBuilder();
using (var results = await driveItem.DriveId.AsDriveFile().OpenAsync(_googleApiClient, DriveFile.ModeReadOnly, null))
using (var inputStream = results.DriveContents.InputStream)
using (var streamReader = new StreamReader(inputStream))
{
while (streamReader.Peek() >= 0)
fileContexts.Append(await streamReader.ReadLineAsync());
}
Log.Debug(TAG, fileContexts.ToString());

sub folder in not creating on azure in asp.net mvc5 application

I am ruing my website on azure, every folder is present on site directory in azure but uploadimages is my sub folder of content is absent from wwwroot, and images is not uploading also
I am using
var path =Path.Combine(Server.MapPath("~/Content/UploadImages/")+filename);
same with document upload
According to your description, I have tested on my side, please follow below to find out whether it could help you.
As you said, you got the target file path by this code:
var path = Path.Combine(Server.MapPath("~/Content/UploadImages/") + filename);
Before uploading files, please make sure that the directory in your web server “~/Content/UploadImages/” is existed.
Here is my test code:
MVC controller method
[HttpPost]
public JsonResult UploadFiles()
{
try
{
foreach (string file in Request.Files)
{
var fileContent = Request.Files[file];
if (fileContent != null && fileContent.ContentLength > 0)
{
var stream = fileContent.InputStream;
var fileName = Path.GetFileName(fileContent.FileName);
string baseDir = Server.MapPath("~/Content/UploadImages/");
if (!Directory.Exists(baseDir))
Directory.CreateDirectory(baseDir);
var path = Path.Combine(baseDir, fileName);
using (var fileStream = System.IO.File.Create(path))
{
stream.CopyTo(fileStream);
}
}
}
}
catch (Exception e)
{
return Json(new
{
Flag = false,
Message = string.Format("File Uploaded failed with exception:{0}", e.Message)
});
}
return Json(new
{
Flag = true,
Message = "File uploaded successfully!"
});
}
Additionally, for long-term consideration, you could store your files on Azure Blob Storage which could bring you some benefits, such as:
1.Serving images or documents directly to a browser
2.Storing files for distributed access
3.When you scale up your site, your site could run in multiple Web Server instances which could access the same files & docs simultaneously
For more details, please refer to this link: https://azure.microsoft.com/en-us/documentation/articles/storage-dotnet-how-to-use-blobs/

Where are files saved while debugging a Silverlight 5 Application in Internet Explorer 10?

I have some code that saves an xml file to the file system.
public static void Save(T obj, string FileName)
{
if (Application.Current.HasElevatedPermissions)
{
string myDocuments = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
string path = System.IO.Path.Combine(myDocuments, FileName);
using (var writer = new StreamWriter(path))
{
var serializer = new XmlSerializer(typeof(T));
serializer.Serialize(writer, obj);
writer.Flush();
}
}
else
{
throw new Exception("Cannot Save File. Application Requires Elevated permissions.");
}
}
While debugging using Internet Explorer 10 the file is not saved to the listed path in the path variable "C:\Users\Travis\Documents\Save.xml"
I call load with the exact same path "C:\Users\Travis\Documents\Save.xml" and the file loads correctly but the file still does not exist at the listed location.
I searched the file system with no results for Save.xml but it has to exist since it is able to load after application exit.
If I access the same page using Chrome the file is created successfully at the location.
I am wondering where Internet Explorer saves the file?
I found that if I uncheck "Enable Protected Mode" in IE's Security tab then the file is created in the location as expected.

How to read files from project folders?

When the first time my app starts on a windows phone, I want to get some files(xml/images) from project folders and write them to the isolated storage .
How do I detect that my app is running for the first time?
How do I access file in project folders?
Here is another way to read files from your visual studio project. The following shows how to read a txt file but can be used for other file as well. Here the file is in the same directory as the .xaml.cs file.
var res = App.GetResourceStream(new Uri("test.txt", UriKind.Relative));
var txt = new StreamReader(res.Stream).ReadToEnd();
make sure your file is marked as Content.
If you mean project folders as in the folders in your visual studio project, I usually right click on the files and set the build action to 'Embedded Resource'. At runtime, you can read the data from the embedded resource like so:
// The resource name will correspond to the namespace and path in the file system.
// Have a look at the resources collection in the debugger to figure out the name.
string resourcePath = "assembly namespace" + "path inside project";
Assembly assembly = Assembly.GetExecutingAssembly();
string[] resources = assembly .GetManifestResourceNames();
List<string> files = new List<string>();
if (resource.StartsWith(resourcePath))
{
StreamReader reader = new StreamReader(assembly.GetManifestResourceStream(resource), Encoding.Default);
files.Add(reader.ReadToEnd());
}
To read the images you would need something like this to read the stream:
public static byte[] ReadAllBytes(Stream input)
{
byte[] buffer = new byte[32 * 1024];
using (MemoryStream ms = new MemoryStream())
{
int read;
while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, read);
}
return ms.ToArray();
}
}

Resources