Save and Load file in HoloLens using Unity editer - unity3d

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).

Related

How do I upload files from a phone to my Amazon S3 server?

I'm developing a mobile app with Unity and using S3 to store and retrieve assets, I can download asset bundles just fine from the server to the phone, but how do I upload files from the phone to the server?
I used the PostObject function from the AWS Unity SDK, and it works fine if I upload from the computer as I know the directory, but I'm not sure how to get the phone's photo gallery to upload to the s3 server.
This is the PostObject function
public void PostObject(string fileName)
{
ResultText.text = "Retrieving the file";
var stream = new FileStream("file://" + Application.streamingAssetsPath + "/" + fileName,
FileMode.Open, FileAccess.Read, FileShare.Read);
Debug.Log("kek");
ResultText.text += "\nCreating request object";
var request = new PostObjectRequest()
{
Bucket = S3BucketName,
Key = fileName,
InputStream = stream,
CannedACL = S3CannedACL.Private,
Region = _S3Region
};
ResultText.text += "\nMaking HTTP post call";
Client.PostObjectAsync(request, (responseObj) =>
{
if (responseObj.Exception == null)
{
ResultText.text += string.Format("\nobject {0} posted to bucket {1}",
responseObj.Request.Key, responseObj.Request.Bucket);
}
else
{
ResultText.text += "\nException while posting the result object";
ResultText.text += string.Format("\n receieved error {0}",
responseObj.Response.HttpStatusCode.ToString());
}
});
}
And this is where I'm using it to upload the picture taken from the phone to the server
public void TakePicture(int maxSize)
{
NativeCamera.Permission permission = NativeCamera.TakePicture((path) =>
{
Debug.Log("Image path: " + path);
if (path != null)
{
// Create a Texture2D from the captured image
Texture2D imageTexture = NativeCamera.LoadImageAtPath(path, maxSize);
if (imageTexture == null)
{
Debug.Log("Couldn't load texture from " + path);
return;
}
//picturePreview.gameObject.SetActive(true);
//picturePreview.texture = imageTexture;
Texture2D readableTexture = DuplicateTexture(imageTexture);
StartCoroutine(AddImageJob(readableTexture));
//Saves taken photo to the Image Gallery
if (isSaveFiles)
{
NativeGallery.SaveImageToGallery(imageTexture, "AReview", "test");
//Upload to Amazon S3
aws.PostObject(imageTexture.name);
aws.PostObject("test");
}
}
}, maxSize);
Debug.Log("Permission result: " + permission);
}
Any clues?
Thank you.

Adding video in Allure Report using Allure jenkins plugin

I was trying various ways to embed a test run video in Allure Report plugin with Protractor.
we can do it if we add a video Folder inside the Allure Report folder and add the video path in the allure description . So then Allure displays and play the video in description part.
However, i wanted to achieve the same using the Allure Jenkins plugin. Can you please let me know if there is any way to embed and play the video in allure report generated using allure jenkins plugin.
I saw the Video on you tube where they are running video inside the Allure report in jenkins. But not sure how they have setup. Please help?
https://www.youtube.com/watch?v=74zD5q9DKTw
seems has no business of "jenkins plugin", you could rewrite the testngListener , and add the vedios with "Attachement"
#Override
public void onTestFailure(ITestResult result) {
super.onTestFailure(result);
String mp4 = store + "\\" + sessionId + ".mp4";
File file = new File(mp4);
if (file.exists()) {
attachRecord(mp4);
}
}
#Attachment(value = "record screen", type = "video/mp4")
private byte[] attachRecord(String mp4) {
System.out.println("mp4 -->" + mp4);
Path content = Paths.get(mp4);
InputStream is = null;
try {
is = Files.newInputStream(content);
} catch (IOException e) {
e.printStackTrace();
}
return is2ByeteArray(is);
}
public static byte[] is2ByeteArray(InputStream is) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buff = new byte[100];
int rc = 0;
while (true) {
try {
if (!((rc = is.read(buff, 0, 100)) > 0)) break;
} catch (IOException e) {
e.printStackTrace();
}
baos.write(buff, 0, rc);
}
return baos.toByteArray();
}

Apache commons net FTP clients hangs unpredictably

