Database file cannot be found - c#

In my Windows Phone 8 C#/XAML .NET 4.5 project I'm using (with the help of LINQ-2-SQL) a local database (SQLite probably) created by another member of the team.
But when I run the application, it throws an exception:
The database file cannot be found. Check the path to the database. [ Data Source = C:\Data\Users\DefApps\AppData\{XXXXX-XXXXX-XXXXXX-XXXXX}\Local\database.sdf ]
The .sdf file with the database is in the project in /Database/database.sdf and the properties are set to Build action: Embedded resource & Copy to output directory: Copy always.
In the databaseContext.cs, which is a class used as context (not sure I'm naming it right, I'm new to linq-2-sql), the connection string is defined as:
Data Source=isostore:/database.sdf
Is this the right settings? What can I do to make it work?

You will have to move the database to isolated storage first. Heres how you could do it.
public static void MoveReferenceDatabase()
{
// Obtain the virtual store for the application.
IsolatedStorageFile iso = IsolatedStorageFile.GetUserStoreForApplication();
// Create a stream for the file in the installation folder.
using (Stream input = Application.GetResourceStream(new Uri("DutchMe.sdf", UriKind.Relative)).Stream)
{
// Create a stream for the new file in the local folder.
using (IsolatedStorageFileStream output = iso.CreateFile("DutchMe.sdf"))
{
// Initialize the buffer.
byte[] readBuffer = new byte[4096];
int bytesRead = -1;
// Copy the file from the installation folder to the local folder.
while ((bytesRead = input.Read(readBuffer, 0, readBuffer.Length)) > 0)
{
output.Write(readBuffer, 0, bytesRead);
}
}
}
}
Else
set the connection string to Data Source=appdata:/database.sdf . I am not very sure about the second solution.

Related

Download files from server asp.net core 404 response

I'm trying to download a set of files from the server as zip file. Locally I can do it with no problem, but now that I deployed the app in a windows server 2019 (IIS), when I try to download the files I get the 404 - File or directory not found.
To download the set of files as zip I'm using the SharpZipLib library. The file paths are all correct and I can access them thru the file system in the server.
First I'm uploading the files in a folder inside the wwwroot where I published the app. The structure of my folders inside wwwroot is:
wwwroot
docs
contracts
My method to download the files as zip:
public async Task<FileResult> DownloadZipAsync() {
List<string> filePaths = //linq query to get the file paths.
//Example of file path: C:\inetpub\wwwroot\SRO\wwwroot\docs\contracts\testing.pdf
var name = "contracts";
var webRoot = _hostingEnvironment.WebRootPath;
var fileName = name + ".zip";
var tempOutput = webRoot + "\\docs\\contracts\\" + fileName;
using (ZipOutputStream zipOutputStream = new ZipOutputStream(System.IO.File.Create(tempOutput))) {
zipOutputStream.SetLevel(9);
byte[] buffer = new byte[4096];
for (int index = 0; index < filePaths.Count; index++) {
ZipEntry entry = new ZipEntry(name + "\\" + Path.GetFileName(filePaths[index]));
entry.DateTime = DateTime.Now;
entry.IsUnicodeText = true;
zipOutputStream.PutNextEntry(entry);
using (FileStream fileStream = System.IO.File.OpenRead(filePaths[index])) {
int sourceBytes;
do {
sourceBytes = fileStream.Read(buffer, 0, buffer.Length);
zipOutputStream.Write(buffer, 0, sourceBytes);
} while (sourceBytes > 0);
}
}
zipOutputStream.Finish();
zipOutputStream.Flush();
zipOutputStream.Close();
}
byte[] finalReuslt = System.IO.File.ReadAllBytes(tempOutput);
if (System.IO.File.Exists(tempOutput)) {
System.IO.File.Delete(tempOutput);
}
if (finalReuslt == null && !finalReuslt.Any()) {
throw new Exception(String.Format("Nothing found"));
}
return File(finalReuslt, "application/zip", fileName);
}
Things I've tried to fix the issue:
In the server I gave my deployment folder permissions (full control) for IIS_IUSRS user
For my deployment folder I created the user DefaultAppPool and gave full permissions as well.
In IIS -> Application Pools -> myappPoolforNetCore -> Advanced Settings -> Identity - changed between ApplicationPoolIdentity and LocalSystem.
Maybe my download method is not working properly when deployed. I suspect the issue can be in the using statement, specifically in the System.IO.File.Create() method.
I 'deployed' the app on my local development machine thru Development-time IIS support in Visual Studio for ASP.NET Core. Link
I did the same three steps I mentioned above, and in this case it works, with one difference being that the paths of files are different (since my app is 'deployed' locally) and they point to my C:/.... directory.
Any help would be appreciated because I'm stuck in this problem for quite a while.
Thanks
Did you check the MIME Types ?
Try to add
.zip - application/zip
or
.zip - application/x-zip

