Xamarin.Forms how open default email client on device? - xamarin

In Xamarin.Forms if you want to open the device's default browser by tapping a Label with a link, it's simple as this:
private void WebUrl_TapGestureRecognizer_Tapped(object sender, EventArgs e)
{
var label = sender as Label;
string url = "http://" + label.Text;
Device.OpenUri(new Uri(url));
}
Is there a similarly simple way to open the device's default email client with an open NewMessage with email address?
private void EmailClient_TapGestureRecognizer_Tapped(object sender, EventArgs e)
{
var label = sender as Label;
// what goes here?
}
Thank you.

Try with:
var address = "your.address#gmail.com";
Device.OpenUri(new Uri($"mailto:{address}"));
Hope this helps.-

I actually use a Dependency Service so that I have more control over what I can send to mail client.
First I created an interface to be used by the dependency service called IEmailService.
public interface IEmailService
{
void CreateEmail(List<string> emailAddresses, List<string> ccs, string subject, string body, string htmlBody);
}
My Dependency Service for Android looks like this:
[assembly: Xamarin.Forms.Dependency(typeof(EmailService))]
namespace Droid.Services
{
public class EmailService : IEmailService
{
public void CreateEmail(List<string> emailAddresses, List<string> ccs, string subject, string body, string htmlBody)
{
var email = new Intent(Android.Content.Intent.ActionSend);
if (emailAddresses?.Count > 0)
{
email.PutExtra(Android.Content.Intent.ExtraEmail, emailAddresses.ToArray());
}
if (ccs?.Count > 0)
{
email.PutExtra(Android.Content.Intent.ExtraCc, ccs.ToArray());
}
email.PutExtra (Android.Content.Intent.ExtraSubject, subject);
email.PutExtra (Android.Content.Intent.ExtraText, body);
email.PutExtra (Android.Content.Intent.ExtraHtmlText, htmlBody);
email.SetType ("message/rfc822");
MainActivity.SharedInstance.StartActivity(email);
}
}
}
For iOS:
[assembly: Xamarin.Forms.Dependency(typeof(EmailService))]
namespace iOS.Services
{
public class EmailService : NSObject, IEmailService, IMFMailComposeViewControllerDelegate
{
public void CreateEmail(List<string> emailAddresses, List<string> ccs, string subject, string body, string htmlBody)
{
var vc = new MFMailComposeViewController();
vc.MailComposeDelegate = this;
if(emailAddresses?.Count > 0)
{
vc.SetToRecipients(emailAddresses.ToArray());
}
if(ccs?.Count > 0)
{
vc.SetCcRecipients(ccs.ToArray());
}
vc.SetSubject(subject);
vc.SetMessageBody(htmlBody, true);
vc.Finished += (sender, e) =>
{
vc.DismissModalViewController(true);
};
UIApplication.SharedApplication.Windows[0].
RootViewController.PresentViewController(vc, true, null);
}
}
}
Then I can just call this in my code:
DependencyService.Get<IEmailService>().CreateEmail(recipients, ccs, subject, body, bodyHtml);
This will open the mail client on each platform with the to, subject and body fields optionally poplulated.
I hope that helps.

You can use Launcher.OpenAsync(uri) exists in Xamarin.Essentials. OpenUri is obsolete as of version 4.3.0. uri = $"mailto:{address}?subject={emailSubject}&body={body content}";

Related

MAUI send sms without user interaction in Maui

I want to send a SMS in MAUI without opening the default messages App, I want to send the SMS silently in background. Does anyone know how to implement it?
Here is the implementation in MAUI.
Tested for Android and it works without opening the messages app. Here is the implementation for Android and iOS (not tested).
in the shared project create this class:
public partial class SmsService
{
public partial void Send(string address, string message);
}
Implementation for Android platform:
public partial class SmsService
{
public partial void Send(string phonenbr, string message)
{
SmsManager smsM = SmsManager.Default;
smsM.SendTextMessage(phonenbr, null, message, null, null);
}
}
Implementation for iOS platform (not tested):
public partial class SmsService
{
public partial void Send(string address, string message)
{
if (!MFMailComposeViewController.CanSendMail)
return;
MFMessageComposeViewController smsController = new MFMessageComposeViewController();
smsController.Recipients = new[] { address };
smsController.Body = message;
EventHandler<MFMessageComposeResultEventArgs> handler = null;
handler = (sender, args) =>
{
smsController.Finished -= handler;
var uiViewController = sender as UIViewController;
if (uiViewController == null)
{
throw new ArgumentException("sender");
}
uiViewController.DismissViewControllerAsync(true);
};
smsController.Finished += handler;
UIApplication.SharedApplication.KeyWindow.RootViewController.PresentViewControllerAsync(smsController, true);
}
}

