How to backup/restore SQLite database in React native - sqlite

I am using andpor/react-native-sqlite-storage for managing SQLite database in React native. Now I want to backup all my database into a encrypted file then restore this at later time. I know how to do this in android but don't know how to implement this in react native.
if it is in android below code can help me to backup the database without encryption.
final String inFileName = "/data/data/<your.app.package>/databases/foo.db";
File dbFile = new File(inFileName);
FileInputStream fis = new FileInputStream(dbFile);
String outFileName = Environment.getExternalStorageDirectory()+"/database_copy.db";
// Open the empty db as the output stream
OutputStream output = new FileOutputStream(outFileName);
// Transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = fis.read(buffer))>0){
output.write(buffer, 0, length);
}
// Close the streams
output.flush();
output.close();
fis.close();
So my question is how I can do this on React Native. If there any libraries available please suggest to me.

Same approach can be followed in react-native too using react-native-fs package.
import RNFS from 'react-native-fs';
RNFS.readFile("/data/data/<your.app.package>/databases/foo.db", "base64")
.then(value => RNFS
.getAllExternalFilesDirs()
.then(path => RNFS.writeFile(path + "/" + "database_copy.db", value, "base64"))
.then(() => console.log("Successful"))
)

Here is what I did:
import DocPicker from 'react-native-document-picker'
import RNFS from 'react-native-fs'
async function restoreDB() {
try {
const rsPicker = await DocPicker.pickSingle()
const filePath = rsPicker.uri
await RNFS.copyFile(filePath, '/data/data/<your.app.package>/databases/foo.db')
msgInfo('Success Restore Database');
} catch (e) {
msgError(e)
}
}
async function backupDB() {
try {
const currDate = format(new Date(), 'dd_MM_yyyy_HHmmss')
const destPath = RNFS.ExternalStorageDirectoryPath + 'foo_' + currDate + '.db'
await RNFS.copyFile('/data/data/<your.app.package>/databases/foo.db',
destPath)
msgInfo('Success Backup Database');
} catch (e) {
msgError(e)
}
}

Related

Download multiple files (50mb) blazor server-side

i can't really find a way to download a 100mb zip file from the server to the client and also show the progress while downloading. So how will this look for a normal api controller i can add to my server-side project? if lets say i have 3 files i want to download at 50mb each.
i have tried using JSInterop like this, but this is not showing the progress of the file download, and how will i do if i want to download 3 seperate files at the same time?
try
{
//converting file into bytes array
var dataBytes = System.IO.File.ReadAllBytes(file);
await JSRuntime.InvokeVoidAsync(
"downloadFromByteArray",
new
{
ByteArray = dataBytes,
FileName = "download.zip",
ContentType = "application/force-download"
});
}
catch (Exception)
{
//throw;
}
JS:
function downloadFromByteArray(options: {
byteArray: string,
fileName: string,
contentType: string
}): void {
// Convert base64 string to numbers array.
const numArray = atob(options.byteArray).split('').map(c => c.charCodeAt(0));
// Convert numbers array to Uint8Array object.
const uint8Array = new Uint8Array(numArray);
// Wrap it by Blob object.
const blob = new Blob([uint8Array], { type: options.contentType });
// Create "object URL" that is linked to the Blob object.
const url = URL.createObjectURL(blob);
// Invoke download helper function that implemented in
// the earlier section of this article.
downloadFromUrl({ url: url, fileName: options.fileName });
// At last, release unused resources.
URL.revokeObjectURL(url);
}
UPDATE:
if im using this code, it will show me the progress of the file. But how can i trigger it from my code? This way does not do it. But typing the url does.
await Http.GetAsync($"Download/Model/{JobId}");
Controller
[HttpGet("download/model/{JobId}")]
public IActionResult DownloadFile([FromRoute] string JobId)
{
if (JobId == null)
{
return BadRequest();
}
var FolderPath = $"xxxx";
var FileName = $"Model_{JobId}.zip";
var filePath = Path.Combine(environment.WebRootPath, FolderPath, FileName);
byte[] fileBytes = System.IO.File.ReadAllBytes(filePath);
return File(fileBytes, "application/force-download", FileName);
}
UPDATE 2!
i have got it download with progress and click with using JSInterop.
public async void DownloadFiles()
{
//download all selectedFiles
foreach (var file in selectedFiles)
{
//download these files
await JSRuntime.InvokeAsync<object>("open", $"Download/Model/{JobId}/{file.Name}", "_blank");
}
}
Now the only problem left is.. it only downloads the first file out of 3.