Unzip .zip file from Assets folder to Internal Storage (Xamarin.Android)

So the question is pretty simple. I'm using Xamarin.Android and I have a zip file in the Assets folder named "MyZipFile.zip", which I want extracted to the following path: System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
It sounds simple enough, but I cannot figure out how to read the Asset into memory through the AssetManager and then unzip it at the targeted location.
Is there a simple way to do this?
The Android Java framework includes a Java.Util.Zip package, so without adding any additional app libraries, I directly use it instead of using C# framework code, thus no bloat that linking can not remove.
So basically you are creating an asset stream and feeding that to a ZipInputStream and iterating over each ZipEntry in that zip stream to either create directories or files to your destination path.
UnZipAssets
public void UnZipAssets(string assetName, string destPath)
{
byte[] buffer = new byte[1024];
int byteCount;
var destPathDir = new Java.IO.File(destPath);
destPathDir.Mkdirs();
using (var assetStream = Assets.Open(assetName, Android.Content.Res.Access.Streaming))
using (var zipStream = new ZipInputStream(assetStream))
{
ZipEntry zipEntry;
while ((zipEntry = zipStream.NextEntry) != null)
{
if (zipEntry.IsDirectory)
{
var zipDir = new Java.IO.File(Path.Combine(destPath, zipEntry.Name));
zipDir.Mkdirs();
continue;
}
// Note: This is deleting existing entries(!!!) for debug purposes only...
#if DEBUG
if (File.Exists(Path.Combine(destPath, zipEntry.Name)))
File.Delete(Path.Combine(destPath, zipEntry.Name));
#endif
using (var fileStream = new FileStream(Path.Combine(destPath, zipEntry.Name), FileMode.CreateNew))
{
while ((byteCount = zipStream.Read(buffer)) != -1)
{
fileStream.Write(buffer, 0, byteCount);
}
}
Log.Debug("UnZipAssets", zipEntry.Name);
zipEntry.Dispose();
}
}
}
Usage:
UnZipAssets("gameModLevels.zip", Path.Combine(Application.Context.CacheDir.AbsolutePath, "assets"));
Note: Even through the asset/zip steam is fast, depending upon number/size of the zip entries and the speed of the flash the entry is being written to, this should be done on a background thread as not to block UI thread and cause an ANR

Windows Phone 8 IsolatedStorageFileStream

I'm making a WP8.1 Silverlight app, it's basically done, but I have one big problem.
public void CheckAndCopyDBToIsoStore(params bool[] list)
{
// Obtain a reference to the application's isolated storage
IsolatedStorageFile iso = IsolatedStorageFile.GetUserStoreForApplication();
//Only copy db file over if it does not already exist
if (!iso.FileExists("TankolasKonyveloDB.sdf") || (list.Length == 1 && list[0] == true))
{
using (Stream input = Application.GetResourceStream(new Uri("TankolasKonyveloDB.sdf",
UriKind.Relative)).Stream)
{
using (IsolatedStorageFileStream output = iso.CreateFile("TankolasKonyveloDB.sdf"))
{
byte[] readBuffer = new byte[4096];
int bytesRead = -1;
// Copy the file from the install folder to isolated storage.
while ((bytesRead = input.Read(readBuffer, 0, readBuffer.Length)) > 0)
{
output.Write(readBuffer, 0, bytesRead);
}
output.Close();
output.Dispose();
iso.Dispose();
}
}
}
}
I have this method in App.xaml.cs, it is called once in the constructor on application start without parameters and it copies the empty database to the isostore if it's not already there. It's working well. The next thing I'd like to do is, that if I click a button I call this method again with a bool argument with a value of true. When I do this, I want to copy the empty database again over the existing in runtime.
At the line
IsolatedStorageFileStream output = iso.CreateFile("TankolasKonyveloDB.sdf")
I get an exception:
Operation not permitted on IsolatedStorageFileStream
I googled it and the answers were I must close and dispose the connection and everything, but the problem is still there. Instead of iso.CreateFile I tried OpenFile with FileMode.OpenOrCreate, Create and CreateNew... None of them worked.
So the thing is, I want to copy the .sdf file to the isostore if it doesn't already exist and I don't want to copy it again on every startup, unless I express that by clicking that button.
If somebody has a solution to this or an idea, please help me!

