Xamarin Encoding - xamarin

I'm trying to adjust the accent in my code but it's not working, like below:
byte[] nBytes = Encoding.GetEncoding("ISO-8859-1").GetBytes(TagsConvert(texto));
socket.Send(nBytes);
The result is like this in the printer: tri?ngulo, I need the result to be triângulo.
Another previous attempt I made was:
byte[] reset = Encoding.ASCII.GetBytes("\x0A");
byte[] nBytes = Encoding.ASCII.GetBytes(TagsConvert(texto));
socket.Send(nBytes);
socket.Send(reset);
I wasn't successful either.

Related

How to encode a repeated google.protobuf.any?

I have a message and I would like to package it into an any repeated google proto type::
Is there a way to encode an repeated any message type?
Can I even use repeated tag with google.protobuf.any?
message Onesensor{
string name=1
string type=2
int32_t reading=3
}
/** Any Message **/
message RepeatedAny{
repeated google.protobuf.any sensors = 1;
}
I am looking for an example, currently using nanopb to encode.
Sure, it is just a regular message.
https://github.com/nanopb/nanopb/tree/master/tests/any_type shows how to encode a single Any message, encoding many is like encoding any array. You'll have a choice between allocating statically, allocating dynamically or using callbacks. Or you can just encode a single subfield at a time into output stream, because concatenating encoded concatenates arrays in protobuf format.
I think I found my issue, I cannot use(repeated tag on the google.protobuf.any, as I would like to append the RepeatedAny messages in the final binary):
message Onesensor{
string name=1
string type=2
int32_t reading=3
}
message RepeatedAny{
repeated google.protobuf.any sensors = 1;
}
Instead I should use something like this:
message Onesensor{
string name=1
string type=2
int32_t reading=3
}
message SensorAny{
google.protobuf.any sensor = 1;
}
message RepeatedAny{
repeated SensorAny sensors = 1;
}
I should not use the repeated tag on the google.protobuf.any, I should be using it on a message that contains the google.protobuf.any instead, so that the protobinary can contain the format (sensors1), (sensors2).....(sensorsN), one or more SensorAny messages.
Below is the sample code, if someone finds this question in the future for nanopb:
/* First encode the SensorAny message by setting the value of the first field,
The first field of this message is of type google.protobuf.any, so it should have
1. sensor.type_url
2. sensor.value
*/
void* pBufAny = calloc(1, sBufSize);
pb_ostream_t ostream_any = pb_ostream_from_buffer(pBufAny, sBufSize);
SensorAny SensorAnyProto = SensorAny_init_default;
SensorAnyProto.has_message = true;
SensorAnyProto.sensor.type_url.arg = "type.googleapis.com/SensorAny.proto";
SensorAnyProto.sensor.type_url.funcs.encode = Proto_encode_string;
ProtoEncodeBufferInfo_t BufInfo = {
.Buffer = pBuf, /* I have already filled and encoded Onesensor message previously as pBuf */
.BufferSize = ostream.bytes_written,
};
SensorAnyProto.sensor.value.funcs.encode = Proto_encode_buffer;
SensorAnyProto.sensor.value.arg = &BufInfo;
pb_encode(&ostream_any, SensorAny_fields, &SensorAnyProto);
free(pBuf);
// Now Use the above encoded Any message buffer pBufAny to set the first repeated field in RepeatedAny
RepeatedAny SensorAnyRepeated = RepeatedAny_init_default;
ProtoEncodeBufferInfo_t AnyBufInfo = {
.Buffer = pBufAny,
.BufferSize = ostream_any.bytes_written,
};
AnyRepeated.sensors.arg=&AnyBufInfo;
AnyRepeated.sensors.funcs.encode = Proto_encode_buffer;
void* pBufAnyRepeated = calloc(1, sBufSize);
pb_ostream_t ostream_repeated = pb_ostream_from_buffer(pBufAnyRepeated, sBufSize);
!pb_encode(&ostream_repeated, RepeatedAny_fields, &AnyRepeated);
free(pBufAny);

getting NegativeByteArraySizeException from ContentResolver's openAssetFileDescriptor method for reading vCardUri. Is there any workaround to fix it?

