xamarin access protected firebase realtime database with nuget package FirebaseAuthentication.net - c#

im beginner in firebase and im using two nuget packages FirebaseAuthentication.net and FirebaseDatabase.net .
im trying to write to a protected firebase realtime database that has a rule that look like this
{
"rules": {
".read": "auth.uid != null",
".write": "auth.uid != null"
}
}
i randomly tryed SignInWithOAuthAsync method however it throws an Exception [ mail auth type connot be used like this. use method specifc to email & password authentication]
private async void Button_Clicked(object sender, EventArgs e)
{
try
{
var authProvider = new FirebaseAuthProvider(new FirebaseConfig(webApiKey));
var savedfirebaseauth = JsonConvert.DeserializeObject<FirebaseAuth>(Preferences.Get("MyFirebaseRefreshToken", ""));
await authProvider.SignInWithOAuthAsync(FirebaseAuthType.EmailAndPassword, savedfirebaseauth.FirebaseToken);
//inserting info into the database
await firebaseClient.Child("users").Child("some uid1").PutAsync(new userinfo
{
firstName = "noor",
secondName = "mohammed"
});
//clear the entry
recordData.Text = "";
}catch(Exception ex)
{
await App.Current.MainPage.DisplayAlert("Alert", ex.Message, "OK");
}
}
pleace let me know if my question needs more Clarificatio thanks in advance.

Related

How to check if the device has biometrics

I am new to Xamarin forms and coding in general, I want to check if the device has biometrics as soon as the app is launched. I came across this video that shows how to do it using a button, I wanted to use it as soon as I open the app. can you help?
btnFPLogin.Clicked += FingerPrint;
private async void FingerPrint(object sender, EventArgs e)
{
var result = await CrossFingerprint.Current.IsAvailableAsync(true);
Plugin.Fingerprint.Abstractions.FingerprintAuthenticationResult auth;
if (result)
{
try
{
var res = await App.Current.MainPage.DisplayAlert("Success", "Your data are saved", "Ok", "Cancel");
auth = await CrossFingerprint.Current.AuthenticateAsync("Authenticate access");
if (auth.Authenticated)
{
await App.Current.MainPage.DisplayAlert("Results are here", "Valid fingerprint found", "Ok");
}
else
{
await App.Current.MainPage.DisplayAlert("Results are here", "Invalid fingerprint", "Ok");
}
}
catch
{
await App.Current.MainPage.DisplayAlert("permission to use FaceID", "We need permission to use FaceID", "Ok");
}
}
}
you've answered your own question. To check if a device supports biometric login, use the CrossFingerprint plugin
var result = await CrossFingerprint.Current.IsAvailableAsync(true);
if you want to check this on app launch, put it in the OnStart method of the App class

cognitive vision library error : the remote server returned an error (401) in xamarin project

when I am trying to use cognitive vision library in xamarin project , I got an error message : the remote server returned an error (401)
I am using a VisionServiceClient object
this code is a code to analyze the picked picture .
I can't fix the error .
any advice , please ?
PS : is there is any problem in using free trial Api key ? this may be the cause of the error ?
and should I have a credit card to create a cognitive vision resource instance in https://portal.azure.com/#home ?
this is the main_page code :
using Microsoft.ProjectOxford.Vision;
using Microsoft.ProjectOxford.Vision.Contract;
using Plugin.Connectivity;
using Plugin.Media;
using Plugin.Media.Abstractions;
using System;
using System.IO;
using System.Threading.Tasks;
using Xamarin.Forms;
namespace ComputerVisionSample
{
public partial class MainPage : ContentPage
{
private readonly VisionServiceClient visionClient;
public MainPage()
{
InitializeComponent();
this.visionClient =
new VisionServiceClient("my_api_key");
}
private async Task<AnalysisResult> AnalyzePictureAsync(Stream inputFile)
{
if (!CrossConnectivity.Current.IsConnected)
{
await DisplayAlert("Network error",
"Please check your network connection and retry.", "OK");
return null;
}
VisualFeature[] visualFeatures = new VisualFeature[] { VisualFeature.Adult,
VisualFeature.Categories, VisualFeature.Color, VisualFeature.Description,
VisualFeature.Faces, VisualFeature.ImageType, VisualFeature.Tags };
AnalysisResult analysisResult =
await visionClient.AnalyzeImageAsync(inputFile,
visualFeatures);
return analysisResult;
}
private async void UploadPictureButton_Clicked(object sender, EventArgs e)
{
if (!CrossMedia.Current.IsPickPhotoSupported)
{
await DisplayAlert("No upload", "Picking a photo is not supported.", "OK");
return;
}
var file = await CrossMedia.Current.PickPhotoAsync();
if (file == null)
return;
this.Indicator1.IsVisible = true;
this.Indicator1.IsRunning = true;
Image1.Source = ImageSource.FromStream(() => file.GetStream());
try
{
this.BindingContext = await AnalyzePictureAsync(file.GetStream());
}
catch (Exception ex)
{
await DisplayAlert("Error", ex.Message, "OK");
return;
}
finally
{
this.Indicator1.IsRunning = false;
this.Indicator1.IsVisible = false;
}
}
}
}
If you have a 401, that means:
you did not provide a subscription key
or you provide one, but it is not matching the region where your resource is
You are using the default endpoint/region of ComputerVision by doing this:
this.visionClient = new VisionServiceClient("my_api_key");
And you are using an old package (Microsoft.ProjectOxford.Vision was the project codename).
So, you should do the following:
1 - Switch to the latest package called Microsoft.Azure.CognitiveServices.Vision.ComputerVision, available on Nuget here
2 - Create your client by doing the following:
var visionClient = new ComputerVisionClient(new ApiKeyServiceClientCredentials("yourAPIkeyHere")))
{
Endpoint = "yourEndpointHere"
})
Endpoint format is: "https://region.api.cognitive.microsoft.com", for example for West Europe: "https://westeurope.api.cognitive.microsoft.com"
There may be some changes in the method you are calling or the parameters because of the package change, but you will now be up-to-date

