Cancel Or Exit from PromptDialog.Choice Flow in Microsoft Bot Framework - frameworks

i have a Prompt with 4 options, the last option is user can quit the Prompt,
i want to implement some code so that the bot exit the Prompt
Image
PromptDialog.Choice(context, this.OnOptionSelected, new List<string>() { FlightsOption, HotelsOption, TrainOption, GobackOption }, "Sure..! Tell me what booking would like to make..?", "Not a valid option", 3);
in above image i had implemented quit option on which if user selects quit it goes to Switch case of quit.
i had also tried context.quit but it throws error
private async Task OnOptionSelected(IDialogContext context, IAwaitable<string> result)
{
try
{
string optionSelected = await result;
switch (optionSelected)
{
case FlightsOption:
context.Call(new FlightDialog(), this.ResumeAfterOptionDialog);
break;
case HotelsOption:
context.Call(new HotelsDialog(), this.ResumeAfterOptionDialog);
break;
case TrainOption:
context.Call(new TrainDialog(), this.ResumeAfterOptionDialog);
break;
case GobackOption:
//want some code here to quit the form
break;
}
}

First of all this is not a Form Flow. This is prompt.
Now You can do something like, either you exit the dialog from the stack like this
try
{
string optionSelected = await result;
switch (optionSelected)
{
case FlightsOption:
context.Call(new FlightDialog(), this.ResumeAfterOptionDialog);
break;
case HotelsOption:
context.Call(new HotelsDialog(), this.ResumeAfterOptionDialog);
break;
case TrainOption:
context.Call(new TrainDialog(), this.ResumeAfterOptionDialog);
break;
case GobackOption:
context.Done<object>(null);
break;
}
}
Or,
You can tell something and then wait for other message in the same dialog like this
try
{
string optionSelected = await result;
switch (optionSelected)
{
case FlightsOption:
context.Call(new FlightDialog(), this.ResumeAfterOptionDialog);
break;
case HotelsOption:
context.Call(new HotelsDialog(), this.ResumeAfterOptionDialog);
break;
case TrainOption:
context.Call(new TrainDialog(), this.ResumeAfterOptionDialog);
break;
case GobackOption:
await context.PostAsync("Ok, you came back. Now tell something new.");
context.Wait(MessageReceivedAsync);
break;
}
}
And the next message will go here
public virtual async Task MessageReceivedAsync(IDialogContext context, IAwaitable<IMessageActivity> result)
{
var message = await result;
context.Wait(MessageReceivedAsync);
}

Related

Unable to catch Google cloud storage exception

I have a function in my flutter app to download a file from google cloud and store it locally. This function works for existing files, but when I try to download a non existent file, it fails to catch the 'file not found' exception. I'm obviously doing something wrong, but I can't figure it out!
bool downloadFile({required String localFile, required String remoteFile}) {
try {
final storageRef = FirebaseStorage.instance.ref();
final remoteFileRef = storageRef.child(remoteFile);
final file = File(localFile);
final downloadTask = remoteFileRef.writeToFile(file);
downloadTask.snapshotEvents.listen((taskSnapshot) {
switch (taskSnapshot.state) {
case TaskState.running:
print('TaskState.running');
break;
case TaskState.paused:
print('TaskState.paused');
break;
case TaskState.success:
print('TaskState.success');
break;
case TaskState.canceled:
print('TaskState.canceled');
break;
case TaskState.error:
print('TaskState.error');
break;
}
});
//} on firebase_core.FirebaseException catch (error) {
} catch (e) {
print("########### got ex");
return false;
}
return true;
}

DART : I have a switch case of enums, which are buttons, but all cases are executing only once. It wont work the second time i click the same button

Below is the switch case code, the main problem I have is, the code is fine for the first time that is appropriate output is rendered, but when I click the button (enum for example Scholarships) the code wont execute
PopupMenuButton(
onSelected: (Category selectedOffer) {
switch (selectedOffer) {
case Category.Scholarships:
{
offersData.showScholarshipsOnly();
}
break;
case Category.Investing:
{
offersData.showInvestingOnly();
}
break;
case Category.Courses:
{
offersData.showCoursesOnly();
}
break;
case Category.Discounts:
{
offersData.showDiscountsOnly();
}
break;
case Category.Finance:
{
offersData.showFinanceOnly();
}
break;
case Category.All:
{
offersData.showAll();
} break;
}
These are the functions which are linked to the above conditions
List<Offers> get offerList {
if (_showScholarships) {
return _offerList.where((selOffer) =>
selOffer.category.name.contains('Scholarships')).toList();
}
else if (_showCourses) {
return _offerList.where((selOffer) =>
selOffer.category.name.contains('Courses')).toList();
}
else if (_showInvesting) {
return _offerList.where((selOffer) =>
selOffer.category.name.contains('Investing')).toList();
}
else if (_showFinance) {
return _offerList.where((selOffer) =>
selOffer.category.name.contains('Finance')).toList();
}
else if (_showDiscounts) {
return _offerList.where((selOffer) =>
selOffer.category.name.contains('Discounts')).toList();
}
else if (_showAll) {
return _offerList.where((selOffer) =>
selOffer.category.name.contains(
'Investing,Finance,Discounts,Insurance,Courses,Scholarships'))
.toList();
}
return _offerList;
}

Amplify DataStore: How to know when sync is finished?

How can we know that DataStore has finished the sync?
When doing the first await DataStore.query(MyEntity) after the user logged in, DataStore is returning right away and not waiting for the data to be synced with the cloud.
I want to wait for the sync to be completed and put a loading when the data isn't synced yet.
make your model class observable so that it can check for data in realtime
Amplify.DataStore.observeQuery(MyEntity.classType).listen((event) {
if (event.isSynced) {//boolean value
print("Synced Successfully!");
// even you can get synced data here also
List< MyEntity> items = event.items;
} else {
//Show ProgressBar Here
print("Fetching Data From Cloud");
}
});
You can listen to events on the datastore channel with Amplify.Hub.listen.
details:
subscription = Amplify.Hub.listen([HubChannel.DataStore], (dynamic hubEvent) async {
switch (hubEvent.eventName) {
case 'networkStatus':
_amplifyIsUp.value = hubEvent.payload.active;
break;
case 'subscriptionsEstablished':
_amplifyMessage.value = 'Starting to sync from cloud...';
break;
case 'syncQueriesStarted':
_amplifyIsSyncing.value = true;
_amplifyMessage.value = 'Syncing...';
break;
case 'modelSynced':
ModelSyncedEvent mse = hubEvent.payload;
_amplifyMessage.value = '${mse.modelName} has been sync\'d from cloud...';
break;
case 'syncQueriesReady':
_amplifyMessage.value = 'Done!';
_amplifyIsSyncing.value = false;
///do your bits here
onSyncsReady.call();
break;
case 'ready':
_amplifyIsSyncing.value = false;
break;
case 'subscriptionDataProcessed':
SubscriptionDataProcessedEvent sdpe = hubEvent.payload;
_amplifyMessage.value = 'Syncing ${sdpe.element.model.classType.modelName()}...';
if (sdpe.element.model is DeviceStatus) {
DeviceStatus ds = sdpe.element.model as DeviceStatus;
if (ds.clientID == _clientService.client.id && ds.status == Status.REQUESTSTATUS) {
_statusService.performHeartbeat();
}
}
break;
case 'outboxMutationEnqueued':
_amplifyIsSyncing.value = true;
_amplifyHasDirt.value = true;
break;
case 'outboxMutationProcessed':
OutboxMutationEvent ome = hubEvent.payload;
_amplifyIsSyncing.value = false;
break;
case 'outboxStatus':
OutboxStatusEvent ose = hubEvent.payload;
if (ose.isEmpty) {
_amplifyIsSyncing.value = false;
_amplifyHasDirt.value = false;
} else {
_amplifyHasDirt.value = true;
}
break;
}
});
boop

How can you setup a flutter rawkeyboardlistener to read {} (curly brackets) instead of square brackets?

I have a flutter solution that interprets a QR code via a scanning device. I use the RawKeyboardListener to read the scanned QR code that then parses it into a variable.
The QR value is an object {something: somethingelse}, but when read by the RawKeyboardListener, it reads the {} as [] and as a result, the object is then invalid.
String runtime = event.runtimeType.toString();
if (event.data.logicalKey != LogicalKeyboardKey.enter) {
setState(() {
scannedItem += runtime == 'RawKeyUpEvent' ? event.data.keyLabel : '';
});
} else if (scannedItem != '') {
setState(() {
var data = json.decode(scannedItem);
});
}
I played around with the solution and ended up fixing it, though I do feel there is a better way of resolving this
if (event.data.isShiftPressed) {
switch (event.data.logicalKey.debugName) {
case 'Bracket Left':
keyLabel = '{';
break;
case 'Bracket Right':
keyLabel = '}';
break;
case 'Quote':
keyLabel = '"';
break;
case 'Semicolon':
keyLabel = ':';
break;
default:
keyLabel = keyLabel.toUpperCase();
break;
}
}

Flutter BLoC:Global exception handler for mapEventToState

I use felangel's bloc library. I fetch data by using a repository in mapEventToState method .If the repository throws an exception, I want to catch it on a global exception handler.
#override
Stream<MyState> mapEventToState(Event event) async* {
if (event is MyEvent) {
try {
var data = await repository.fetchData();
yield MyState(data);
} catch (e) {
//There may be many exceptions
}
}
}
Is there any way catch exceptions without try-catch blocks and what is best practice?
You could write a util for managing errors. I wrote something for this. It could be an idea for you.
static String handleError(Error error) {
String errorDescription = "";
if (/*error is SomethingError*/) {
switch (error.type) {
case ErrorType.CANCEL:
errorDescription = "ErrorType.CANCEL";
break;
case ErrorType.CONNECT_TIMEOUT:
errorDescription = "ErrorType.CONNECT_TIMEOUT";
break;
case ErrorType.DEFAULT:
errorDescription = "ErrorType.DEFAULT";
break;
case ErrorType.RECEIVE_TIMEOUT:
errorDescription = "ErrorType.RECEIVE_TIMEOUT";
break;
case ErrorType.RESPONSE:
switch (error.response.toString()) {
case "usernamePasswordFail":
errorDescription = "usernamePasswordFail";
break;
default:
errorDescription = "errorDescription";
}, ${error.response.data ?? ''}";
break;
}
break;
case ErrorType.SEND_TIMEOUT:
errorDescription = "ErrorType.SEND_TIMEOUT";
break;
}
} else {
errorDescription = "somethingElseError";
}
return errorDescription;
}