sending email in xamarin forms - c#

I'm trying to send an email in my xamarin forms project, I have tried both in the iPhone simulator and on an iPhone device. When I push the send email button on the iPhone, nothing happens, not even a debug error. I have also made sure i am logged in with my email on the device.
I have used serviceDependency and followed the setup at this link:
https://developer.xamarin.com/recipes/ios/shared_resources/email/send_an_email/
my interface:
public interface InterfaceEmail
{
void sendEmail();
}
iOS implementation:
[assembly: Xamarin.Forms.Dependency(typeof(SendEmail))]
namespace myProject.iOS
{
public partial class SendEmail : InterfaceEmail
{
MFMailComposeViewController mailController;
public SendEmail() {}
public void sendEmail()
{
if (MFMailComposeViewController.CanSendMail)
{
mailController = new MFMailComposeViewController();
mailController.SetToRecipients (new string[] {"my#email.com"});
mailController.SetSubject ("test mail");
mailController.SetMessageBody ("This is a test", false);
mailController.Finished += (object sender, MFComposeResultEventArgs e) =>
{
Console.WriteLine(e.Result.ToString());
e.Controller.DismissViewController(true, null);
};
UIApplication.SharedApplication.KeyWindow.RootViewController.PresentViewController(mailController, true, null);
}}}}
Implementation in my shared code:
async void Handle_ToolbarButton(object sender, System.EventArgs e)
{
var action = await DisplayActionSheet("What do you want to do?", "Abort", null, "Send email");
if(action == "Send email")
{
DependencyService.Get<InterfaceEmail>().sendEmail();
}
}
Does anyone have an idea on what could be wrong here?