Android camera photo should not store in device and SD card

I am using Xamarin Android application, Using crossplugi,.device info to taking the photo, as per the requirement I need to strore image in DB not in the devices.
public async void ExecuteCameraCommand()
{
int iCount = 0;
if (!CrossMedia.Current.IsCameraAvailable || !CrossMedia.Current.IsTakePhotoSupported)
{
// await _dialogService.DisplayAlertAsync("No Camera", ":( No camera available.", "OK");
return;
}
iCount = iCount + 1;
var file = await CrossMedia.Current.TakePhotoAsync(new Plugin.Media.Abstractions.StoreCameraMediaOptions
{
SaveToAlbum = false,
});
if (file == null)
return;
}
The file object has a GetStream method. You can use this to get the data and then save it to the database. Something like this:
Stream fileStream = file.GetStream();
byte[] buffer = new byte[fileStream.Length];
fileStream.Read(buffer, 0, (int)fileStream.Length);
//Save to the database
I assume you are storing the photos locally on the device in something like a SQLite database. Bear in mind the photos can be several megabytes in size. When I did this I stored the photos on the file system on the device and saved a record in the database of their path and name to avoid bloating the database.

How to upload a PDF in firebase using flutter?

I am new to flutter and firebase,I want to upload PDF into firebase using flutter please help me to solve this by providing some resources or links..
Thanks in advance.
You can use this dependency https://pub.dev/packages/file_picker to upload any kind of file to database.
final mainReference = FirebaseDatabase.instance.reference().child('Database');
Future getPdfAndUpload()async{
var rng = new Random();
String randomName="";
for (var i = 0; i < 20; i++) {
print(rng.nextInt(100));
randomName += rng.nextInt(100).toString();
}
File file = await FilePicker.getFile(type: FileType.CUSTOM, fileExtension: 'pdf');
String fileName = '${randomName}.pdf';
print(fileName);
print('${file.readAsBytesSync()}');
savePdf(file.readAsBytesSync(), fileName);
}
Future savePdf(List<int> asset, String name) async {
StorageReference reference = FirebaseStorage.instance.ref().child(name);
StorageUploadTask uploadTask = reference.putData(asset);
String url = await (await uploadTask.onComplete).ref.getDownloadURL();
print(url);
documentFileUpload(url);
return url;
}
void documentFileUpload(String str) {
var data = {
"PDF": str,
};
mainReference.child("Documents").child('pdf').set(data).then((v) {
});
}
By this you can upload file to firebase storage and insert the url to realtime database.

Getting 403 error when trying to retrieve an Azure blob on Web API request