How to use an interface

I'm trying to build my first xamarin app, which I'm building using forms. One of the features of the app is sending users locations and have to do that even if the app is in the background. So I came across James Montemagno's GeolocatorPlugin, which promised to do just that.
As the documentation was not that clear on how to implement his plugin in the background I looked through the projects closed issues and found a guy which gave an example of a simple case of using the plugin with a service. (https://github.com/jamesmontemagno/GeolocatorPlugin/issues/272)
I've adopted the code and created the service. The service are using an interface to start the service and now my problem is how to make use of the interface to make the service run.
In my shared project I put the interface and the viewmodel and in xamarin.android project I put the service.
The interface - IGeolocationBackgroundService:
public interface IGeolocationBackgroundService {
void StartService();
void StartTracking();
}
The viewmodel - GeolocatorPageViewModel:
public class GeolocatorPageViewModel
{
public Position _currentUserPosition { get; set; }
public string CoordinatesString { get; set; }
public List<string> userPositions { get; set; }
public ICommand StartTrackingCommand => new Command(async () =>
{
if (CrossGeolocator.Current.IsListening)
{
await CrossGeolocator.Current.StopListeningAsync();
}
CrossGeolocator.Current.DesiredAccuracy = 25;
CrossGeolocator.Current.PositionChanged += Geolocator_PositionChanged;
await CrossGeolocator.Current.StartListeningAsync(
TimeSpan.FromSeconds(3), 5);
});
private void Geolocator_PositionChanged(object sender, PositionEventArgs e)
{
var position = e.Position;
_currentUserPosition = position;
var positionString = $"Latitude: {position.Latitude}, Longitude: {position.Longitude}";
CoordinatesString = positionString;
Device.BeginInvokeOnMainThread(() => CoordinatesString = positionString);
userPositions.Add(positionString);
Debug.WriteLine($"Position changed event. User position: {CoordinatesString}");
}
}
The service - GeolocationService:
[assembly: Xamarin.Forms.Dependency(typeof(GeolocationService))]
namespace MyApp.Droid.Services
{
[Service]
public class GeolocationService : Service, IGeolocationBackgroundService
{
Context context;
private static readonly string CHANNEL_ID = "geolocationServiceChannel";
public GeolocatorPageViewModel ViewModel { get; private set; }
public override IBinder OnBind(Intent intent)
{
return null;
}
public GeolocationService(Context context)
{
this.context = context;
CreateNotificationChannel();
}
private void CreateNotificationChannel()
{
NotificationChannel serviceChannel = new NotificationChannel(CHANNEL_ID,
"GeolocationService", Android.App.NotificationImportance.Default);
NotificationManager manager = context.GetSystemService(Context.NotificationService) as NotificationManager;
manager.CreateNotificationChannel(serviceChannel);
}
//[return: GeneratedEnum]
public override StartCommandResult OnStartCommand(Intent intent, [GeneratedEnum] StartCommandFlags flags, int startId)
{
var newIntent = new Intent(this, typeof(MainActivity));
newIntent.AddFlags(ActivityFlags.ClearTop);
newIntent.AddFlags(ActivityFlags.SingleTop);
var pendingIntent = PendingIntent.GetActivity(this, 0, newIntent, 0);
var builder = new Notification.Builder(this, CHANNEL_ID);
var notification = builder.SetContentIntent(pendingIntent)
.SetSmallIcon(Resource.Drawable.ic_media_play_light)
.SetAutoCancel(false)
.SetTicker("Locator is recording")
.SetContentTitle("GeolocationService")
.SetContentText("Geolocator is recording for position changes.")
.Build();
StartForeground(112, notification);
//ViewModel = new GeolocatorPageViewModel();
return StartCommandResult.Sticky;
}
public void StartService()
=> context.StartService(new Intent(context, typeof(GeolocationService)));
public void StartTracking()
{
ViewModel = new GeolocatorPageViewModel();
ViewModel.StartTrackingCommand.Execute(null);
}
}
}
So be clear, I need to start the service and I'm not used to interfaces, so how do I call the interface?
use DependencyService to get a reference to your service and then start it
var svc = DependencyService.Get<IGeolocationBackgroundService>();
svc.StartService();
svc.StartTracking();

How to invoke async activity in UIPath

I am trying to execute custom asyncCodeActivity in UIPath. Added the package, passing all data, however UIPath just hangs when it reaches custom activity and does not throw any exceptions/or stops. I tried to create Class Library using CodeActivity and AsyncCodeActivity - my activity should make several APICalls but I get result it just stops when it reaches my custom activity and does not go to the next one. Is there any example how to create async custom activity for UIPath? My class library worked ok when I tried to test it outside of UIpath. Will appreciate any help.
My class library using CodeActivity:
public class AddInvoice : CodeActivity
{
[Category("Input")]
[RequiredArgument]
public InArgument<string> PickupZip { get; set; }
[Category("Output")]
[RequiredArgument]
public OutArgument<String> Output { get; set; }
public async Task<string> ApiTest(CodeActivityContext context)
{
try
{
var origin = await GoogleAPIWrapper.GetAddressByZip(PickupZip.Get(context));
string PickupAddress;
string DeliveryAddress;
var inv = new IList();
if (origin.StatusId >= 0)
{
invoice.PickupCity = origin.Locality;
invoice.PickupState = origin.AdminLevel1;
}
else
{
invoice.PickupCity = null;
invoice.PickupState = null;
}
var tkn = token.Get(context);
var client = new HttpClient();
HttpClientHandler handler = new HttpClientHandler();
client = new HttpClient(handler, false);
client.BaseAddress = new Uri("http://test.test.com/");
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + tkn);
StringContent content = new StringContent(JsonConvert.SerializeObject(inv), Encoding.UTF8, "application/json");
var response = await client.PostAsync("api/insert/", content);
var resultContent = response.StatusCode;
Output.Set(context, resultContent.ToString());
}
catch (Exception e)
{
Output.Set(context, e.ToString());
}
return "ok";
}
protected override void Execute(CodeActivityContext context)
{
try
{
string result = ApiTest(context).GetAwaiter().GetResult();
}
catch (Exception e)
{
Output.Set(context, e.ToString());
}
}
public class IList
{
public string PickupState { get; set; }
public string PickupCity { get; set; }
}
}
Classes that derive from CodeActivity are synchronous by default. Since UiPath is based on Windows Workflow, deriving from an AsyncCodeActivity class should work.
You didn't ask explicitly for it, but since you're essentially calling a web service, have a look at the Web Activities package, the HTTP Request in particular. This also comes with JSON deserialization. You can find more information about web service integration here, for example (disclaimer: I am the author).

