Google Dart HTTP Error Checking - dart

I'm attempting to detect whether a connection refused error is taking place with the following tutorial: https://www.dartlang.org/dart-by-example/#http-requests-and-responses ; However, I continue to receive the method not found exception and cannot receive any feedback whether my HTTP Response was working or not. Any ideas would be appreciated. Please let me know if you need more information. --ignore "shroot".
handleFailure(error) {
print('Something went wrong.');
print(error.message);
}
void loadData(String url) {
//url = "${baseRestfulUrl}"+ QUERY_ALL_TARGET_ASSETS_BASE_URL;
print(url);
//call the web server asynchronously
var request = HttpRequest.getString(url).then(onDataLoaded);
request.catchError(handleFailure);
if (request == null) {
var warn = (shroot.querySelector('#warning')
..text = "No records could be found to match the search criteria."
..style.color = "Red");
ButtonElement resetBtn = shroot.querySelector("#reset-btn");
resetBtn.disabled = true;
}
else if(request == 404)
{
var warn = (shroot.querySelector('#warning')
..text = "Error serving data. Please restart server."
..style.color = "Red");
}
else if(request == "ERR_CONNECTION_REFUSED")
{
var warn = (shroot.querySelector('#warning')
..text = "Error serving data. Please restart server."
..style.color = "Red");
}
else if(request != null)
{
var warn = (shroot.querySelector('#warning')
..text = ""
..style.color = "#fff");
ButtonElement resetBtn = shroot.querySelector("#reset-btn");
resetBtn.disabled = false;
}
else {
var warn = (shroot.querySelector('#warning')
..text = "Error serving data. Please restart server."
..style.color = "Red");
ButtonElement resetBtn = shroot.querySelector("#reset-btn");
resetBtn.disabled = false;
}
}