Discord.NET C# Change Content of SocketMessage

So I am listening to the event whenever anyone on the server sends a message to any text channel with my bot. I want to detect swear words like "fuck" and change it to "f*ck".
I was unable to replace my message just normally only with reflection but it did not help since it only replaced it in the instance of the SocketMessage but it did not change the message on the server.
Any solution for that?
Framework: 4.6
Discord.NET: 1.0.2
Code:
private async Task MsgRec(SocketMessage e)
{
try
{
if (e.Content.Contains("fuck"))
{
foreach(PropertyInfo info in typeof(SocketMessage).GetProperties())
{
if (info.Name == "Content")
{
info.SetValue(e,e.Content.Replace("fuck", "f*ck"));
}
}
}
}
catch (Exception ex)
{
await e.Author.SendMessageAsync(ex.StackTrace);
}
}
Update I also tried this without any success:
var rMessage = (RestUserMessage) await e.Channel.GetMessageAsync(e.Id);
await rMessage.ModifyAsync(msg => msg.Content = e.Content.Replace("fuck", "f*ck"));
Discord, like other chat programs, does not allow you to change messages of users. You can not censor what a user wrote, you can only delete the whole message.
maybe you could try something like this
private async Task MsgRec(SocketMessage e)
{
var msg = e as SocketUserMessage;
if (msg == null) return;
if (msg.Content.Contains("fuck"))
{
var newMsg = msg.Content.Replace("fuck", "f*ck");
await Context.Channel.SendMessageAsync(newMsg);
}
}

How to use Telegram API in C# to send a message

