xamarin - closing activity from fragment - android-fragments

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();
}
);
}

Related

How to make the application window maximized by default

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();
}
}

Chatjs: how to fetch friends list from sql database

I am using ChatJs in my asp.net webapplication with signalr adapter. How to show the online user from database on page load.As i am new to asp.net please guide me. thanks in advance
/// <summary>
/// This method is STUB. This will SIMULATE a database of users
/// </summary>
private static readonly List<DbUserStub> dbUsersStub = new List<DbUserStub>();
// <summary>
/// This method is STUB. In a normal situation, the user info would come from the database so this method wouldn't be necessary.
/// It's only necessary because this class is simulating the database
/// </summary>
/// <param name="newUser"></param>
public static void RegisterNewUser(DbUserStub newUser)
{
if (newUser == null) throw new ArgumentNullException("newUser");
dbUsersStub.Add(newUser);
}

[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;
}
}

What do I return from a POST action called from an external site?

I have a Payment controller, which exposes an HttpPost action method called Notify. This action is posted to when my external payment service sends me an Immediate Payment Notification (IPN), and it's sole purpose is to update my data based on the data I receive in the IPN. It never returns a view, so what should my action method return? I'm sure the payment service wants an HTTP 200 or something in response to the IPN post.
You could return an empty result:
return new EmptyResult();
return new HttpStatusCodeBoundedResult(200, "IPN accepted");
return new HttpStatusCodeBoundedResult(400, "Bad IPN request");
.
public class HttpStatusCodeBoundedResult : HttpStatusCodeResult
{
/// <summary>
/// Initializes a new instance of <see cref="HttpStatusCodeBoundedResult"/>.
/// </summary>
/// <param name="statusCode">The status code.</param>
public HttpStatusCodeBoundedResult(int statusCode) : base(statusCode)
{
}
/// <summary>
/// Initializes a new instance of <see cref="HttpStatusCodeBoundedResult"/>.
/// </summary>
/// <param name="statusCode">The status code.</param>
/// <param name="statusDescription">The status description. Will be
/// truncated to 512 characters and have \r\n characters stripped.</param>
public HttpStatusCodeBoundedResult(int statusCode, string statusDescription)
: base(statusCode, ApplyHttpResponseBoundary(statusDescription, 512))
{
}
private static string ApplyHttpResponseBoundary(string input, int length)
{
input = input.Replace("\r", string.Empty).Replace("\n", string.Empty);
return input.Length <= length ? input : input.Substring(0, length);
}
}
You can just make it return void.

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