How to load PDF in Xamarin Forms

I have a Xamarin Forms app where I want to open a locally stored PDF. I don't need to load them within the app, I'm fine with shelling out to the device's default document viewer for PDFs. How can I do this?
I tried sending a WebView to the PDF, but that didn't work, I just got a blank page.
I've recently done this in my own project using a custom renderer. First implement an empty Xamarin forms view such as (I've included a bindable FilePath attribute):
public class PdfViewer : View
{
public static readonly BindableProperty FilePathProperty =
BindableProperty.Create<DocumentViewer, string>(p => p.FilePath, null);
public string FilePath
{
get
{
return (string)this.GetValue(FilePathProperty);
}
set
{
this.SetValue(FilePathProperty, value);
}
}
}
Then create an iOS Renderer that will be registered for this control. This renderer can, as it is within an iOS project, use the Quick Look Preview Controller to delegate to the built in iOS pdf viewer:
[assembly: ExportRenderer(typeof(PdfViewer), typeof(DocumentViewRenderer))]
public class DocumentViewRenderer
: ViewRenderer<PdfViewer, UIView>
{
private QLPreviewController controller;
protected override void OnElementChanged(ElementChangedEventArgs<DocumentViewer> e)
{
base.OnElementChanged(e);
this.controller = new QLPreviewController();
this.controller.DataSource = new DocumentQLPreviewControllerDataSource(e.NewElement.FilePath);
SetNativeControl(this.controller.View);
}
private class DocumentQLPreviewControllerDataSource : QLPreviewControllerDataSource
{
private string fileName;
public DocumentQLPreviewControllerDataSource(string fileName)
{
this.fileName = fileName;
}
public override int PreviewItemCount(QLPreviewController controller)
{
return 1;
}
public override QLPreviewItem GetPreviewItem(QLPreviewController controller, int index)
{
var documents = NSBundle.MainBundle.BundlePath;
var library = Path.Combine(documents, this.fileName);
NSUrl url = NSUrl.FromFilename(library);
return new QlItem(string.Empty, url);
}
private class QlItem : QLPreviewItem
{
public QlItem(string title, NSUrl uri)
{
this.ItemTitle = title;
this.ItemUrl = uri;
}
public override string ItemTitle { get; private set; }
public override NSUrl ItemUrl { get; private set; }
}
}
}
I haven't compiled and run this as I've extracted it from my larger project but in general this should work.
I had to do something and solve it using a DependencyService . You can use it to open the pdf depending on each platform
I show you an example of how to solve it on Android :
IPdfCreator.cs:
public interface IPdfCreator
{
void ShowPdfFile();
}
MainPage.cs:
private void Button_OnClicked(object sender, EventArgs e)
{
DependencyService.Get<IPdfCreator>().ShowPdfFile();
}
PdfCreatorAndroid.cs
[assembly: Dependency(typeof(PdfCreatorAndroid))]
namespace Example.Droid.DependecyServices
{
public class PdfCreatorAndroid : IPdfCreator
{
public void ShowPdfFile()
{
var fileLocation = "/sdcard/Template.pdf";
var file = new File(fileLocation);
if (!file.Exists())
return;
var intent = DisplayPdf(file);
Forms.Context.StartActivity(intent);
}
public Intent DisplayPdf(File file)
{
var intent = new Intent(Intent.ActionView);
var filepath = Uri.FromFile(file);
intent.SetDataAndType(filepath, "application/pdf");
intent.SetFlags(ActivityFlags.ClearTop);
return intent;
}
}
}
Result:
http://i.stack.imgur.com/vrwzt.png
Here there is a good project that uses MuPDF Library in xamarin . I've tested it and it works properly.
With MuPDF you can zoom out , zoom in and even write some note on PDFs.

