Xamarin forms visual studio for Mac clean-namespace problem - xamarin.forms

I have created a Xamarin forms application using .net standard. Then I added a .net standard library project to the solution that will include common codes such as renders, behaviours etc. I include the reference of common .net standard library project to the main Xamarin forms project by right clicking on dependencies and Edit References menu. Finally I try to include the namespace of renderer files on the content page of main Xamarin forms by specifying the below line
using Xamarin.Forms;
namespace MyProject.Shared.Renderer
{
public class ExtendedEntry : Entry
{
public static readonly BindableProperty IsBorderErrorVisibleProperty = BindableProperty.Create(nameof(IsBorderErrorVisible), typeof(bool), typeof(ExtendedEntry),
false, BindingMode.TwoWay);
public bool IsBorderErrorVisible
{
get { return (bool)GetValue(IsBorderErrorVisibleProperty); }
set { SetValue(IsBorderErrorVisibleProperty, value); }
}
public static readonly BindableProperty BorderErrorColorProperty = BindableProperty.Create(nameof(BorderErrorColor), typeof(Color), typeof(ExtendedEntry),
null, BindingMode.TwoWay);
public Color BorderErrorColor
{
get { return (Color)GetValue(BorderErrorColorProperty); }
set { SetValue(BorderErrorColorProperty, value); }
}
public static readonly BindableProperty ErrorTextProperty = BindableProperty.Create(nameof(ErrorText), typeof(string), typeof(ExtendedEntry), string.Empty,
BindingMode.TwoWay);
public string ErrorText
{
get { return (string)GetValue(ErrorTextProperty); }
set { SetValue(ErrorTextProperty, value); }
}
}
}
xmlns:controls=“clr-namespace:MyProject.Shared.Renderer:assembly:MyProject.Shared”
Then I reference the control as
<controls:ExtendedEntry />
But this gives build error that says ExtendedEntry is not found in the assembly MyProject.Shared
Please help

Well actually this issue is quite common what happens is your project is not compiled properly or after compiling the bin and obj are missing this class which is fine.
Solution:
Delete all bin obj folders from all the projects in your solution.
Now individually build all your projects based on dependency i.e. if you have four projects A, B, iOS and Android and B is dependent on A i.e. it has a reference to A then you will first clean build A then B and then any amongst iOS and Android.
If even after this your issue is not resolved then you might want to restart VS all together
In case you still face this issue feel free to revert.
Good luck

Sorry...I had done blunder...a real blunder.
I typed ":" instead of "=" in assembly attribute.
It should be
xmlns:controls=“clr-namespace:MyProject.Shared.Renderer:assembly=MyProject.Shared”

Related

How to do Login with Firebase integration in .NET MAUI?

I'm trying to login with integration to social networks, more specifically to Google in .NET MAUI. I've done it with Xamarin Forms and it worked perfectly, however, in MAUI a standard error is occurring:
Error CS0246 The type or namespace name 'Android' could not be found (are you missing a using directive or an assembly reference?) LoginWithRedes (net6.0-ios), LoginWithRedes (net6.0-maccatalyst), LoginWithRedes (net6.0-windows10.0.19041) C:\MAUI\LoginWithRedes\LoginWithRedes\Platforms\Android\GoogleManager.cs
Libraries not being recognized
Packages I added to the project
Code of the GoogleManager.CS Class where the standard error occurs to me:
`[assembly: Dependency(typeof(GoogleManager))]
namespace LoginWithRedes.Platforms.Android
{
public class GoogleManager : Java.Lang.Object, IGoogleManager, GoogleApiClient.IConnectionCallbacks, GoogleApiClient.IOnConnectionFailedListener
{
public static GoogleApiClient _googleApiClient { get; set; }
public static GoogleManager Instance { get; private set; }
public bool IsLogedIn { get; set; }
Context _context;
public GoogleManager()
{
_context = global::Android.App.Application.Context;
Instance = this;
}
public void Login()
{
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DefaultSignIn)
.RequestEmail()
.Build();
_googleApiClient = new GoogleApiClient.Builder((_context).ApplicationContext)
.AddConnectionCallbacks(this)
.AddOnConnectionFailedListener(this)
.AddApi(Auth.GOOGLE_SIGN_IN_API, gso)
.AddScope(new Scope(Scopes.Profile))
.Build();
Intent signInIntent = Auth.GoogleSignInApi.GetSignInIntent(_googleApiClient);
((MainActivity)Forms.Context).StartActivityForResult(signInIntent, 1);
_googleApiClient.Connect();
}
public void Logout()
{
var gsoBuilder = new GoogleSignInOptions.Builder(GoogleSignInOptions.DefaultSignIn).RequestEmail();
GoogleSignIn.GetClient(_context, gsoBuilder.Build())?.SignOut();
_googleApiClient.Disconnect();
}
public void OnAuthCompleted(GoogleSignInResult result)
{
if (result.IsSuccess)
{
IsLogedIn = true;
Application.Current.MainPage = new MainPage();
}
else
{
}
}`
OnActivityResult method that I implemented in MainActivity class
If anyone can help me with this error, I would be very grateful.
Note: I'm new to Xamarin and Maui.
Thank you very much in advance
I'm also new to Maui, and in my experience, these errors were caused by using native Xamarin libraries in Maui. Xamarin targets each platform separately using separate nuget packages. Maui's combined 1-project architecture means you need to use packages that work for both at once.
At least when I was getting started a few months ago, these weren't readily available. Firebase client was not yet released for .NET 6.0 (Multiplatform by default).
Things may have changed since then. But I had great success using Firebase with this plugin https://github.com/TobiasBuchholz/Plugin.Firebase. It wraps up the platform specific libraries into a single project API, with a really easy to use c# interface. You can use await and stuff as you would expect. Calling the native APIs was difficult, and required a lot of code duplication. This plugin saves a lot of time, and I haven't yet run into any problems.
The documentation on the plugin is a bit sparse, but hey, it's free and works.