For a better way to send email without even writing platform specific code install this nuget into your solution
xam.plugin.Messaging(https://www.nuget.org/packages/Xam.Plugins.Messaging/)
Then write the code below in PCL
var email = new EmailMessageBuilder()
.To("to.plugins#xamarin.com")
.Subject("Xamarin Messaging Plugin")
.Body("Well hello there from Xam.Messaging.Plugin")
.Build();
You can also add attachments. For more details please go through https://github.com/cjlotz/Xamarin.Plugins/blob/master/Messaging/Details.md

Probably it is related to this bug:
https://bugzilla.xamarin.com/show_bug.cgi?id=58933
Just remove DisplayActionSheet.
Or if you want to use it, then there is a temporary solution in this Xamarin forum topic
Add
await Task.Delay(100);
after DisplayActionSheet

The iPhone simulator will always return false to CanSendMail as it can not send mail. On a physical device, you will need to configure at least on e mail account.
Also:
Typo in:
[assembly: Xamarin.Forms.Dependency(typeof(sendEmail))]
Should be:
[assembly: Xamarin.Forms.Dependency(typeof(SendEmail))]
Typo in:
mailController.Finnished += ~~~~~
Should be:
mailController.Finished += ~~~~~

Related

How to use Bluetooth in C#/.net?

I'm trying to do an UI with C# on Visual Studio (on PC[windows10]) and connect some bluetooth devices.
I'm using Windows.Devices.Radios & Windows.Devices.Bluetooth, but I have some troubles with that. After few steps I try to use the bluetooth when I press a button.
This is the code
private async void btnStart_ClickAsync(object sender, EventArgs e)
{
Repl test = new Repl();
var radio = await Radio.RequestAccessAsync();
if (access != RadioAccessStatus.Allowed)
{
return;
}
BluetoothAdapter adapter = await BluetoothAdapter.GetDefaultAsync();
if (null != adapter)
{
var btRadio = await adapter.GetRadioAsync();
if (bluetoothState)
{
await btRadio.SetStateAsync(RadioState.On);
}
else
{
await btRadio.SetStateAsync(RadioState.Off);
}
}
string connect = $"connect {macRight}\r\n";
//string start = "start\r\n";
await BaseCommands.repl.ParseLine(connect);
}
after the 1st request I'm always in the "return;"
I saw some people saying use x32 or x64 and x86. I already try that but I don't know why it doesn't work for me ...
I also saw some post saying change something in the Manifest, but I don't know where to find it :/
I'm a beginner with C#/.NET so if someone can help me to fix that i will appreciate =)
PS : I have another project which use bluetooth and it work perfectly so I have no ideas to fix my own project ...

Ozeki VoIP not receiving audio

I have been working on a Softphone project in c# and have been using Ozeki VoIP SDK.
So far I have got the softphone successfully registering and making outbound calls. However, I can not hear the called party but they can hear me. (Me being the softphone and called party being a Cisco SPA504G Phone)
2-Way audio is fine when using other applications (Such as X-Lite)
The SIP Trace shows I am sending but not receiving any RTP packages, is this something I have done wrong in my code (See below) or an issue on the PBX side. (Thirdlane PBX)
void CreateCall()
{
string numberToDial = txtNum.Text;
logOutput("Call " + numberToDial);
txtLog.ScrollToCaret();
call = softphone.CreateCallObject(phoneLine, numberToDial);
call.CallStateChanged += call_CallStateChanged;
call.Start();
}
private void SetupDevices()
{
connector.Connect(microphone, mediaSender);
connector.Connect(mediaReceiver, speaker);
mediaSender.AttachToCall(call);
mediaReceiver.AttachToCall(call);
microphone.Start();
speaker.Start();
}
void call_CallStateChanged(object sender, CallStateChangedArgs e)
{
if (e.State == CallState.Answered)
{
WireUpCallEvents();
}
if (e.State == CallState.Completed)
{
WireDownCallEvents();
}
logOutput("Call state: " + e.State);
}
private void WireUpCallEvents()
{
call.CallStateChanged += (call_CallStateChanged);
SetupDevices();
}
private void WireDownCallEvents()
{
call.CallStateChanged -= (call_CallStateChanged);
}
After trying another extension on another PBX I found that the issue was caused by the additional setting "nat" not being set. Once I set this with the value "yes" I was able to get 2-way audio on both parties.
This was a Thridlane PBX so the setting was in "Selected Tenants PBX" => "Extensions and Contacts" => "User Extensions" => (The extension number I was using) => Phone.

Discord.net and TwitchLib C# Communication

I am stuck on a personal project to create a question bot for a twitch channel I mod for. The idea is to take questions in channel with the prefix [q] followed by the question. It then posts the question into #questions in discord. I have both sides of the bot working in their own right, however, I cannot figure out how to actually send a message to discord from that point. Here is an example of what I have.
Twitch receiving a messaging:
TwitchClient tclient;
DiscordClient dclient;
CommandService commands;
private void Client_OnMessageReceived(object sender, OnMessageReceivedArgs e)
{
if (e.ChatMessage.Message.StartsWith("[q]", StringComparison.InvariantCultureIgnoreCase))
{
// Do stuff here
}
} else if(e.ChatMessage.Message.StartsWith("!uptime", StringComparison.InvariantCultureIgnoreCase))
{
tclient.SendMessage(GetUptime()?.ToString() ?? "Offline");
} else if(e.ChatMessage.Message.StartsWith("[test]", StringComparison.InvariantCultureIgnoreCase))
{
tclient.SendMessage("Received");
}
}
And on the discord side I can send a message directly to them via:
public void dMessage(object sender, MessageEventArgs e)
{
//TODO: Add !clearall to clear a channel
//TODO: Add !start and !stop
if (e.Message.RawText.StartsWith("test"))
{
e.Channel.SendMessage(e.User.Mention + "Test confirmed");
}
else if (e.Message.RawText.StartsWith("test2"))
{
e.User.SendMessage("Test 2 confirmed");
}
}
Or I can:
commands.CreateCommand("test").Do(async (e) =>
{
await e.Channel.SendMessage("test 1 confirmed");
});
I am using TwitchLib by swiftyspiffy 1.4.9 nuget.org/packages/TwitchLib/1.4.9 and Discord.Net 0.9.6 w/ Discord.Net.Commands 0.9.6
But the scopes of the two sides seem to be completely independant and I cannot figure out how to get them to communicate. I even put them both into one large file for testing purposes. I seem to not grasp something important. I apologize if this is covered somewhere, I couldn't find anything like my problem.

How to programmatically pair a bluetooth device

