C# file path mimic via database - c#

Here is a challenge for you - .NET C# 4.0 or below.
I have a basic C# application which has a single button on a form.
The button uses an API which takes a file path as a parameter for the location of an audio file.
The API then allows the calling of the file e.g. someoneElsesAPI.Play("C:\myfile.vox") to play the file.
I do not have control over the API. I have to use the API - no choice there.
The problem is, the audio file (.vox) is stored in a database (as a blob).
How do I supply a file name to the API yet provide something that is streamed from the database in order to play the file?
For example, in ASP.NET one can display an image dynamically by using a handler or aspx page and response outputting as an image. I want to do the same trick for an audio file in a C# desktop application.
The type of audio file is irrelevant - I need to know how to call a file via a file path which doesn't exist (but does exist as a blob in a database).
hehe I don't ask for much do I?
Mucho thanks.
Best of luck in this challenge!
Dan.

I don't think that it can be done in any reasonable way. Instead you could easily fetch the blob. Save it to a temporary file and give the path of the temporary file to the API. It will not provide any kind of streaming, but as you can probably imagine, overriding the way .net handles the file system is not something that can easily be done. And why would you? If this is a real problem for you, I would recommend changing the API you use to another one that supports what you are trying to achieve instead of looking for hacky solutions.

Read the blob from the database, store the file into a temporary file, then pass the temp file name into the api

Depending on how the API opens files, you might be able to use a NamedPipe as a "virtual file".
This command line example creates a named pipe called hello.txt, and writes some "data" to it.
using System;
using System.IO;
using System.IO.Pipes;
namespace TestNamedPipe
{
class Program
{
static void Main(string[] args)
{
using (var pipe = new NamedPipeServerStream("hello.txt"))
{
pipe.WaitForConnection();
using (var writer = new StreamWriter(pipe))
{
writer.WriteLine("Hello, World!");
}
}
}
}
}
Now you can run "type \\.\pipe\hello.txt" from a command prompt to see how the pipe can be read by some apps as though it were a file. The "file name" will always be "\\.\pipe\" followed by the pipe name.
This doesn't work for all apps or APIs, though. For example "sort.exe \\.\pipe\hello.txt" works, but "more.exe \\.\pipe\hello.txt" doesn't.

Related

Creating/Writing/Zip/Unzip a file in UWP

edit: About the path-problem. I will try to get there later. For now I just need help for zip a file. Could not find a way to do this yet.
Im currently going through a few basics and I don't know what I have to look for to get to where I want to be. So, what are my goals?:
I want to create a name.json file here C:\Users\Username\Desktop
Then I want to compress name.json to an zip file.
I also created another file Testfile.zip on my Desktop. I want to unzip that file.
So far I created a name.json file. But I cannot find a solution on how to create one on the desktop.
I could not find a solution on compressing name.json so far.
public MainPage()
{
this.InitializeComponent();
createJson();
UnzipFile();
}
public async void createJson()
{
string text = "This text";
string json = JsonConvert.SerializeObject(text);
var file = await ApplicationData.Current.LocalFolder.CreateFileAsync("name.json");
await FileIO.WriteTextAsync(file, json);
}
public async void UnzipFile()
{
var localFolder = ApplicationData.Current.LocalFolder;
var archive = await localFolder.GetFileAsync("Testfile.zip");
ZipFile.ExtractToDirectory(archive.Path, localFolder.Path);
}
Working with .zip files is possible using System.IO.Compression.ZipArchive and related classes. You are already using ZipFile.ExtractToDirectory which is the right approach here. However, the issue you are facing is rather related to permissions.
UWP apps are sandboxed which means they are not allowed to touch any filesystem location by default. This is to ensure better security and easier uninstallation of apps. This however means you cannot easily create a file on the user's desktop, as your app does not have access there. The only folders your app can freely access are those accessible by ApplicationData.Current and then those it declares access to in application manifest. You can also declare broad filesystem access here to get access to all locations on the PC.
To further complicate this, there are two types of I/O APIs in UWP. The modern StorageFile API which is async enabled, but tad slower, and the classic file I/O APIs in C# which includes ZipFile and ZipArchive. The main disadvantage of the classic APIs is that they always have access only to application folders and you can never access any other system paths, even if you declare broad filesystem access.
However, even without declaring broad filesystem access capability you can manually get access to the folder/file of user's choosing using FolderPicker, FileOpenPicker and FileSavePicker. Using these you can let the user choose the destination where you will save the file or open a file.
Finally - to circumvent the limitation of not being able to use the classic file I/O APIs, you can first unzip the .zip file in a temporary folder inside ApplicationData.Current.LocalFolder and then use the StorageFile.MoveAndReplaceAsync(IStorageFile) or StorageFile.MoveAsync(IStorageFolder) method to move the files to the location the user has chosen using FileSavePicker.
For further info you can check out this blog post with a tutorial on using .zip in UWP.

How to save and read a xml file from another website?

