Invalid Private length Issue - hedera-hashgraph

throw new _BadKeyError.default(`invalid private key length: ${data.length} bytes`);
getting this error while setting up test environment
const { Client } = require("#hashgraph/sdk");
require("dotenv").config();
async function main() {
//Grab your Hedera testnet account ID and private key from your .env file
const myAccountId = process.env.MY_ACCOUNT_ID;
const myPrivateKey = process.env.MY_PRIVATE_KEY;
// If we weren't able to grab it, we should throw a new error
if (myAccountId == null ||
myPrivateKey == null ) {
throw new Error("Environment variables myAccountId and myPrivateKey must be present");
}
// Create our connection to the Hedera network
// The Hedera JS SDK makes this really easy!
const client = Client.forTestnet();
client.setOperator(myAccountId, myPrivateKey);
console.log('success');
client.close();
}
main();
above code i ran and got the error.kindly someone check

The error message given points me to think your private key may be off. Double-check your .env file and ensure you have entered in your private key correctly.

Related

Dart - HTTPClient download file to string

In the Flutter/Dart app that I am currently working on need to download large files from my servers. However, instead of storing the file in local storage what I need to do is to parse its contents and consume it one-off. I thought the best way to accomplish this was by implementing my own StreamConsumer and overriding the relvant methods. Here is what I have done thus far
import 'dart:io';
import 'dart:async';
class Accumulator extends StreamConsumer<List<int>>
{
String text = '';
#override
Future<void> addStream(Stream<List<int>> s) async
{
print('Adding');
//print(s.length);
return;
}
#override
Future<dynamic> close() async
{
print('closed');
return Future.value(text);
}
}
Future<String> fileFetch() async
{
String url = 'https://file.io/bse4moAYc7gW';
final HttpClientRequest request = await HttpClient().getUrl(Uri.parse(url));
final HttpClientResponse response = await request.close();
return await response.pipe(Accumulator());
}
Future<void> simpleFetch() async
{
String url = 'https://file.io/bse4moAYc7gW';
final HttpClientRequest request = await HttpClient().getUrl(Uri.parse(url));
final HttpClientResponse response = await request.close();
await response.pipe(File('sample.txt').openWrite());
print('Simple done!!');
}
void main() async
{
print('Starting');
await simpleFetch();
String text = await fileFetch();
print('Finished! $text');
}
When I run this in VSCode here is the output I get
Starting
Simple done!! //the contents of the file at https://file.io/bse4moAYc7gW are duly saved in the file
sample.txt
Adding //clearly addStream is being called
Instance of 'Future<int>' //I had expected to see the length of the available data here
closed //close is clearly being called BUT
Finished! //back in main()
My understanding of the underlying issues here is still rather limited. My expectation
I had thought that I would use addStream to accumulate the contents being downloaded until
There is nothing more to download at which point close would be called and the program would display exited
Why is addStream showing instance of... rather than the length of available content?
Although the VSCode debug console does display exited this happens several seconds after closed is displayed. I thought this might be an issue with having to call super.close() but not so. What am I doing wrong here?
I was going to delete this question but decided to leave it here with an answer for the benefit of anyone else trying to do something similar.
The key point to note is that the call to Accumulator.addStream does just that - it furnishes a stream to be listened to, no actual data to be read. What you do next is this
void whenData(List<int> data)
{
//you will typically get a sequence of one or more bytes here.
for(int value in data)
{
//accumulate the incoming data here
}
return;
}
function void whenDone()
{
//now that you have all the file data *accumulated* do what you like with it
}
#override
Future<void> addStream(Stream<List<int>> s) async
{
s.listen(whenData,onDone:whenDone);
//you can optionally ahandler for `onError`
}

StackOverflowError while reading file from reactive GridFS

I have a problem with the ReactiveGridFsTemplate. I am trying to read a GridFS file written with the old GridFS (com.mongodb.gridfs) instead of the new GridFS (com.mongodb.client.gridfs.model.GridFS) with an UUID as an ID instead of the ObjectId. Reading the GridFS file metainfo goes fine, but as soon as I want to get the ReactiveGridFsResource it blows with a nice new MongoGridFSException("Custom id type used for this GridFS file").
The culprit is the code below from ReactiveGridFsTemplate which calls the getObjectId() instead of the getId(). Should it call this method or can that be rewritten to the getId() method?
public Mono<ReactiveGridFsResource> getResource(GridFSFile file) {
Assert.notNull(file, "GridFSFile must not be null!");
return Mono.fromSupplier(() -> {
GridFSDownloadStream stream = this.getGridFs().openDownloadStream(file.getObjectId());
return new ReactiveGridFsResource(file, BinaryStreamAdapters.toPublisher(stream, this.dataBufferFactory));
});
}
I hacked the ReactiveGridFsTemplate to use getId() instead of getObjectId() but now it gives me a stackoverflow exception. Can someone tell me what I'm doing wrong?
ReactiveGridFsTemplate reactiveGridFsTemplate = new ReactiveGridFsTemplate(mongoDbDFactory, operations.getConverter(), "nl.loxia.collectie.buitenlandbladen.dgn", 1024) {
public Mono<ReactiveGridFsResource> getResource(GridFSFile file) {
Assert.notNull(file, "GridFSFile must not be null!");
return Mono.fromSupplier(() -> {
GridFSDownloadStream stream = this.getGridFs().openDownloadStream(file.getId());
return new ReactiveGridFsResource(file, BinaryStreamAdapters.toPublisher(stream, this.dataBufferFactory));
});
}
};
var q = Query.query((Criteria.where("_id").is("5449d9e3-7f6d-47b7-957d-056842f190f7")));
List<DataBuffer> block = reactiveGridFsTemplate
.findOne(q)
.flatMap(reactiveGridFsTemplate::getResource)
.flux()
.flatMap(ReactiveGridFsResource::getDownloadStream)
.collectList()
.block();
The stacktrace: https://gist.github.com/nickstolwijk/fa77681572db1d91941d85f6c845f2f4
Also, this code hangs due to the stackoverflow exception. Is that correct?