I recently bought a Lilypad Simblee BLE Board and I'd like to pair it programmatically to my computer (using the 32feet.NET library in C#).
I'm aware the "How to programmatically pair a bluetooth device" has already been asked on StackOverflow (here for example), however for some reason, all my attempts to pair the device programmatically have failed. Indeed, I successfully paired the device with the "Manage Bluetooth devices" window in Windows 10 Settings panel (Settings > Devices > Bluetooth).
Firstly, I don't know the pairing method (either legacy or SSP) to use with my device. Windows never asked me for a PIN or something, so I guess it's SSP, but I'm unsure.
I searched on Google how to do a SSP pairing request with 32feet.NET: I found this.
However, once it discovered my device (the device discovery works properly), the pairing request instantly fails.
My code:
using InTheHand.Net.Bluetooth;
using InTheHand.Net.Sockets;
using System;
using System.Collections.Generic;
namespace HLK_Client
{
class HLKBoard
{
public event HLKBoardEventHandler HLKBoardConnectionComplete;
public delegate void HLKBoardEventHandler(object sender, HLKBoardEventArgs e);
private BluetoothClient _bluetoothClient;
private BluetoothComponent _bluetoothComponent;
private List<BluetoothDeviceInfo> _inRangeBluetoothDevices;
private BluetoothDeviceInfo _hlkBoardDevice;
private EventHandler<BluetoothWin32AuthenticationEventArgs> _bluetoothAuthenticatorHandler;
private BluetoothWin32Authentication _bluetoothAuthenticator;
public HLKBoard()
{
_bluetoothClient = new BluetoothClient();
_bluetoothComponent = new BluetoothComponent(_bluetoothClient);
_inRangeBluetoothDevices = new List<BluetoothDeviceInfo>();
_bluetoothAuthenticatorHandler = new EventHandler<BluetoothWin32AuthenticationEventArgs>(_bluetoothAutenticator_handlePairingRequest);
_bluetoothAuthenticator = new BluetoothWin32Authentication(_bluetoothAuthenticatorHandler);
_bluetoothComponent.DiscoverDevicesProgress += _bluetoothComponent_DiscoverDevicesProgress;
_bluetoothComponent.DiscoverDevicesComplete += _bluetoothComponent_DiscoverDevicesComplete;
}
public void ConnectAsync()
{
_inRangeBluetoothDevices.Clear();
_hlkBoardDevice = null;
_bluetoothComponent.DiscoverDevicesAsync(255, true, true, true, false, null);
}
private void PairWithBoard()
{
Console.WriteLine("Pairing...");
bool pairResult = BluetoothSecurity.PairRequest(_hlkBoardDevice.DeviceAddress, null);
if (pairResult)
{
Console.WriteLine("Success");
}
else
{
Console.WriteLine("Fail"); // Instantly fails
}
}
private void _bluetoothComponent_DiscoverDevicesProgress(object sender, DiscoverDevicesEventArgs e)
{
_inRangeBluetoothDevices.AddRange(e.Devices);
}
private void _bluetoothComponent_DiscoverDevicesComplete(object sender, DiscoverDevicesEventArgs e)
{
for (int i = 0; i < _inRangeBluetoothDevices.Count; ++i)
{
if (_inRangeBluetoothDevices[i].DeviceName == "HLK")
{
_hlkBoardDevice = _inRangeBluetoothDevices[i];
PairWithBoard();
return;
}
}
HLKBoardConnectionComplete(this, new HLKBoardEventArgs(false, "Didn't found any \"HLK\" discoverable device"));
}
private void _bluetoothAutenticator_handlePairingRequest(object sender, BluetoothWin32AuthenticationEventArgs e)
{
e.Confirm = true; // Never reach this line
}
}
}
Why does the pairing request fail?
The answer to the question you linked has a plausible suggestion... did you read it?
Also you should look at this question as well.
32feet library is built around legacy pairing, so that you either need to know the pin of the device you are connecting to, or you supply it with a null to get a popup window to enter a pin.
It also says that the windows function used by 32feet is deprecated in newer versions of windows. If that's true, the reason it's failing instantly is because you've passed a null pin in your pairing request and for it to proceed windows needs to show a dialog which no longer exists.
What happens if you try to connect with the pin "0000" or "1234" ?
I'm looking at the source code of WindowsBluetoothSecurity.cs in 32feet.net and I see if a pairing request fails, it logs the error code to Debug.WriteLine, any chance you could post that error code here?
One good work around to this problem might be to import BluetoothAuthenticateDeviceEx and use that manually to complete the pairing request. If you don't want to do this manually, it looks like in the latest version of the 32feet source, there is actually a SSP pairing method that utilises this method but it's not public and it's not used anywhere so you'll need to access it via reflection:
typeof(BluetoothSecurity)
.GetMethod("PairRequest", BindingFlags.Static | BindingFlags.NonPublic)
.Invoke(null, new object[] { _hlkBoardDevice.DeviceAddress, BluetoothAuthenticationRequirements.MITMProtectionNotRequired });

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

Categories