I have this link: http://www.bnro.ro/nbrfxrates.xml to an xml file with daily Currency.
I want to save this xml in folder of my website ex. (~/Content/CurrencyXml).
I want to save it every day, first time when a user is accessing my website (must replace the old file).
I want also to read it in a static method which return an object with each currency type like property, in order to access it something like this:
price=model.Eur * 100;
Can you help me with an example of how to save a copy of this xml and how to read it?
You can try something like this to read the file and save it
public void readFile()
{
XmlDocument document = new XmlDocument();
document.Load("http://www.bnro.ro/nbrfxrates.xml");
document.Save(Path.Combine(
Server.MapPath("~/Content/CurrencyXml"),"myFile.xml"));
}
and in here you can find very usefull information:
XmlDocument Microsoft
Here's an example for the windows service:
Walkthrough: Creating a Windows Service Application in the Component Designer
Here's an example on how to download xml using WebClient:
How can I download an XML file using C#?
Here's an example on how to save a file to your server:
C# save files to folder on server instead of local
Then use what #Augustin suggested.
If you do use the flag file scenario, I would advice to save the xml file to a temporary file and only when fully downloaded, overwrite your original one and make sure to handle locking, overwriting time, etc... One other solution would be to use a temp variable that holds the current filename and when you download a new file, just give it a new name and when downloaded, set that variable name to the new filename and make sure that your load function uses that variable and loads the data from the new filename. Don't forget to delete your old file(s), but at least it will avoid locking issues if any and you can always try to delete the file later again.
If will very much depend if your website if being access 24/7 or not. If it isn't it is less of an issue as you could use the windows service to download this file when you know it's not being used. If you use the windows service, while being used, same as above would apply. If you're using Azure, you could use a WebJob. I'm sure there are many different solutions to handle this and you just have to find the one that will meet your needs.

Visual Studio - Read specified file on launch

I'm working with a simple program that has to read data from a txt file and than display it. The thing is that i would like to read a specified extension files (for example .log) automatically.
So, i would like to do it as a simple Windows user - double click file and than the program opens. The problem is that this program is working but it's nor loading the file on start and tbh i have no idea if I should program it somehow? Any hints?
Thanks!
The easiest way to make it load the file automatically is to allow it accept the file path as a parameter and then do a load operation. As for having your program open automatically when a user double clicks on that file type I would recommend checking out this CodeProject
Sound like you want to associate file type with your application. This is done via windows registers. Try for example this article http://msdn.microsoft.com/en-us/library/windows/desktop/hh127451(v=vs.85).aspx

Web Api 2 RESTFUL Image Upload

I'm new in Web Api and I'm working on my first project. I'm working on mobile CRM system for our company.
I want to store companies logo, customers face foto etc.
I found some tutorials on this topic, but unfortunately some of them was old (doesn't use async) and the others doesn't work.
At the end I found this one:
http://www.intstrings.com/ramivemula/articles/file-upload-using-multipartformdatastreamprovider-in-asp-net-webapi/
It works correctly, but I don't understand a few things.
1) Should I use App_Data (or any other folder like /Uploads) for storing this images, or rather store images in database?
2) Can I set only supported images like .jpg, .png and reject any other files?
3) How can I processed image in upload method? Like resize, reduce size of the file, quality etc?
Thank you
1) We are storing files in a different location than app_data. We have a few customer groups and we gave them all a unique folder that we get from the database. Storing in database is also an option but if you go down this road, make sure that the files you are saving don't belong directly to a table that you need to retrieve often. There is no right or wrong, but have a read at this question and answer for some pros and cons.
2) If you foollowed that guide, you can put a check inside the loop to check the file ending
List<string> denyList = new List<string>();
denyList.Add(".jpg");
foreach (MultipartFileData file in provider.FileData)
{
string fileName = Path.GetFileName(file.LocalFileName);
if(denyList.Contains(Path.GetExtension(fileName))
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
files.Add(Path.GetFileName(file.LocalFileName));
}
3) Resizing images is something that I have never personally done my self, but I think you should have a look at the System.Drawing.Graphics namespace.
Found a link with an accepted answer for downresize of picture: ASP.Net MVC Image Upload Resizing by downscaling or padding
None of the questions are actually related to Web API or REST.
If you are using SQL Server 2008 or newer the answer is use FILESTREAM columns. This looks like a column in database with all its advantages (i.e. backup, replication, transactions) but the data is actually stored in file system. So you get the best of each world, i.e. it will not happen that someone deletes the file accidentally so database will reference an inexistent file, or vice versa, records from database are deleted but files not so you'll end up with a bunch of orphan files. Using a database has many advantages, i.e. metadata can be associated with files and permissions are easier to set up.
This depends on how files are uploaded. I.e. if using multipart forms then examine content type of each part before part is saved. You can even create your own MultipartStreamProvider class. Being an API maybe the upload method has a stream or byte array parameter and a content type parameter, in this case just test the value of content type parameter before content is saved. For other upload methods do something similar depending on what the input is.
You can use .Net's built in classes (i.e. Bitmap: SetResolution, RotateFlip, to resize use a constructor what accepts a size), or if you are not familiar with image processing rather choose an image processing library.
All of the above work in Asp.Net, MVC, Web API 1 and 2, custom HTTP handlers, basically in any .Net code.
#Binke
Never user string operations on paths. I.e. fileName.split('.')[1] will not return the extension if file name is like this: some.file.txt, and will fail with index out of range error if file has no extension.
Always use file API, i.e. Path.GetExtension.
Also using the extension to get content type is not safe especially when pictures and videos are involved, just think of avi extension what is used by many video formats.
files.Add(Path.GetFileName(file.LocalFileName)) should be files.Add(fileName).

Open file on start up

I don't know what it is called but I want to be able to double click on my saved file and then my program should open and load the file. What is this called and how do I do it?
I am using c# wpf and .net 4.0
BR
How about the last 2 fields, what am I supposed to write there?
That is a file association, if you want this to happen on a client machine you need to register your application as the default application for a given extension. This question might be handy.
To actually handle the opening you need to process the arguments that are handed to your application, they will contain the file path. You can get the arguments either in the override of Application.OnStartup (e.Args) or Environment.GetCommandLineArgs.
you need to register the file extension and associate it to your program, either during the setup using certain APIs or from code when program executes the first time.
check these ones:
How to associate a file extension to the current executable in C#
Associate File Extension with Application
personally I do not like the 100% registry approach, there should be some Windows APIs for that and we should let those APIs to work without worrying about the Registry from our side, in my opinion.

Categories

Resources