I wrote a foreground application in C# which collects images from different servers and stores them on SD card, USB stick, or disk.
In the application manifest, I set read/write filetypes and access to
removable drives.
The application is working if I use a USB Stick to store data, or
if I use the system SD card. But if I use an external HDD to store the data, the StorageFolder.GetFolderFromPathAsync(DirName) fails. Why?
The path is in both cases "E:\". In that Path I create sub directories,
where files should be created:
public async void GetWebImage(String urlStr, String filename)
{
try
{
try
{
String DirName = Path.GetDirectoryName(filename);
String FileName = Path.GetFileName(filename);
// Folder Struktur erzeugen
var rootFolder = await StorageFolder.GetFolderFromPathAsync(DirName);
var http_file = await rootFolder.CreateFileAsync(FileName, CreationCollisionOption.ReplaceExisting);
HttpWebRequest httpWebRequest = HttpWebRequest.CreateHttp(urlStr);
HttpWebResponse response = (HttpWebResponse)await httpWebRequest.GetResponseAsync();
Stream resStream = response.GetResponseStream();
using (var stream = await http_file.OpenAsync(FileAccessMode.ReadWrite))
{
await resStream.CopyToAsync(stream.AsStreamForWrite());
}
response.Dispose();
}
catch (Exception ex)//any exceptions happend while saving the picture
{
String s = ex.ToString();
}
}
catch (Exception ex)
{
String s = ex.ToString();
}
}
The Path and storage to external drives I get this way :
// Get Path to first external Drive, otherwise "ExternalStorageFolder==null"
public StorageFolder ExternalStorageFolder;
private async void GetFirstExternalStoragePath()
{
try
{
StorageFolder externalDevices;
IReadOnlyList<StorageFolder> externalDrives;
externalDevices = Windows.Storage.KnownFolders.RemovableDevices;
externalDrives = await externalDevices.GetFoldersAsync();
ExternalStorageFolder = externalDrives[0];
TxtStatus.Text = "External Drive:"+ ExternalStorageFolder.Path + " found.";
}
catch (Exception ex)
{
String s = "No external Drive found\n" + ex.ToString();
TxtStatus.Text = s;
ExternalStorageFolder = null;
}
}
If I access directly via "ExternalStorageFolder" I get no "access denied"
But if I use the "GetFolderFromPathAsync(DirName) this fails... Why?
Related
I'm trying to Save and Load Vector3 Coordinates in HoloLens App the program works on my laptop using unity but it will not save or load a file in the HoloLens.
Here is the program I am using to create the path for saving and loading. Any help would be appreciated.
public GameData Load()
{
string fullPath = Path.Combine(dataDirPath, dataFileName);
GameData loadedData = null;
if (File.Exists(fullPath))
{
try
{
string dataToLoad = "";
using (FileStream stream = new FileStream(fullPath, FileMode.Open))
{
using (StreamReader reader = new StreamReader(stream))
{
dataToLoad = reader.ReadToEnd();
}
}
loadedData = JsonUtility.FromJson<GameData>(dataToLoad);
}
catch (Exception e)
{
UnityEngine.Debug.LogError("Error occured when trying to load data from filr: " + fullPath + "\n" + e);
}
}
return loadedData;
}
public void Save (GameData data)
{
string fullPath = Path.Combine(dataDirPath, dataFileName);
try
{
Directory.CreateDirectory(Path.GetDirectoryName(fullPath));
string dataToStore = JsonUtility.ToJson(data, true);
using (FileStream stream = new FileStream(fullPath, FileMode.Create))
{
using (StreamWriter writer = new StreamWriter(stream))
{
writer.Write(dataToStore);
}
}
}
catch (Exception e)
{
UnityEngine.Debug.LogError("Error occured when trying to save data to file: " + fullPath + "\n" + e);
}
}
}
If I understand this correctly, you're debugging remotely. To clarify, your application cannot access files on HoloLens until you deploy it to HoloLens. And for how to access files on HoloLens, you can refer Create, write, and read a file - UWP applications | Microsoft Learn and Working with File on Hololens 2 (UWP to .NET).
Recently we had a production deployment of normal windows store app. It was working fine for few days and after some days performance is very very slow. Our application follows Gate keeper pattern where store app hits gate keeper and gate keeper to rest service and rest service to database (everything is hosted in cloud).
After analyzing we found that Gatekeeper web app is taking more time to respond. We have taken memory dump for the web app and analyzed using WinDbg and found an issue with AAD access token where lock count is measured as 2. And attached is the result taken from memory dump.
Here is the actual code to get access token (we are using cert based authentication)
public static void GetCert()
{
try
{
var clientAssertionCertPfx = Helper.FindCertificateByThumbprint(WebConfigurationManager.AppSettings["CertificateThumbPrint"]);
AssertionCert = new ClientAssertionCertificate(WebConfigurationManager.AppSettings["ida:ClientID"], clientAssertionCertPfx);
}
catch (Exception ex)
{
throw ex;
}
}
public static async Task<string> GetAccessToken(string authority, string resource, string scope)
{
try
{
string userName = "";
GetCert();
var context = new AuthenticationContext(authority, TokenCache.DefaultShared);
AuthenticationResult result = null;
var bootstrapContext = ClaimsPrincipal.Current.Identities.First().BootstrapContext as System.IdentityModel.Tokens.BootstrapContext;
if (bootstrapContext != null)
{
userName = ClaimsPrincipal.Current.FindFirst(ClaimTypes.Upn) != null ? ClaimsPrincipal.Current.FindFirst(ClaimTypes.Upn).Value : ClaimsPrincipal.Current.FindFirst(ClaimTypes.Email).Value;
if (!string.IsNullOrEmpty(bootstrapContext.Token))
{
UserAssertion userAssertion = new UserAssertion(bootstrapContext.Token, "urn:ietf:params:oauth:grant-type:jwt-bearer", userName);
AuthenticationContext authContext = new AuthenticationContext(authority);
result = await authContext.AcquireTokenAsync(resource, AssertionCert, userAssertion);
return result != null ? result.AccessToken : null;
}
return null;
}
else
{
return null;
}
}
catch (Exception ex)
{
LogErrorDetails objLogDetails = new LogErrorDetails();
ErrorLog objErrorLog = new ErrorLog();
objLogDetails.ErrorDescription = ex.Message;
objLogDetails.ErrorNumber = ex.HResult;
objLogDetails.strErrorContext = "Helper";
objLogDetails.strErrorContextArea = "GetAccessToken";
objLogDetails.strTrace = ex.StackTrace;
await objErrorLog.InsertErrorLog(objLogDetails);
return null;
}
}
While running this code locally we are not getting any issue with the access token and it is fast. Only in production environment performance is very slow and not sure it is with the access token or any other parameter.
Could you please help us in analyzing what went wrong with our code.
I'm using gwtupload.client.MultiUploader to upload zip files on the server in GWT. Then on the server I transform zip file to array of bytes to insert into database. As the result 50% of files in database are corrupted. Here a little bit of my code.
#UiField(provided = true)
MultiUploader muplDef;
public MyClass(){
muplDef = new MultiUploader();
muplDef.setValidExtensions("zip");
muplDef.addOnFinishUploadHandler(onFinishUploaderHandler);
muplDef.addOnCancelUploadHandler(onCancelUploaderHander);
}
private final IUploader.OnFinishUploaderHandler onFinishUploaderHandler = new IUploader.OnFinishUploaderHandler() {
#SuppressWarnings("incomplete-switch")
#Override
public void onFinish(IUploader uploader) {
switch (uploader.getStatus()) {
case SUCCESS:
attachZip = true;
}
}
};
private final IUploader.OnCancelUploaderHandler onCancelUploaderHander = new IUploader.OnCancelUploaderHandler() {
#Override
public void onCancel(IUploader uploader) {
attachZip = false;
}
};
Byte Array
String fileName = "D:\1.zip";
File f = new File(fileName);
byte[] edocBinary = new byte[(int) f.length()];
RandomAccessFile ff;
try {
ff = new RandomAccessFile(f, "r");
ff.readFully(edocBinary);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
My questions are: Files can be correpted even if I have OnFinishUploaderHandler and case:SUCCESS? There are other cases like ERROR, maybe this case will check the file? Or the problem is with the transformation to byte array? Can you provide me some advices, thanks.
As you said, you had two steps :
1- Uploading the zip file
2- Inserting the zip file in the database
If the step 1 is done correctly, you're gonna get a success showing that the file is transfered correcly from client to the server, what you do after that is not managed by GwtUpload.
So I guess the corruption happened when you try to insert the file in the database. If you are using MySQL Try this http://www.codejava.net/java-se/jdbc/insert-file-data-into-mysql-database-using-jdbc
I have some JavaScript code that upload file to server using ajax and form data and server side java code that accept it. I can upload English file name. But when I uploaded other Unicode file name, the file name I got in server side is unreadable. The following is code snippet.
JavaScript
var f = new FormData();
f.append("file", file);
xhr.send(f);
Java
public void upload(MultipartFormDataInput input) {
Map<String, List<InputPart>> uploadForm = input.getFormDataMap();
List<InputPart> inputParts = uploadForm.get("user_file[]");
IFileInfo file = null;
for (InputPart inputPart : inputParts) {
try {
MultivaluedMap<String, String> header = inputPart.getHeaders();
fileName = getFileName(header);
System.out.println("File name is " + fileName);
} catch (IOException e) {
e.printStackTrace();
}
}
}
private String getFileName(MultivaluedMap<String, String> header) {
System.out.println("Headers is " + header.getFirst("Content-Disposition"));
String[] contentDisposition = header.getFirst("Content-Disposition")
.split(";");
for (String filename : contentDisposition) {
if ((filename.trim().startsWith("filename"))) {
String[] name = filename.split("=");
String finalFileName = name[1].trim().replaceAll("\"", "");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return finalFileName;
}
}
return "unknown";
}
When I upload "大家好.jpg" , I got server side log showing the following.
Headers is form-data; name="user_file[]"; filename="���������.jpg"
File name is ���������.jpg
I think browser encode file name before uploading it.But I don't know which encoding did it used or how to decode it back. Any help is much appreciated.
I have a rest service written to receive a file and save it.
The problem is that when I receive more than 2 requests, the files are not written only the last request is taken into consideration and written.
Here is my code:
#POST
#RequestMapping(value = "/media/{mediaName}/{mediaType}")
#Produces(MediaType.APPLICATION_OCTET_STREAM)
#ResponseBody
public String updateResourceLocally(#FormDataParam("rawData") InputStream rawData, #PathVariable("mediaName") String mediaName, #PathVariable("mediaType") String mediaType) {
logger.info("Entering updateResourceLocally for " + jobId + "; for media type: " + mediaType);
final String storeDir = "/tmp/test/" + mediaName + ("/");
final String finalExtension = mediaType;
final InputStream finalRawData = rawData;
// new Thread(new Runnable() {
// public void run() {
// writeToFile(finalRawData, storeDir, finalExtension);
// }
// }).start();
writeToFile(finalRawData, storeDir, finalExtension);
// int poolSize = 100;
// ExecutorService executor = Executors.newFixedThreadPool(poolSize);
// executor.execute(new Runnable() {
// #Override
// public void run() {
// writeToFile(rawData, storeDir, finalExtension);
// }
// });
logger.info("File uploaded to : " + storeDir);
return "Success 200";
}
I tried to put the writeToFile into threads, but still no success. Here is what writeToFile does
public synchronized void writeToFile(InputStream rawData,
String uploadedFileLocation, String extension) {
StringBuilder finalFileName = null;
String currentIncrement = "";
String fileName = "raw";
try {
File file = new File(uploadedFileLocation);
if (!file.exists()) {
file.mkdirs();
}
while (true) {
finalFileName = new StringBuilder(fileName);
if (!currentIncrement.equals("")) {
finalFileName.append("_").append(currentIncrement).append(extension);
}
File f = new File(uploadedFileLocation + finalFileName);
if (f.exists()) {
if (currentIncrement.equals("")) {
currentIncrement = "1";
} else {
currentIncrement = (Integer.parseInt(currentIncrement) + 1) + "";
}
} else {
break;
}
}
int read = 0;
byte[] bytes = new byte[1024];
OutputStream out = new FileOutputStream(new File(uploadedFileLocation + finalFileName));
while ((read = rawData.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
out.flush();
out.close();
} catch (IOException e) {
throw new RuntimeException(e.getMessage());
}
}
The writeToFile creates a folder and writes a file, if the file already exists, it appends 1 and then increments the 1 accordingly and writes the file, so I would get raw.zip, raw-1.zip, etc.
I think the inputstream bytes are being lost, am I correct in my assumption?
NOTE: I do not have a UI client, I am using Poster a Firefox extension.
Update: What I am trying to achieve here is very simple
I receive number of requests with files attached
I need to save them. If the mediaName and mediaType are the same, then I need to append something to the filename and save it in the same location
If they are different I do not have a problem
The problem I am facing with the current code is that, when I post multiple time to the same URL, I have file-names created according to what I want, but the file content is not right, they vary depending on when the request came in and only the last POST's request is written properly.
Eg. I have a zip file of size 250MB, when I post 5 time, the 1st four will have random sizes and the 5th will have the complete 250MB, but the previous four should also have the same content.
You must separate the stream copy from the free filename assignation. The stream copy must be done within the calling thread (jersey service). Only the file naming operation must be common to all threads/requests.
Here is your code with a little refactoring :
getNextFilename
This file naming operation must be synchronized to guarantee each call gives a free name. This functions creates an empty file to guarantee the next call to work, because the function relies on file.exists().
public synchronized File getNextFilename(String uploadedFileLocation, String extension)
throws IOException
{
// This function MUST be synchronized to guarantee unicity of files names
// Synchronized functions must be the shortest possible to avoid threads waiting each other.
// No long job such as copying streams here !
String fileName = "raw";
//Create directories (if not already existing)
File dir = new File(uploadedFileLocation);
if (!dir.exists())
dir.mkdirs();
//Search for next free filename (raw.<extension>, else raw_<increment>.<extension>)
int currentIncrement = 0;
String finalFileName = fileName + "." + extension;
File f = new File(uploadedFileLocation + finalFileName);
while (f.exists())
{
currentIncrement++;
finalFileName = fileName + "_" + currentIncrement + "." + extension;
f = new File(uploadedFileLocation + finalFileName);
}
//Creates the file with size 0 in order to physically reserve the file "raw_<n>.extension",
//so the next call to getNextFilename will find it (f.exists) and will return "raw_<n+1>.extension"
f.createNewFile();
//The file exists, let the caller fill it...
return f;
}
writeToFile
Must not be synchronized !
public void writeToFile(InputStream rawData, String uploadedFileLocation, String extension)
throws IOException
{
//(1) Gets next available filename (creates the file with 0 size)
File file = getNextFilename(uploadedFileLocation, extension);
//(2) Copies data from inputStream to file
int read = 0;
byte[] bytes = new byte[1024];
OutputStream out = new FileOutputStream(file);
while ((read = rawData.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
out.flush();
out.close();
}