How to make the application window maximized by default - xamarin.forms

How I can make my Xamarin.Forms UWP application have its main window maximized upon its launch?

You should use this answer: Maximize UWP app window on launch as #Dishant says but you should add this code to method OnLaunched into App class into App.xaml.cs file of your project UWP and add correct namespaces like this:
using Windows.Graphics.Display;
using Windows.UI.ViewManagement;
sealed partial class App : Application
{
/// <summary>
/// Initializes the singleton application object. This is the first line of authored code
/// executed, and as such is the logical equivalent of main() or WinMain().
/// </summary>
public App()
{
this.InitializeComponent();
this.Suspending += OnSuspending;
}
/// <summary>
/// Invoked when the application is launched normally by the end user. Other entry points
/// will be used such as when the application is launched to open a specific file.
/// </summary>
/// <param name="e">Details about the launch request and process.</param>
protected override void OnLaunched(LaunchActivatedEventArgs e)
{
Frame rootFrame = Window.Current.Content as Frame;
/* ************** CALL METHOD HERE ************** */
MaximizeWindowOnLoad();
// Do not repeat app initialization when the Window already has content,
// just ensure that the window is active
if (rootFrame == null)
{
// Create a Frame to act as the navigation context and navigate to the first page
rootFrame = new Frame();
rootFrame.NavigationFailed += OnNavigationFailed;
Xamarin.Forms.Forms.Init(e);
if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
{
//TODO: Load state from previously suspended application
}
// Place the frame in the current Window
Window.Current.Content = rootFrame;
}
if (rootFrame.Content == null)
{
// When the navigation stack isn't restored navigate to the first page,
// configuring the new page by passing required information as a navigation
// parameter
rootFrame.Navigate(typeof(MainPage), e.Arguments);
}
// Ensure the current window is active
Window.Current.Activate();
}
/* ************** SEE HERE ************** */
private void MaximizeWindowOnLoad()
{
var view = DisplayInformation.GetForCurrentView();
// Get the screen resolution (APIs available from 14393 onward).
var resolution = new Size(view.ScreenWidthInRawPixels, view.ScreenHeightInRawPixels);
// Calculate the screen size in effective pixels.
// Note the height of the Windows Taskbar is ignored here since the app will only be given the maxium available size.
var scale = view.ResolutionScale == ResolutionScale.Invalid ? 1 : view.RawPixelsPerViewPixel;
var bounds = new Size(resolution.Width / scale, resolution.Height / scale);
ApplicationView.PreferredLaunchViewSize = new Size(bounds.Width, bounds.Height);
ApplicationView.PreferredLaunchWindowingMode = ApplicationViewWindowingMode.PreferredLaunchViewSize;
}
/// <summary>
/// Invoked when Navigation to a certain page fails
/// </summary>
/// <param name="sender">The Frame which failed navigation</param>
/// <param name="e">Details about the navigation failure</param>
private void OnNavigationFailed(object sender, NavigationFailedEventArgs e)
{
throw new Exception("Failed to load Page " + e.SourcePageType.FullName);
}
/// <summary>
/// Invoked when application execution is being suspended. Application state is saved
/// without knowing whether the application will be terminated or resumed with the contents
/// of memory still intact.
/// </summary>
/// <param name="sender">The source of the suspend request.</param>
/// <param name="e">Details about the suspend request.</param>
private void OnSuspending(object sender, SuspendingEventArgs e)
{
var deferral = e.SuspendingOperation.GetDeferral();
//TODO: Save application state and stop any background activity
deferral.Complete();
}
}

Related

embedding a xamarin forms content page