I am creating a .VCF file for backing up the Contacts. The process of creating and inserting the data get failed because of the FileDescriptor's method getDeclaredLength which returns the size -1 for the length of the vCard-URI which I got from the ContentResolver's openAssetFileDiscritor method.
This is the exact same Question as asked here by Balakrishna Avulapati. but the only problem for asking the same question here is that, the proposed solution is a bit hard for me to understand. which do not salve my problem. The comment by #pskink in the solution of above link could be useful but i am anable to find the full source code, as there is only 1 line provided in the comment.
I am using the fllowing code,
Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_VCARD_URI, lookupKey);
AssetFileDescriptor fd = resolver.openAssetFileDescriptor(uri, "r");
FileInputStream fis = fd.createInputStream();
byte[] b = new byte[(int)fd.getDeclaredLength()];
fis.read(b);
Please give your kind sugestions. Thank you :)
So I figured it out by myself, and I'm posting the answer in case of somebody get the similar problem and stuck for the solution. So the code before byte[] b = new byte[(int)fd.getDeclaredLength()]; is same. Change this line to byte[] buf = readBytes(fis); and the method readBytes(FileInputStream fis) is below.
public byte[] readBytes(InputStream inputStream) throws IOException {
// this dynamically extends to take the bytes you read
ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
// this is storage overwritten on each iteration with bytes
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
// we need to know how may bytes were read to write them to the byteBuffer
int len = 0;
while ((len = inputStream.read(buffer)) != -1) {
byteBuffer.write(buffer, 0, len);
}
// and then we can return your byte array.
return byteBuffer.toByteArray();
}
Hope this help. Cheers

Learning Processing - How do I use saveBytes()?

I'm having trouble with saveBytes(). When I call saveBytes(), it doesn't actually save the bytes into a file, like it should. The file is in the same folder, and is correctly named. The bytes just aren't being written into the file.
Here is my code:
int varOne = 0;
int varTwo = 4;
int varThree = 2;
void setup(){
size(500, 500);
}
void draw(){
saveTheBytes();
}
void saveTheBytes(){
byte[] byteArray = {(byte)varOne, (byte)varTwo, (byte)varThree}
saveBytes("filename.txt", byteArray)
}
Any help is appreciated. Thanks!
Other than the missing semicolons at the end of each statement in saveTheBytes() the code looks legit.
One note: you're overwriting this file multiple times a second in draw(). Maybe you meant to do that once in setup() ?
Double check the filesize of your file: it should be exactly 3 bytes.
These aren't going to be visible in a text editor (as they are ASCII characters NULL, END OF TRANSMISSION and START OF TEXT).
You should see the bytes in a with a hex editor as 0x00 0x04 0x02.
Here's a preview using HexFiend on OSX:

Covert xamarin.image into base 64 format

I need to Convert a xamarin forms image into a base64 format, Can anyone help me with this?
This is how i've being trying to do it, but it doesent work.
var inputStream = signatureImage.Source.GetValue(UriImageSource.UriProperty);
//Getting Stream as a Memorystream
var signatureMemoryStream = inputStream as MemoryStream;
if (signatureMemoryStream == null)
{
signatureMemoryStream = new MemoryStream();
inputStream.CopyTo(signatureMemoryStream);
}
//Adding memorystream into a byte array
var byteArray = signatureMemoryStream.ToArray();
//Converting byte array into Base64 string
base64String = Convert.ToBase64String(byteArray);
"signatureImage" is the image name.
Once you get your file path , you can use the following code that worked for me.
var stream = file.GetStream();
var bytes = new byte [stream.Length];
await stream.ReadAsync(bytes, 0, (int)stream.Length);
string base64 = System.Convert.ToBase64String(bytes);
I found it here
Image is just a control in Xamarin forms to display the image.
It is not something from which you can get your image byte array out.
You will be better of using the Media Plugin and save it to disk. Then load it via memory stream and convert.
You can also use FFImageLoading. It has 2 methods which can be of use for you :
GetImageAsJpgAsync(int quality = 90, int desiredWidth = 0, int desiredHeight = 0)
GetImageAsPngAsync(int desiredWidth = 0, int desiredHeight = 0)
The SO question - Convert Image into byte array in Xamarin.Forms shows how to do it in Platform specific code here.
The forum thread (Convert Image to byte[]) has a good discussion on why you can't get it from the control.
You can do this as below as well
var base64String = Convert.ToBase64String(File.ReadAllBytes(file.Path))

How to decode the image which is a base64 string, in Dart?

