Why am I getting Zxing.Mobile.MobileBarcodeScanner( ) constructor error? - xamarin.android

I am using Zxing.Mobile to scan a barcode in my monodroid app. I am using Xamarin. According to their documentation following line of code should work:
var scanner = new ZXing.Mobile.MobileBarcodeScanner();
scanner.Scan().ContinueWith(t => {
if (t.Result != null)
Console.WriteLine("Scanned Barcode: " + t.Result.Text);
});
But i am getting following error:
The type 'Zxing.Mobile.MobileBarcodeScanner()' does not contain a constructor that takes '0' arguments
Any idea why am i getting this error and how can i get rid of it? Thanks in advance.

You need to provide the Context, as mentioned above, he just didn't put the context into the constructor. Heh. Hence causing confusion.
var scanner = new ZXing.Mobile.MobileBarcodeScanner(this.Context);
scanner.Scan().ContinueWith(t => {
if (t.Result != null)
Console.WriteLine("Scanned Barcode: " + t.Result.Text);
});`

This works for me
async void HandleBarcodeButtonClick(object sender, EventArgs e)
{
var scanner = new ZXing.Mobile.MobileBarcodeScanner(this);
string barcode = string.Empty;
await scanner.Scan().ContinueWith(t =>
{
if (t.Result != null)
barcode = t.Result.Text;
});
}

The constructor needs more than 0 arguments. From here:
//NOTE: On Android you MUST pass a Context into the Constructor!
var scanner = new ZXing.Mobile.MobileBarcodeScanner();
scanner.Scan().ContinueWith(t => {
if (t.Result != null)
Console.WriteLine("Scanned Barcode: " + t.Result.Text);
});

Related

How fix this null check issue?

Dart Language:
This is plugin issue
xmpp_stone plugin
I can't fix this issue
anyone known please replay
[![enter image description here]
https://i.stack.imgur.com/FHe0O.png
Dart Language:
This is plugin issue
xmpp_stone plugin
I can't fix this issue
anyone known please replay
[![enter image description here]
https://i.stack.imgur.com/FHe0O.png
This is full code issue in xmpp_stone plugin
import 'dart:io';
import 'package:xmpp_stone/src/logger/Log.dart';
import 'package:console/console.dart';
import 'dart:async';
import 'dart:convert';
import 'package:xmpp_stone/xmpp_stone.dart' as xmpp;
import 'package:image/image.dart' as image;
final String TAG = 'example';
class ExampleConnectionStateChangedListener implements xmpp.ConnectionStateChangedListener {
late xmpp.Connection _connection;
late xmpp.MessagesListener _messagesListener;
StreamSubscription<String>? subscription;
ExampleConnectionStateChangedListener(xmpp.Connection connection, xmpp.MessagesListener messagesListener) {
_connection = connection;
_messagesListener = messagesListener;
_connection.connectionStateStream.listen(onConnectionStateChanged);
}
#override
void onConnectionStateChanged(xmpp.XmppConnectionState state) {
if (state == xmpp.XmppConnectionState.Ready) {
Log.d(TAG, 'Connected');
_connection.getMamModule().queryAll();
var vCardManager = xmpp.VCardManager(_connection);
vCardManager.getSelfVCard().then((vCard) {
if (vCard != null) {
Log.d(TAG, 'Your info' + vCard.buildXmlString());
}
});
var messageHandler = xmpp.MessageHandler.getInstance(_connection);
var rosterManager = xmpp.RosterManager.getInstance(_connection);
messageHandler.messagesStream.listen(_messagesListener.onNewMessage);
sleep(const Duration(seconds: 1));
var receiver = 'yyy#gmail.com';
var receiverJid = xmpp.Jid.fromFullJid(receiver);
rosterManager.addRosterItem(xmpp.Buddy(receiverJid)).then((result) {
if (result.description != null) {
print("TAG, 'add roster'" + result.description!);
}
});
sleep(const Duration(seconds: 1));
vCardManager.getVCardFor(receiverJid).then((vCard) {
if (vCard != null) {
print("TAG, 'Receiver info'" + vCard.buildXmlString());
if (vCard != null && vCard.image != null) {
var file = File('test456789.jpg')..writeAsBytesSync(image.encodeJpg(vCard.image!));
print("TAG, IMAGE SAVED TO: ${file.path}");
}
}
});
var presenceManager = xmpp.PresenceManager.getInstance(_connection);
presenceManager.presenceStream.listen(onPresence);
}
}
void onPresence(xmpp.PresenceData event) {
Log.d(TAG, 'presence Event from ' + event.jid!.fullJid! + ' PRESENCE: ' + event.showElement.toString());
}
}
Stream<String> getConsoleStream() {
return Console.adapter.byteStream().map((bytes) {
var str = ascii.decode(bytes);
str = str.substring(0, str.length - 1);
return str;
});
}
class ExampleMessagesListener implements xmpp.MessagesListener {
#override
void onNewMessage(xmpp.MessageStanza? message) {
if (message!.body != null) {
Log.d(TAG ,format(
'New Message from {color.blue}${message.fromJid!.userAtDomain}{color.end} message: {color.red}${message.body}{color.end}'));
}
}
#override
void onChatMessage(xmpp.MessageStanza? message) {
print(message);
if (message!.body != null) {
Log.d(TAG,format(
'New Message from {color.blue}${message.fromJid!.userAtDomain}{color.end} message: {color.red}${message.body}{color.end}'));
}
}
}
sendmessageforxmpp(){
var userAtDomain = 'xxx#gmail.com';
var password = 'password';
var jid = xmpp.Jid.fromFullJid(userAtDomain);
var account = xmpp.XmppAccountSettings(userAtDomain, jid.local,
jid.domain, password, 5222, resource: 'xmppstone');
var connection = xmpp.Connection(account);
var receiver = 'yyy#gmail.com';
var receiverJid = xmpp.Jid.fromFullJid(receiver);
Log.d(TAG, receiverJid.fullJid.toString());
var messageHandler =
xmpp.MessageHandler.getInstance(connection);
messageHandler.sendMessage(receiverJid, "str");
}
Your problem is that you are not using xmpp_stone correctly and therefore ends up in a situation where the internal state of xmpp_stone does not match what the developer of the package have intended.
I do, however, think the package are badly designed in such a way that wrong usage are very likely to happen so I would not blame you for getting into trouble.
The problem is the following in your code:
var connection = xmpp.Connection(account);
// ..
var messageHandler = xmpp.MessageHandler.getInstance(connection);
messageHandler.sendMessage(receiverJid, "str");
You are here creating a Connection but the underlying socket are never created. The default value for the internal state of Connection are XmppConnectionState.Idle. But when you are later trying to sendMessage, your code ends up running this from the package:
void write(message) {
Log.xmppp_sending(message);
if (isOpened()) {
_socket!.write(message);
}
}
bool isOpened() {
return state != XmppConnectionState.Closed &&
state != XmppConnectionState.ForcefullyClosed &&
state != XmppConnectionState.Closing &&
state != XmppConnectionState.SocketOpening;
}
The isOpened() ends up returning true since it sees XmppConnectionState.Idle as an open state where messages are allowed to be sent.
But that is not the case here since we never asked Connection to open actually do any connection and therefore _socket ends up being null. Since the package are trying to do ! on null, the application crashes.
For an actual solution, we can get inspired from the example implementation from xmpp_dart:
https://github.com/vukoye/xmpp_dart/blob/master/example/example.dart
We can here see they have a connection.connect(); call. But, I am going to guess this really only works because the example are not going to use the connection right after this call. The problem is that it is implemented like the following:
void connect() {
if (_state == XmppConnectionState.Closing) {
_state = XmppConnectionState.WouldLikeToOpen;
}
if (_state == XmppConnectionState.Closed) {
_state = XmppConnectionState.Idle;
}
if (_state == XmppConnectionState.Idle) {
openSocket();
}
}
Future<void> openSocket() async {
connectionNegotatiorManager.init();
setState(XmppConnectionState.SocketOpening);
try {
return await Socket.connect(account.host ?? account.domain, account.port)
.then((Socket socket) {
// if not closed in meantime
if (_state != XmppConnectionState.Closed) {
setState(XmppConnectionState.SocketOpened);
So connect() returns void but calls openSocket() which does return a Future that would be able to tell us when the connection are actually ready.
I would therefore instead suggest using openSocket() directly and make your sendmessageforxmpp() method async so we can await on the connection being open.
So your code should look like:
Future<void> sendmessageforxmpp() async {
var userAtDomain = 'xxx#gmail.com';
var password = 'password';
var jid = xmpp.Jid.fromFullJid(userAtDomain);
var account = xmpp.XmppAccountSettings(
userAtDomain, jid.local, jid.domain, password, 5222,
resource: 'xmppstone');
var connection = xmpp.Connection(account);
await connection.openSocket(); // <--- the important change :)
var receiver = 'yyy#gmail.com';
var receiverJid = xmpp.Jid.fromFullJid(receiver);
Log.d(TAG, receiverJid.fullJid.toString());
var messageHandler = xmpp.MessageHandler.getInstance(connection);
messageHandler.sendMessage(receiverJid, "str");
}
This error is usually occurring when you use the bang operator (!) on a nullable value that was not properly initialized, like
yourvariable!.somefield
The above assumes that yourvariable will not be null as this point. If it's null, then reality is in conflict with the assumption I have just described.

Xamarin set Cookies in Multiplatform iOS app using (Hybrid)WebView

I followed example from here (https://learn.microsoft.com/en-gb/xamarin/xamarin-forms/app-fundamentals/custom-renderer/hybridwebview#invoke-c-from-javascript) to setup WebView for my project and I can invoke C# code from WebView page event, that is working fine.
However, before sending a request I have to setup a Cookie and that cookie should be passed to remote server. I followed several examples from net I am getting it to work for Android but iOS its not working.
Code I got from another Stackoverflow question as follows.
Android Working
var cookieManager = CookieManager.Instance;
cookieManager.SetAcceptCookie(true);
cookieManager.RemoveAllCookie();
var cookies = UserInfo.CookieContainer.GetCookies(new System.Uri(AppInfo.URL_BASE));
for (var i = 0; i < cookies.Count; i++)
{
string cookieValue = cookies[i].Value;
string cookieDomain = cookies[i].Domain;
string cookieName = cookies[i].Name;
cookieManager.SetCookie(cookieDomain, cookieName + "=" + cookieValue);
}
iOS Not Working
// Set cookies here
var cookieUrl = new Uri(AppInfo.URL_BASE);
var cookieJar = NSHttpCookieStorage.SharedStorage;
cookieJar.AcceptPolicy = NSHttpCookieAcceptPolicy.Always;
foreach (var aCookie in cookieJar.Cookies)
{
cookieJar.DeleteCookie(aCookie);
}
var jCookies = UserInfo.CookieContainer.GetCookies(cookieUrl);
IList<NSHttpCookie> eCookies =
(from object jCookie in jCookies
where jCookie != null
select (Cookie) jCookie
into netCookie select new NSHttpCookie(netCookie)).ToList();
cookieJar.SetCookies(eCookies.ToArray(), cookieUrl, cookieUrl);
I have tried code from WebView documentation here, Cookie section (https://learn.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/webview?tabs=macos#cookies)
I'll really appreciate if anybody can point out what I am doing wrong any hints.
Thanks.
Update
In my HybridWebViewRenderer method I am adding my custom Cookie as follows.
protected override void OnElementChanged(VisualElementChangedEventArgs e)
{
base.OnElementChanged(e);
if (e.OldElement != null)
{
userController.RemoveAllUserScripts();
userController.RemoveScriptMessageHandler("invokeAction");
HybridWebView hybridWebView = e.OldElement as HybridWebView;
hybridWebView.Cleanup();
}
if (e.NewElement != null)
{
string cookieDomain = new System.Uri(((HybridWebView)Element).Uri).Host;
foreach (var c in NSHttpCookieStorage.SharedStorage.Cookies)
{
Console.WriteLine("Cookie (Delete)" + c.Name);
NSHttpCookieStorage.SharedStorage.DeleteCookie(c);
}
var cookieDict = new NSMutableDictionary();
cookieDict.Add(NSHttpCookie.KeyDomain, new NSString("." + cookieDomain));
cookieDict.Add(NSHttpCookie.KeyName, new NSString("ABC"));
cookieDict.Add(NSHttpCookie.KeyValue, new NSString("123e4567-e89b-12d3-a456-426652340003"));
cookieDict.Add(NSHttpCookie.KeyPath, new NSString("/"));
cookieDict.Add(NSHttpCookie.KeyExpires, DateTime.Now.AddDays(1).ToNSDate());
var myCookie = new NSHttpCookie(cookieDict);
NSHttpCookieStorage.SharedStorage.SetCookie(myCookie);
string filename = $"{hybridView.Uri}";
var request = new NSMutableUrlRequest(new NSUrl(filename));
var wkNavigation = LoadRequest(request);
}
}
In AppDelegate I have added.
public override bool FinishedLaunching(UIApplication app, NSDictionary options)
{
global::Xamarin.Forms.Forms.Init();
LoadApplication(new App());
NSHttpCookieStorage.SharedStorage.AcceptPolicy = NSHttpCookieAcceptPolicy.Always;
return base.FinishedLaunching(app, options);
}
Still no luck :( .........
You need to set the cookie in the shared storage.
Set your shared storage policy to always accept your own cookies.
In your ApplicationDelegate:
NSHttpCookieStorage.SharedStorage.AcceptPolicy = NSHttpCookieAcceptPolicy.Always;

share image Xamarin Ios

I'm using Xamarin forms, and in my application has a button to share the problem that is being in my android application I got doing with Intent but in my application ios'm not knowing how to do, someone could help me?
using android
public async Task<bool> Share(ImageSource image)
{
Intent shareIntent = new Intent(Intent.ActionSend);
bitmapToShare = await GetBitmap (image);
if (bitmapToShare != null) {
CreateDirectoryForPictures("Xpto");
var filePath = System.IO.Path.Combine (dir.AbsolutePath, string.Format("xpto_{0}.png",Guid.NewGuid()));
var stream = new FileStream (filePath, FileMode.Create);
bitmapToShare.Compress (Bitmap.CompressFormat.Png, 100, stream);
stream.Close ();
Java.IO.File file = new Java.IO.File (filePath);
shareIntent.SetType ("image/*");
shareIntent.PutExtra (Intent.ExtraStream, Android.Net.Uri.FromFile (file));
shareIntent.AddFlags (ActivityFlags.GrantReadUriPermission);
Forms.Context.StartActivity (Intent.CreateChooser (shareIntent, "Compartilhar"));
}
return true;
}
private static async Task ShareImageAsyc(ImageSource image, string message, string url = null)
{
var handler = image.GetHandler();
if (handler == null) return;
var uiImage = await handler.LoadImageAsync(image);
var items = new List<NSObject> { new NSString(message ?? string.Empty) };
if (!url.IsNullOrEmpty())
items.Add(new NSString(url));
items.Add(uiImage);
var controller = new UIActivityViewController(items.ToArray(), null);
UIApplication.SharedApplication.KeyWindow.RootViewController.GetTopViewController()
.PresentViewController(controller, true, null);
}
From: https://github.com/jimbobbennett/JimLib.Xamarin/blob/master/JimLib.Xamarin.ios/Sharing/Share.cs

Counting trending tweets with geo code

I am trying to find trending tweets by each city in Turkey. but "TwitterGeoLocationSearch" result return zero . I am using TweetSharp 2.0 and visual studio 2010.
Please check my code block. Here:
private void btnTweetSearch_Click(object sender, EventArgs e)
{
service = new TwitterService("xxxx", "xxxxx", "xxxxxxx", "xxxxxxxx");
var CityGeoCode = new TwitterGeoLocationSearch(37.0000000, 35.3213330, 10, TwitterGeoLocationSearch.RadiusType.Km);
var tweetss = service.Search(new SearchOptions { Q = " Turkey ", Count = 1000, Geocode = CityGeoCode });
var TweetwithGeo = tweetss.Statuses.Where(x => x.Location != null );
foreach (var tweet in TweetwithGeo)
{
lbTweetWindow.Items.Add(tweet.Text);
}
}
}
Any help, would be very appreciated. Thank you.
Your code is perfectly executing.
Just go to twitter developers and get your consumerKey, consumerSecret, AccessToken, AccessTokenSecret
private void btnTweetSearch_Click(object sender, EventArgs e)
{
/* Your Authentication Code */
var service = new TwitterService(_consumerKey, _consumerSecret);
service.AuthenticateWith(_accessToken, _accessTokenSecret);
/* Your Tweet Extracting code */
var CityGeoCode = new TwitterGeoLocationSearch(37.0000000, 35.3213330, 10, TwitterGeoLocationSearch.RadiusType.Km);
var tweetss = service.Search(new SearchOptions { Q = " Turkey ", Count = 1000, Geocode = CityGeoCode });
var TweetwithGeo = tweetss.Statuses.Where(x => x.Location != null );
foreach (var tweet in TweetwithGeo)
{
lbTweetWindow.Items.Add(tweet.Text);
}
}

How to change Element innerHtml to Dart SDK 0.7.1

I am using dart-message https://github.com/mkozhukh/dart-message. It has function
...
MessageBox(String text, String header, String css){
_box = new DivElement();
...
_box.onClick.listen(_clickHandler);
if (header != null)
html.write("<div class='dhtmlx_popup_title'>$header</div>");
html.write("<div class='dhtmlx_popup_text'><span>$text</span></div>");
html.write("<div class='dhtmlx_popup_controls'>");
}
String addButton(String text, String result){
if (html != null){
html.write("<div class='dhtmlx_popup_button' result='$result' ><div>$text</div></div>");
} else
throw new Exception(".addButton must be used before .show");
}
_clickHandler(Event event){
String result = event.target.attributes["result"];
if (result == null)
result = event.target.parent.attributes["result"];
hide(result); //<=== ERROR result alway return null
}
And
Future<String> show(){
if (html != null){
//finalize html initialization
html.write("</div>");
_box.innerHtml = html.toString(); //<===== ERROR after line : Removing disallowed attribute <DIV result="ok">
html = null;
}
...
}
...
How to change this code to SDK 0.7.1.
Thanks you very much.
I changed code
_box.innerHtml = html.toString();
==>
_box.setInnerHtml(html.toString(), treeSanitizer : new NullTreeSanitizer());
and it work.

Resources