Add AdMob in MAUI by Xamarin.GooglePlayServices.Ads.Lite - c#

I am trying to implement AdMob for my application. I need Banners, Full screen, and Native ads.
I was able to create full screen and banner ads by this Nuget https://github.com/marcojak/MauiMTAdmob.
But unfortunately it don't contains native ads.
So I am trying to rewrite the implementations from the tutorial for Xamarin with Xamarin.GooglePlayServices.Ads.Lite Nuget. But there are things here that I don't know how to change.
Code which I trying to rewrite:
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
//add test ads and we will remove after upload :::
RequestConfiguration.Builder builder = new RequestConfiguration.Builder();
builder = builder.SetTestDeviceIds(new string[] { "your id in output" });
MobileAds.RequestConfiguration = builder.Build();
Android.Gms.Ads.MobileAds.Initialize(ApplicationContext);
//
LoadApplication(new App());
}
When I change global::Xamarin.Forms.Forms.Init(this, savedInstanceState); -> Microsoft.Maui.Controls.Compatibility.Forms.Init() I don't see overwrite which accepts this parameters.
I am not sure what should I put there builder = builder.SetTestDeviceIds(new string[] { "your id in output" }); Should I add Banner, Full screen and Native ads Id?
And LoadApplication(new App()); don't exist in MAUI.
Is anyone able to solve my problem or provide an example implementation for MAUI?

Related

How to display a DatePicker popup in .NET MAUI project?

For Xamarin projects to display Date picker in popup I used Acr.UserDialogs, but it is not compatible with .NET MAUI.
Is there a port or something like this for .NET MAUI?
If no, how can I display a date popup for a .NET MAUI project?
According to the link you provided, The newest version of the Acr.UserDialogs package has supported the .net maui.
And you can check the package owner's sample which shows how to use Acr.UserDialogs version 8.0.1.
Sample link: https://github.com/aritchie/userdialogs/tree/master/sample/Sample
To use .net6 version of Acr.UserDialogs package, I have to initialize it in MauiProgram instead of MainActivity.
My MauiProgram class looks like that, note the ConfigureLifecycleEvents part. It is relevant to the subject.
public static class MauiProgram
{
public static MauiApp CreateMauiApp()
{
var builder = MauiApp.CreateBuilder();
builder.UseMauiApp<App>().ConfigureFonts(fonts =>
{
// configuring fonts here, (not related to the subject)
})
.ConfigureLifecycleEvents(events =>
{
#if ANDROID
events.AddAndroid(android => android.OnApplicationCreate(app => UserDialogs.Init(app)));
#endif
})
// other useXXXXX() calls (not related to the subject)
return builder.Build();
}
}
To init UserDialogs correctly in Android, to also provide UserDialogs with DependencyInjection (ConstructorInjection) i do it in my MainApplication.cs
protected override MauiApp CreateMauiApp()
{
UserDialogs.Init(this);
return MauiProgram.CreateMauiApp();
}
In this case you can also apply UserDialogs to your DependencyInjection service like
builder.Services.AddSingleton<IUserDialogs>(UserDialogs.Instance);
in your MauiProgram.cs.
So the ConfigureLifecycleEvents isn't needed anymore and you can also avoid this ugly #if pattern ;)

Error occurred attempting to retrieve page templates. Contact administrator and check page builder feature registered correctly the MVC project