I tried to get the image from clipboard when I press ctrl+v on a page, with the code from a gist, which will console.log the image content it gets.
I found the image content is a long base64 string with a special prefix:
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEEAAAAUCAYAAADStFABAAAJHElEQVRYCXVXWXObVxl+Pu2yFsuyLMnxHtdpY8c4pHXptOkEGKBlYDowYXLLLeGSX8D/gBvuErhgmElpJkCZNsswjhPZsbHGJo6Rl1pybMuyZEnWyvsc9xVfMvCOj8457/K8y9k+W5lMpi0EJcuywDn7ZrMJh8OBVqulYsMnT2WqSx3ylWivdnZM6lOPPRuJcpIdQ23IVz2Oyadvl8tlevLUL2XEUFv1Qx2S8lXnjAu4yPhfAdGARJmCaTAMgqS2drkGQrmOKVfHyrP3xFW5vbdj6Jg98eyLoPGTT1KZxklfHDudzk4hyNN8XDqgsT1YBkOi3G5gd8ixBkQHKqMd7SnTADRAlVGXpBjUI6mdYpGvTZNTPcUwhvJjT5oyO5baKJbmx7nZCQrSaDSMQzXQxGhAZXtgylOber1ukqat6qqO4tGeMi0Ie+oQw+6L+vYEFUftdFXZU6Z8xV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3sZ2Bt52N2bGryIR+W98xCQRU3O1UqlUWxNQh6w2HXrl5ke5jPzKCg7X1+WOyBqAUCKJqNwZPZOT5sKsyCtBYiHZiGNfPXXokye2WSsi/9UiDrMrKBd3jF0gPIiexCSiAzNwyD3BS8serNpTmXz6IBGv1qpifWcZ2/vrck3JHSZfc9FIAkPxNzDWPymXpV9ejXoHj7aKzUUyeHNzc20NXFdQnZJPxUAgYBzqSlDvVHZHqVRCVb4Z7CtOGxaAPOqRFJ9j8kOhEDwejzmX9MUgmfjJyYnBUxv604DJ0wIQQ4k6QXkluGAaH/HouyAfdfqtQVsuDmNRHO3Nv9K6LdQRewZHJYIQlA50p5Cvcl4wTFoLRxmDVAfkK3FMPAZHIh5xGbBiaME4Vz/kaSMG9dmTxzHjI5b6JTZt6cvOo402xTZ2ymSvRAGVlBiQBkWeBsTx63rkKRb1mCTn1GMjj8GpHuck9pRrUZRPv4yHRLnGpjyNi3MtDnXteelYMSknkU+b/wD4ldY7nz0NzAAAAABJRU5ErkJggg==
How to decode it to binary? I tried to remove the prefix data:image/png;base64, and use a base64 library to decode the rest into binary, and save it to a image.png file. But the file can't be displayed, with invalid format error.
But if I paste the whole string to http://base64online.org/decode/, it can play the image as well.
The base64 library I used is https://github.com/wstrange/base64, and my code is:
import 'package:base64_codec/base64_codec.dart';
var body = /* the long str above */;
var prefix = "data:image/png;base64,";
var bStr = body.substring(prefix.length);
var bs = Base64Codec.codec.decodeList(bStr.codeUnits);
var file = new File("image.png");
file.writeAsBytesSync(bs);
I don't know where is wrong :(
Try using the crypto package from the Dart SDK. This creates an image.png that opens fine (I believe it's this image... )
library foo;
import 'package:crypto/crypto.dart';
import 'dart:io';
void main() {
var body = "data:image/png;base64,iVBORw0KGgoAAAANSUh... snip";
var prefix = "data:image/png;base64,";
var bStr = body.substring(prefix.length);
var bytes = CryptoUtils.base64StringToBytes(bStr); // using CryptoUtils from Dart SDK
var file = new File("image.png");
file.writeAsBytesSync(bytes);
}
You'll need to add crypto to your pubspec.yaml :
dependencies:
crypto: any
The library linked at https://github.com/wstrange/base64, also notes in the README:
Deprecated
Note: The Dart SDK now includes a Base64 codec with url safe options. Unless you need streaming support, you should use the SDK methods as they are slightly faster.
See CryptoUtils
See also How to native convert string -> base64 and base64 -> string
Decoding as a string and then writing the bytes works:
var prefix = "data:image/png;base64,";
var bStr = body.substring(prefix.length);
var bs = Base64Codec.codec.decodeString(bStr);
var file = new File("image.png");
file.writeAsBytesSync(bs.codeUnits);
The easiest approach is:
import 'dart:convert';
final result = base64Decode(stringValue);

Resources