Xamarin - Switch statement for Follow and unFollow - visual-studio-2010

I'm trying to make a follow and unfollow techniques to user profile
I made this code but the main problem is that the user followed successfully but if you tap the button again the toast will show that unfollowed and the button image will change (like you will follow again) but if you refresh the following image show again it's like nothing happen
switch (BtnFollow?.Tag?.ToString())
{
case "Add": //Sent follow
BtnFollow.SetColor(Color.ParseColor(AppSettings.MainColor));
BtnFollow.SetImageResource(Resource.Drawable.ic_tick);
BtnFollow.Tag = "friends";
DataUser.IsFollowing = true;
Toast.MakeText(Context, Context.GetText(Resource.String.Lbl_Sent_successfully_followed),
ToastLength.Short)?.Show();
PollyController.RunRetryPolicyFunction(new List<Func<Task>> { () => RequestsAsync.User.FollowUnFollowUserAsync(UserId, true) });
break;
case "friends": //Sent un follow
BtnFollow.SetColor(Color.ParseColor("#444444"));
BtnFollow.SetImageResource(Resource.Drawable.ic_add);
BtnFollow.Tag = "Add";
DataUser.IsFollowing = false;
Toast.MakeText(Context, Context.GetText(Resource.String.Lbl_Sent_successfully_Unfollowed),
ToastLength.Short)?.Show();
PollyController.RunRetryPolicyFunction(new List<Func<Task>> { () => RequestsAsync.User.FollowUnFollowUserAsync(UserId, false) });
break;
}
var dataUser = GlobalContext?.MainFragment?.ArtistsAdapter?.ArtistsList?.FirstOrDefault(a => a.Id == DataUser.Id);
if (dataUser != null)
{
dataUser.IsFollowing = DataUser.IsFollowing;
GlobalContext.MainFragment.ArtistsAdapter.NotifyDataSetChanged();
}
}
catch (Exception exception)
{
Methods.DisplayReportResultTrack(exception);
}
}
and this code to check the following status
if (DataUser.IsFollowing != null && DataUser.IsFollowing.Value) // My Friend
{
BtnFollow.SetColor(Color.ParseColor(AppSettings.MainColor));
BtnFollow.SetImageResource(Resource.Drawable.ic_tick);
BtnFollow.Tag = "friends";
}
else //Not Friend
{
BtnFollow.SetColor(Color.ParseColor("#444444"));
BtnFollow.SetImageResource(Resource.Drawable.ic_add);
BtnFollow.Tag = "Add";
}
}

Related

Can you guys help me how I can do refactoring code in nestjs

Hey guys I'm trying to refactor the two methods. As you can see in the code below, 'checkKioskUserPhone' and 'sendKioskUserPin' has almost similar logics. The only difference is the below part.
if (isConfirmedAuthCode && isSetPin) {
await this.userService.sendPin(user.id, Builder(AuthorizePhoneDto).phone(user.phone).build());
}
So my approach was to create another method that can combine common parts of the methods. and remove the common part in each method..
Hmm..but can't figure out how exactly..
Can you guys help me?!...
private async commonMethods(user) {
if (!user) {
throw new NotFoundException('User not found');
}
if (user.provider !== Provider.KIOSK) {
throw new ConflictException('You are already joined App.');
}
const isConfirmedAuthCode = user.authCode === 'OK' ? true : false;
const isSetPin = user.pin ? true : false;
if (!isConfirmedAuthCode && !isSetPin) {
await this.userService.authenticatePhone(user.id, Builder(AuthorizePhoneDto).phone(user.phone).build());
}
}
async checkKioskUserPhone(kioskLoginDto: KioskLoginDto): Promise<ResponseDto<UserAuthDto>> {
const user = await this.userService.findOne({ where: { phone: kioskLoginDto.phone } });
if (!user) {
throw new NotFoundException('User not found');
}
if (user.provider !== Provider.KIOSK) {
throw new ConflictException('You are already joined App.');
}
const isConfirmedAuthCode = user.authCode === 'OK' ? true : false;
const isSetPin = user.pin ? true : false;
if (!isConfirmedAuthCode && !isSetPin) {
await this.userService.authenticatePhone(user.id, Builder(AuthorizePhoneDto).phone(user.phone).build());
}
const jwtInfo = await this.createToken(this.removeCredentialField(user));
return Builder<ResponseDto<UserAuthDto>>(ResponseDto)
.result(Builder(UserAuthDto).isConfirmedAuthCode(isConfirmedAuthCode).isSetPin(isSetPin).jwtInfo(jwtInfo).build())
.build();
}
async sendKioskUserPin(kioskLoginDto: KioskLoginDto): Promise<ResponseDto<UserAuthDto>> {
const user = await this.userService.findOne({ where: { phone: kioskLoginDto.phone } });
if (!user) {
throw new NotFoundException('User not found');
}
if (user.provider !== Provider.KIOSK) {
throw new ConflictException('You are already joined App.');
}
const isConfirmedAuthCode = user.authCode === 'OK' ? true : false;
const isSetPin = user.pin ? true : false;
if (!isConfirmedAuthCode && !isSetPin) {
await this.userService.authenticatePhone(user.id, Builder(AuthorizePhoneDto).phone(user.phone).build());
}
if (isConfirmedAuthCode && isSetPin) {
await this.userService.sendPin(user.id, Builder(AuthorizePhoneDto).phone(user.phone).build());
}
const jwtInfo = await this.createToken(this.removeCredentialField(user));
return Builder<ResponseDto<UserAuthDto>>(ResponseDto)
.result(Builder(UserAuthDto).isConfirmedAuthCode(isConfirmedAuthCode).isSetPin(isSetPin).jwtInfo(jwtInfo).build())
.build();
}