This is my Application.config File
public class ApplicationConfig
{
public static void RegisterFeatures(IApplicationBuilder builder)
{
// Enable required Kentico features
// Uncomment the following to use the Page builder feature
//builder.UsePageBuilder();
//builder.UseScheduler();
builder.UsePageRouting(new PageRoutingOptions
{
//EnableAlternativeUrls = true
});
}
And am getting this error when am ready to achieve this
I was trying to add these as page and get this error
Why is the UsePageBuilder commented out? This has to be enabled in order to use page builder. I would also recommend checking this post on Kentico's DevNet and there are also other discussions on this topic on the devnet.kentico.com site.

Singup/Registration page for Xamarin.Forms UWP & Android

I'm trying to create a signup/registration page for my Xamarin.Forms app. I've done a fair bit of reading on this and I've learned that authentication is a complicated process so it's best to use a service like OAuth or Azure Active Directory. I even created an account with Azure and connected my app (I think) but the documentation is sparse as far as implementing a registration page. OAuth seemed to have a pretty good tutorial on their site but it was only for Android and iOS, and my app is for Android & UWP. Is there anyone that can show how to implement a registration page in Xamarin.Forms? I don't have much of a user base yet so I'd like to use a service that's free or very cost effective, maybe like a pay per user model.
After connecting my Azure project in Visual Studio this code was auto-generated in a file called Startup.Auth.cs:
public partial class Startup
{
public void ConfigureAuth(IAppBuilder app)
{
app.UseWindowsAzureActiveDirectoryBearerAuthentication(
new WindowsAzureActiveDirectoryBearerAuthenticationOptions
{
Tenant = ConfigurationManager.AppSettings["ida:Tenant"],
TokenValidationParameters = new TokenValidationParameters
{
ValidAudience = ConfigurationManager.AppSettings["ida:Audience"]
},
MetadataAddress = ConfigurationManager.AppSettings["ida:MetadataAddress"],
});
}
}
And this file Startup.MobileApp.cs:
public partial class Startup
{
public static void ConfigureMobileApp(IAppBuilder app)
{
HttpConfiguration config = new HttpConfiguration();
new MobileAppConfiguration()
.UseDefaultConfiguration()
.ApplyTo(config);
// Use Entity Framework Code First to create database tables based on your DbContext
Database.SetInitializer(new MobileServiceInitializer());
MobileAppSettingsDictionary settings = config.GetMobileAppSettingsProvider().GetMobileAppSettings();
if (string.IsNullOrEmpty(settings.HostName))
{
app.UseAppServiceAuthentication(new AppServiceAuthenticationOptions
{
// This middleware is intended to be used locally for debugging. By default, HostName will
// only have a value when running in an App Service application.
SigningKey = ConfigurationManager.AppSettings["SigningKey"],
ValidAudiences = new[] { ConfigurationManager.AppSettings["ValidAudience"] },
ValidIssuers = new[] { ConfigurationManager.AppSettings["ValidIssuer"] },
TokenHandler = config.GetAppServiceTokenHandler()
});
}
app.UseWebApi(config);
}
}
But I have no idea how to work with these. What I do know is how to make a page with xaml and work with user inputs in the code behind (C#), but once I have user input like a new user name and such how do I connect to the authentication service? Any help would be appreciated, either in the form of detailed instructions or a link to a tutorial. Also I am not looking to use a 3rd party login such as login with Google or login with Facebook.

FirebaseAuth.Instance is null when trying to sign in/create account

I am trying to log into Firebase using an Email and Password in Xamarin Forms. Everything was working fine originally until it suddenly stopped. When calling the CreateUserWithEmailAndPasswordAsync method, I get a null reference exception because my FirebaseAuth.Instance comes through as null.
I initialise my app and call GetInstance in my MainActivity and the code previously worked so I am unsure of the problem.
MainActivity.cs
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
FirebaseOptions options = new FirebaseOptions.Builder()
.SetApiKey("--ApiKey--")
.SetApplicationId("--AppId--")
.Build();
FirebaseApp app = FirebaseApp.InitializeApp(this, options);
FirebaseAuth authInstance = FirebaseAuth.GetInstance(app);
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
LoadApplication(new App());
}
FirebaseAuth.Instance is null
public async Task<string> RegisterWithEmailPassword(string email, string password, bool isTrainer)
{
try
{
var user = await FirebaseAuth.Instance.CreateUserWithEmailAndPasswordAsync(email, password);
var token = await user.User.GetIdTokenAsync(false);
user.User.SendEmailVerification();
return token.Token;
}
catch (Exception e)
{
return e.Message;
}
}
I am obviously expecting CreateUserWithEmailAndPasswordAsync to use the email and password I provide it to create a new user in my Firebase App. When it tries to add this to my "user" variable I get the exception since Instance is null.
EDIT: After looking a bit deeper, it seems the problem may be coming from the InitializeApp method in MainActivity. Examining my "app" after, the Uid property has this error "Firebase.FirebaseApiNotAvailableException: firebase-auth is not linked, please fall back to unauthenticated mode" (see screenshot below). I assume this is why GetInstance() is returning null. After some googling I cannot really find any info on this area that is of use to me.
Uid error Firebase
My suggestion is to downgrade your Firebase NuGets and make sure they have the same version.
I had the same problem (FirebaseAuth.Instance is null, and Uid property of FirebaseApp is what you described) when I upgraded my Android SDK from v8.1 to v9.0, and along with it these Firebase NuGets from version 60.1142.1 to the latest version:
Xamarin.Firebase.Auth (71.1605.0)
Xamarin.Firebase.Common (71.1610.0)
Xamarin.Firebase.Core (71.1601.0)
Xamarin.FIrebase.Database (71.1601.0)
Xamarin.Firebase.lid (71.1710.0)
As you can see the latest versions are not the same (I'm not sure if this is the cause of the problem).
In addition to these, I also kept getting weird errors like
The "ConvertResourcesCases" task failed unexpectedly.
when I build the solution. After I downgraded them those errors also stopped showing up.
Related posts:
FirebaseAuth.getInstance() is null

Disable application insights in debug

How can I disable application insights automatically when using a debug configuration and enable it only on release?
Is it possible to do this without creating another instrumentation key only for debug?
I have trackevent statements scattered all over the code, enclosing them inside a debug preprocessor check is not an ideal solution.
My current solution is to set the Build Action of the ApplicationInsights.config file to None so that it's not copied to the project's output directory, but this isn't a process that can be automated based on the active build configuration.
There is a Developer Mode but needs to be changed manually (if it was possible to conditionally set the config file, emptying the instrumentationkey solved problem as well). See http://apmtips.com/blog/2015/02/02/developer-mode/
Reference: http://blogs.msdn.com/b/visualstudioalm/archive/2015/01/07/application-insights-support-for-multiple-environments-stamps-and-app-versions.aspx
You can try to use TelemetryConfiguration.DisableTelemetry Property
Something like this way..
#if DEBUG
TelemetryConfiguration.Active.DisableTelemetry = true;
#endif
As an addition to the other solutions I would suggest to add the following let's say to the Global.asax:
protected void Application_Start()
{
DisableApplicationInsightsOnDebug();
// do the other stuff
}
/// <summary>
/// Disables the application insights locally.
/// </summary>
[Conditional("DEBUG")]
private static void DisableApplicationInsightsOnDebug()
{
TelemetryConfiguration.Active.DisableTelemetry = true;
}
The advantage of this is, that it needs no change to the configs and it works better with some tools like ReSharper which will understand it better than #-directives.
NOTE: This option only existed in Visual Studio 2019
For ASP.NET Core projects the App Insights are ON by default, which actually logs a ton of info into debug window.
To disable it go to "TOOLS --> Options --> Projects and Solutions --> Web Projects" and check "Disable local Application Insights for Asp.Net Core web projects."
Below is the image for disabling local app insights.
For more info on the issue you can see the official github issue here
Running an ASP.NET Core 2.1 web application with Visual Studio 2017 (15.9.2) the "Disable local Application Insights for Asp.Net Core web projects" did not clear up the output in my Debug window.
However adding the following to Configure() in Startup.cs did the job;
if (_env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
TelemetryConfiguration.Active.DisableTelemetry = true;
TelemetryDebugWriter.IsTracingDisabled = true;
}
Note that the IsTracingDisabled was the key solution, but I left in DisableTelemetry for good measure! Plus having both lines next to one another is helpful when searching for similar references between .NET Framework & .NET Core projects in the same solution.
As explained in the question not deploying or deploying an ApplicationInsights.config without <instrumentationkey>key</instrumentationkey> block events from being generated.
You can then put the instrumentation key in code (only on release in my case)
#if !DEBUG
Microsoft.ApplicationInsights.Extensibility.TelemetryConfiguration.Active.InstrumentationKey = "instrumentation key";
#endif
Every TelemetryClient created after this call will have the correct key and will track events so you don't have to change the code in all places.
Not calling the method above or leaving the parameter empty will block events because there isn't a key configured.
Basically the ApplicationInsights.config file overrides any code that set the instrumentation key, removing the <instrumentationkey>key</instrumentationkey> inside it will let you use code to configure the key.
If you remove the file completely it doesn't work.
Here is the confirm:
"If you want to set the key dynamically - for example if you want to send results from your application to different resources - you can omit the key from the configuration file, and set it in code instead."
Reference: https://azure.microsoft.com/en-us/documentation/articles/app-insights-configuration-with-applicationinsights-config/#_instrumentationkey
As of ASP.NET Core 3.1:
To disable logging any App Insights telemetry to Azure:
public void Configure(IApplicationBuilder app, IHostingEnvironment env,
TelemetryConfiguration configuration)
{
configuration.DisableTelemetry = true;
}
To disable logging telemetry events to the Output window:
TelemetryDebugWriter.IsTracingDisabled = true;
(the above can be called from anywhere, but the sooner in your application's lifecycle, the better).
Both can be used together to suppress all Application Insights activity in your code. I guard with an #if DEBUG directive to ensure that AppInsights does nothing on my local machine, but does emit events when published to our dev server in the Azure cloud:
public void Configure(IApplicationBuilder app, IHostingEnvironment env,
TelemetryConfiguration configuration)
{
if (env.IsDevelopment())
{
#if DEBUG
configuration.DisableTelemetry = true;
TelemetryDebugWriter.IsTracingDisabled = true;
#endif
}
}
I have decided to use both approaches. I have moved the InstrumentationKey to the Web.config and it will be replaced by the transformation from Web.Release.config or Web.Debug.config. (don't forget to remove it from the ApplicationInsights.config file). Then I have called this method from the Application_Start()
public static void RegisterTelemetryInstrumentationKey()
{
if (string.IsNullOrWhiteSpace(WebConfigurationManager.AppSettings["TelemetryInstrumentationKey"])
{
TelemetryConfiguration.Active.DisableTelemetry = true;
}
else
{
TelemetryConfiguration.Active.InstrumentationKey = AppSettings.TelemetryInstrumentationKey;
}
}
I've just had the same issue.
We wanted to control the setting in the web.config so added a DisableAITelemetry key within our app settings:
<appSettings>
<add key="DisableAITelemetry" value="true" />
</appSettings>
With live and demo builds, we won't include a value (so that it defaults to false).
We could then solve it by adding this:
bool disable;
string disableAiTelemetry = ConfigurationManager.AppSettings["DisableAITelemetry"];
bool.TryParse(disableAiTelemetry, out disable);
TelemetryConfiguration.Active.DisableTelemetry = disable;
Slightly different play on some of the other solutions. Put this in your global.asax:
Microsoft.ApplicationInsights.Extensibility.Implementation.TelemetryDebugWriter.IsTracingDisabled = Debugger.IsAttached;
It will turn off app insights debug output when running under the debugger, but allow it under Ctrl+F5 scenarios and debug builds published to test servers
We've found the easiest way to prevent it from tracing into the Debug log is as simple as:
Extensibility.Implementation.TelemetryDebugWriter.IsTracingDisabled = True
In an ASP.NET Core application, you can add the following to the Startus.cs to turn off Application Insights in the Development environment:
if (env.IsDevelopment()) {
TelemetryConfiguration.Active.DisableTelemetry = true;
}
Add this to the constructor, right after the builder.AddApplicationInsightsSettings(); command and you'll no longer see AI logs clogging up your debug console.
Microsoft.ApplicationInsights.AspNetCore Version 2.1
services.AddApplicationInsightsTelemetry(options =>
{
options.EnableDebugLogger = false;
});
The solution suggested above has been deprecated (reference: https://github.com/microsoft/applicationinsights-dotnet/issues/1152). In dotnet core the new way to dynamically disable telemetry is this:
public void ConfigureServices(IServiceCollection services)
{
services.AddApplicationInsightsTelemetry();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, TelemetryConfiguration configuration)
{
configuration.DisableTelemetry = true;
...
}
(reference: https://learn.microsoft.com/en-us/azure/azure-monitor/app/asp-net-core#disable-telemetry-dynamically)
And if you want to disable telemetry in a custom WebApplicationFactory (when doing integration tests) you can do this:
public class CustomWebApplicationFactory<TStartup> : WebApplicationFactory<TStartup> where TStartup : class
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
builder.ConfigureServices((context, services) =>
{
// Disable application insights during testing.
services.Configure<TelemetryConfiguration>(
(telemetryConfig) => {
telemetryConfig.DisableTelemetry = true;
});
});
base.ConfigureWebHost(builder);
}
}
For more context about integration testing see https://learn.microsoft.com/en-us/aspnet/core/test/integration-tests?view=aspnetcore-5.0
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
#region Disable Application Insights debug informations
#if DEBUG
TelemetryConfiguration.Active.DisableTelemetry = true;
TelemetryDebugWriter.IsTracingDisabled = true;
#endif
#endregion
//...
}
Since .NET Core 3.1:
var telemetryConfiguration = TelemetryConfiguration.CreateDefault();
telemetryConfiguration.DisableTelemetry = true;
var telemetryClient = new TelemetryClient(telemetryConfiguration); // Use this instance
TelemetryDebugWriter.IsTracingDisabled = true;
We can modify the file “appsetting.json” and add the following attributes
"ApplicationInsights": {
"EnableRequestTrackingTelemetryModule": false,
"EnableEventCounterCollectionModule": false,
"EnableDependencyTrackingTelemetryModule": false,
"EnablePerformanceCounterCollectionModule": false,
"EnableDiagnosticsTelemetryModule": false
}
More information you can find here.

Categories

Resources