How can the application user save data to one of his own cloud storage? - file-upload

In my cn1 application, I want to make it possible for the user to back up their own cloud storage. For example, your own Dropbox account.
I was looking for a solution on the WEB. I think what I found (dropbox-codenameone-sdk) I can only manage a known account because I need to know consumerSecret and consumerKey. When I write the code, I don't know the actual user account information.
Based on the operation of other applications, I assume I have to log in to the actual user his account (eg Dropbox).
Please help what API calls can I do this.

Use the Share API in Display. You can zip the data using the zip cn1lib and save it in a file within the file system then use the share API to let the user pick a native app to share it with. On the simulator it will have options such as email/facebook but on the device you should have more options.

I think I'm using the API properly. Although I did not set correctly the file access on my phone.
However, the error occured in the simulator.
The mail and DropBox sharing on my android phone is successful.
I don't like the file getting a prefix (IMG_20200112_204126_). Can I change this?
I include screenshots and a code snippet.
Best regards, Péter
public ShareForm(Resources resourceObjectInstance, Form parentForm) {
this.parentForm = parentForm;
this.theme = resourceObjectInstance;
Layout layout = new BoxLayout(BoxLayout.Y_AXIS);
setLayout(layout);
getToolbar().setBackCommand("", e -> {
this.parentForm.showBack();
});
/* file exist on simulator */
/* String filePath = FileSystemStorage.getInstance().getAppHomePath() + "temp/vendeg_201807011754.json"; */
/* file exist on phone */
String filePath = "file:///storage/emulated/0/Download/stratos.pdf";
String mimeType = "application/octet-stream";
boolean exist = FileSystemStorage.getInstance().exists(filePath);
long size = FileSystemStorage.getInstance().getLength(filePath);
SpanLabel spanLabel0 = new SpanLabel("File path: " + filePath);
SpanLabel spanLabel1 = new SpanLabel("File exist: " + exist);
SpanLabel spanLabel2 = new SpanLabel("File size: " + size);
ShareButton shareButton = new ShareButton();
shareButton.setText("Share data (ShareButton)");
shareButton.addActionListener(e-> {
shareButton.setImageToShare(filePath, mimeType);
shareButton.actionPerformed(e);
});
Button shareButton1 = new Button("Share data (Share API in Display)");
FontImage.setMaterialIcon(shareButton1, FontImage.MATERIAL_SHARE);
shareButton1.addActionListener(e -> {
Display.getInstance().share(null, filePath, mimeType, shareButton1.getBounds(new Rectangle()));
});
addComponent(spanLabel0);
addComponent(spanLabel1);
addComponent(spanLabel2);
addComponent(shareButton);
addComponent(shareButton1);
}

Related

Kotlin - get Firebase Image DownloadUrl returns "com.google.android.gms.tasks.zzu"