Trying to call code in my controller but getting Null Reference error

Don't want to over-complicate the issue, but I think I need to post all the code that's hooked into this error.
Using MvcMailer and introduced a separate Send mechanism (for use with Orchard CMS' own EMail).
The MvcMailer Code:
1) AskUsMailer.cs:
public class AskUsMailer : MailerBase, IAskUsMailer
{
public AskUsMailer()
: base()
{
//MasterName = "_Layout";
}
public virtual MvcMailMessage EMailAskUs(AskUsViewModel model)
{
var mailMessage = new MvcMailMessage { Subject = "Ask Us" };
ViewData.Model = model;
this.PopulateBody(mailMessage, viewName: "EMailAskUs");
return mailMessage;
}
}
2) IAskUsMailer.cs:
public interface IAskUsMailer : IDependency
{
MvcMailMessage EMailAskUs(AskUsViewModel model);
}
3) AskUsController.cs: (GETTING NULL REFERENCE ERROR BELOW)
[Themed]
public ActionResult Submitted()
{
//This is the new call (see new code below):
//Note: Debugging steps through eMailMessagingService,
//then shows the null reference error when continuing to
//SendAskUs
eMailMessagingService.SendAskUs(askUsData);
//Below is normal MvcMailer call:
//AskUsMailer.EMailAskUs(askUsData).Send();
return View(askUsData);
}
Note: askUsData is defined in a separate block in the controller:
private AskUsViewModel askUsData;
protected override void OnActionExecuting(ActionExecutingContext
filterContext)
{
var serialized = Request.Form["askUsData"];
if (serialized != null) //Form was posted containing serialized data
{
askUsData = (AskUsViewModel)new MvcSerializer().
Deserialize(serialized, SerializationMode.Signed);
TryUpdateModel(askUsData);
}
else
askUsData = (AskUsViewModel)TempData["askUsData"] ??
new AskUsViewModel();
TempData.Keep();
}
protected override void OnResultExecuted(ResultExecutedContext
filterContext)
{
if (filterContext.Result is RedirectToRouteResult)
TempData["askUsData"] = askUsData;
}
I did not know how to get my EMailMessagingService.cs (see below) call into the controller, so in a separate block in the controller I did this:
private IEMailMessagingService eMailMessagingService;
public AskUsController(IEMailMessagingService eMailMessagingService)
{
this.eMailMessagingService = eMailMessagingService;
}
I think this is part of my problem.
Now, the new code trying to hook into Orchard's EMail:
1) EMailMessagingServices.cs:
public class EMailMessagingService : IMessageManager
{
private IAskUsMailer askUsMailer;
private IOrchardServices orchardServices;
public EMailMessagingService(IAskUsMailer askUsMailer,
IOrchardServices orchardServices)
{
this.orchardServices = orchardServices;
this.askUsMailer = askUsMailer;
this.Logger = NullLogger.Instance;
}
public ILogger Logger { get; set; }
public void SendAskUs(AskUsViewModel model)
{
var messageAskUs = this.askUsMailer.EMailAskUs(model);
messageAskUs.To.Add("email#email.com");
//Don't need the following (setting up e-mails to send a copy anyway)
//messageAskUs.Bcc.Add(AdminEmail);
//messageAskUs.Subject = "blabla";
Send(messageAskUs);
}
....
}
The EMailMessagingService.cs also contains the Send method:
private void Send(MailMessage messageAskUs)
{
var smtpSettings = orchardServices.WorkContext.
CurrentSite.As<SmtpSettingsPart>();
// can't process emails if the Smtp settings have not yet been set
if (smtpSettings == null || !smtpSettings.IsValid())
{
Logger.Error("The SMTP Settings have not been set up.");
return;
}
using (var smtpClient = new SmtpClient(smtpSettings.Host,
smtpSettings.Port))
{
smtpClient.UseDefaultCredentials =
!smtpSettings.RequireCredentials;
if (!smtpClient.UseDefaultCredentials &&
!String.IsNullOrWhiteSpace(smtpSettings.UserName))
{
smtpClient.Credentials = new NetworkCredential
(smtpSettings.UserName, smtpSettings.Password);
}
if (messageAskUs.To.Count == 0)
{
Logger.Error("Recipient is missing an email address");
return;
}
smtpClient.EnableSsl = smtpSettings.EnableSsl;
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
messageAskUs.From = new MailAddress(smtpSettings.Address);
messageAskUs.IsBodyHtml = messageAskUs.Body != null &&
messageAskUs.Body.Contains("<") &&
messageAskUs.Body.Contains(">");
try
{
smtpClient.Send(messageAskUs);
Logger.Debug("Message sent to {0} with subject: {1}",
messageAskUs.To[0].Address, messageAskUs.Subject);
}
catch (Exception e)
{
Logger.Error(e, "An unexpected error while sending
a message to {0} with subject: {1}",
messageAskUs.To[0].Address, messageAskUs.Subject);
}
}
}
Now, in EMailMessagingService.cs I was getting an error that things weren't being implemented, so I auto-generated the following (don't know if this is part of my error):
public void Send(Orchard.ContentManagement.Records.ContentItemRecord recipient, string type, string service, System.Collections.Generic.Dictionary<string, string> properties = null)
{
throw new NotImplementedException();
}
public void Send(System.Collections.Generic.IEnumerable<Orchard.ContentManagement.Records.ContentItemRecord> recipients, string type, string service, System.Collections.Generic.Dictionary<string, string> properties = null)
{
throw new NotImplementedException();
}
public void Send(System.Collections.Generic.IEnumerable<string> recipientAddresses, string type, string service, System.Collections.Generic.Dictionary<string, string> properties = null)
{
throw new NotImplementedException();
}
public bool HasChannels()
{
throw new NotImplementedException();
}
public System.Collections.Generic.IEnumerable<string> GetAvailableChannelServices()
{
throw new NotImplementedException();
}
2) IEMailMessagingServices.cs
public interface IEMailMessagingService
{
MailMessage SendAskUs(AskUsViewModel model);
}
MvcMailer works fine without this addition (outside of Orchard), but I am trying to get everything working within Orchard.
I just cannot figure out what I am doing wrong. Any thoughts?
Sorry for excessive code.
IEmailMessaginService does not implement IDependency, so it can't be found by Orchard as a dependency. That's why it's null.

Resources