I was testing what I done with android emulator and it always worked well but yesterday it suddenly shows my app as a just white blank screen. I dont know the reason why.
This my MainActivity class
using System;
using Android.App;
using Android.Content.PM;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
using Xamarin.Forms;
namespace HealthCareApp.Droid
{
[Activity(Label = "HealthCareApp", Icon = "#mipmap/icon", Theme = "#style/MainTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation | ConfigChanges.UiMode | ConfigChanges.ScreenLayout | ConfigChanges.SmallestScreenSize )]
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
protected override void OnCreate(Bundle savedInstanceState)
{
TabLayoutResource = Resource.Layout.Tabbar;
ToolbarResource = Resource.Layout.Toolbar;
base.OnCreate(savedInstanceState);
Forms.SetFlags("Brush_Experimental");
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
LoadApplication(new Xamarin.Forms.Application());
}
public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
{
Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);
base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
}
App.xaml.cs ( now its giving a error : "initializecomponent is inaccessible due to its protection level" )
using System;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace HealthCareApp
{
public partial class App : Application
{
public App()
{
InitializeComponent();
MainPage = new NavigationPage(new LoginPage());
}
protected override void OnStart()
{
}
protected override void OnSleep()
{
}
protected override void OnResume()
{
}
}
}
You should have a App class somewhere in your project, which contains information of which Forms page to show first and setup stuff like services in a IoC container etc.
Instead of calling
LoadApplication(new Xamarin.Forms.Application());
You should probably call:
LoadApplication(new App());
Related
this code contain all autofac's models I don't want as such.I want to set one by one How can I make this
Asp.Net Core 3.1
var assembly = System.Reflection.Assembly.GetExecutingAssembly();
builder.RegisterAssemblyTypes(assembly).AsImplementedInterfaces()
.EnableInterfaceInterceptors(new ProxyGenerationOptions()
{
Selector = new AspectInterceptorSelector()
}).SingleInstance();
AtuofacBusinessModule.cs
public class AtuofacBusinessModule : Module
{
protected override void Load(ContainerBuilder builder)
{
builder.RegisterType<OrderService>().As<OrderService>();
builder.RegisterType<AuthService>().As<AuthService>();
builder.RegisterType<UserService>().As<UserService>();
var assembly = System.Reflection.Assembly.GetExecutingAssembly();
builder.RegisterAssemblyTypes(assembly).AsImplementedInterfaces()
.EnableInterfaceInterceptors(new ProxyGenerationOptions()
{
Selector = new AspectInterceptorSelector()
}).SingleInstance();
}
You can register it directly as what you want
public class RegisterModule : Module
{
protected override void Load(ContainerBuilder builder)
{
builder.RegisterType<StringService>().As<IStringService>().SingleInstance();
builder.RegisterType<IntService>().As<IIntService>().InstancePerLifetimeScope();
builder.RegisterType<BoolService>().As<IBoolService>().InstancePerDependency();
}
}
startup.cs
public void ConfigureContainer(ContainerBuilder builder)
{
builder.RegisterModule(new RegisterModule());
}
On my Main Page, I will set my label text (#lblStartDateTime) to current time stamp when user click on a button. It will navigate to Second Page, and once I click "done" button, it will go back to Main Page.
When I navigate back to Main Page from Second Page, my label text disappeared. Does anyone know how to keep the label text value after navigation?
Main Page
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace Test
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class MainPage: ContentPage
{
public string previouspagevalue;
public MainPage()
{
InitializeComponent();
}
protected override void OnAppearing()
{
base.OnAppearing();
lblEndDT.Text = previouspagevalue;
}
private void btnOffline_Clicked(object sender, EventArgs e)
{
Navigation.PushAsync(new SecondPage());
string currentDT = DateTime.Now.ToString();
lblStartDT.Text = currentDT;
}
}
}
Second Page
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace Test
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class SecondPage: ContentPage
{
public SecondPage()
{
InitializeComponent();
}
protected void btnDone_Clicked(object sender, EventArgs e)
{
MainPage mainpage = new MainPage();
string edt = DateTime.Now.ToString();
lblEndDateTime.Text = edt;
mainpage.previouspagevalue = lblEndDateTime.Text;
Navigation.PushAsync(mainpage);
}
}
}
In you btnDone_Clicked event , you should use Navigation.PopAsync to go back to MainPage, Navigation.PushAsync(mainpage); means to go to a new MainPage not the previous Page.
protected void btnDone_Clicked(object sender, EventArgs e)
{
Navigation.PopAsync();
}
Please read document to learn about how NavigationPage works.
Update, you can pass the value you need to the SecondPage when you push to SecondPage:
Codes in MainPage:
public partial class MainPage : ContentPage
{
public string previouspagevalue;
public MainPage()
{
InitializeComponent();
previouspagevalue = "I'm previouspagevalue";
}
protected override void OnAppearing()
{
base.OnAppearing();
//if you set the lblEndDT.Text = "someValue"; in the secondPage, there is no need to update it here
lblEndDT.Text = previouspagevalue;
}
private void btnOffline_Clicked(object sender, EventArgs e)
{
//Pass the parametere you need when you go to SecondPage
Navigation.PushAsync(new SecondPage(this, lblEndDT));
string currentDT = DateTime.Now.ToString();
lblStartDT.Text = currentDT;
}
}
SecondPage:
public partial class SecondPage : ContentPage
{
Label MainPagelblEndDT;
MainPage mainPage;
public SecondPage()
{
InitializeComponent();
}
public SecondPage(MainPage mainP,Label lblEndDT)
{
InitializeComponent();
//Get the lblEndDT reference here
MainPagelblEndDT = lblEndDT;
//Get the MainPage reference here
mainPage = mainP;
}
private void Button_Clicked(object sender, EventArgs e)
{
string edt = DateTime.Now.ToString();
//Use it
MainPagelblEndDT.Text = edt;
mainPage.previouspagevalue = MainPagelblEndDT.Text;
Navigation.PopAsync();
}
}
I uploaded a sample project here and you can check it. Feel free to ask me any question if you have.
I would suggest you wrap your pages in a navigation stack, use a NavigationPage and navigate to next page then when you pop back it will maintain your state.
In your App.xaml.cs
MainPage = new NavigationPage(new YourFirstPage);
Then push a page into the navigation and when you want to go back just do a
Navigation.PopAsync();
Goodluck
Feel free to get back if you have queries
I'm playing with the COOL xamarin shell, but I didn't found a way to change icon of the selected tab.
<TabBar Route="sections">
<Tab Title="home">
<Tab.Icon>
<FontImageSource FontFamily="{StaticResource AppIcons}" Glyph="{x:Static framework:Icons.HomePage}" />
</Tab.Icon>
<ShellContent ContentTemplate="{DataTemplate home:HomePage}" Route="home" />
</Tab>
The goal is to use Icons.HomePageFilled instead of Icons.HomePage for this tab only when it's selected. Same logic should apply to other tabs.
I think I got lost in the solutions found on the web. They talk about Custom renderers(ShellTabLayoutAppearanceTracker), Visual states, effects etc ...
But I do not know if it is feasible and what is the ideal solution
You need to use custom renderer of shell to customize the tabbar selected icon on each platform.
In iOS, override the CreateTabBarAppearanceTracker method:
[assembly: ExportRenderer(typeof(AppShell), typeof(MyShellRenderer))]
namespace App30.iOS
{
public class MyShellRenderer : ShellRenderer
{
protected override IShellSectionRenderer CreateShellSectionRenderer(ShellSection shellSection)
{
var renderer = base.CreateShellSectionRenderer(shellSection);
if (renderer != null)
{
}
return renderer;
}
protected override IShellTabBarAppearanceTracker CreateTabBarAppearanceTracker()
{
return new CustomTabbarAppearance();
}
}
public class CustomTabbarAppearance : IShellTabBarAppearanceTracker
{
public void Dispose()
{
}
public void ResetAppearance(UITabBarController controller)
{
}
public void SetAppearance(UITabBarController controller, ShellAppearance appearance)
{
UITabBar myTabBar = controller.TabBar;
if (myTabBar.Items != null)
{
UITabBarItem itemOne = myTabBar.Items[0];
itemOne.Image = UIImage.FromBundle("tab_about.png");
itemOne.SelectedImage = UIImage.FromBundle("tab_feed.png");
UITabBarItem itemTwo = myTabBar.Items[1];
itemTwo.Image = UIImage.FromBundle("tab_feed.png");
itemTwo.SelectedImage = UIImage.FromBundle("tab_about.png");
//The same logic if you have itemThree, itemFour....
}
}
public void UpdateLayout(UITabBarController controller)
{
}
}
}
In Android, override the CreateBottomNavViewAppearanceTracker method:
[assembly: ExportRenderer(typeof(AppShell), typeof(MyShellRenderer))]
namespace App30.Droid
{
public class MyShellRenderer : ShellRenderer
{
public MyShellRenderer(Context context) : base(context)
{
}
protected override IShellBottomNavViewAppearanceTracker CreateBottomNavViewAppearanceTracker(ShellItem shellItem)
{
return new CustomBottomNavAppearance();
}
}
public class CustomBottomNavAppearance : IShellBottomNavViewAppearanceTracker
{
public void Dispose()
{
}
public void ResetAppearance(BottomNavigationView bottomView)
{
}
public void SetAppearance(BottomNavigationView bottomView, ShellAppearance appearance)
{
IMenu myMenu = bottomView.Menu;
IMenuItem myItemOne = myMenu.GetItem(0);
if (myItemOne.IsChecked)
{
myItemOne.SetIcon(Resource.Drawable.tab_about);
}
else
{
myItemOne.SetIcon(Resource.Drawable.tab_feed);
}
//The same logic if you have myItemTwo, myItemThree....
}
}
}
I uploaded a sample project here and you can check it.
I have created a background service and that service is working fine in below Android 6.0 when I kill app.
Also working in Android 6.0 and above but only when I minimize app.
When I kill app in Android 6.0 and above service also kill and not get restart and also not get start on BOOT_COMPLETE.
What to DO?
Can I get a simple example.
I tried this:
MyService.java
public class MyService extends Service {
private MediaPlayer player;
#Nullable
#Override
public IBinder onBind(Intent intent) {
throw new UnsupportedOperationException("Not yet started");
}
public A_ExampleMyService() {
super();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
player = MediaPlayer.create(this, Settings.System.DEFAULT_RINGTONE_URI);
player.setLooping(true);
player.start();
return START_STICKY;
}
#Override
public void onTaskRemoved(Intent rootIntent) {
Intent restartServiceIntent = new Intent(getApplicationContext(), this.getClass());
restartServiceIntent.setPackage(getPackageName());
startService(restartServiceIntent);
super.onTaskRemoved(rootIntent);
}
}
MyActivity.java
public class MyActivity extends Activity {
private Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.a_example_activity);
this.context = this;
Intent background = new Intent(MyActivity.this,MyService.class);
context.startService(background);
}
}
manifest.xml
<manifest>
<application>
<service>
<android:name=".MyService">
<android:enabled="true">
<android:exported="true"/>
</application>
</manifest>
I am trying to implement an InterceptAttribute which should intercept any method I add the attribute to. I have it working in a WebAPI solution, however, I cannot get it to work in an MVC 5 application. The code is the same in both projects. The following code is the attribute I created.
using Ninject;
using Ninject.Extensions.Interception;
using Ninject.Extensions.Interception.Attributes;
using Ninject.Extensions.Interception.Request;
namespace Questionnaire.Common.InterceptAttributes
{
public class InterceptCacheAttribute : InterceptAttribute
{
public double TimeOut { get; set; }
public override IInterceptor CreateInterceptor(IProxyRequest request)
{
var cacheInterceptor = request.Kernel.Get<CacheInterceptor>();
cacheInterceptor.TimeOut = TimeOut;
return cacheInterceptor;
}
}
}
The CacheInterceptor code is as follows:
using System;
using System.Text;
using Ninject;
using Ninject.Extensions.Interception;
using Ninject.Extensions.Interception.Request;
namespace Questionnaire.Common.Interceptors
{
public class CacheInterceptor : IInterceptor
{
[Inject]
public ICaching Cache { get; set; }
public double TimeOut { get; set; }
public void Intercept(IInvocation invocation)
{
var minutes = Cache.TimeOutMinutes;
if (Math.Abs(TimeOut - default(double)) > 0)
{
minutes = TimeOut;
}
invocation.ReturnValue = Cache.Get(GenerateCacheKey(invocation.Request), minutes, delegate
{
invocation.Proceed();
return invocation.ReturnValue;
});
}
private static string GenerateCacheKey(IProxyRequest request)
{
var sb = new StringBuilder(request.Method.Name).Append(".");
foreach (var argument in request.Arguments)
{
if (argument == null)
{
sb.Append("null");
}
else if (argument is string && argument.ToString().Length < 50)
{
sb.Append((string)argument);
}
else
{
sb.Append(argument.GetHashCode());
}
sb.Append(".");
}
sb.Remove(sb.Length - 1, 1);
return sb.ToString();
}
}
}
Finally I added the attribute to the following method.
using System.Configuration;
using Questionnaire.Common.InterceptAttributes;
namespace Questionnaire.Common.Utility
{
public class ConfigurationUtilities
{
[InterceptCache(TimeOut = 1440)]
public virtual string GetEnvironmentConnectionString(string name)
{
var connectionStringSettings = ConfigurationManager.ConnectionStrings[name + "_" + HostEnvironment];
return connectionStringSettings != null ? connectionStringSettings.ConnectionString : null;
}
}
}
Code execution never enters into the InterceptCacheAttribute class. I have put debug points within that class and the CacheInterceptor class and the debug points are never hit. The method the attribute is on executes just fine, but, I want it to be intercepted and that is not happening. I have the same code in a different project. That project is a WebAPI project which works great. The methods are intercepted and everything functions as it should. Can someone explain to me why I can't get it to work in the MVC 5 application? I would greatly appreciate it.
answer to BatteryBackupUnit's question:
The answer is I can't. The following is my NinjectWebCommon.cs class.
[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(Mayo.Questionnaire.App_Start.NinjectWebCommon), "Start")]
[assembly: WebActivatorEx.ApplicationShutdownMethodAttribute(typeof(Mayo.Questionnaire.App_Start.NinjectWebCommon), "Stop")]
namespace Questionnaire.App_Start
{
using System;
using System.Web;
using System.Web.Http;
using System.Linq;
using ApplicationExtensions;
using Microsoft.Web.Infrastructure.DynamicModuleHelper;
using Ninject;
using Ninject.Web.Common;
public static class NinjectWebCommon
{
private static readonly Bootstrapper bootstrapper = new Bootstrapper();
public static void Start()
{
DynamicModuleUtility.RegisterModule(typeof(OnePerRequestHttpModule));
DynamicModuleUtility.RegisterModule(typeof(NinjectHttpModule));
bootstrapper.Initialize(CreateKernel);
}
public static void Stop()
{
bootstrapper.ShutDown();
}
private static IKernel CreateKernel()
{
var kernel = new StandardKernel();
try
{
kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();
GlobalConfiguration.Configuration.DependencyResolver = new NinjectDependencyResolver(kernel);
RegisterServices(kernel);
return kernel;
}
catch
{
kernel.Dispose();
throw;
}
}
private static void RegisterServices(IKernel kernel)
{
foreach (var module in from assembly in AppDomain.CurrentDomain.GetAssemblies()
select assembly.GetNinjectModules()
into modules
from module in modules
where !kernel.GetModules().Any(m => m.Name.Equals(module.Name))
select module)
{
kernel.Load(module);
}
}
}
}
Inside the RegisterServices method every assembly in the application is iterated over and any classes that inherit from NinjectModule are loaded. However, I can't verify that it is working because I can't debug it. I have tried, but, execution is never stopped within the class. I know that the class is being instantiated and that the modules are being loaded because I have bindings in those modules that are working, however, I can't verify it.