I want use Telegram API in C# for send a simple message to a number. I found some lib's on GitHub but I am not able to use them.
Can anyone give a simple code ? Can I simply make HTTP calls ?
Install-Package Telegram.Bot
Create a bot using the botfather
get the api key using the /token command (still in botfather)
use this code:
var bot = new Api("your api key here");
var t = await bot.SendTextMessage("#channelname or chat_id", "text message");
You can now pass a channel username (in the format #channelusername)
in the place of chat_id in all methods (and instead of from_chat_id in
forwardMessage). For this to work, the bot must be an administrator in
the channel.
https://core.telegram.org/bots/api
Here is the easiest way I found so far. I found it here, thanks to Paolo Montalto https://medium.com/#xabaras/sending-a-message-to-a-telegram-channel-the-easy-way-eb0a0b32968
After creating a Telegram bot via BotFather and getting your destination IDs
via https://api.telegram.org/bot[YourApiToken]/getUpdates
you can send a message to your IDs by issuing an HTTP GET request to Telegram BOT API using the following URL https://api.telegram.org/bot[YourApiToken]/sendMessage?chat_id=[DestitationID]&text=[MESSAGE_TEXT]
Details on a simple way to create a bot and get IDs may be found here: https://programmingistheway.wordpress.com/2015/12/03/send-telegram-messages-from-c/
You can test those url strings even directly in browser.
Here is a simple method I use in C# to send messages, without dependency on any bot api related dll and async calls complication:
using System.Net;
...
public string TelegramSendMessage(string apilToken, string destID, string text)
{
string urlString = $"https://api.telegram.org/bot{apilToken}/sendMessage?chat_id={destID}&text={text}";
WebClient webclient = new WebClient();
return webclient.DownloadString(urlString);
}
use this code :)
with https://github.com/sochix/TLSharp
using TeleSharp.TL;
using TLSharp;
using TLSharp.Core;
namespace TelegramSend
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
TelegramClient client;
private async void button1_Click(object sender, EventArgs e)
{
client = new TelegramClient(<your api_id>, <your api_key>);
await client.ConnectAsync();
}
string hash;
private async void button2_Click(object sender, EventArgs e)
{
hash = await client.SendCodeRequestAsync(textBox1.Text);
//var code = "<code_from_telegram>"; // you can change code in debugger
}
private async void button3_Click(object sender, EventArgs e)
{
var user = await client.MakeAuthAsync(textBox1.Text, hash, textBox2.Text);
}
private async void button4_Click(object sender, EventArgs e)
{
//get available contacts
var result = await client.GetContactsAsync();
//find recipient in contacts
var user = result.users.lists
.Where(x => x.GetType() == typeof(TLUser))
.Cast<TLUser>()
.Where(x => x.first_name == "ZRX");
if (user.ToList().Count != 0)
{
foreach (var u in user)
{
if (u.phone.Contains("3965604"))
{
//send message
await client.SendMessageAsync(new TLInputPeerUser() { user_id = u.id }, textBox3.Text);
}
}
}
}
}}
There is now WTelegramClient, using the latest Telegram Client API protocol (connecting as a user, not bot).
The library is very complete but also very easy to use. Follow the README on GitHub for an easy introduction.
To send a message to someone can be as simple as:
using TL;
using var client = new WTelegram.Client(); // or Client(Environment.GetEnvironmentVariable)
await client.LoginUserIfNeeded();
var result = await client.Contacts_ResolveUsername("USERNAME");
await client.SendMessageAsync(result.User, "Hello");
//or by phone number:
//var result = await client.Contacts_ImportContacts(new[] { new InputPhoneContact { phone = "+PHONENUMBER" } });
//client.SendMessageAsync(result.users[result.imported[0].user_id], "Hello");
1-first create a channel in telegram (for example #mychanel)
2-create a telegram bot (for example #myTestBot) and get api token for next step
3-add #myTestBot to your channel(#mychanel) as administrator user
4-use below code for send message:
var bot = new TelegramBotClient("api_token_bot");
var s = await bot.SendTextMessageAsync("#mychanel", "your_message");
this code work for me:
using System.Net;
public class TelegramBot
{
static readonly string token = "123456789:AAHsxzvZLfFAsfAY3f78b8t6MXw3";
static readonly string chatId = "123456789";
public static string SendMessage(string message)
{
string retval = string.Empty;
string url = $"https://api.telegram.org/bot{token}/sendMessage?chat_id={chatId}&text={message}";
using(var webClient = new WebClient())
{
retval = webClient.DownloadString(url);
}
return retval;
}
}
I've written a client library for accessing Telegram bot's API and its source code is available in the Github. You can browse to the Telebot.cs file to see a sample of how to send a message to the bot API.
Github URL: github.com/mrtaikandi/Telebot
Nuget URL: nuget.org/packages/Telebot
Same unexplicable errors.
Solution: elevate the framework dastination to minimum 4.6; errors disappear.
Perhaps official support pages at
https://telegrambots.github.io/book/1/quickstart.html
are a little bit confusing saying: "...a .NET project targeting versions 4.5+"
bye
Just look and learn how to make a POST HTTP request with your favorite language.
Then learn how to use Telegram Bot API with the documentation:
https://core.telegram.org/bots
https://core.telegram.org/bots/api

Bing Maps GetRoute gives '0x8004231C' error

I'm trying to show a route from point-to-point on the bing-maps (testing on real device). I've entered 2 waypoints (GeoCoordinate) and I'm trying to get the route via the Windows PhoneToolKit using the await query.GetRouteAsync(). Unfortunately, I'm getting an unknown error:
The result of the async call:
'e.Result' threw an exception of type 'System.Reflection.TargetInvocationException'
The inner exception:
Exception from HRESULT: 0x8004231C
I've checked the MSDN website and noticed that this errorcode is not listed in the errorlist...
The related code is below. I've used the exact same code as in the sample set of the Windows Phone Toolkit, but removed the things which has nothing to do with getting the route:
private async void BtnShowRoute_Tap(object sender, System.Windows.Input.GestureEventArgs e)
{
try
{
RouteQuery query = new RouteQuery();
List<GeoCoordinate> wayPoints = new List<GeoCoordinate>();
wayPoints.Add(new GeoCoordinate(47.23449, -121.172447));
wayPoints.Add(new GeoCoordinate(47.062638, -120.691795));
query.Waypoints = wayPoints;
Route route = await query.GetRouteAsync();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
throw;
}
}
I have no idea what is going wrong here. Does anyone else experienced this issue? If so, did you resolve it? And how?
Note: I'm running Windows Phone 8.1. Dev Preview
This happens when the underlying service call times out before completing the query. Hopefully this will be fixed in next version , but for now you can use following code:
private async void BtnShowRoute_Tap(object sender, System.Windows.Input.GestureEventArgs e)
{
RouteQuery query = new RouteQuery();
List<GeoCoordinate> wayPoints = new List<GeoCoordinate>();
wayPoints.Add(new GeoCoordinate(47.23449, -121.172447));
wayPoints.Add(new GeoCoordinate(47.062638, -120.691795));
query.Waypoints = wayPoints;
query .QueryCompleted += geoQ_QueryCompleted;
query.GetRouteAsync();
}
private void geoQ_QueryCompleted(object sender, QueryCompletedEventArgs<Route> e)
{
try
{
Route myRoute = e.Result;
}
catch (TargetInvocationException)
{
Thread.Sleep(1000); // waiting for completing the query
geoQ_QueryCompleted(sender, e);
}
}

Categories