Create a text file in Google Glass - google-glass

I am able to install native apps in Google Glass now. I hope to know how to create a text file using native apps in Google Glass so that I can save data to text files.
Thanks!

Since Glass is an Android device and you are writing native Android apps for it, you should be able to write text files like you would on any other Android device.
The Android documentation on data storage should be helpful.

I tried the following code to create a file in Google Glass. The following code works with Android, which has a sd card. But does not work for Google Glass. Does anyone know how to create a text file in the Glass? Thanks!
public void SaveSubjectID(String filename, Context ctx) {
try {
//Find the directory for the SD Card using the API
//*Don't* hardcode "/sdcard"
// Toast.makeText(getBaseContext(), "files", Toast.LENGTH_SHORT).show();
//create a folder in a app.
//http://stackoverflow.com/questions/6911041/how-to-​create-folder-into-sd-card-in-android
File rootDirect = new File(Environment.getExternalStorageDirectory() + "/SmartTexting");
if(!rootDirect.exists())
{ rootDirect.mkdir() ;
}
File subjectDirect = new File(Environment.getExternalStorageDirectory() + "/SmartTexting/"+"subject");
if(!subjectDirect.exists())
{ subjectDirect.mkdir() ;
}
//File sdcard = Environment.getExternalStorageDirectory();
File file = new File(subjectDirect,filename);
// Toast.makeText(getBaseContext(), "files created", Toast.LENGTH_SHORT).show();
FileOutputStream fos2 = new FileOutputStream(file, true);
String outline = "test"
+ "\n";
fos2.write(outline.getBytes());
fos2.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

I hope you have found out the correct answer by now, still this answer goes for all those who haven't found yet.
Code for writing file to google glass:
try {
File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
File f = new File(path,"file_new.txt");
f.createNewFile();
Log.d("file pathhhh", "result"+f.getAbsolutePath());
Log.d("file created", "result"+f.createNewFile());
FileOutputStream fOut = new FileOutputStream(f);
//FileOutputStream fileout=openFileOutput(f);
OutputStreamWriter outputWriter=new OutputStreamWriter(fOut);
//writer = new FileWriter(file1);
//writer.write(text.toString());
outputWriter.write(text.toString());
/** Closing the writer object */
outputWriter.close();
Log.d("success", "success"+Environment.getExternalStorageState()+Environment.getStorageState(path));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
The key is to write file in DCIM folder and dont expect the file will be created then only.
To see whether the file has been created or not, shut down the glass and power it on again, you will find the new file in the DCIM folder

Related

Accessing uploaded files from Camunda task

The final task of a Camunda process must write the files uploaded by the user to an specific folder. So, I've created the following 'Service task' as the last one of the process:
Then, from the Java project, I've added the FinishArchiveDelegate class with the following code:
package com.ower.abpar.agreements;
import org.camunda.bpm.engine.delegate.DelegateExecution;
import org.camunda.bpm.engine.delegate.JavaDelegate;
public class FinishArchiveDelegate implements JavaDelegate {
#Override
public void execute(DelegateExecution execution) throws Exception {
System.out.println("Process finished: "+execution.getVariables());
}
}
When I check the logs, I see that I can see the document names, like:
document_1 => FileValueImpl [mimeType=image/jpeg, filename=Test_agreement1.jpg, type=file, isTransient=false]
The problem is that it only shows the file name and I'd need to request it from Camunda's database to copy it to another folder. Any suggestion or idea?
Thanks!
After some tests, I realized that I can get not only the name but all the uploaded files content using execution.getVariable(DOCUMENT_VARIABLE_NAME). So this is what I did:
// Get the uploaded file content
Object fileData = execution.getVariable("filename");
// The following returns a FileValueImpl object with metadata
// about the uploaded file, such as the name
FileValueImpl fileMetadata = FileValueImpl)execution.getVariableLocalTyped("filename")
// Set the destination file name
String destinationFileName = DEST_FOLDER + fileMetadata.getFilename();
...
// Create an InputStream from the file's content
InputStream in = (ByteArrayInputStream)fileData;
// Create an OutputStream to copy the data to the destination folder
OutputStream out = new FileOutputStream(destinationFileName);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
Hope this helps someone, cheers!

How to load files to local file system with vibed?

I need to send data from web-browser to local FS. For sending data I am using Vue-JS component
<file-upload class="my-file-uploader" name="myFile" id="myCustomId" action="/upload" multiple>Inside Slot Text</file-upload>
My server side based on vibed. But I can't find example how to save binary data to local FS.
router.any("/upload", &upload);
...
void upload(HTTPServerRequest req, HTTPServerResponse res)
{
}
It's seems that I should use HTTPServerRequest.files But I can't understand how to use it. User upload takes is multiple files.
You can find a lot of examples within the Vibe.d Github repository.
For example there's a small uploader.
router.post("/upload", &uploadFile);
...
void uploadFile(scope HTTPServerRequest req, scope HTTPServerResponse res)
{
auto pf = "file" in req.files;
enforce(pf !is null, "No file uploaded!");
try moveFile(pf.tempPath, Path(".") ~ pf.filename);
catch (Exception e) {
logWarn("Failed to move file to destination folder: %s", e.msg);
logInfo("Performing copy+delete instead.");
copyFile(pf.tempPath, Path(".") ~ pf.filename);
}
res.writeBody("File uploaded!", "text/plain");
}
I don't know much about Vue.js, but it seems they use file too.

C++/CX - GetFileAsync throws breakpoint error

I am trying to open a xml file from my Assets folder, but unfortunately I am only able to open my xml file by using a FileOpenPicker which is not the most ideal situation when I have to constantly fetch my xml file, without disturbing the user of course.
FileOpenPicker^ openPicker = ref new FileOpenPicker();
openPicker->ViewMode = PickerViewMode::List;
openPicker->SuggestedStartLocation = PickerLocationId::Desktop;
openPicker->FileTypeFilter->Append(".xml");
task<StorageFile^>(
openPicker->PickSingleFileAsync()).then([this](StorageFile^ file) {
if (nullptr != file) {
task<Streams::IRandomAccessStream^>(file->OpenAsync(FileAccessMode::Read)).then([this](Streams::IRandomAccessStream^ stream)
{
IInputStream^ deInputStream = stream->GetInputStreamAt(0);
DataReader^ reader = ref new DataReader(deInputStream);
reader->LoadAsync(stream->Size);
String^ strXml = reader->ReadString(stream->Size);
});
}
});
I am now trying to reconstruct this code into a code which loads up my xml file without letting the user choose. I tried the following approach:
String^ xmlFile = "Assets\MyXmlFile.xml";
StorageFolder^ InstallationFolder = Windows::ApplicationModel::Package::Current->InstalledLocation;
task<StorageFile^>(
InstallationFolder->GetFileAsync(xmlFile)).then([this](StorageFile^ file) {
if (nullptr != file) {
task<Streams::IRandomAccessStream^>(file->OpenAsync(FileAccessMode::Read)).then([this](Streams::IRandomAccessStream^ stream)
{
IInputStream^ deInputStream = stream->GetInputStreamAt(0);
DataReader^ reader = ref new DataReader(deInputStream);
reader->LoadAsync(stream->Size);
String^ strXml = reader->ReadString(stream->Size);
stream->FlushAsync();
});
}
});
I think I get errors at the GetFileAsync which I am not able to solve and I am asking you, the community to try and help me.
Your code worked for me with one modification: the xmlFile string contains a backslash that needs to be escaped:
String^ xmlFile = "Assets\\MyXmlFile.xml";
Note also that if you just right-clicked "Assets" in your project and chose "Add new item", that item may have ended up in your root project folder (which is the default). If you want it to be deployed to the Assets subfolder it will need to physically live there on disk in the assets subdirectory, not just be in the Assets filter. (Unlike in C#, the C++ project "folders" are actually filters and do not reflect physical directory location.)

Saving txt file using saveFileDialog (C++)

I can't manage to save a text file using the "saveFileDialog".
I have looked trough many forums and tutorials, but i cant get the right information from neither.
So far i have managed to open the Save file dialog and it actualy saves an empty text file with the right name and path,BUT, and this is the part i have trouble with, its EMPTY, and i dont know where you show what information to save on the file and what methods to use!
Here is the code :
private: System::Void button3_Click(System::Object^ sender, System::EventArgs^ e) {
saveFileDialog1->ShowDialog();
}
private: System::Void saveFileDialog1_FileOk(System::Object^ sender, System::ComponentModel::CancelEventArgs^ e) {
System::IO::FileStream ^ fs = safe_cast<System::IO::FileStream^>(saveFileDialog1->OpenFile());
}
So can somebody tell me how and what to do?
Thanks in advance!
You use the save file dialog to get a path where to save your file. So basically you would need
saveFileDialog.showDialog();
String filename = saveFileDialog.FileName;
System.IO.StreamWriter file = new System.IO.StreamWriter(filename)
file.writeLine("This is a test");
file.close();
This is just a quick example :D

Why does WebSharingAppDemo-CEProviderEndToEnd sample still need a client db connection after scope creation to perform sync

I'm researching a way to build an n-tierd sync solution. From the WebSharingAppDemo-CEProviderEndToEnd sample it seems almost feasable however for some reason, the app will only sync if the client has a live SQL db connection. Can some one explain what I'm missing and how to sync without exposing SQL to the internet?
The problem I'm experiencing is that when I provide a Relational sync provider that has an open SQL connection from the client, then it works fine but when I provide a Relational sync provider that has a closed but configured connection string, as in the example, I get an error from the WCF stating that the server did not receive the batch file. So what am I doing wrong?
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
builder.DataSource = hostName;
builder.IntegratedSecurity = true;
builder.InitialCatalog = "mydbname";
builder.ConnectTimeout = 1;
provider.Connection = new SqlConnection(builder.ToString());
// provider.Connection.Open(); **** un-commenting this causes the code to work**
//create anew scope description and add the appropriate tables to this scope
DbSyncScopeDescription scopeDesc = new DbSyncScopeDescription(SyncUtils.ScopeName);
//class to be used to provision the scope defined above
SqlSyncScopeProvisioning serverConfig = new SqlSyncScopeProvisioning();
....
The error I get occurs in this part of the WCF code:
public SyncSessionStatistics ApplyChanges(ConflictResolutionPolicy resolutionPolicy, ChangeBatch sourceChanges, object changeData)
{
Log("ProcessChangeBatch: {0}", this.peerProvider.Connection.ConnectionString);
DbSyncContext dataRetriever = changeData as DbSyncContext;
if (dataRetriever != null && dataRetriever.IsDataBatched)
{
string remotePeerId = dataRetriever.MadeWithKnowledge.ReplicaId.ToString();
//Data is batched. The client should have uploaded this file to us prior to calling ApplyChanges.
//So look for it.
//The Id would be the DbSyncContext.BatchFileName which is just the batch file name without the complete path
string localBatchFileName = null;
if (!this.batchIdToFileMapper.TryGetValue(dataRetriever.BatchFileName, out localBatchFileName))
{
//Service has not received this file. Throw exception
throw new FaultException<WebSyncFaultException>(new WebSyncFaultException("No batch file uploaded for id " + dataRetriever.BatchFileName, null));
}
dataRetriever.BatchFileName = localBatchFileName;
}
Any ideas?
For the Batch file not available issue, remove the IsOneWay=true setting from IRelationalSyncContract.UploadBatchFile. When the Batch file size is big, ApplyChanges will be called even before fully completing the previous UploadBatchfile.
// Replace
[OperationContract(IsOneWay = true)]
// with
[OperationContract]
void UploadBatchFile(string batchFileid, byte[] batchFile, string remotePeer1
I suppose it's simply a stupid example. It exposes "some" technique but assumes you have to arrange it in proper order by yourself.
http://msdn.microsoft.com/en-us/library/cc807255.aspx