I work with the C# language not java and do not yet know how to get a reference to an object in FireBaseStorage. I have the following code that should output a link from Fire Base Storage, but instead it outputs System.Threading.Tasks.Tast`1[The system.Line]
Tell me how do I get a link to a file from FireBaseStorage using FireSharp and FireBase libraries
here is my code: (C#)
FirebaseStorage storage = new FirebaseStorage("*******-****.appspot.com");
var starsRef = storage.Child("test.txt");
string link = starsRef.GetDownloadUrlAsync().ToString();
MessageBox.Show(link);
Don't know above C# that much, but whenever we do an asynchronous calls, don't we have to wait for result ? "await". Cause your ouput seems your thread is waiting for the result. System.Threading.Tasks.Tast`1[The system.Line]
Try using await before getting downloadUrl string link = await starsRef.GetDownloadUrlAsync().ToString(); and make your mehtod asynchronous in which you are writing your code.
C#
private void button28_ClickAsync(object sender, EventArgs e)
{
// Create a reference to the file we want to download
_ = getLinkAsync();
getLinkAsync();
}
public async Task getLinkAsync()
{
FirebaseStorage storage = new FirebaseStorage("firstbd-****.appspot.com");
var starsRef = storage.Child("test.txt");
string link = await starsRef.GetDownloadUrlAsync();
MessageBox.Show(link);
}
Related
I'm using Xamarin signaturepadView on capturing Signature. Also, saving the signature works fine. I also want to capture the text and stuff.
This is what I want to capture
Instead I got this
You can also use Xamarin.Essentials: Screenshot to capture the whole view of the Signature. Here's the sample code below for your reference:
private async void Button_Clicked(object sender, EcentArgs e){
if(Screenshot.IsCaptureSupported){
var screenshot = await Screenshot.CaptureAsync();
var stream = await screenshot.OpenReadAsync();
ImageScreenshot.Source = ImageSource.FromStream(() => stream);
}
}
When I create a database I want to initialize it with a ton of data.
I have the following initialization service.
// This needs to be a top-level method because it's run on a background isolate
DatabaseConnection _backgroundConnection() {
// construct the database. You can also wrap the VmDatabase in a "LazyDatabase" if you need to run
// work before the database opens.
final database = VmDatabase.memory();
return DatabaseConnection.fromExecutor(database);
}
Future<void> _initDatabase(Map<String, dynamic> args) async {
var moorIsolate = await MoorIsolate.spawn(_backgroundConnection);
var connection = await moorIsolate.connect();
var db = BillingDatabase.connect(connection);
_initBillingSpecialties(db, args["specialties"]);
}
Future<void> _initBillingSpecialties(BillingDatabase db, String specialtiesJson) async {
var json = jsonDecode(specialtiesJson);
var jsonSpecialties = json["specialties"] as List<dynamic>;
var specialities = jsonSpecialties.map((s) =>
DbSpecialtiesCompanion(name: Value(s["specialty_name"]),
mohNumber: Value(s["moh_specialty"]))).toList();
return db.specialtyDao.saveAllSpecialties(specialities);
}
#injectable
class InitDbService {
Future<void> initDatabase() async {
WidgetsFlutterBinding.ensureInitialized();
var specialties = await rootBundle.loadString("lib/assets/billing_specialties.json");
compute(_initDatabase, {"specialties": specialties});
//initDbSync(specialties);
}
Future<void> initDbSync(String specialtiesJson) async {
var json = jsonDecode(specialtiesJson);
var jsonSpecialties = json["specialties"] as List<dynamic>;
var specialities = jsonSpecialties.map((s) =>
DbSpecialtiesCompanion(name: Value(s["specialty_name"]),
mohNumber: Value(s["moh_specialty"]))).toList();
var dao = GetIt.instance.get<SpecialtyDao>();
return dao.saveAllSpecialties(specialities);
}
}
initDbSync runs and inserts just fine. While db.specialtyDao.saveAllSpecialties(specialities); never actually exectues any SQL. I have it printing log statements for the moment so I can see what it's doing.
Update: I found out that VmDatabase.memory(logStatements: true); was needed to see the SQL. I can see it printing the statements.
I'm running on a simulator so I can look at the raw db file. And there's nothing there. When I query in the app there's also nothing there.
So what's not really clear in the documentation is that VmDatabase.memory(); opens up a new database in memory. Not takes the database from memory.
You want to take your reference to the file that you pass in the constructor, and use
VmDatabase(File(dbFile));
then it will actually run on your sql.
This is actually a 2-part question related directly to .net core 3.0 and specifically with PipeWriter: 1) How should I read in the HttpResponse body? 2) How can I update the HttpResponse? I'm asking both questions because I feel like the solution will likely involve the same understanding and code.
Below is how I got this working in .net core 2.2 - note that this is using streams instead of PipeWriter and other "ugly" things associated with streams - eg. MemoryStream, Seek, StreamReader, etc.
public class MyMiddleware
{
private RequestDelegate Next { get; }
public MyMiddleware(RequestDelegate next) => Next = next;
public async Task Invoke(HttpContext context)
{
var httpResponse = context.Response;
var originalBody = httpResponse.Body;
var newBody = new MemoryStream();
httpResponse.Body = newBody;
try
{
await Next(context);
}
catch (Exception)
{
// In this scenario, I would log out the actual error and am returning this "nice" error
httpResponse.StatusCode = StatusCodes.Status500InternalServerError;
httpResponse.ContentType = "application/json"; // I'm setting this because I might have a serialized object instead of a plain string
httpResponse.Body = originalBody;
await httpResponse.WriteAsync("We're sorry, but something went wrong with your request.");
return;
}
// If everything worked
newBody.Seek(0, SeekOrigin.Begin);
var response = new StreamReader(newBody).ReadToEnd(); // This is the only way to read the existing response body
httpResponse.Body = originalBody;
await context.Response.WriteAsync(response);
}
}
How would this work using PipeWriter? Eg. it seems that working with pipes instead of the underlying stream is preferable, but I can not yet find any examples on how to use this to replace my above code?
Is there a scenario where I need to wait for the stream/pipe to finish writing before I can read it back out and/or replace it with a new string? I've never personally done this, but looking at examples of PipeReader seems to indicate to read things in chunks and check for IsComplete.
To Update HttpRepsonse is
private async Task WriteDataToResponseBodyAsync(PipeWriter writer, string jsonValue)
{
// use an oversized size guess
Memory<byte> workspace = writer.GetMemory();
// write the data to the workspace
int bytes = Encoding.ASCII.GetBytes(
jsonValue, workspace.Span);
// tell the pipe how much of the workspace
// we actually want to commit
writer.Advance(bytes);
// this is **not** the same as Stream.Flush!
await writer.FlushAsync();
}
I tried to use the following methods, but all of them appeared as not implemented in Uno (Android). What can I do?
Is there any Xamarin.Essentials alternative?
Or other NuGet package?
Or should I use native implementations on each platform?
And is it even possible to implement it in Uno directly?
var pdfFile = StorageFile.GetFileFromApplicationUriAsync(..);
pdfFile.CopyAsync(..);
(await pdfFile.OpenReadAsync()).AsStreamForRead(); // AsStreamForRead() not implemented
I'm using v1.45.0 of Uno.UI.
As David Oliver pointed out in his answer,
Uno hasn't implemented most of the Windows.StorageFile APIs, as for
the most part there are alternatives available in System.IO, which
will work cross-platform.
So...
To open file from the app package we can set its build action to Embedded Resource instead of Content. And instead of StorageFile.GetFileFromApplicationUriAsync() method we can use this code:
public Stream GetStreamFromResourceFile(string filename, Type callingType = null)
{
var assembly = (callingType ?? GetType()).Assembly;
string foundResourceName = assembly.GetManifestResourceNames().FirstOrDefault(r => r.EndsWith(filename, StringComparison.InvariantCultureIgnoreCase));
if (foundResourceName == null)
throw new FileNotFoundException("File was not found in application resources. Ensure that the filename is correct and its build action is set to 'Embedded Resource'.", filename);
return assembly.GetManifestResourceStream(foundResourceName);
}
to copy a file
await pdfFile.CopyAsync(..);
we change to:
await pdfFile.CopyToAsync(newFile);
and to get a stream for read
(await pdfFile.OpenReadAsync()).AsStreamForRead();
we use:
File.OpenRead(pdfFile);
So in the end we have:
string filename = "File.pdf";
var pdfFile = GetStreamFromResourceFile(filename, GetType());
string newFilePath = Path.Combine(ApplicationData.Current.LocalFolder.Path, filename);
using (var newFile = File.Create(newFilePath))
{
await pdfFile.CopyToAsync(newFile);
}
var fileStream = File.OpenRead(newFilePath);
Uno hasn't implemented most of the Windows.StorageFile APIs, as for the most part there are alternatives available in System.IO, which will work cross-platform.
If you're trying to display a pdf, however, there's no cross-platform option currently. On Android the best way to display a pdf is to launch an intent, on iOS it's possible to display the pdf in a WebView.
Partial example code for Android:
public async Task Read(CancellationToken ct, string filePath)
{
var intent = new Intent(Intent.ActionView);
var file = new Java.IO.File(filePath);
var contentUri = Android.Support.V4.Content.FileProvider.GetUriForFile(ContextHelper.Current, _fileProviderAuthority, file);
intent.SetFlags(ActivityFlags.GrantReadUriPermission);
intent.SetDataAndType(contentUri, "application/pdf");
StartActivity(intent);
}
Partial example code for iOS:
<ios:WebView
Source="{Binding FilePath}"
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch" />
I want to develop a Dragon Timer Windows Store App for GuildWars 2.
Whatever, I save a timestamp in a sql database. To get this timestamp in the app, I made a php script that writes the content of the database to a page. Now I'm trying to receive that string via the HttpClient.GetStringAsync() Method. Here's the code snipped:
async Task<Dictionary<String, DateTime>> GetKillTimes()
{
Dictionary<String, DateTime> killTimes = new Dictionary<String,DateTime>();
HttpClient httpClient = new HttpClient();
Task<string> getStringTask = httpClient.GetStringAsync("http://www.wp10454523.server-he.de/truhentimer/getTimes.php");
String rawKillTimes = await getStringTask;
//Parse to Dictionary...
return killTimes;
}
I tried some different Methods I got from google (WebRequest ...), but every one got stuck at the Get-Part. Am I maybe misinterpreting the function? Shouldn't I get the content of the page, which is a simple String?
You have to use await keyword as web request & response in WinRT are asynchronous so you have to use await keyword. await before httpClient.GetStringAsync(...)
Task<string> getStringTask = await httpClient.GetStringAsync("http://www.wp10454523.server-he.de/truhentimer/getTimes.php");