I have been trying to embed a ContentPage in UWP following this tutorial
My code is rather simple, here is my content page :
<?xml version="1.0" encoding="utf-8" ?>
<local:CustomContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="NavigationPannel2.PageTest1"
xmlns:local="clr-namespace:NavigationPannel2"
BackgroundColor="Aqua">
<ContentPage.Content>
<Grid>
<Button Text="To Page 2"
Clicked="Button_Clicked"/>
</Grid>
</ContentPage.Content>
</local:CustomContentPage>
(CustomContentPage just adds a custom navigation event :)
using System;
using System.Collections.Generic;
using System.Text;
using Xamarin.Forms;
namespace NavigationPannel2
{
public class CustomContentPage : ContentPage
{
public EventHandler<NavigateEvent> navigation_push_event;
public CustomContentPage()
{
}
}
}
I initialize Forms.Init() in OnLaunched :
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.ApplicationModel;
using Windows.ApplicationModel.Activation;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
namespace NavigationPannel2.UWP
{
/// <summary>
/// Provides application-specific behavior to supplement the default Application class.
/// </summary>
sealed partial class App : Application
{
/// <summary>
/// Initializes the singleton application object. This is the first line of authored code
/// executed, and as such is the logical equivalent of main() or WinMain().
/// </summary>
public App()
{
this.InitializeComponent();
this.Suspending += OnSuspending;
}
/// <summary>
/// Invoked when the application is launched normally by the end user. Other entry points
/// will be used such as when the application is launched to open a specific file.
/// </summary>
/// <param name="e">Details about the launch request and process.</param>
protected override void OnLaunched(LaunchActivatedEventArgs e)
{
Xamarin.Forms.Forms.Init(e);
Frame rootFrame = Window.Current.Content as Frame;
// Do not repeat app initialization when the Window already has content,
// just ensure that the window is active
if (rootFrame == null)
{
// Create a Frame to act as the navigation context and navigate to the first page
rootFrame = new Frame();
rootFrame.NavigationFailed += OnNavigationFailed;
Xamarin.Forms.Forms.Init(e);
if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
{
//TODO: Load state from previously suspended application
}
// Place the frame in the current Window
Window.Current.Content = rootFrame;
}
if (rootFrame.Content == null)
{
// When the navigation stack isn't restored navigate to the first page,
// configuring the new page by passing required information as a navigation
// parameter
rootFrame.Navigate(typeof(MainPage), e.Arguments);
}
// Ensure the current window is active
Window.Current.Activate();
}
/// <summary>
/// Invoked when Navigation to a certain page fails
/// </summary>
/// <param name="sender">The Frame which failed navigation</param>
/// <param name="e">Details about the navigation failure</param>
void OnNavigationFailed(object sender, NavigationFailedEventArgs e)
{
throw new Exception("Failed to load Page " + e.SourcePageType.FullName);
}
/// <summary>
/// Invoked when application execution is being suspended. Application state is saved
/// without knowing whether the application will be terminated or resumed with the contents
/// of memory still intact.
/// </summary>
/// <param name="sender">The source of the suspend request.</param>
/// <param name="e">Details about the suspend request.</param>
private void OnSuspending(object sender, SuspendingEventArgs e)
{
var deferral = e.SuspendingOperation.GetDeferral();
//TODO: Save application state and stop any background activity
deferral.Complete();
}
}
}
And I use this page as content for my UWP MainPage :
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using Xamarin.Forms;
using Xamarin.Forms;
using Xamarin.Forms.Platform.UWP;
using Windows.UI.Core;
namespace NavigationPannel2.UWP
{
public sealed partial class MainPage
{
public MainPage()
{
this.InitializeComponent();
LoadApplication(new NavigationPannel2.App());
CustomContentPage page = new PageTest1();
Content = page.CreateFrameworkElement();
}
}
}
But the page seems to have lost its dynamic layout : when i resize the window everything stays still…
How Can I solve this ?

xamarin - closing activity from fragment