Xamarin Forms native customrenderer

I have followed James Montemagno's guide on how to make a custom renderer for round images in my Xamarin Forms Shared Project.
https://blog.xamarin.com/elegant-circle-images-in-xamarin-forms/
(being a true copy of the guide it feels redundant to actually add the code itself to my project but please comment if that is not the case)
It is working flawless, however, I need to change the colour of the circle border dynamically with the press of a button when the app is running.
But since the colour of the circle is set natively in each renderer I am uncertain how I could possibly change it from my shared code.
Maybe this snippet can help:
public class CircleImage : Image
{
public static readonly BindableProperty CurvedBackgroundColorProperty =
BindableProperty.Create(
nameof(CurvedBackgroundColor),
typeof(Color),
typeof(CurvedCornersLabel),
Color.Default);
public Color CurvedBackgroundColor
{
get { return (Color)GetValue(CurvedBackgroundColorProperty); }
set { SetValue(CurvedBackgroundColorProperty, value); }
}
}
//Android/iOS
[assembly: ExportRenderer(typeof(CircleImage), typeof(CircleImageRenderer))]
namespace SchedulingTool.iOS.Renderers
{
public class CircleImageRenderer : ImageRenderer
{
protected override void OnElementChanged(ElementChangedEventArgs<Image> e)
{
base.OnElementChanged(e);
if (e.NewElement != null)
{
var xfViewReference = (CircleImage)Element;
//Here you can reference xfViewReference.CurvedBackgroundColor to assign what ever is binded.
}
}
}
}
I hope you get the main idea, you can create your own bindable properties and access them on the Native Renderer.
If everything does not go as expected you can always download the NuGet (which has everything you need):
https://github.com/jamesmontemagno/ImageCirclePlugin

Keeping screen turned on for certain pages