We tried all the solutions provided in this post (FTP client hangs) but none of them is working. We are using version 3.6 of commons net. Sometimes it hangs while uploading a file, sometimes will checking existence of a directory. Max. file size is around 400 MB. But sometime it hangs even for a small file size < 1KB. Below is the fragment of code:
public boolean uploadData(String inputFilePath, String destinationFolderName) {
if (StringUtil.isNullOrBlank(inputFilePath) || StringUtil.isNullOrBlank(destinationFolderName)) {
LOGGER.error("Invalid parameters to uploadData. Aborting...");
return false;
}
boolean result = false;
FTPSClient ftpClient = getFTPSClient();
if (ftpClient == null) {
logFTPConnectionError();
return false;
}
try {
loginToFTPServer(ftpClient);
result = uploadFileToFTPServer(ftpClient, inputFilePath, destinationFolderName);
} catch (Exception e) {
logErrorUploadingFile(inputFilePath, e);
return false;
} finally {
try {
logoutFromFTPServer(ftpClient);
} catch (Exception e) {
logErrorUploadingFile(inputFilePath, e);
result = false;
}
}
return result;
}
private FTPSClient getFTPSClient() {
FTPSClient ftpClient = null;
try {
ftpClient = new FTPSClient();
LOGGER.debug("Connecting to FTP server...");
ftpClient.setConnectTimeout(connectTimeOut);
ftpClient.connect(server);
int reply = ftpClient.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftpClient.disconnect();
LOGGER.error("Could not connect to FTP server. Aborting.");
return null;
}
} catch (Exception e) {
LOGGER.error("Could not connect to FTP server.", e);
return null;
}
return ftpClient;
}
private void loginToFTPServer(FTPSClient ftpClient) throws Exception {
ftpClient.setDataTimeout(DATA_TIMEOUT);
ftpClient.login(ftpUserName, ftpPassword);
ftpClient.enterLocalPassiveMode();
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
LOGGER.debug("FTP Client Buffer Size Before:" + ftpClient.getBufferSize());
ftpClient.setBufferSize(BUFFER_SIZE);
LOGGER.debug("FTP Client Buffer Size After:" + ftpClient.getBufferSize());
ftpClient.execPBSZ(0);
ftpClient.execPROT("P");
ftpClient.setControlKeepAliveTimeout(300);
LOGGER.debug("Logged into FTP server.");
}
private void logoutFromFTPServer(FTPSClient ftpClient) throws Exception {
LOGGER.debug("Logging out from FTP server.");
ftpClient.logout();
ftpClient.disconnect();
LOGGER.debug("FTP server connection closed.");
}
private boolean uploadFileToFTPServer(FTPSClient ftpClient, String inputFilePath, String destinationFolderName) {
boolean result = false;
String remoteLocationFile;
File ftpFile = new File(inputFilePath);
try (InputStream inputStream = new FileInputStream(ftpFile)) {
String fileName = ftpFile.getName();
remoteLocationFile = (destinationFolderName == null || destinationFolderName.isEmpty())
? ftpFile.getName()
: destinationFolderName + File.separator + fileName;
LOGGER.info("Storing file " + ftpFile.getName() + " of size "
+ ftpFile.length() + " in folder " + remoteLocationFile);
result = ftpClient.storeFile(remoteLocationFile, inputStream);
if(result) {
LOGGER.info("Successfully stored file " + ftpFile.getName() + " in folder " + remoteLocationFile);
} else {
LOGGER.error("Unable to store file " + ftpFile.getName() + " in folder " + remoteLocationFile);
}
return result;
} catch (Exception e) {
logErrorUploadingFile(inputFilePath, e);
}
return result;
}
The application is hosted in apache tomcat 8. What could be other causes of this issue and how should we fix them? This is crucial functionality of our application and we may even consider to use alternate API if that is stable. Please suggest.
Adding ftpClient.setSoTimeout(20000); has fixed the issue.
Adding a enterLocalPassiveMode right before the retreiveFile should solve this issue.
You also need to add
ftpClient.setControlKeepAliveTimeout(300);
or Check this code which will resolve the hanging issue

Raspberry Windows 10 difference between external USB Stick and external Harddisc

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?

Using websockets through the simple websockets for webgl asset in unity3d, can connect but can't transmit messages