How to cancel skill's Dialog from Virtual Assistant while using MS Bot Framework V4

We are using bot-framework version 4.x
"botbuilder": "4.11.0",
"botbuilder-ai": "4.11.0",
"botbuilder-applicationinsights": "4.11.0",
"botbuilder-azure": "4.11.0",
"botbuilder-dialogs": "4.11.0",
"botbuilder-lg": "4.11.0",
"botbuilder-testing": "4.11.0",
"botframework-config": "4.11.0",
"botframework-connector": "4.11.0"
Case
We need to start a Dialog in Virtual Assistant and cancel any ongoing Skill dialog (If any)
Example
LiveChat - part of Virtual Assistant
CreateIncidentDialog - part of skill
Suppose we are in the middle of CreateIncidentDialog and the user wants to start LiveChat. We are supposed to start LiveChat and cancel current CreateIncidentDialog.
Sample Code
MainDialog.ts in Virtual Assistant
If current Dialog is a part of skill, we are starting a dialog with activity.type as EVENT for skill.
switch (gIntent) {
case 'Escalate': {
// Checking if current Dialog is a part of Skill
if (isSkill) {
const activity: Activity = innerDc.context.activity;
if ((activity.value === null || activity.value === undefined)) {
activity.value = { userState: userProfile };
};
activity.type = ActivityTypes.Event;
activity.name = "liveChat";
const skillDialogArgs: BeginSkillDialogOptions = {
activity: activity as Activity
};
await innerDc.beginDialog(EvaConfig.LUIS_DEFAULT_INTENT, skillDialogArgs);
} else {
await innerDc.cancelAllDialogs();
}
// code for starting LiveChat goes here
// .....
// .....
// .....
}
MainDialog.ts in Skill
If activity.type is EVENT and name is 'liveChat', cancel dialogs.
protected async onContinueDialog(innerDc: DialogContext): Promise<DialogTurnResult> {
try {
let activity = innerDc.context.activity;
if (innerDc.context.activity.type === ActivityTypes.Message) {
// .....
// .....
// .....
} else if (activity.type === ActivityTypes.Event) {
const ev = activity;
if (ev.name !== undefined && ev.name.trim().length > 0) {
switch (ev.name) {
case 'liveChat': {
await innerDc.cancelAllDialogs(true);
return await innerDc.endDialog();
}
}
}
}
return await super.onContinueDialog(innerDc);
} catch (e) {
console.log(`Error onContinueDialog ---> ${e} `);
return await this.hanldeException(innerDc);
}
}
Issue
The above code is not able to cancel the skill's dialog correctly. If we try to start a new dialog after the cancellation of skill dialog, it again sends an activity with activity.type as EVENT to routeStep method of MainDilaog.ts in Skill. Please find the sample code below for the same.
routeStep method of MainDialog.ts in Skill
protected async routeStep(stepContext: WaterfallStepContext): Promise<DialogTurnResult> {
console.log('skill routeStep');
if (activity.type === ActivityTypes.Message && activity.text !== undefined && activity.text.trim().length > 0) {
// .....
// .....
// .....
} else if (activity.type === ActivityTypes.Event) {
const ev = activity;
if (ev.name !== undefined && ev.name.trim().length > 0) {
switch (ev.name) {
case 'SampleAction': {
// .....
// .....
// .....
}
}
} else {
// If we try to start a new dialog, control comes here
await stepContext.context.sendActivity({
type: ActivityTypes.Trace,
text: 'An event with no name was received but not processed.'
});
}
}
} else {
await this.responder.replyWith(stepContext.context, MainResponses.responseIds.dontHavePermissionServiceNow);
await this.complete(stepContext);
}
return await stepContext.next();
}
Step to Reproduce
Step 1. Start a Dialog in Skill
Step 2. End the Dialog in the Skill and start a Dialog in VA
Step 3. Start a new Dialog
Thanks.
Edward