I am trying to have an authenticated (by JWT) GET request return an image stored in an Azure blob. When I run the project on my local machine and use postman to request an image and the request goes through and I do get the image I requested. However, once I deploy the code to Azure and hit the same endpoint I get a 403. The code fails at the line in which I try to invoke DownloadToStreamAsync. Here is the code I'm using:
public async Task<BlobDownloadModel> DownloadBlob(Guid blobId)
{
try
{
//get picture record
Picture file = await _media.GetPictureAsync(blobId);
await _log.CreateLogEntryAsync("got picture record");
// get string format blob name
var blobName = file.PictureId.ToString() + file.Extension;
await _log.CreateLogEntryAsync("got name of blob " + blobName);
if (!String.IsNullOrEmpty(blobName))
{
await _log.CreateLogEntryAsync("blob not empty");
var blob = _container.GetBlockBlobReference(blobName);
await _log.CreateLogEntryAsync("got blob: " + blob.ToString());
var ms = new MemoryStream();
await blob.DownloadToStreamAsync(ms);
await _log.CreateLogEntryAsync("blob downloaded to memory stream");
var lastPos = blob.Name.LastIndexOf('/');
var fileName = blob.Name.Substring(lastPos + 1, blob.Name.Length - lastPos - 1);
var download = new BlobDownloadModel
{
BlobStream = ms,
BlobFileName = fileName,
BlobLength = blob.Properties.Length,
BlobContentType = blob.Properties.ContentType
};
return download;
}
}
catch(Exception ex)
{
await _log.CreateLogEntryAsync("exception thrown: " + ex.ToString());
}
I would greatly appreciate any help I can get.
UPDATE:
I changed my code to this and tried again:
public async Task<AzureBlobModel> DownloadBlob(Guid blobId)
{
try
{
//get picture record
Picture file = await _media.GetPictureAsync(blobId);
await _log.CreateLogEntryAsync("got picture record");
// get string format blob name
var blobName = file.PictureId.ToString() + file.Extension;
await _log.CreateLogEntryAsync("got name of blob " + blobName);
if (!String.IsNullOrEmpty(blobName))
{
await _log.CreateLogEntryAsync("blob not empty");
var blob = _container.GetBlockBlobReference(blobName);
await _log.CreateLogEntryAsync("got blob: " + blob.ToString());
// Strip off any folder structure so the file name is just the file name
var lastPos = blob.Name.LastIndexOf('/');
var fileName = blob.Name.Substring(lastPos + 1, blob.Name.Length - lastPos - 1);
await _log.CreateLogEntryAsync("got fileName: " + fileName);
//await blob.DownloadToStreamAsync(ms);
await _log.CreateLogEntryAsync("about to open read stream");
var stream = await blob.OpenReadAsync();
await _log.CreateLogEntryAsync("opened read stream");
var result = new AzureBlobModel()
{
FileName = fileName,
FileSize = blob.Properties.Length,
Stream = stream,
ContentType = blob.Properties.ContentType
};
await _log.CreateLogEntryAsync("blob downloaded to memory stream");
return result;
// Build and return the download model with the blob stream and its relevant info
//var download = new BlobDownloadModel
//{
// BlobStream = ms,
// BlobFileName = fileName,
// BlobLength = blob.Properties.Length,
// BlobContentType = blob.Properties.ContentType
//};
//return download;
}
}
catch(Exception ex)
{
await _log.CreateLogEntryAsync("exception thrown: " + ex.ToString());
}
await _log.CreateLogEntryAsync("returning null");
// Otherwise
return null;
}
the results from the log for the last try is this:
request received and authenticated, timestamp UTC: 3/10/2017 5:28:26 AM - 5:28:26 AM
id received: b3bc7faf-0c86-4ce2-af84-30636825a485 - 5:28:27 AM
got picture record -5:28:27 AM
got name of blob b3bc7faf-0c86-4ce2-af84-30636825a485.JPG - 5:28:27 AM
blob not empty - 5:28:27 AM
got blob: Microsoft.WindowsAzure.Storage.Blob.CloudBlockBlob - 5:28:27 AM
got fileName: b3bc7faf-0c86-4ce2-af84-30636825a485.JPG - 5:28:27 AM
about to open read stream - 5:28:27 AM
I was able to retrieve the name of the file/blob which eliminates an incorrect account key as the culprit of the issue.
SOLUTION
I was able to get my code to work with the following code:
public async Task<AzureBlobModel> DownloadBlob(Guid blobId)
{
try
{
//get picture record
Picture file = await _media.GetPictureAsync(blobId);
// get string format blob name
var blobName = file.PictureId.ToString() + file.Extension;
if (!String.IsNullOrEmpty(blobName))
{
var blob = _container.GetBlockBlobReference(blobName);
// Strip off any folder structure so the file name is just the file name
var lastPos = blob.Name.LastIndexOf('/');
var fileName = blob.Name.Substring(lastPos + 1, blob.Name.Length - lastPos - 1);
var fileLength = blob.Properties.Length;
var stream = await blob.OpenReadAsync();
var result = new AzureBlobModel()
{
FileName = fileName,
FileSize = blob.Properties.Length,
Stream = stream,
ContentType = blob.Properties.ContentType
};
return result;
}
}
catch(Exception ex)
{
await _log.CreateLogEntryAsync("exception thrown: " + ex.ToString());
}
await _log.CreateLogEntryAsync("returning null");
// Otherwise
return null;
}
However, once I deploy the code to Azure and hit the same endpoint I get a 403.
Firstly, please check your Azure account and key to ensure they are correct. Secondly, please check the clock on the server. The storage services ensure that a request is no older than 15 minutes by the time it reaches the service. if the time on your server is not sync with storage server, it will give your 403 error.
I was able to solve the problem by using the following code:
public async Task<AzureBlobModel> DownloadBlob(Guid blobId)
{
try
{
//get picture record
Picture file = await _media.GetPictureAsync(blobId);
// get string format blob name
var blobName = file.PictureId.ToString() + file.Extension;
if (!String.IsNullOrEmpty(blobName))
{
var blob = _container.GetBlockBlobReference(blobName);
// Strip off any folder structure so the file name is just the file name
var lastPos = blob.Name.LastIndexOf('/');
var fileName = blob.Name.Substring(lastPos + 1, blob.Name.Length - lastPos - 1);
var fileLength = blob.Properties.Length;
var stream = await blob.OpenReadAsync();
var result = new AzureBlobModel()
{
FileName = fileName,
FileSize = blob.Properties.Length,
Stream = stream,
ContentType = blob.Properties.ContentType
};
return result;
}
}
catch(Exception ex)
{
await _log.CreateLogEntryAsync("exception thrown: " + ex.ToString());
}
await _log.CreateLogEntryAsync("returning null");
// Otherwise
return null;
}

I get invalidRequest Exception thrown: 'Microsoft.Graph.ServiceException' in mscorlib.ni.dll

I am integrating Onedrive SDK with the UWP part of my Xamarin App. Once I press the download button I get the Onedrive signin page but it throws the above error in this line:
try
{
var appFolder = await OneDriveClient.Drive.Special.AppRoot.Request().GetAsync();
Debug.WriteLine(appFolder.Name);
}
catch (ServiceException e )
{
Debug.WriteLine(e.Message +" " + e.Error.Code);
}
here is the full relevant code:
public async Task Download(string filename)
{
//AccountSelectionLoaded();
await InitializeClient();
try
{
var appFolder = await OneDriveClient.Drive.Special.AppRoot.Request().GetAsync();
Debug.WriteLine(appFolder.Name);
}
catch (ServiceException e )
{
Debug.WriteLine(e.Message +" " + e.Error.Code);
}
var file = await OneDriveClient.Drive.Special.AppRoot.Children[filename].Content.Request().GetAsync();
//var fileStream = await fileBuilder.Content.Request().GetAsync();
IStorageFile appFile = await ApplicationData.Current.LocalFolder.CreateFileAsync("test.db3",
CreationCollisionOption.OpenIfExists);
byte[] fileBytes;
using (DataReader reader = new DataReader(file.AsInputStream()))
{
fileBytes = new byte[file.Length];
await reader.LoadAsync((uint)file.Length);
reader.ReadBytes(fileBytes);
}
Debug.WriteLine(fileBytes.Length);
Debug.WriteLine("Writing");
await FileIO.WriteBytesAsync(appFile, fileBytes);
Debug.WriteLine("End of writing");
}
private async Task InitializeClient()
{
if (OneDriveClient == null)
{
Task authTask;
var msaAuthProvider = new MsaAuthenticationProvider(oneDriveConsumerClientId,oneDriveConsumerReturnUrl,scopes);
await msaAuthProvider.AuthenticateUserAsync();
OneDriveClient = new OneDriveClient(oneDriveConsumerBaseUrl, msaAuthProvider);
AuthenticationProvider = msaAuthProvider;
}
}
Thank you for reporting this issue. Indeed, we can see a associated issue using OneDrive .NET SDK 2.0.4 in a UWP app
I will report this issue through internal way.
As a workaround, please see this blog: Windows 10 - Implementing a UWP App with the Official OneDrive SDK
Laurent Bugnion described the detailed steps(and also a demo) to enable OneDrive features in a UWP app.
private IOneDriveClient _client;
public MainPage()
{
InitializeComponent();
AuthenticateButton.Click += async (s, e) =>
{
var scopes = new[]
{
"onedrive.readwrite",
"onedrive.appfolder",
"wl.signin"
};
_client = OneDriveClientExtensions.GetClientUsingOnlineIdAuthenticator(
_scopes);
var session = await client.AuthenticateAsync();
Debug.WriteLine($"Token: {session.AccessToken}");
};
}
At that time, the project is using 1.2.0 SDK which is still working now.

Resources