The link you added is about Dart I/O and Command Line Apps. This doesn't apply to Dart in the browser.
Dart has to delegate to the browser API with limited capabilities and therefore there are differences.
In the case of an error an instance of ProgressEvent is passed to this method
handleFailure(error) {
print('Something went wrong.');
// print(error.message); // ProgressEvent doesn't have a `message` getter
// the progress event doesn't provide any further information
if(error is ProgressEvent && (error as ProgressEvent).type == 'error') {
print('An error has occured'); // as we already know because `handleFailure()` was called
}
}
this code
if (request == null) {
is actually called before the request was sent because it is not inside a .then
var request = HttpRequest.getString(url).then(onDataLoaded);
request.catchError(handleFailure)
.then((e) {
if(request == null) { // doesn't make sense because you just assigned a value to request
...
}
});

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.

How to send mail with attachments in Flutter?

I found dart plugin called mailer3: "^1.1.9". Previously I create an image in mobile temp directory. In Flutter mobile app I try to send this saved picture using mailer3 plugin as a mail. The mail reach the destination, I don't get error but seems lost the attachment in process.
In dart it works very well and send the attachment as well. In flutter I can use the temp directory to show the image in app but cannot be able attache to mail.
The image location is in the temp folder of the device:
'/data/user/0/com.myApp.myApp/app_flutter/20180700087.jpg'
I can show the image using below code:
new FileImage(File('$newDekontImage'),
Error:
E/flutter (21184): [ERROR:topaz/lib/tonic/logging/dart_error.cc(16)] Unhandled exception:
E/flutter (21184): FileSystemException: Cannot open file, path = '/data/user/0/com.myApp.myApp/app_flutter/20180700087.jpg' (OS Error: No such file or directory, errno = 2)
How to send mail with attachments in Flutter with provided information in this question?
The Flutter Code:
// TODO: SEND MAIL
void _sendMail() async {
if (!_formKey.currentState.validate()) {
return;
} else {
_formKey.currentState.save();
var _options = new GmailSmtpOptions()
..username = “mymailaddress#gmail.com"
..password = “myPassword”;
var _emailTransport = new SmtpTransport(_options);
var _envelope = new Envelope()
..from = "mymailaddress#gmail.com"
..recipients.add(_receiverMailAddress)
..subject = "${_userDekontDetails[0][0].toString()} - Receipt”
..attachments.add(await new Attachment(file: await new File('$newDekontImage')))
..text = "${_userDekontDetails[0][0].toString()} - Receipt"
..html = '<h3>${_userDekontDetails[0][0].toString()} Receipt.</h3>'
'<p>Hi, registered under my name, I am sending the receipt (${widget._currentUserReceiptNo}) with attached to this mail.</p>'
'<p></p>'
'<h5>Regards, </br></h5>'
'${_userDekontDetails[0][0].toString()}';
_emailTransport.send(_envelope)
..then((envelope) => print('Email sent'))
..catchError((e) => print('Error occured: $e'));
}
}
As of this writing, the mailer3 plugin is outdated and mailer is the most up-to-date plugin for sending emails. The mailer plugin currently contains important fixes that mailer2 and mailer3 has. I suggest opting to use mailer package instead of mailer3.
Here's a port of your code snippet from mailer3 to mailer
_sendMail(String username, String accessToken) async {
// Read https://pub.dev/documentation/mailer/latest/smtp_server_gmail/gmailSaslXoauth2.html
var _emailTransport = gmailSaslXoauth2(username, accessToken);
var _envelope = new Message()
..from = "mymailaddress#gmail.com"
..recipients.add("recepient#gmail.com")
..subject = '{EMAIL_SUBJECT_GOES_HERE}'
// Read https://pub.dev/documentation/mailer/latest/mailer/FileAttachment-class.html
..attachments
.add(FileAttachment(File('{FILE_PATH}')))
..text = '{PLAIN_TEXT_GOES_HERE}'
..html = '{HTML_CONTENT_GOES_HERE}';
send(_envelope, _emailTransport)
..then((envelope) => print('Email sent'))
..catchError((e) => print('Error occured: $e'));
}
I have used enough_mail, Hope it will be helpful.
MessageBuilder messageBuilder = MessageBuilder();
Future<bool> onFileSelect(BuildContext context) async {
final result = await FilePicker.platform
.pickFiles(type: FileType.any, allowMultiple: true, withData: true);
if (result == null) {
return false;
}
for (final file in result.files) {
final lastDotIndex = file.path.lastIndexOf('.');
MediaType mediaType;
if (lastDotIndex == -1 || lastDotIndex == file.path.length - 1) {
mediaType = MediaType.fromSubtype(MediaSubtype.applicationOctetStream);
} else {
final ext = file.path.substring(lastDotIndex + 1);
mediaType = MediaType.guessFromFileExtension(ext);
}
messageBuilder.addBinary(file.bytes, mediaType, filename: file.name);
}
return true;
}
Future<void> sendMail(BuildContext buildContext) async {
setState(() {
needToFreezeUi = true;
});
MySnackBar.show(buildContext, MySnackBar.loadingIcon, "Please wait...!");
SmtpClient smtpClient = SmtpClient(domain, isLogEnabled: true);
try {
await smtpClient.connectToServer(
"$serverPrefix.${userInfo.domainName}",
smtpServerPort,
isSecure: isSmtpServerSecure
);
await smtpClient.ehlo();
await smtpClient.authenticate(userInfo.email, userInfo.password);
messageBuilder.from = [MailAddress('', userInfo.email)];
messageBuilder.to = [MailAddress('', toTextEditCtl.text)];
messageBuilder.cc = selectedCCEmailInfos.map((e) => MailAddress('',e.emailAddress)).toList();
messageBuilder.bcc = selectedBCCEmailInfos.map((e) => MailAddress('',e.emailAddress)).toList();
messageBuilder.subject = subjectTextEditCtl.text;
String htmlText = await htmlEditorController.getText();
messageBuilder.addTextHtml(htmlText);
messageBuilder.hasAttachments ? messageBuilder.getPart(
MediaSubtype.multipartAlternative,
recursive: false
) : messageBuilder.addPart(
mediaSubtype: MediaSubtype.multipartAlternative,
insert: true
);
if (!messageBuilder.hasAttachments) {
messageBuilder.setContentType(
MediaType.fromSubtype(MediaSubtype.multipartAlternative)
);
}
MimeMessage mimeMessage = messageBuilder.buildMimeMessage();
SmtpResponse smtpResponse = await smtpClient.sendMessage(mimeMessage);
MySnackBar.hide(buildContext);
if(smtpResponse.isOkStatus){
MySnackBar.show(buildContext,MySnackBar.successIcon,"Mail send successfully");
clearInputFields(buildContext);
}else {
MySnackBar.show(buildContext,MySnackBar.errorIcon,"Something went wrong, please try again!");
}
} on SmtpException catch (e) {
MySnackBar.show(buildContext,MySnackBar.errorIcon,"Something went wrong, please try again!");
}
setState(() {
needToFreezeUi = false;
});
}
============================
dependencies:
enough_mail: ^1.3.4
html_editor_enhanced: ^1.4.0
file_picker: ^3.0.2+2

In NServiceBus full duplex application Server could not send/reply/return message

I have created a ASP.Net Web API project and using this link. NServiceBus is integrated with web api. Here is my configuration at web api as a client.
Configure.Serialization.Xml();
Configure.Transactions.Enable();
Configure.With()
.DefineEndpointName(Constants.ClientName)
.DefaultBuilder()
.ForWebApi()
.Log4Net()
.UseTransport<Msmq>()
.PurgeOnStartup(false)
.UnicastBus()
.ImpersonateSender(false)
.CreateBus()
.Start();
This is how I'm sending message to Server
var response = await Bus.Send(Constants.ServerName, request)
.Register<ResponseModel>((NServiceBus.CompletionResult completionResult) =>
{
ResponseModel responseMessage = null;
if (completionResult != null && completionResult.Messages.Length > 0)
{
var status = completionResult.Messages[0] as RequestStatus?;
if (status == RequestStatus.Successful)
{
responseMessage = TransactionManager.TransactionDictionary[request.RequestId].ResponseModel;
}
}
return responseMessage;
});
This is how I'm sending response from Server. I have commented some lines to show what I have already tried.
public void Handle(RequestModel message)
{
ProcessRequest(message).RunSynchronously();
}
private async Task ProcessRequest(RequestModel message)
{
....
ResponseModel response = new ResponseModel();
response.RequestId = message.RequestId;
response.Result = await responseMessage.Content.ReadAsStringAsync();
//Bus.Send(Util.Constants.ClientName, response);
//Bus.Reply(response);
//Bus.Reply<ResponseModel>((ResponseModel response) =>
//{
// response = Bus.CreateInstance<ResponseModel>(r =>
// {
// r.RequestId = message.RequestId;
// r.Result = responseMessage.Content.ReadAsStringAsync().Result;
// });
//});
await Bus.Send(Util.Constants.ClientName, response).Register((NServiceBus.CompletionResult completionResult) =>
{
if (completionResult != null && completionResult.Messages.Length > 0)
{
var msg = completionResult.Messages[0];
if (msg != null)
{
var status = (RequestStatus)msg;
return status;
}
}
return RequestStatus.Error;
});
....
}
From any of the above response methods ultimately all messages end up in error queue.
Previously I was getting 'Could not enlist message' error. Now it is not throwing that error. But Server could not send message to Client.
I could not get what I'm doing wrong. Please also suggest if you see any scope for improvements.
I'm not sure if TransactionScope work correctly with async/await in C#. According to this question (Get TransactionScope to work with async / await) in .NET 4.5.1 there was introduced option for TransactionScope that enable mixing it with async/await. Unfortunately NServiceBus doesn't support .NET 4.5/4.5.1 so try just remove async/await.

XMPP strophe Connection attach process failed

I'm able to create a XMPP connection on page load. However whenever I move to another pages, I want to use the same connection to remove recurring notifications in client. I've used following code.
$(document).bind('connect', function (ev, data) {
var jid = $.jStorage.get('JID', null);
var sid = $.jStorage.get('SID', null);
var rid = $.jStorage.get('RID', null);
if ((jid != null) && (sid != null) && (rid != null)) {
var conn = new Strophe.Connection("http://localhost:5280/xmpp-httpbind");
conn.attach(jid, sid, rid, function () {
alert('Connection attach success.');
Gab.connection = conn;
});
}
else {
var conn = new Strophe.Connection("http://localhost:5280/xmpp-httpbind");
conn.connect(data.jid, data.password, function (status) {
if (status === Strophe.Status.CONNECTED) {
$(document).trigger('connected');
} else if (status === Strophe.Status.DISCONNECTED) {
$(document).trigger('disconnected');
}
});
Gab.connection = conn;
}
});
And in unload:
$(window).unload(function () {
if (Gab.connection != null) {
Gab.connection.pause();
$.jStorage.set('JID', Gab.connection.jid);
$.jStorage.set('SID', Gab.connection.sid);
$.jStorage.set('RID', Gab.connection.rid);
} else {
$.jStorage.flush();
}
// Gab.connection = null;
alert('paused/disconnected');
})
It attaches to connection, however as soon as it attaches, it says (POST http://localhost:5280/xmpp-httpbind 404 Not Found 36ms) in Firebug console. Any ideas?
Thanks in advance.
You should not trust unload. Instead store/update your RID on every cb from the xmpp server. Make sure your RID is getting incremented on each call as well.
Make sure to inspect the body of the message. Some XMPP servers return HTTP 404 on terminate.

How can we send/get the http headers information with AJAX?

Is there any way to send/get the http headers (like, content-type... ) through AJAX?. Then, can please explain me, what will we archive by passing the http headers in AJAX and where will use this technique?.
Thanks
I'm no expert,
But you should look at the AJAX object XmlHttpHeader and the wikipedia article here.
EDIT: quoting the www.w3.org reference:
function test(data) {
// taking care of data
}
function handler() {
if(this.readyState == 4 && this.status == 200) {
// so far so good
if(this.responseXML != null && this.responseXML.getElementById('test').firstChild.data)
// success!
test(this.responseXML.getElementById('test').firstChild.data);
else
test(null);
} else if (this.readyState == 4 && this.status != 200) {
// fetched the wrong page or network error...
test(null);
}
}
var client = new XMLHttpRequest();
client.onreadystatechange = handler;
client.open("GET", "unicorn.xml");
client.send();
If you just want to log a message to the server:
function log(message) {
var client = new XMLHttpRequest();
client.open("POST", "/log");
client.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
client.send(message);
}
Or if you want to check the status of a document on the server:
function fetchStatus(address) {
var client = new XMLHttpRequest();
client.onreadystatechange = function() {
// in case of network errors this might not give reliable results
if(this.readyState == 4)
returnStatus(this.status);
}
client.open("HEAD", address);
client.send();
}

Resources