I am using a portable project so do not have direct access to native code.
I have an interface in my project that allows me to access native objects in the Android/iOS projects. We use this primarily for playing audio.
Android, for example, has things like
Window w = new Window();
w.SetFlags(WindowManagerFlags.Fullscreen, WindowManagerFlags.KeepScreenOn);
However the main issue would be accessing a Window object. I could pass a Xamarin.Forms.Page object to the native code, but there would be no way (I don't think) to cast it to a native Android Window object to access the flags.
Is there a way to do this with a portable project?
You can't do this without platform specific services or renderers. A portable project will have to call platform specific code in order to achieve this.
From that platform specific code, either as a DependencyService or Renderer, you can access the Window object through the Forms.Context. The Forms.Context is your Android Activity, through which you can reach the Window object.
On Android it works like this:
Android.Views.Window window = (Forms.Context as Activity).Window;
window.SetFlags(WindowManagerFlags.KeepScreenOn);
On iOS you can try this (Apple docs):
UIApplication.SharedApplication.IdleTimerDisabled = true;
Now there is a plugin doing exactly what Tim wrote
https://learn.microsoft.com/en-us/xamarin/essentials/screen-lock
simple source code is here
https://github.com/xamarin/Essentials/blob/main/Samples/Samples/ViewModel/KeepScreenOnViewModel.cs
using System.Windows.Input;
using Xamarin.Essentials;
using Xamarin.Forms;
namespace Samples.ViewModel
{
public class KeepScreenOnViewModel : BaseViewModel
{
public KeepScreenOnViewModel()
{
RequestActiveCommand = new Command(OnRequestActive);
RequestReleaseCommand = new Command(OnRequestRelease);
}
public bool IsActive => DeviceDisplay.KeepScreenOn;
public ICommand RequestActiveCommand { get; }
public ICommand RequestReleaseCommand { get; }
void OnRequestActive()
{
DeviceDisplay.KeepScreenOn = true;
OnPropertyChanged(nameof(IsActive));
}
void OnRequestRelease()
{
DeviceDisplay.KeepScreenOn = false;
OnPropertyChanged(nameof(IsActive));
}
}
}
For Xamarin Forms Android.
Renders file I included below code
Window window = (Forms.Context as Activity).Window;
window.AddFlags(WindowManagerFlags.KeepScreenOn);

Caliburn.Micro for WPF Controls Project

My current situation is that I have a winforms application which I would like to create a new WPF controls library projects to start showing new screens in WPF. I would really like to leverage the Caliburn.Micro framework but im struggling getting it set up. I currently have my bootstrapper as a Singleton so that I can initialize it and also Im setting the useApplication property in the base contructor to false. I'm not sure where to go from here any help would be appreciated. thanks
public class AppBootstrapper : BootstrapperBase
{
private static AppBootstrapper bootsrapper;
public static void InitializeInstance()
{
if (bootsrapper == null)
{
bootsrapper = new AppBootstrapper();
}
}
public AppBootstrapper() : base(false)
{
Initialize();
}
}

Asp.net MVC VirtualPathProvider views parse error

I am working on a plugin system for Asp.net MVC 2. I have a dll containing controllers and views as embedded resources.
I scan the plugin dlls for controller using StructureMap and I then can pull them out and instantiate them when requested. This works fine. I then have a VirtualPathProvider which I adapted from this post
public class AssemblyResourceProvider : VirtualPathProvider
{
protected virtual string WidgetDirectory
{
get
{
return "~/bin";
}
}
private bool IsAppResourcePath(string virtualPath)
{
var checkPath = VirtualPathUtility.ToAppRelative(virtualPath);
return checkPath.StartsWith(WidgetDirectory, StringComparison.InvariantCultureIgnoreCase);
}
public override bool FileExists(string virtualPath)
{
return (IsAppResourcePath(virtualPath) || base.FileExists(virtualPath));
}
public override VirtualFile GetFile(string virtualPath)
{
return IsAppResourcePath(virtualPath) ? new AssemblyResourceVirtualFile(virtualPath) : base.GetFile(virtualPath);
}
public override CacheDependency GetCacheDependency(string virtualPath, IEnumerable virtualPathDependencies,
DateTime utcStart)
{
return IsAppResourcePath(virtualPath) ? null : base.GetCacheDependency(virtualPath, virtualPathDependencies, utcStart);
}
}
internal class AssemblyResourceVirtualFile : VirtualFile
{
private readonly string path;
public AssemblyResourceVirtualFile(string virtualPath)
: base(virtualPath)
{
path = VirtualPathUtility.ToAppRelative(virtualPath);
}
public override Stream Open()
{
var parts = path.Split('/');
var resourceName = Path.GetFileName(path);
var apath = HttpContext.Current.Server.MapPath(Path.GetDirectoryName(path));
var assembly = Assembly.LoadFile(apath);
return assembly != null ? assembly.GetManifestResourceStream(assembly.GetManifestResourceNames().SingleOrDefault(s => string.Compare(s, resourceName, true) == 0)) : null;
}
}
The VPP seems to be working fine also. The view is found and is pulled out into a stream. I then receive a parse error Could not load type 'System.Web.Mvc.ViewUserControl<dynamic>'. which I can't find mentioned in any previous example of pluggable views. Why would my view not compile at this stage?
Thanks for any help,
Ian
EDIT:
Getting closer to an answer but not quite clear why things aren't compiling. Based on the comments I checked the versions and everything is in V2, I believe dynamic was brought in at V2 so this is fine. I don't even have V3 installed so it can't be that. I have however got the view to render, if I remove the <dynamic> altogether.
So a VPP works but only if the view is not strongly typed or dynamic
This makes sense for the strongly typed scenario as the type is in the dynamically loaded dll so the viewengine will not be aware of it, even though the dll is in the bin. Is there a way to load types at app start? Considering having a go with MEF instead of my bespoke Structuremap solution. What do you think?
The settings that allow parsing of strongly typed views are in ~/Views/Web.Config. When the view engine is using a virtual path provider, it is not in the views folder so doesn't load those settings.
If you copy everything in the pages node of Views/Web.Config to the root Web.Config, strongly typed views will be parsed correctly.
Try to add content of Views/Web.config directly to your main web.config under specific location, e.g. for handling virtual paths like ~/page/xxx. See more details here: http://blog.sergkazakov.com/2011/01/aspnet-strongly-typed-view-and-virtual.html
Is there a way to load types at app start?
Yes, you may use BuildManager.AddReferencedAssembly(assembly), where assembly is the one, containing the requested type. So, once you use MEF, the last should be easy, but beware, everything should be done before Application_Start, so you may wish to use PreApplicationStartMethodAttribute.

Resources