Firebase Unity - Get all children into an array/generic list after GetValueAsync?

How can I get data back as an array or generic list from a Firebase database in Unity3D without knowing ahead of time what the name (key) of the children are?
I have been trying out the new Unity Firebase plugin, and I am having an issue figuring out how to get all the children in a specific location, and put the names (the key) and the values into arrays or generic lists so that I can work on the data locally. Forgive me for being so new to Firebase and probably using bad techniques to do this, and this plugin being so new its pretty hard for me to get much outside help, as there are not a lot of docs and tutorials out there on Firebase Unity.
In this particular case I am trying to create "instant messaging" like functionality, without the use of Firebase messaging, and just using regular Firebase database stuff instead. It might have been easier to use Firebase messaging, but mostly for the sake of learning and customization I want to do this on my own with just the Firebase database.
I insert data into the database like this:
public void SendMessage(string toUser, string msg)
{
Debug.Log(String.Format("Attempting to send message from {0} to {1}", username, toUser));
DatabaseReference reference = FirebaseDatabase.DefaultInstance.GetReference("Msgs");
string date = Magnet.M.GetCurrentDate();
// send data to the DB
reference.Child(toUser).Child(username).Child(date).SetValueAsync(msg);
// user receiving message / user sending message > VALUE = "hello dude|20170119111325"
UpdateUsers();
}
And then I try and get it back like this:
public string[] GetConversation(string userA, string userB)
{
// get a conversation between two users
string[] convo = new string[0];
FirebaseDatabase.DefaultInstance.GetReference("Msgs").GetValueAsync().ContinueWith(task =>
{
Debug.Log("Getting Conversation...");
if (task.IsFaulted || task.IsCanceled)
{
Debug.LogError("ERROR: Task error in GetConversation(): " + task.Exception);
}
else if (task.IsCompleted)
{
DataSnapshot snapshot = task.Result;
string[] messagesA = new string[0], messagesB = new string[0];
if(snapshot.HasChild(userA))
{
// userA has a record of a conversation with other users
if(snapshot.Child(userA).HasChild(userB)) // userB has sent messages to userA before
{
Debug.Log("Found childA");
long count = snapshot.Child(userA).Child(userB).ChildrenCount;
messagesA = new string[count];
var kids = snapshot.Child(userA).Child(userB).Children;
Debug.Log(kids);
for (int i = 0; i < count; i++)
{
// this won't work, but is how I would like to access the data
messagesA[i] = kids[i].Value.ToString(); // AGAIN.... will not work...
}
}
}
if(snapshot.HasChild(userB))
{
if(snapshot.Child(userB).HasChild(userA)) // userA sent a message to userB before
{
Debug.Log("Found childB");
long count = snapshot.Child(userB).Child(userA).ChildrenCount;
messagesA = new string[count];
var kids = snapshot.Child(userB).Child(userA).Children;
Debug.Log(kids);
// messy incomplete testing code...
}
}
// HERE I WOULD ASSIGN ALL THE MESSAGES BETWEEN A AND B AS 'convo'...
}
Debug.Log("Done Getting Conversation.");
});
return convo;
}
But obviously this won't work, because DataSnapshot won't let me access it like an array or generic list using indices, and I can't figure out how to treat the data when I don't know the names (the keys) of all the children, and just want to get them out one by one in any order... and since they are named by the date/time they are entered into the DB, I won't know ahead of time what the childrens names (keys) are, and I can't just say "GetChild("20170101010101")" because that number is generated when its sent to the DB from any client.
FYI here is what the DB looks like:
Figured out the answer to your question. Here's my code snippet. Hope this would help!
void InitializeFirebase() {
FirebaseApp app = FirebaseApp.DefaultInstance;
app.SetEditorDatabaseUrl ("https://slol.firebaseio.com/");
FirebaseDatabase.DefaultInstance
.GetReference ("Products").OrderByChild ("category").EqualTo("livingroom")
.ValueChanged += (object sender2, ValueChangedEventArgs e2) => {
if (e2.DatabaseError != null) {
Debug.LogError (e2.DatabaseError.Message);
}
if (e2.Snapshot != null && e2.Snapshot.ChildrenCount > 0) {
foreach (var childSnapshot in e2.Snapshot.Children) {
var name = childSnapshot.Child ("name").Value.ToString ();
text.text = name.ToString();
Debug.Log(name.ToString());
//text.text = childSnapshot.ToString();
}
}
};
}
Firebase developer here.
Have you tried to use Value at the top level Snapshot? It should return to you an IDictionary where the values can also be lists or nested dictionaries. You will have to use some dynamic inspection to figure out what the values are.