How to detect brave using navigator

I am trying to detect brave using navigator. I referred to this post, https://stackoverflow.com/a/60954062/14443512
I tried this condition,
(navigator.brave && await navigator.brave.isBrave() || false)
But I get error, Property 'brave' does not exist on type 'Navigator'.
Am I missing any configuration here?
My code block,
export const errorMessage = (networkError: netError): string | undefined => {
const {statusCode, message} = networkError;
if (statusCode === undefined) {
return message;
}
if (statusCode < 400) {
return undefined;
}
switch (statusCode) {
case 401:
return 'authn error';
case 403:
if(navigator.brave && await navigator.brave.isBrave() || false)
return 'browser not supported';
else
return 'authz error';
case 500:
if (message.includes("invalid value")) {
return invalidString;
}
break;
}
if (statusCode < 500) {
return 'error';
}
return 'serverError';
};
I think that the declaration should be something like this:
export {}; // there must be at least one export in this file
declare global {
interface Navigator {
brave: {
isBrave(): boolean;
};
}
interface Global {
document: Document;
window: Window;
navigator: Navigator,
}
}

ZXing is not scanning on Android (Xamarin app)

I am using below code to scan a QR code in my Xamarin. I am currently testing it on Samsung Galaxy (Android) and I am able to view the camera streaming but it is not scanning any QR code.
How can I fix this please to get the result of the QR scanned?
public void Scan()
{
try
{
scanner.Options = new MobileBarcodeScanningOptions()
{
UseFrontCameraIfAvailable = false, //update later to come from settings
PossibleFormats = new List(),
TryHarder = true,
AutoRotate = false,
TryInverted = true,
DelayBetweenContinuousScans = 2000,
};
scanner.VerticalOptions = LayoutOptions.FillAndExpand;
scanner.HorizontalOptions = LayoutOptions.FillAndExpand;
// scanner.IsVisible = false;
scanner.Options.PossibleFormats.Add(BarcodeFormat.QR_CODE);
// scanner.Options.PossibleFormats.Add(BarcodeFormat.DATA_MATRIX);
// scanner.Options.PossibleFormats.Add(BarcodeFormat.EAN_13);
scanner.OnScanResult += (result) => {
// Stop scanning
scanner.IsAnalyzing = false;
scanner.IsScanning = false;
if (scanner.IsScanning)
{
scanner.AutoFocus();
}
// Pop the page and show the result
Device.BeginInvokeOnMainThread(async () => {
if (result != null)
{
await DisplayAlert("Scan Value", result.Text, "OK");
}
});
};
mainGrid.Children.Add(scanner, 0, 1);
}
catch (Exception ex)
{
DisplayAlert("Scan Value", ex.ToString(), "Error");
}
}
Maybe you are using the wrong event handler, or missing an event, also the camera never focuses:
the condition is never true, due to this fragment of code:
scanner.IsScanning = false;
if (scanner.IsScanning)
{
scanner.AutoFocus();
}

aurelia - Custom Element validation

I have a custom element (a partial URL) called #customElement('partialurl')
partialurl.js
get isValid(){
if (this.element === undefined || this.element === null){
return false;
}
else{
const partialUrl = new RegExp('^\/[a-z0-9]+([-\/](?:[a-z0-9]+))*(\.(?:jpeg|jpg|gif|png|htm|html|asp|xml|txt|pdf))?$');
if (partialUrl.test(this.element)) {
return true;
} else {
return false;
}
}
}
My question is how do I reference the 'isValid'?
For example - this file references the custom element
html
<partialurl disabled.bind="readonly" value.bind="baseContent.LinkDestination" />
js
bind(){
return this.dataContext.getContent(this.id)
.then(baseContent => {
this.baseContent = baseContent;
this.validator = this.validation.on(this)
.ensure('baseContent.LinkDestination').isValidFromCustomElement();
}); }
I know the above doesn't work, I am new to Aurelia and still finding my feet with it.

Resources