I have my fragment that will display transactions. It is a recyclerView. When I click one transaction from fragment, it will be displayed in a form with corresponding values where I can delete or update it.
How can I close the activity through fragment where my fragment connected before I start another activity?
Sorry for not updating my question nor giving an answer. After trials, I just thought of passing the activity on fragment constructor then close the activity using activity.Finish(); when I click on item in recycler view
private Expense_Objects expenseObject;
private Denomination_Objects denominationObject;
private Activity activity;
/// <summary>
/// Fragment for Petty Cash
/// </summary>
/// <param name="expenseObject">Expense Object</param>
/// <param name="denominationObject">Denomination Object</param>
/// <param name="activity">Activity where fragment will reside</param>
public Fragment_PettyCash(Expense_Objects expenseObject,
Denomination_Objects denominationObject, Activity activity)
{
this.pcExpenseObject = pcExpenseObject;
this.denominationObject = denominationObject;
this.activity = activity;
}
/// <summary>
/// Setting up recyclerView
/// </summary>
/// <param name="recyclerView">recyclerView</param>
private void setUpRecyclerView(RecyclerView recyclerView)
{
recyclerView.SetLayoutManager(new LinearLayoutManager(recyclerView.Context));
recyclerView.SetAdapter(new SimpleStringRecyclerViewAdapter(recyclerView.Context,
expenseObject.payeeList, expenseObject.totalAmountList));
recyclerView.SetItemClickListener((rv, position, view) =>
{
//doing other stuffs
Context context = view.Context;
Intent intent = new Intent(context, typeof(UpdateDeleteExpense));
intent.PutExtra(IntentExtras.denominationSerialized,
JsonConvert.SerializeObject(denominationObject));
intent.PutExtra(IntentExtras.pettyCashExpenseSerialized,
JsonConvert.SerializeObject(expenseObject));
context.StartActivity(intent);
activity.Finish();
}
);
}

Can there be multiple instances of a dependency in Xamarin.Forms?