Just having a problem on my mac trying to send strings over web sockets using this https://www.assetstore.unity3d.com/en/#!/content/38367
Lots of adapted code below from here mainly http://www.codepool.biz/how-to-implement-a-java-websocket-server-for-image-transmission-with-jetty.html and the web socket sharp echotest example.
I can connect but there is no sign of strings in my Jetty server console window (on a ws server running in java(eclipse)).
Iā€™m basically just trying to send a ā€œ1ā€ to my server over a websocket connection with the unity editor (5) at the moment, to prompt the server to start sending PNG files encoded as byte arrays, so I can put them back together in a C# script and apply them to a texture.
this is the script, I want to attach it to a game object like a plane or a cube and display the updating images sent over the web socket from my Jetty server, but at the moment I'm just stuck trying to send a message and see it pop up in my eclipse console window.
using UnityEngine;
using System.Collections;
using System;
public class socketTexture : MonoBehaviour {
// Use this for initialization
IEnumerator Start () {
WebSocket w = new WebSocket(new Uri("ws://192.168.0.149:8080/"));
yield return StartCoroutine(w.Connect());
Debug.Log ("Connected");
w.SendString("I'm client");
w.SendString("1");
while (true)
{
byte[] reply = w.Recv();
if (reply != null)
{
Debug.Log ("Received: "+reply);
var tex = new Texture2D(300, 300, TextureFormat.PVRTC_RGBA4, false);
// Load data into the texture and upload it to the GPU.
tex.LoadRawTextureData(reply);
tex.Apply();
// Assign texture to renderer's material.
GetComponent<Renderer>().material.mainTexture = tex;
}
if (w.Error != null)
{
Debug.LogError ("Error: "+w.Error);
break;
}
yield return 0;
}
w.Close();
}
}
...And the relevant code from the jetty server, but this works, I've tested it with some javascript and I can load the PNGs back into the browser window, so I'm definitely doing something wrong in Unity
#OnWebSocketMessage //part request from websocket client (remote browser)
public void onMessage( String message) {
System.out.println("message");
if (message.equals("1") || message.equals("2") || message.equals("3") || message.equals("4") ) {
System.out.println("Part " + message + " joined");
System.out.println( UIMain.usersPath + "/" + message + ".png" );
final String testVar = ( UIMain.usersPath + "/" + message + ".png" );
task = new FileWatcher( new File(testVar) ) {
protected void onChange( File file ) {
// here we code the action on a change
System.out.println( "File "+ file.getName() +" has changed!" );
try {
File f = new File(testVar);
BufferedImage bi = ImageIO.read(f);
ByteArrayOutputStream out = new ByteArrayOutputStream();
ImageIO.write(bi, "png", out);
ByteBuffer byteBuffer = ByteBuffer.wrap(out.toByteArray());
mSession.getRemote().sendBytes(byteBuffer);
out.close();
byteBuffer.clear();
}
catch (IOException e) {
e.printStackTrace();
}
}
};
Timer timer1 = new Timer(); {
timer1.schedule(task , new Date(), 40 );
}
}
else if (message.equals( "0")) {
zerocounter = zerocounter + 1;
if (zerocounter >= 2) {
task.cancel();
}
}
else if (message.equals( "Hi there, client here")) {
System.out.println( "Client says: " + message );
}
}
Any help would be really appreciated, been lurking on here for years, hopefully getting to the stage soon where I can help out others a bit too.
Benedict
Edit:
This is my console error message in Unity
FormatException: Invalid length. System.Convert.FromBase64String
(System.String s) (at
/Users/builduser/buildslave/mono-runtime-and-classlibs/build/mcs/class/corlib/System/Convert.cs:146)
EchoTest+c__Iterator0.MoveNext () (at
Assets/Example/EchoTest.cs:11)
I'm pretty sure the problem arises from websocket sharp for webgl. I need to send the message as a byte array.
OK So Joakim Erdfelt was right, the server was not configured to handle Byte[] messages. Here's what I added to fix it:
#OnWebSocketMessage
public void onMessage(byte[] buffer, int offset, int length) throws UnsupportedEncodingException {
System.out.println(buffer);
String sFclientOutStr = new String(buffer, "UTF-8");
sFclientOut = Integer.parseInt(sFclientOutStr);
System.out.println(sFclientOut);
if ((sFclientOut > 0) & (sFclientOut < 500)) {
System.out.println("Part " + sFclientOut + " joined");
System.out.println( UIMain.usersPath + "/" + sFclientOutStr + ".png" );
final String testVar = ( UIMain.usersPath + "/" + sFclientOutStr + ".png" );
task = new FileWatcher( new File(testVar) ) {
protected void onChange( File file ) {
// here we code the action on a change
System.out.println( "File "+ file.getName() +" has changed!" );
try {
File f = new File(testVar);
BufferedImage bi = ImageIO.read(f);
ByteArrayOutputStream out = new ByteArrayOutputStream();
ImageIO.write(bi, "png", out);
ByteBuffer byteBuffer = ByteBuffer.wrap(out.toByteArray());
mSession.getRemote().sendBytes(byteBuffer);
out.close();
byteBuffer.clear();
}
catch (IOException e) {
e.printStackTrace();
}
}
};
Timer timer1 = new Timer(); {
timer1.schedule(task , new Date(), 40 );
}
}
else if (sFclientOutStr.equals("0")) {
zerocounter = zerocounter + 1;
if (zerocounter >= 2) {
task.cancel();
}
}
else if (sFclientOutStr.equals( "I'm client")) {
System.out.println( "Client says: " + sFclientOutStr );
}
}
These links helped explain it for me http://www.programcreek.com/java-api-examples/index.php?api=org.eclipse.jetty.websocket.api.annotations.OnWebSocketMessage
http://www.eclipse.org/jetty/documentation/current/jetty-websocket-api-annotations.html