Windows 8 StorageFile.GetFileFromPathAsync Using UNC Path

Has anyone EVER managed to use a windows 8 app to copy files from a unc dir to a local dir ?
According to the official documentation here
It is possible to connect to a UNC path
I am using the std FILE ACCESS sample and have changed one line of code to read as below
I have added all the capabilities
Added .txt as a file type
The UNC path is read write to everyone and is located on the same machine..
But I keep getting Access Denied Errors.
Can anyone possibly provide me with a working example
This is driving me mad and really questioning the whole point of win 8 dev for LOB apps.
TIA
private async void Initialize()
{
try
{
//sampleFile = await Windows.Storage.KnownFolders.DocumentsLibrary.GetFileAsync(filename);
string myfile = #"\\ALL387\Temp\testfile.txt";
sampleFile = await Windows.Storage.StorageFile.GetFileFromPathAsync(myfile);
}
catch (FileNotFoundException)
{
// sample file doesn't exist so scenario one must be run
}
catch (Exception e)
{
var fred = e.Message;
}
}
I have sorted this out and the way I found best to do it was to create a folder object
enumnerate over the files in the folder object
copy the files one at a time to the local folder then access them
It seems that you can't open the files, but you can copy them. ( which was what I was trying to achieve in the first place )
Hope this helps
private async void Initialize()
{
try
{
var myfldr = await Windows.Storage.StorageFolder.GetFolderFromPathAsync(#"\\ALL387\Temp");
var myfiles = await myfldr.GetFilesAsync();
foreach (StorageFile myfile in myfiles)
{
StorageFile fileCopy = await myfile.CopyAsync(KnownFolders.DocumentsLibrary, myfile.Name, NameCollisionOption.ReplaceExisting);
}
var dsd = await Windows.Storage.KnownFolders.PicturesLibrary.GetFilesAsync();
foreach (var file in dsd)
{
StorageFile sampleFile = await Windows.Storage.StorageFile.GetFileFromPathAsync(file.Path);
}
}
catch (FileNotFoundException)
{
// sample file doesn't exist so scenario one must be run
}
catch (Exception e)
{
var fred = e.Message;
}
}

Database problem: how to diagnose and fix the problem?

I created an application which stores values into the database and retrieves the stored data. While running an application in run mode everything seems to work fine (the values are stored and retrieved successfully) but when I run in the debug mode the process throws IllegalStateException and so far haven't found a cause.
The method which retrieves an object Recording is the following:
public Recording getRecording(String filename) {
Recording recording = null;
String where = RECORDING_FILENAME + "='" + filename + "'";
Log.v(TAG, "retrieving recording: filename = " + filename);
try {
cursor = db.query(DATABASE_TABLE_RECORDINGS, new String[]{RECORDING_FILENAME, RECORDING_TITLE, RECORDING_TAGS, RECORDING_PRIVACY_LEVEL, RECORDING_LOCATION, RECORDING_GEO_TAGS, RECORDING_GEO_TAGGING_ENABLED, RECORDING_TIME_SECONDS, RECORDING_SELECTED_COMMUNITY}, where, null, null, null, null);
if (cursor.getCount() > 0) {
cursor.moveToFirst();
//String filename = c.getString(0);
String title = cursor.getString(1);
String tags = cursor.getString(2);
int privacyLevel = cursor.getInt(3);
String location = cursor.getString(4);
String geoTags = cursor.getString(5);
int iGeoTaggingEnabled = cursor.getInt(6);
String recordingTime = cursor.getString(7);
String communityID = cursor.getString(8);
cursor.close();
recording = new Recording(filename, title, tags, privacyLevel, location, geoTags, iGeoTaggingEnabled, recordingTime, communityID);
}
}
catch (SQLException e) {
String msg = e.getMessage();
Log.w(TAG, msg);
recording = null;
}
return recording;
}
and it is called from another class (Settings):
private Recording getRecording(String filename) {
dbAdapter = dbAdapter.open();
Recording recording = dbAdapter.getRecording(filename);
dbAdapter.close();
return recording;
}
While running through the code above everything works fine but then I notice an exception in another thread:
alt text http://img509.imageshack.us/img509/862/illegalstateexception.jpg
and don't know neither what is the possible cause of this exception nor how to debug the code from that thread to diagnose the cause.
I would be very thankful if anyone knew what is the possible issue here.
Thank you!
Looks like that cursor.close() is inside an "if" - that's when SQLiteCursor.finalize() will throw an IllegalStateException (I googled for it). You migh be getting an empty recordset, for instance, if some other process/thread didn't have the time to commit.
Close it always, even if it's result set is empty.
I'd also advice you to access fields by names, not indices, for future compatibility. And do both close()s in finally{} blocks.

Resources