WP8 - WebBrowser control to display images from resource folder

I am working on WP8application, I have few images in location Resources\Graphics\ i am trying to display images from these folder, but its not picking the path.
Here is my code :
<img src=\"/Resources;component/Graphics/"+ImageName).Append("\" ") this is in my string which i am using in my WebBrowserControl.
WebBrowserControl.NavigateToString(html); // here html is a string which has all the html code in it.
But its not display the images. What is the issue here how to fix this ?
I faced a similar issue when I tried to open images that have been saved to local storage. I could solve this by putting an HTML file at the same location so that I could access the files with "./filename.ext".
It did not work with any of the resource path constructions that I used to access the local file within the webview.
The only way to achieve this is by storing in the images and the dynamically generated Html content file in the Isolated storage of the application.
Go through this link for how to store the content in Isolated storage and display it using Web browser control: http://msdn.microsoft.com/en-us/library/windowsphone/develop/ff431811(v=vs.105).aspx
Here you go,
First of all store the images,which you want to show on the Html files into the Isolated storage of the application using the following method.
public static void CopyContentToIsolatedStorage(string file)
{
// Obtain the virtual store for the application.
IsolatedStorageFile iso = IsolatedStorageFile.GetUserStoreForApplication();
if (iso.FileExists(file))
return;
var fullDirectory = System.IO.Path.GetDirectoryName(file);
if (!iso.DirectoryExists(fullDirectory))
iso.CreateDirectory(fullDirectory);
// Create a stream for the file in the installation folder.
using (Stream input = Application.GetResourceStream(new Uri(file, UriKind.Relative)).Stream)
{
// Create a stream for the new file in isolated storage.
using (IsolatedStorageFileStream output = iso.CreateFile(file))
{
// Initialize the buffer.
byte[] readBuffer = new byte[4096];
int bytesRead = -1;
// Copy the file from the installation folder to isolated storage.
while ((bytesRead = input.Read(readBuffer, 0, readBuffer.Length)) > 0)
{
output.Write(readBuffer, 0, bytesRead);
}
}
}
By calling the method as,
CopyContentToIsolatedStorage("Graphics/ImageName.png");//Pass the image folder path here
And then,form the Html dynamically like shown the below
StringBuilder HtmlString = new StringBuilder(#"<html><head><title>Test html File</title></head>");
HtmlString.Append(#"<body>");
HtmlString.Append(#"<img src=""Graphics/""#"+ ImageName + "/>");
HtmlString.Append(#"</body></html>");
And then save the Html file into Isolated Storage using the following code
var bytes = Encoding.UTF8.GetBytes(html.ToString());
using (IsolatedStorageFile iso = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream output = iso.CreateFile("Testfile.html"))
{
output.Write(bytes, 0, bytes.Length);
}
}
Now call that html file using your browser control like below,
WebBrowserControl.Navigate(new Uri("Testfile.html", UriKind.Relative));

How to retrieve .dotx and .csv files from Resources Folder in C#?

I have an application that uses a template file and a CSV file. It works perfectly fine since I do have the said files on my computer and I am referencing their paths. The only thing I want to do is that when the software is published and installed (and the said files are in the Resources folder so it would make them an embedded resource), the csv and template files would be copied to a directory folder that my program would use. Preferably the paths it would be copied to would be something like this : "C:\FILES" + template.dotx .
Now how do I get/retrieve the said files from the Resources Folder in my software into a new folder?
You could call
System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceNames();
And inspect which embedded resources are accessible. Then you can compare that against what you are passing in to see if you are indeed accomplishing what you expected to.
string FileExtractTo = "C:\FILES";
DirectoryInfo dirInfo = new DirectoryInfo(FileExtractTo);
if (!dirInfo.Exists())
dirInfo.Create();
using (Stream input = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName))
using (Stream output = File.Create(FileExtractTo + "\template.dotx"))
{
CopyStream(input, output);
}
CopyStream Method:
public static void CopyStream(Stream input, Stream output)
{
// Insert null checking here for production
byte[] buffer = new byte[8192];
int bytesRead;
while ((bytesRead = input.Read(buffer, 0, buffer.Length)) > 0)
{
output.Write(buffer, 0, bytesRead);
}
}

Categories