I am trying to upload images to Real time Firebase Database by creating two folders using Compressor library and need to display image like messenger with username but i am unable to display image due to url issue
var filePath = mStorageRef!!.child("chat_profile_images")
.child(userId + ".jpg")
//Create another directory for thumbimages ( smaller, compressed images)
var thumbFilePath = mStorageRef!!.child("chat_profile_images")
.child("thumbs")
.child(userId + ".jpg")
filePath.putFile(resultUri)
.addOnCompleteListener{
task: Task<UploadTask.TaskSnapshot> ->
if (task.isSuccessful) {
//Let's get the pic url
var donwloadUrl = task.result?.storage?.downloadUrl.toString()
Log.d(TAG, "Profilepic link: $donwloadUrl")
//Upload Task
var uploadTask: UploadTask = thumbFilePath
.putBytes(thumbByteArray)
uploadTask.addOnCompleteListener{
task: Task<UploadTask.TaskSnapshot> ->
var thumbUrl = task.getResult()?.storage?.downloadUrl.toString()
Log.d(TAG, "Profilepic link: $thumbUrl")
i tried to change downloadUrl
filepath.downloadUrl.toString
thumbFilePath.downloadUrl.toString
but both these values getting "com.google.android.gms.tasks.zzu"
i also tried to change
task.result.sessionurl.downloadUrl.toString
for this one i am getting downloadUrl but not a complete solution for my problem as still i cannot display image i need to get thumbUrl downloadUrl
You have the exact same and very common misunderstanding as in this question, except it's in java. You should follow the documentation here to understand get getDownloadUrl works. As you can see from the linked API documentation, it's not a property getter, it's actually a method that returns a Task<Uri> that tracks the asynchronous fetch of the URL you want, just like the upload task:
filePath.downloadUrl
.addOnSuccessListener { urlTask ->
// download URL is available here
val url = urlTask.result.toString()
}.addOnFailureListener { e ->
// Handle any errors
}
This will only work after the upload is fully complete.
Correct way of getting download link after uploading
here
Just putting out there, I also encounter the same problem,
but both these values getting "com.google.android.gms.tasks.zzu"
but it wasn't the same mistake from the OP
used addOnCompleteListener instead of addOnSuccesslistener
My Error code:
imageRef.downloadUrl.addOnCompleteListener { url ->
val imageURL = url.toString()
println("imageURL: $imageURL , url: $url")
addUserToDatabase(imageURL)
}

Read a file from the cache in CEFSharp

I need to navigate to a web site that ultimately contains a .pdf file and I want to save that file locally. I am using CEFSharp to do this. The nature of this site is such that once the .pdf appears in the browser, it cannot be accessed again. For this reason, I was wondering if once you have a .pdf displayed in the browser, is there a way to access the source for that file in the cache?
I have tried implementing IDownloadHandler and that works, but you have to click the save button on the embedded .pdf. I am trying to get around that.
OK, here is how I got it to work. There is a function in CEFSharp that allows you to filter an incoming web response. Consequently, this gives you complete access to the incoming stream. My solution is a little on the dirty side and not particularly efficient, but it works for my situation. If anyone sees a better way, I am open for suggestions. There are two things I have to assume in order for my code to work.
GetResourceResponseFilter is called every time a new page is downloaded.
The PDF is that last thing to be downloaded during the navigation process.
Start with the CEF Minimal Example found here : https://github.com/cefsharp/CefSharp.MinimalExample
I used the WinForms version. Implement the IRequestHandler and IResponseFilter in the form definition as follows:
public partial class BrowserForm : Form, IRequestHandler, IResponseFilter
{
public readonly ChromiumWebBrowser browser;
public BrowserForm(string url)
{
InitializeComponent();
browser = new ChromiumWebBrowser(url)
{
Dock = DockStyle.Fill,
};
toolStripContainer.ContentPanel.Controls.Add(browser);
browser.BrowserSettings.FileAccessFromFileUrls = CefState.Enabled;
browser.BrowserSettings.UniversalAccessFromFileUrls = CefState.Enabled;
browser.BrowserSettings.WebSecurity = CefState.Disabled;
browser.BrowserSettings.Javascript = CefState.Enabled;
browser.LoadingStateChanged += OnLoadingStateChanged;
browser.ConsoleMessage += OnBrowserConsoleMessage;
browser.StatusMessage += OnBrowserStatusMessage;
browser.TitleChanged += OnBrowserTitleChanged;
browser.AddressChanged += OnBrowserAddressChanged;
browser.FrameLoadEnd += browser_FrameLoadEnd;
browser.LifeSpanHandler = this;
browser.RequestHandler = this;
The declaration and the last two lines are the most important for this explanation. I implemented the IRequestHandler using the template found here:
https://github.com/cefsharp/CefSharp/blob/master/CefSharp.Example/RequestHandler.cs
I changed everything to what it recommends as default except for GetResourceResponseFilter which I implemented as follows:
IResponseFilter IRequestHandler.GetResourceResponseFilter(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request, IResponse response)
{
if (request.Url.EndsWith(".pdf"))
return this;
return null;
}
I then implemented IResponseFilter as follows:
FilterStatus IResponseFilter.Filter(Stream dataIn, out long dataInRead, Stream dataOut, out long dataOutWritten)
{
BinaryWriter sw;
if (dataIn == null)
{
dataInRead = 0;
dataOutWritten = 0;
return FilterStatus.Done;
}
dataInRead = dataIn.Length;
dataOutWritten = Math.Min(dataInRead, dataOut.Length);
byte[] buffer = new byte[dataOutWritten];
int bytesRead = dataIn.Read(buffer, 0, (int)dataOutWritten);
string s = System.Text.Encoding.UTF8.GetString(buffer);
if (s.StartsWith("%PDF"))
File.Delete(pdfFileName);
sw = new BinaryWriter(File.Open(pdfFileName, FileMode.Append));
sw.Write(buffer);
sw.Close();
dataOut.Write(buffer, 0, bytesRead);
return FilterStatus.Done;
}
bool IResponseFilter.InitFilter()
{
return true;
}
What I found is that the PDF is actually downloaded twice when it is loaded. In any case, there might be header information and what not at the beginning of the page. When I get a stream segment that begins with %PDF, I know it is the beginning of a PDF so I delete the file to discard any previous contents that might be there. Otherwise, I just keep appending each segment to the end of the file. Theoretically, the PDF file will be safe until you navigate to another PDF, but my recommendation is to do something with the file as soon as the page is loaded just to be safe.

ASP.net - Uploading Files Associated with a Database Record?

I know that there are tons of examples of multi-part form data uploading in ASP.net. However, all of them just upload files to the server, and use System.IO to write it to server disk space. Also, the client side implementations seem to handle files only in uploading, so I can't really use existing upload plugins.
What if I have an existing record and I want to upload images and associate them with the record? Would I need to write database access code in the upload (Api) function, and if so, how do I pass that record's PK with the upload request? Do I instead upload the files in that one request, obtain the file names generated by the server, and then make separate API calls to associate the files with the record?
While at it, does anyone know how YouTube uploading works? From a user's perspective, it seems like we can upload a video, and while uploading, we can set title, description, tags, etc, and even save the record. Is a record for the video immediately created before the API request to upload, which is why we can save info even before upload completes?
Again, I'm not asking HOW to upload files. I'm asking how to associate uploaded files with an existing record and the API calls involved in it. Also, I am asking for what API calls to make WHEN in the user experience when they also input information about what they're uploading.
I'm assuming you're using an api call to get the initial data for displaying a list of files or an individual file. You would have to do this in order to pass the id back to the PUT method to update the file.
Here's a sample of the GET method:
[HttpGet]
public IEnumerable<FileMetaData> Get()
{
var allFiles = MyEntities.Files.Select(f => new FileMetaData()
{
Name = f.Name,
FileName = f.FileName,
Description = f.Description,
FileId = f.Id,
ContentType = f.ContentType,
Tags = f.Tags,
NumberOfKB = f.NumberOfKB
});
return allFiles;
}
Here's a sample of the POST method, which you can adapt to be a PUT (update) instead:
[HttpPost]
[ValidateMimeMultipartContentFilter]
public async Task<IHttpActionResult> PutFile()
{
try
{
var streamProvider =
await Request.Content.ReadAsMultipartAsync(new InMemoryMultipartFormDataStreamProvider());
//We only allow one file
var thisFile = files[0];
//For a PUT version, you would grab the file from the database based on the id included in the form data, instead of creating a new file
var file = new File()
{
FileName = thisFile.FileName,
ContentType = thisFile.ContentType,
NumberOfKB = thisFile.ContentLength
};
//This is the file metadata that your client would pass in as formData on the PUT / POST.
var formData = streamProvider.FormData;
if (formData != null && formData.Count > 0)
{
file.Id = formData["id"];
file.Description = formData["description"];
file.Name = formData["name"] ?? string.Empty;
file.Tags = formData["tags"];
}
file.Resource = thisFile.Data;
//For your PUT, change this to an update.
MyEntities.Entry(file).State = EntityState.Detached;
MyEntities.Files.Add(file);
await MyEntities.SaveChangesAsync();
//return the ID
return Ok(file.Id.ToString());
}
I got the InMemoryMultipartFormDataStreamProvider from this article:
https://conficient.wordpress.com/2013/07/22/async-file-uploads-with-mvc-webapi-and-bootstrap/
And adapted it to fit my needs for the form data I was returning.

How to get a deep link of my application from the Windows Phone Marketplace using .NET code?

How do I get a deep link of my application programmatically from the Windows Phone Marketplace, so that I can use it in my code?
Getting the AppDeeplink is quite useful for example in ShareStatusTask and ShareLinkTask.
It is possible, however you have to use some non-trivial code for getting the real AppID from within your app Manifest file. Here's what I do:
First save somewhere in resources the string for Windows Phone app deeplinks, this is simple:
"http://windowsphone.com/s?appId={0}"
Then you have to find the real AppId by opening the App Manifest file and finding the proper tag, I use this code inside my MarketplaceHelper for doing so:
static MarketplaceHelper()
{
try
{
// load product details from WMAppManifest.xml
XElement app = XElement.Load("WMAppManifest.xml").Descendants("App").Single();
Title = GetValue(app, "Title");
Version = new Version(GetValue(app, "Version"));
Author = GetValue(app, "Author");
Publisher = GetValue(app, "Publisher");
Description = GetValue(app, "Description");
// remove the surrounding braces
string productID = GetValue(app, "ProductID");
ProductID = Regex.Match(productID, "(?<={).*(?=})").Value;
}
catch (Exception e)
{
// should not happen, every application has this field and should containt the ProductID and Version
}
}
private static string GetValue(XElement app, string attrName)
{
XAttribute at = app.Attribute(attrName);
return at != null ? at.Value : null;
}
If the Manifest is there and is properly formatted, and it should be, otherwise the app won't work, you can get this way any data you want.
Now you can construct the deeplink like this:
string deeplink = string.Format(AppResources.DeepLinkFormat, MarketplaceHelper.ProductID);

windows 8 modern ui apps - access to data

Where can i find folder with installed modern ui apps? Im developing some app which uses .txt files to store information (win8 doesnot support datebase on arm - facepalm) but they seem to not work properly - thats why i want to access them.
Thanks!
That is not the correct way of doing things in Metro. I assume you mean db files, or txt files. Simply access the local text file from the project folder.
Here is a great tutorial on how you would go about doing so: http://www.codeproject.com/Articles/432876/Windows-8-The-Right-Way-to-Read-Write-Files-in-Win
An example:
private async void ProjectFile()
{
// settings
var _Path = #"Metro.Helpers.Tests\MyFolder\MyFolder.txt";
var _Folder = Windows.ApplicationModel.Package.Current.InstalledLocation;
// acquire file
var _File = await _Folder.GetFileAsync(_Path);
Assert.IsNotNull(_File, "Acquire file");
// read content
var _ReadThis = await Windows.Storage.FileIO.ReadTextAsync(_File);
Assert.AreEqual("Hello world!", _ReadThis, "Contents correct");
}