I have mirrored some code from XLabs to get Network State Tracking on my device from here: Xlabs INetwork Android Implementation
I've pretty much aligned it with coding standards here and changed some method names - everything is working fine, except for some reason on the android implementation i am unable to get my event handlers to respond, the same way they do on iOS.
This is my Adaptation for Android:
[assembly: Dependency(typeof(STM.Droid.DependencyInjection.Network))]
[assembly: UsesPermission("android.permission.ACCESS_NETWORK_STATE")]
[assembly: UsesPermission("android.permission.ACCESS_WIFI_STATE")]
[assembly: UsesPermission("android.permission.CHANGE_NETWORK_STATE")]
[assembly: UsesPermission("android.permission.CHANGE_WIFI_STATE")]
namespace Namespace.Droid
{
[BroadcastReceiver(Enabled = true)]
[IntentFilter(new [] { Android.Net.ConnectivityManager.ConnectivityAction })]
public class Network : BroadcastReceiver, INetwork
{
/// <summary>
/// Internets the connection status.
/// </summary>
/// <returns>NetworkStatus.</returns>
public NetworkStatus GetConnectionStatus()
{
var status = NetworkStatus.NotReachable;
using (var cm = (ConnectivityManager)Application.Context.GetSystemService(Context.ConnectivityService))
using (var ni = cm.ActiveNetworkInfo)
{
if (ni != null && ni.IsConnectedOrConnecting)
{
var name = ni.TypeName.ToUpper();
if (name.Contains("WIFI"))
{
status = NetworkStatus.ReachableViaWiFiNetwork;
}
else if (name.Contains("MOBILE"))
{
status = NetworkStatus.ReachableViaCarrierDataNetwork;
}
else
{
status = NetworkStatus.ReachableViaUnknownNetwork;
}
}
}
return status;
}
private readonly object lockObject = new object();
private EventHandler<NetworkStatus> _reachabilityChanged;
public event EventHandler<NetworkStatus> ReachabilityChanged
{
add
{
lock (this.lockObject)
{
this._reachabilityChanged += value;
}
}
remove
{
lock (this.lockObject)
{
this._reachabilityChanged -= value;
}
}
}
/// <summary>
/// Occurs when [reachability changed].
/// </summary>
// public event EventHandler<NetworkStatus> ReachabilityChanged;
/// <summary>
/// Determines whether the specified host is reachable.
/// </summary>
/// <param name="host">The host.</param>
/// <param name="timeout">The timeout.</param>
public Task<bool> IsReachableAsync(string host, TimeSpan timeout)
{
return Task.Run(
() =>
{
try
{
var address = InetAddress.GetByName(host);
return address != null; // && (address.IsReachable((int)timeout.TotalMilliseconds) || );
}
catch (UnknownHostException)
{
return false;
}
});
}
/// <summary>
/// Determines whether [is reachable by wifi] [the specified host].
/// </summary>
/// <param name="host">The host.</param>
/// <param name="timeout">The timeout.</param>
public async Task<bool> IsReachableByWifiAsync(string host, TimeSpan timeout)
{
return GetConnectionStatus() == NetworkStatus.ReachableViaWiFiNetwork && await IsReachableAsync(host, timeout);
}
/// <summary>
/// This gets called by OS when the <see cref="ConnectivityManager.ConnectivityAction"/> <see cref="Intent"/> fires.
/// </summary>
/// <param name="context">Context for the intent.</param>
/// <param name="intent">Intent information.</param>
public override void OnReceive(Context context, Intent intent)
{
// this is a workaround - which oddly enough forwards events the way i would expect it to.
MessagingCenter.Send(this as INetwork, string.Empty, GetConnectionStatus());
// THIS IS ALWAYS NULL!
var handler = _reachabilityChanged;
if (handler != null)
{
var connectionStatus = this.GetConnectionStatus();
handler(this, connectionStatus);
}
}
}
}
The error in question occurs in OnReceive.
While in debugging i do notice that the handlers are attached correctly on the PCL side - there will just be null on that _reachabilityChanged field oddly enough.
As debugging indicates i am apparently getting
{md50e2cce2f1202796e628729fe0540389b.Network#b422684}
on the droid OnReceive method for "this"
while on the PCL side i am getting
{md50e2cce2f1202796e628729fe0540389b.Network#b562641}
when calling DependencyService.Get
To me this looks like the reason the handler list is empty, is because i am subscribing my handler on another instance and therefore do not get any handlers when a different instance of Network calls OnReceive.
Is it even possible for Xamarin.Forms DependencyService to provide 2 or more instances of an instance? Because that would surprise me a lot...
UPDATE:
In case someone needs a workaround - this works as well:
public event EventHandler<NetworkStatus> ReachabilityChanged
{
add { MessagingCenter.Subscribe(value.Target, string.Empty, (INetwork d, NetworkStatus a) => value(d, a)); }
remove { MessagingCenter.Unsubscribe<INetwork>(value.Target, string.Empty); }
}
for new instance
_client = DependencyService.Get<YOUINTERFACE>(DependencyFetchTarget.NewInstance);
by default DependencyService is keep single

[OpenStack .NET API]: Is there a way to combine the Object creation and Container creation in one call?

Currently I do this
try
{
cloudFilesProvider.CreateObjectFromFile(inStrContainerName, inStrSrcFilePath, strDesFileName, 4096, FileMetaData);
}
catch (ItemNotFoundException ex1)
{
try
{
cloudFilesProvider.CreateContainer(inStrContainerName);
cloudFilesProvider.CreateObjectFromFile(inStrContainerName, inStrSrcFilePath, strDesFileName, 4096, FileMetaData);
}
catch(Exception ex2)
{
return false;
}
}
So essentially if the container does not exist then its 3 separate API calls.
Is there a more efficient way to do this?
You can simplify the code by reducing it to the following two lines.
cloudFilesProvider.CreateContainer(inStrContainerName);
cloudFilesProvider.CreateObjectFromFile(inStrContainerName, inStrSrcFilePath, strDesFileName, 4096, FileMetaData);
CreateContainer is safe to call for a container that already exists. It returns ContainerCreated if the container is created, or ContainerExists if the container was not created because it already exists.
PS: The return values (with information like the above) for the IObjectStorageProvider methods will be well documented for release 1.2.0.0.
Edit: To reduce the number of API calls your code makes, you could use a cache class like the following. The CreateIfNecessary method attempts to create the container only if it is not previously known to exist. The ClearCache method provides a manual method for continuing to use the cache even if you delete a container.
This code is currently untested.
public class ContainerManager
{
private readonly CloudFilesProvider _provider;
private readonly string _region;
private readonly bool _useInternalUrl;
private readonly CloudIdentity _identity;
private readonly HashSet<string> _containers = new HashSet<string>();
public ContainerManager(CloudFilesProvider provider, string region, bool useInternalUrl, CloudIdentity identity)
{
if (provider == null)
throw new ArgumentNullException("provider");
_provider = provider;
_region = region;
_useInternalUrl = useInternalUrl;
_identity = identity;
}
/// <summary>
/// Clears the cache of known containers.
/// </summary>
/// <remarks>
/// <alert class="warning">
/// If a container was deleted after this cache was in use, this method must be called or
/// <see cref="CreateIfNecessary(string)"/> could fail to create a container which does not
/// exist.
/// </alert>
/// </remarks>
public void ClearCache()
{
lock (_containers)
{
_containers.Clear();
}
}
/// <summary>
/// Ensures that a container exists in the Cloud Files store.
/// </summary>
/// <remarks>
/// <alert class="warning">
/// If a container was deleted after this cache was in use, and <see cref="ClearCache()"/>
/// has not been called, this method could fail to create a container which does not exist.
/// </alert>
/// </remarks>
/// <param name="container">The name of the container to create.</param>
/// <exception cref="ArgumentNullException">If <paramref name="container"/> is <c>null</c>.</exception>
/// <exception cref="ArgumentException">If <paramref name="container"/> is empty.</exception>
/// <returns><c>true</c> if the container was created; otherwise <c>false</c> if the container already existed.</returns>
public bool CreateIfNecessary(string container)
{
if (container == null)
throw new ArgumentNullException("container");
if (string.IsNullOrEmpty(container))
throw new ArgumentException("container cannot be empty");
// don't try to create the same container multiple times
if (_containers.Contains(container))
return false;
ObjectStore result = _provider.CreateContainer(container, _region, _useInternalUrl, _identity);
if (result == ObjectStore.ContainerCreated || result == ObjectStore.ContainerExists)
{
lock (_containers)
{
// add to _containers even if the result is ContainerExists, because that
// means it simply wasn't known to this cache.
_containers.Add(container);
}
}
// only return true if the container was actually created
return result == ObjectStore.ContainerCreated;
}
}

Disposing an Object after a (possibly redirected) request

I have a CustomRequestContext object that has to be disposed after each request. I create it in Page_Load and dispose of it in Page_Unload. The only issue is that in certain circumstances I need to call Server.Transfer to redirect to another aspx page instead. In this case, the object should not be unloaded until the new page is ready to be unloaded. What is the nicest way of achieving this?
create a custom PageBase class for all your asp.net pages as mention below and Dispose the CustomRequestContext on the Page_Load and Page_Unload event.
/// <summary>
/// Base of front end web pages.
/// </summary>
public class PageBase : System.Web.UI.Page
{
/// <summary>
/// Initializes a new instance of the Page class.
/// </summary>
public Page()
{
this.Load += new EventHandler(this.Page_Load);
this.UnLoad += new EventHandler(this.Page_UnLoad);
}
/// <summary>
/// Page Load
/// </summary>
/// <param name="sender">sender as object</param>
/// <param name="e">Event arguments</param>
private void Page_Load(object sender, EventArgs e)
{
try
{
//Dispose the object here, assuming it is IDisposable.
//You can apply your own Disposition steps here..
CustomRequestContext.Dispose();
}
catch
{
//handle the situation gracefully here.
}
}
/// <summary>
/// Page UnLoad
/// </summary>
/// <param name="sender">sender as object</param>
/// <param name="e">Event arguments</param>
private void Page_UnLoad(object sender, EventArgs e)
{
try
{
//Dispose the object here, assuming it is IDisposable.
//You can apply your own Disposition steps here..
CustomRequestContext.Dispose();
}
catch
{
//handle the situation gracefully here.
}
}
}
I solved this problem by allowing the object to be owned by one page at a time. If I wanted to relinquish control from a page, I would set it equal to null and then it would not be released in the page's destructor.

Resources