Restored ImageView after app close and restart - imageview

How to restore an ImageView picked from gallery after close and restart the app. I am using SharedPreferences. To save the state of the URI after the app is closed, however it is not working the image is not set again any help would be appreciate.
public class test extends AppCompatActivity {
private static int RESULT_LOAD_IMAGE = 1;
ImageButton buttonLoadImage;
private static int RESULT_LOAD_IMG = 1;
String imgDecodableString;
public String getImagePathFetch;
ImageView imgView;
public String keyImage = "myImage";
public SharedPreferences sharedPrefEnter, sharedPrefGet;
Intent galleryIntent;
Uri selectedImage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity_layout);
imgView = (ImageView) findViewById(R.id.imageView1);
sharedPrefGet = PreferenceManager.getDefaultSharedPreferences(this);
getImagePathFetch = sharedPrefGet.getString(keyImage, "");
if (!getImagePathFetch.equals("")) {
// tToast("OnCreate Path=" + getImagePathFetch);
Uri uri;
uri = Uri.parse(getImagePathFetch);
imgView.setImageURI(uri);
}
buttonLoadImage = (ImageButton) findViewById(R.id.buttonLoadPicture);
buttonLoadImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AddImage(view);
}
});
}
public void AddImage(View view) {
galleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
// Start the Intent
startActivityForResult(galleryIntent, RESULT_LOAD_IMG);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// When an Image is picked
if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK && null != data) {
// Get the Image from data
selectedImage = data.getData();
sharedPrefEnter = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPrefEnter.edit();
editor.putString(keyImage, selectedImage.toString());
editor.commit();
Uri uri = Uri.parse(selectedImage.toString());
imgView.setImageURI(uri);
}
}
}

// get the path of the image
sharedPrefGet = PreferenceManager.getDefaultSharedPreferences(this);
getImagePathFetch = sharedPrefGet.getString(keyImage, "");
if (!getImagePathFetch.equals("")) {
// tToast("OnCreate Path = " + getImagePathFetch); //TESTING
// parse path from toString to uri
uriImage = Uri.parse(getImagePathFetch);
// explicitly check for the permission at runtime since API 23
int permissionCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
// Permission not granted
if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE },
WRITE_EXTERNAL_STORAGE);
} else // Permission granted
{
InputStream imageStream = null;
try {
imageStream = getContentResolver().openInputStream(uriImage);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Bitmap yourSelectedImage = BitmapFactory.decodeStream(imageStream);
Bitmap imageResized = getResizedBitmap(yourSelectedImage, 480, 480); // resized
// Image
imgView.setImageBitmap(imageResized);
} // end if
}
//Check permission result.
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions,
#NonNull int[] grantResults) {
switch (requestCode) {
case WRITE_EXTERNAL_STORAGE:
if ((grantResults.length > 0) && (grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
InputStream imageStream = null;
try {
imageStream = getContentResolver().openInputStream(uriImage);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Bitmap yourSelectedImage = BitmapFactory.decodeStream(imageStream);
Bitmap imageResized = getResizedBitmap(yourSelectedImage, 480, 480); // resized
// Image
imgView.setImageBitmap(imageResized);
}
break;
default:
break;
}
}

Related

How to change DatePicker Ok and Cancel button text in Xamarin forms?

I have an Xamarin.Forms app that supports many languages. How do I show the Calender for the DatePicker with DatePicker Ok and Cancel button text in local language text from resource file?
My custom renderer
[assembly: ExportRenderer(typeof(CustomImageDatePicker), typeof(CustomImageDatePickerRenderer))]
namespace AMS.Droid.Renderers
{
public class CustomImageDatePickerRenderer : DatePickerRenderer
{
public CustomImageDatePickerRenderer(Context context) : base(context)
{
}
protected override void OnElementChanged(ElementChangedEventArgs<DatePicker> e)
{
try
{
base.OnElementChanged(e);
CustomImageDatePicker element = (CustomImageDatePicker)this.Element;
if (Control == null)
return;
Control.Background = null;
if (Control != null && this.Element != null && !string.IsNullOrEmpty(element.Image))
{
Control.Background = AddPickerStyles(element.Image);
}
}
catch (Exception ex)
{
var message = ex.Message;
}
}
public LayerDrawable AddPickerStyles(string imagePath)
{
GradientDrawable gd = new GradientDrawable();
gd.SetColor(Android.Graphics.Color.Transparent);
gd.SetCornerRadius(25);
gd.SetStroke(3, Android.Graphics.Color.Black);
this.Control.SetBackgroundColor(Android.Graphics.Color.Transparent);
this.Control.SetPadding(20, 10, -50, 10);
Drawable[] layers = { gd, GetDrawable(imagePath) };
LayerDrawable layerDrawable = new LayerDrawable(layers);
layerDrawable.SetLayerInset(1, 0, 0, 30, 0);
return layerDrawable;
}
private BitmapDrawable GetDrawable(string imagePath)
{
try
{
int resID = Resources.GetIdentifier(imagePath.ToLower(), "drawable", this.Context.PackageName);
var drawable = ContextCompat.GetDrawable(this.Context, Resource.Drawable.brandIcon);
drawable.SetBounds(0, 0, (int)(drawable.IntrinsicWidth * 0.5),
(int)(drawable.IntrinsicHeight * 0.5));
var bitmap = ((BitmapDrawable)drawable).Bitmap;
var result = new BitmapDrawable(Resources, Bitmap.CreateScaledBitmap(bitmap, 60, 60, true));
result.Gravity = Android.Views.GravityFlags.Right;
//result.SetBounds(10, 10, 50, 0);
return result;
}
catch(Exception ex)
{
var message = ex.Message;
}
return null;
}`
Xaml:
<customDatePicker:CustomDatePicker
x:Name="dpFromDate"
DateSelected="FromDate_Selected"
Margin="10,5,10,0"
Image="brandIcon.png"/>
You could do this with custom renderer.
On Android, the DatePicker dialog can be customized by overriding the CreateDatePickerDialog method in a custom renderer.
[assembly: ExportRenderer(typeof(Xamarin.Forms.DatePicker), typeof(CustomDatePickerRenderer))]
namespace App10.Droid
{
public class CustomDatePickerRenderer : DatePickerRenderer
{
public CustomDatePickerRenderer(Context context) : base(context)
{
}
protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.DatePicker> e)
{
base.OnElementChanged(e);
//Disposing
if (e.OldElement != null)
{
datePicker = null;
}
//Creating
if (e.NewElement != null)
{
datePicker = e.NewElement;
}
}
DatePickerDialog pickerDialog;
private Xamarin.Forms.DatePicker datePicker;
protected override DatePickerDialog CreateDatePickerDialog(int year, int month, int day)
{
pickerDialog = new DatePickerDialog(Context, (o, e) =>
{
datePicker.Date = e.Date;
((IElementController)datePicker).SetValueFromRenderer(VisualElement.IsFocusedPropertyKey, false);
}, year, month, day);
//ok
pickerDialog.SetButton((int)DialogButtonType.Positive, "(FR)-DONE", OnDone);
//cancel
pickerDialog.SetButton((int)DialogButtonType.Negative, "(FR)-CLEAR", OnCancel);
return pickerDialog;
}
private void OnCancel(object sender, DialogClickEventArgs e)
{
datePicker.Unfocus();
}
private void OnDone(object sender, DialogClickEventArgs e)
{
datePicker.Date = ((DatePickerDialog)sender).DatePicker.DateTime;
datePicker.Unfocus();
}
}
}
You could replace the (FR)-DONE and (FR)-CLEAR with your own local language text from resource file
//ok
pickerDialog.SetButton((int)DialogButtonType.Positive, "(FR)-DONE", OnDone);
//cancel
pickerDialog.SetButton((int)DialogButtonType.Negative, "(FR)-CLEAR", OnCancel);

Xamarin Forms Custom Map Pin

In one of the apps I'm working on I require the use of custom map pins and I've followed the guide on Xamarin https://developer.xamarin.com/guides/xamarin-forms/application-fundamentals/custom-renderer/map/customized-pin/ as well as borrowed their sample code to try and make my own example.
It works to a degree in such that the info window is actually updated to the custom layout but the map pin never changes.
My CustomMapRenderer:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using Android.Content;
using Android.Gms.Maps;
using Android.Gms.Maps.Model;
using Android.Widget;
using Xamarin.Forms;
using Xamarin.Forms.Maps;
using Xamarin.Forms.Maps.Android;
using WorkingWithMaps.Droid.Renderers;
using WorkingWithMaps;
[assembly: ExportRenderer(typeof(CustomMap), typeof(CustomMapRenderer))]
namespace WorkingWithMaps.Droid.Renderers
{
public class CustomMapRenderer : MapRenderer, GoogleMap.IInfoWindowAdapter, IOnMapReadyCallback
{
GoogleMap map;
List<CustomPin> customPins;
bool isDrawn;
protected override void OnElementChanged(Xamarin.Forms.Platform.Android.ElementChangedEventArgs<Map> e)
{
base.OnElementChanged(e);
if (e.OldElement != null)
{
map.InfoWindowClick -= OnInfoWindowClick;
}
if (e.NewElement != null)
{
var formsMap = (CustomMap)e.NewElement;
customPins = formsMap.CustomPins;
((MapView)Control).GetMapAsync(this);
}
}
void IOnMapReadyCallback.OnMapReady(GoogleMap googleMap)
{
map = googleMap;
map.SetInfoWindowAdapter(this);
map.InfoWindowClick += OnInfoWindowClick;
this.NativeMap = googleMap;
}
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);
if (e.PropertyName.Equals("VisibleRegion") && !isDrawn)
{
map.Clear();
foreach (var pin in customPins)
{
var marker = new MarkerOptions();
marker.SetPosition(new LatLng(pin.Pin.Position.Latitude, pin.Pin.Position.Longitude));
marker.SetTitle(pin.Pin.Label);
marker.SetSnippet(pin.Pin.Address);
marker.SetIcon(BitmapDescriptorFactory.FromResource(Resource.Drawable.pin));
map.AddMarker(marker);
}
isDrawn = true;
}
}
protected override void OnLayout(bool changed, int l, int t, int r, int b)
{
base.OnLayout(changed, l, t, r, b);
if (changed)
{
isDrawn = false;
}
}
void OnInfoWindowClick(object sender, GoogleMap.InfoWindowClickEventArgs e)
{
var customPin = GetCustomPin(e.Marker);
if (customPin == null)
{
throw new Exception("Custom pin not found");
}
if (!string.IsNullOrWhiteSpace(customPin.Url))
{
var url = Android.Net.Uri.Parse(customPin.Url);
var intent = new Intent(Intent.ActionView, url);
intent.AddFlags(ActivityFlags.NewTask);
Android.App.Application.Context.StartActivity(intent);
}
}
public Android.Views.View GetInfoContents(Marker marker)
{
var inflater = Android.App.Application.Context.GetSystemService(Context.LayoutInflaterService) as Android.Views.LayoutInflater;
if (inflater != null)
{
Android.Views.View view;
var customPin = GetCustomPin(marker);
if (customPin == null)
{
throw new Exception("Custom pin not found");
}
if (customPin.Id == "Xamarin")
{
view = inflater.Inflate(Resource.Layout.XamarinMapInfoWindow, null);
}
else
{
view = inflater.Inflate(Resource.Layout.MapInfoWindow, null);
}
var infoTitle = view.FindViewById<TextView>(Resource.Id.InfoWindowTitle);
var infoSubtitle = view.FindViewById<TextView>(Resource.Id.InfoWindowSubtitle);
if (infoTitle != null)
{
infoTitle.Text = marker.Title;
}
if (infoSubtitle != null)
{
infoSubtitle.Text = marker.Snippet;
}
return view;
}
return null;
}
public Android.Views.View GetInfoWindow(Marker marker)
{
return null;
}
CustomPin GetCustomPin(Marker annotation)
{
var position = new Position(annotation.Position.Latitude, annotation.Position.Longitude);
foreach (var pin in customPins)
{
if (pin.Pin.Position == position)
{
return pin;
}
}
return null;
}
}
}
and my map page, also heavily borrowed from Xamarin's working with maps guide
using Plugin.Geolocator;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Xamarin.Forms;
using Xamarin.Forms.Maps;
using Xamarin.Forms.Xaml;
namespace WorkingWithMaps
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class MainPage : ContentPage
{
CustomMap map;
Geocoder geoCoder;
String navAdd;
public MainPage()
{
InitializeComponent();
var maplocator = CrossGeolocator.Current;
maplocator.DesiredAccuracy = 1;
geoCoder = new Geocoder();
map = new CustomMap
{
HeightRequest = 100,
WidthRequest = 960,
VerticalOptions = LayoutOptions.FillAndExpand,
IsShowingUser = true
};
map.MapType = MapType.Street;
map.MoveToRegion(MapSpan.FromCenterAndRadius(new Position(55.237208, 10.479160), Distance.FromMeters(500)));
map.IsShowingUser = true;
var street = new Button { Text = "Street" };
var hybrid = new Button { Text = "Hybrid" };
var satellite = new Button { Text = "Satellite" };
street.Clicked += HandleClickedAsync;
hybrid.Clicked += HandleClickedAsync;
//satellite.Clicked += OnReverseGeocodeButtonClicked;
var segments = new StackLayout
{
Spacing = 30,
HorizontalOptions = LayoutOptions.CenterAndExpand,
Orientation = StackOrientation.Horizontal,
Children = { street, hybrid, satellite }
};
Content = new StackLayout
{
HorizontalOptions = LayoutOptions.Center,
Children = { map, segments }
};
Device.BeginInvokeOnMainThread(async () =>
{
try
{
//var currentpos = await maplocator.GetPositionAsync(1000);
//map.MoveToRegion(MapSpan.FromCenterAndRadius(new Position(currentpos.Latitude, currentpos.Longitude), Distance.FromMeters(500)));
if (!maplocator.IsListening)
{
await maplocator.StartListeningAsync(1000, 50, true);
}
}
catch (Exception ex)
{
Debug.WriteLine("Fail" + ex);
}
});
var pin = new CustomPin
{
Pin = new Pin
{
Type = PinType.Place,
Position = new Position(55.240121, 10.469895),
Label = "Testing Pins"
}
};
map.CustomPins = new List<CustomPin> { pin };
map.Pins.Add(pin.Pin);
map.PropertyChanged += (sender, e) =>
{
Debug.WriteLine(e.PropertyName + " just changed!");
if (e.PropertyName == "VisibleRegion" && map.VisibleRegion != null)
CalculateBoundingCoordinates(map.VisibleRegion);
};
maplocator.PositionChanged += (sender, e) =>
{
var position = e.Position;
map.MoveToRegion(MapSpan.FromCenterAndRadius(new Position(position.Latitude, position.Longitude), Distance.FromKilometers(2)));
};
}
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
//async void OnReverseGeocodeButtonClicked(object sender, EventArgs e)
//{
// var possibleAddresses = await geoCoder.GetAddressesForPositionAsync(pin.Position);
// navAdd += possibleAddresses.ElementAt(0) + "\n";
// switch (Device.OS)
// {
// case TargetPlatform.iOS:
// Device.OpenUri(new Uri(string.Format("http://maps.apple.com/?q={0}", WebUtility.UrlEncode(navAdd))));
// break;
// case TargetPlatform.Android:
// Device.OpenUri(new Uri(string.Format("geo:0,0?q={0}", WebUtility.UrlEncode(navAdd))));
// break;
// case TargetPlatform.Windows:
// case TargetPlatform.WinPhone:
// Device.OpenUri(new Uri(string.Format("bingmaps:?where={0}", Uri.EscapeDataString(navAdd))));
// break;
// }
//}
void HandleClickedAsync(object sender, EventArgs e)
{
var b = sender as Button;
switch (b.Text)
{
case "Street":
map.MapType = MapType.Street;
break;
case "Hybrid":
map.MapType = MapType.Hybrid;
break;
case "Satellite":
map.MapType = MapType.Satellite;
break;
}
}
static void CalculateBoundingCoordinates(MapSpan region)
{
var center = region.Center;
var halfheightDegrees = region.LatitudeDegrees / 2;
var halfwidthDegrees = region.LongitudeDegrees / 2;
var left = center.Longitude - halfwidthDegrees;
var right = center.Longitude + halfwidthDegrees;
var top = center.Latitude + halfheightDegrees;
var bottom = center.Latitude - halfheightDegrees;
if (left < -180) left = 180 + (180 + left);
if (right > 180) right = (right - 180) - 180;
Debug.WriteLine("Bounding box:");
Debug.WriteLine(" " + top);
Debug.WriteLine(" " + left + " " + right);
Debug.WriteLine(" " + bottom);
}
}
}
On top of the mentioned issue the implementation has also caused IsShowingUser = True to no longer function as well as
var currentpos = await maplocator.GetPositionAsync(1000);
to throw an exception.
Github repository: https://github.com/Mortp/CustomMapPinsXamarin
First of all I would like to provide 2 links that helped me to understand the problem. Thank you guys.
Xamarin.Forms.Maps 2.3.4 custom MapRenderer disables everything and https://forums.xamarin.com/discussion/92565/android-ionmapreadycallback-forms-2-3-4
Latest Xamarin Maps broke OnElementPropertyChanged with VisibleRegion. They defined that MapRenderer now implements IOnMapReadyCallback and that broke somehow OnElementPropertyChanged (I didn't investigate how and why). As you can see in link I provided there are 2 methods you can go. To keep your renderer implementing IOnMapReadyCallback or not. When I kept IOnMapReadyCallback I started to get 2 pins - one of top another - our custom pin and regular pin. I didn't dig more how that happens and removed IOnMapReadyCallback. After that things became really simple because if you let Xamarin handle it and create NativeMap you can remove some code and make renderer simpler.
Before I post the code I also want to mention that when I fixed it the app started crashing with OutOfMemory exception and I found out that your pin image is 2000 pixels width. I changed it to 40. Below is the code:
public class CustomMapRenderer : MapRenderer, GoogleMap.IInfoWindowAdapter//, IOnMapReadyCallback
{
bool isDrawn;
protected override void OnElementChanged(Xamarin.Forms.Platform.Android.ElementChangedEventArgs<Map> e)
{
base.OnElementChanged(e);
if (e.OldElement != null)
{
NativeMap.InfoWindowClick -= OnInfoWindowClick;
}
}
bool isMapReady;
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);
if (!isMapReady && (NativeMap != null))
{
NativeMap.SetInfoWindowAdapter(this);
NativeMap.InfoWindowClick += OnInfoWindowClick;
isMapReady = true;
}
if (e.PropertyName.Equals("VisibleRegion") && !isDrawn)
{
NativeMap.Clear();
foreach (var pin in ((CustomMap)Element).CustomPins)
{
var marker = new MarkerOptions();
marker.SetPosition(new LatLng(pin.Pin.Position.Latitude, pin.Pin.Position.Longitude));
marker.SetTitle(pin.Pin.Label);
marker.SetSnippet(pin.Pin.Address);
marker.SetIcon(BitmapDescriptorFactory.FromResource(Resource.Drawable.pin));
NativeMap.AddMarker(marker);
}
isDrawn = true;
}
}
protected override void OnLayout(bool changed, int l, int t, int r, int b)
{
base.OnLayout(changed, l, t, r, b);
if (changed)
{
isDrawn = false;
}
}
void OnInfoWindowClick(object sender, GoogleMap.InfoWindowClickEventArgs e)
{
var customPin = GetCustomPin(e.Marker);
if (customPin == null)
{
throw new Exception("Custom pin not found");
}
if (!string.IsNullOrWhiteSpace(customPin.Url))
{
var url = Android.Net.Uri.Parse(customPin.Url);
var intent = new Intent(Intent.ActionView, url);
intent.AddFlags(ActivityFlags.NewTask);
Android.App.Application.Context.StartActivity(intent);
}
}
public Android.Views.View GetInfoContents(Marker marker)
{
var inflater = Android.App.Application.Context.GetSystemService(Context.LayoutInflaterService) as Android.Views.LayoutInflater;
if (inflater != null)
{
Android.Views.View view;
var customPin = GetCustomPin(marker);
if (customPin == null)
{
throw new Exception("Custom pin not found");
}
if (customPin.Id == "Xamarin")
{
view = inflater.Inflate(Resource.Layout.XamarinMapInfoWindow, null);
}
else
{
view = inflater.Inflate(Resource.Layout.MapInfoWindow, null);
}
var infoTitle = view.FindViewById<TextView>(Resource.Id.InfoWindowTitle);
var infoSubtitle = view.FindViewById<TextView>(Resource.Id.InfoWindowSubtitle);
if (infoTitle != null)
{
infoTitle.Text = marker.Title;
}
if (infoSubtitle != null)
{
infoSubtitle.Text = marker.Snippet;
}
return view;
}
return null;
}
public Android.Views.View GetInfoWindow(Marker marker)
{
return null;
}
CustomPin GetCustomPin(Marker annotation)
{
var position = new Position(annotation.Position.Latitude, annotation.Position.Longitude);
foreach (var pin in ((CustomMap)Element).CustomPins)
{
if (pin.Pin.Position == position)
{
return pin;
}
}
return null;
}
}

windows forms, async task exception catching

I have a form, 2 buttons , 1 textbox. Button 1 processes the TaskException_click.
What I wanted to do is understanding the async task/void difference. But checking multiple examples I still do not understand or get it to work. Below my code.
When I click the taskexception button, the unobservedtaskexception is not executed (I expected that).
When I click it another time, the event is executed with the exception of the first click. However the UI is not updated (actually it hangs). Would like to know what I am doing wrong.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace test
{
public partial class main : Form
{
public main()
{
InitializeComponent();
TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException;
}
void TaskScheduler_UnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs e)
{
//textBox1.Text = "Unobserved Exception caught ";
e.SetObserved();
if (this.InvokeRequired)
{
this.Invoke((MethodInvoker)delegate()
{
//codes to do whatever i wan to do with the GUI
//Examples of it would be disposing a flowlayout panel
//and re-adding it back and populating it again to
//show the refreshed values.
textBox1.Text = "Unobserved Exception caught " + e.Exception.Message;
});
}
else
{
textBox1.Text = "Unobserved Exception caught " + e.Exception.Message;
}
}
private int i = 0;
// Add async here! You can always add these to events
private async void TaskException_Click(object sender, EventArgs e)
{
textBox1.Text = "";
try
{
Task t = TaskThrowAnException();
textBox1.Text = "done";
t = null;
Thread.Sleep(100);
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
}
catch (Exception ex)
{
textBox1.Text = "Exception caught";
}
}
private async Task TaskThrowAnException()
{
//await Task.Delay(1000);
i++;
throw new Exception("Task" + i.ToString());
}
private async void VoidException_Click(object sender, EventArgs e)
{
textBox1.Text = "";
try
{
VoidThrowAnException();
textBox1.Text = "done";
}
catch (Exception ex )
{
textBox1.Text = "Exception caught";
}
}
private async void VoidThrowAnException()
{
//await Task.Delay(1000);
throw new Exception("Void");
}
}
}
For the TaskException case the exception is stored in the Task this is the expected behavior for async methods returning Task. If you want the exception to be thrown you need to observe the exception by awaiting the Task or calling Result or Wait() on the Task.
If the exception is unobserved it should get thrown when the Task is finalized, the only thing I can conclude is that somehow the task is not being finalized when you call
Thread.Sleep(100);
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
I am nor sure why the local variable is not GCed, if add another button and you put the code above in the button handler (e.g Clear_Click) everything works as expected. I thought the generated code must somehow have a link to the task variable but I couldn't find any link.
Here is the generated code from Reflector:
namespace WindowsFormsApplication1
{
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
public class Form1 : Form
{
private IContainer components = null;
private int i = 0;
private Button TaskException;
private TextBox textBox1;
private Button VoidException;
public Form1()
{
this.InitializeComponent();
TaskScheduler.UnobservedTaskException += new EventHandler<UnobservedTaskExceptionEventArgs>(this.TaskScheduler_UnobservedTaskException);
}
protected override void Dispose(bool disposing)
{
if (disposing && (this.components != null))
{
this.components.Dispose();
}
base.Dispose(disposing);
}
private void InitializeComponent()
{
this.textBox1 = new TextBox();
this.TaskException = new Button();
this.VoidException = new Button();
base.SuspendLayout();
this.textBox1.Location = new Point(13, 13);
this.textBox1.Multiline = true;
this.textBox1.Name = "textBox1";
this.textBox1.Size = new Size(0x20d, 0x13f);
this.textBox1.TabIndex = 0;
this.TaskException.Location = new Point(13, 0x16d);
this.TaskException.Name = "TaskException";
this.TaskException.Size = new Size(0x9b, 0x17);
this.TaskException.TabIndex = 1;
this.TaskException.Text = "TaskException";
this.TaskException.UseVisualStyleBackColor = true;
this.TaskException.Click += new EventHandler(this.TaskException_Click);
this.VoidException.Location = new Point(0xda, 0x16d);
this.VoidException.Name = "VoidException";
this.VoidException.Size = new Size(0xab, 0x17);
this.VoidException.TabIndex = 2;
this.VoidException.Text = "VoidException";
this.VoidException.UseVisualStyleBackColor = true;
this.VoidException.Click += new EventHandler(this.VoidException_Click);
base.AutoScaleDimensions = new SizeF(6f, 13f);
base.AutoScaleMode = AutoScaleMode.Font;
base.ClientSize = new Size(550, 430);
base.Controls.Add(this.VoidException);
base.Controls.Add(this.TaskException);
base.Controls.Add(this.textBox1);
base.Name = "Form1";
this.Text = "Form1";
base.ResumeLayout(false);
base.PerformLayout();
}
[DebuggerStepThrough, AsyncStateMachine(typeof(<TaskException_Click>d__4))]
private void TaskException_Click(object sender, EventArgs e)
{
<TaskException_Click>d__4 d__;
d__.<>4__this = this;
d__.sender = sender;
d__.e = e;
d__.<>t__builder = AsyncVoidMethodBuilder.Create();
d__.<>1__state = -1;
d__.<>t__builder.Start<<TaskException_Click>d__4>(ref d__);
}
private void TaskScheduler_UnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs e)
{
MethodInvoker method = null;
e.SetObserved();
if (base.InvokeRequired)
{
if (method == null)
{
method = (MethodInvoker) (() => (this.textBox1.Text = "Unobserved Exception caught " + e.Exception.Message));
}
base.BeginInvoke(method);
}
else
{
this.textBox1.Text = "Unobserved Exception caught " + e.Exception.Message;
}
}
[AsyncStateMachine(typeof(<TaskThrowAnException>d__6)), DebuggerStepThrough]
private Task TaskThrowAnException()
{
<TaskThrowAnException>d__6 d__;
d__.<>4__this = this;
d__.<>t__builder = AsyncTaskMethodBuilder.Create();
d__.<>1__state = -1;
d__.<>t__builder.Start<<TaskThrowAnException>d__6>(ref d__);
return d__.<>t__builder.Task;
}
[DebuggerStepThrough, AsyncStateMachine(typeof(<VoidException_Click>d__8))]
private void VoidException_Click(object sender, EventArgs e)
{
<VoidException_Click>d__8 d__;
d__.<>4__this = this;
d__.sender = sender;
d__.e = e;
d__.<>t__builder = AsyncVoidMethodBuilder.Create();
d__.<>1__state = -1;
d__.<>t__builder.Start<<VoidException_Click>d__8>(ref d__);
}
[AsyncStateMachine(typeof(<VoidThrowAnException>d__a)), DebuggerStepThrough]
private void VoidThrowAnException()
{
<VoidThrowAnException>d__a _a;
_a.<>4__this = this;
_a.<>t__builder = AsyncVoidMethodBuilder.Create();
_a.<>1__state = -1;
_a.<>t__builder.Start<<VoidThrowAnException>d__a>(ref _a);
}
[CompilerGenerated]
private struct <TaskException_Click>d__4 : IAsyncStateMachine
{
public int <>1__state;
public Form1 <>4__this;
public AsyncVoidMethodBuilder <>t__builder;
public EventArgs e;
public object sender;
private void MoveNext()
{
try
{
if (this.<>1__state != -3)
{
this.<>4__this.textBox1.Text = "";
try
{
Task task = this.<>4__this.TaskThrowAnException();
this.<>4__this.textBox1.Text = "done";
task = null;
}
catch (Exception)
{
this.<>4__this.textBox1.Text = "Exception caught";
}
Thread.Sleep(100);
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
}
}
catch (Exception exception2)
{
this.<>1__state = -2;
this.<>t__builder.SetException(exception2);
return;
}
this.<>1__state = -2;
this.<>t__builder.SetResult();
}
[DebuggerHidden]
private void SetStateMachine(IAsyncStateMachine param0)
{
this.<>t__builder.SetStateMachine(param0);
}
}
[CompilerGenerated]
private struct <TaskThrowAnException>d__6 : IAsyncStateMachine
{
public int <>1__state;
public Form1 <>4__this;
public AsyncTaskMethodBuilder <>t__builder;
private void MoveNext()
{
try
{
if (this.<>1__state != -3)
{
this.<>4__this.i++;
throw new Exception("Task" + this.<>4__this.i.ToString());
}
}
catch (Exception exception)
{
this.<>1__state = -2;
this.<>t__builder.SetException(exception);
return;
}
this.<>1__state = -2;
this.<>t__builder.SetResult();
}
[DebuggerHidden]
private void SetStateMachine(IAsyncStateMachine param0)
{
this.<>t__builder.SetStateMachine(param0);
}
}
[CompilerGenerated]
private struct <VoidException_Click>d__8 : IAsyncStateMachine
{
public int <>1__state;
public Form1 <>4__this;
public AsyncVoidMethodBuilder <>t__builder;
public EventArgs e;
public object sender;
private void MoveNext()
{
try
{
if (this.<>1__state != -3)
{
this.<>4__this.textBox1.Text = "";
try
{
this.<>4__this.VoidThrowAnException();
this.<>4__this.textBox1.Text = "done";
}
catch (Exception)
{
this.<>4__this.textBox1.Text = "Exception caught";
}
}
}
catch (Exception exception2)
{
this.<>1__state = -2;
this.<>t__builder.SetException(exception2);
return;
}
this.<>1__state = -2;
this.<>t__builder.SetResult();
}
[DebuggerHidden]
private void SetStateMachine(IAsyncStateMachine param0)
{
this.<>t__builder.SetStateMachine(param0);
}
}
[CompilerGenerated]
private struct <VoidThrowAnException>d__a : IAsyncStateMachine
{
public int <>1__state;
public Form1 <>4__this;
public AsyncVoidMethodBuilder <>t__builder;
private void MoveNext()
{
try
{
if (this.<>1__state != -3)
{
SynchronizationContext current = SynchronizationContext.Current;
throw new Exception("Void");
}
}
catch (Exception exception)
{
this.<>1__state = -2;
this.<>t__builder.SetException(exception);
return;
}
this.<>1__state = -2;
this.<>t__builder.SetResult();
}
[DebuggerHidden]
private void SetStateMachine(IAsyncStateMachine param0)
{
this.<>t__builder.SetStateMachine(param0);
}
}
}
}

get value of checked checkbox created dynamically

in this i m fetching data from database i.e. question and answer and accordingly numbers of answer in the database equals to number of checked box created dynamically and i want that the when the user checked the checked box the value of that checked box must me save in sqlite database
public class Multiselect extends Fragment
{
TextView ques;
DefaultHttpClient httpclient;
HttpPost httppost;
HttpResponse httpResponse;
HttpEntity httpEntity;
HttpResponse response;
HttpEntity entity;
InputStream is = null;
String result = null;
StringBuilder sb=null;
BufferedReader reader;
JSONArray jArray;
String line;
String question;
String answer;
int questionno;
int i;
View view;
Context context;
int id=1;
CheckBox checkboxbutton;
final CheckBox[] checkboxbuttons = new CheckBox[50];
LinearLayout l;
//DatabaseMultiselect db;
String text;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}
public void onActivityCreated(Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
view = inflater.inflate(R.layout.multiselect, container, false);
l=(LinearLayout)view.findViewById(R.id.l1);
/*String l1=l.toString();
String strtext=getArguments().getString("next");
Log.e("str",strtext);*/
StrictMode.enableDefaults();
ques=(TextView)view.findViewById(R.id.quesmultiselect);
//db=new DatabaseMultiselect(getActivity());
// db.open();
getMultiselect();
getAnswer(container);
Log.e("id",""+id);
Log.e("count",""+l.getChildCount());
return view;
}
void getMultiselect()
{
try
{
httpclient=new DefaultHttpClient();
// httppost= new HttpPost("http://10.0.2.2/multiselectandroid.php");
httpResponse = httpclient.execute(httppost);
httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
catch(Exception e)
{
Log.e("log_tag", "Error in http connection"+e.toString());
ques.setText("error!!");
}
//convert response to string
try
{
reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}
catch(Exception e)
{
Log.e("log_tag", "Error converting result "+e.toString());
}
//paring data
try
{
jArray = new JSONArray(result);
JSONObject json_data=null;
for(i=0;i<jArray.length();i++)
{
json_data = jArray.getJSONObject(i);
questionno=json_data.getInt("question_no");
question=json_data.getString("question");
Log.e("question",question);
//s=s+""+question;
}
ques.setText(question);
}
catch(JSONException excep)
{
excep.printStackTrace();
//Toast.makeText(getBaseContext(), "Error", Toast.LENGTH_LONG).show();
}
catch (ParseException excep)
{
excep.printStackTrace();
}
}
void getAnswer(ViewGroup container)
{
try
{
httpclient=new DefaultHttpClient();
httppost= new HttpPost("http://10.0.2.2/multiselectanswer.php?questionno="+questionno);
httpResponse = httpclient.execute(httppost);
httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
catch(Exception e)
{
Log.e("log_tag", "Error in http connection"+e.toString());
ques.setText("error!!");
}
//convert response to string
try
{
reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}
catch(Exception e)
{
Log.e("log_tag", "Error converting result "+e.toString());
}
//pairing data
try
{
jArray = new JSONArray(result);
JSONObject json_data=null;
for(i=0;i<jArray.length();i++)
{
json_data = jArray.getJSONObject(i);
answer=json_data.getString("answer");
checkboxbuttons[i] = new CheckBox(container.getContext());
checkboxbuttons[i].setId(id);
l.addView(checkboxbuttons[i]);
checkboxbuttons[i].setText(answer);
checkboxbuttons[i].setTextColor(Color.RED);
int rid=checkboxbuttons[i].getId();
Log.e("rid",""+rid);
id++;
}
/* if(id.getCheckedRadioButton==true)
{
String selected=chk;
Log.e("select",selected);
}*/
}
catch(JSONException excep)
{
excep.printStackTrace();
//Toast.makeText(getBaseContext(), "Error", Toast.LENGTH_LONG).show();
}
catch (ParseException excep)
{
excep.printStackTrace();
}
}
}
public class Multiselect extends Fragment
{
//Declaring variables
TextView ques;
TextView condition;
TextView sectionidtext;
TextView instructions;
String instructionset;
int question_no;
String question1;
String surveyName;
String selectedQues;
String username;
int min_answers;
int max_answers;
int id=1;
DatabaseHandler db;
String rating=null;
View view;
final CheckBox[] answercheckbox = new CheckBox[50];
LinearLayout answersettinglayout;
String answertext;
int count=0;
String limit;
String sectionids;
String date=null;
String time=null;
String tablename="multiselect";
String input_answer=null;
String userid;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
//Getting Question number,user name,survey name,questionnaire name and user id value
Bundle mulitselectBundle=getArguments();
question_no=mulitselectBundle.getInt("questionnum");
surveyName=mulitselectBundle.getString("surveyname");
selectedQues=mulitselectBundle.getString("quesname");
username=mulitselectBundle.getString("username");
userid=mulitselectBundle.getString("userid");
Log.e("mulitselect"," "+question_no);
Log.e("mulitselect",surveyName);
Log.e("mulitselect",selectedQues);
Log.e("mulitselect",username);
Log.e("mulitselect",userid);
}
public void onActivityCreated(Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
view = inflater.inflate(R.layout.multiselect, container, false);
//Getting id of Linear Layout for answers
answersettinglayout=(LinearLayout)view.findViewById(R.id.answersetting);
//Getting id of text view for question
ques=(TextView)view.findViewById(R.id.quesmultiselect);
//Getting id of textview for conditions
condition=(TextView)view.findViewById(R.id.conditionmulti);
//Getting id of textview for section id
sectionidtext=(TextView)view.findViewById(R.id.sectionidmultiselect);
//Getting id of text view for instructions display
instructions=(TextView)view.findViewById(R.id.instructionmultiselect);
//Create object of database
db=new DatabaseHandler(getActivity());
//Function call
retrieveQuestion();
getAnswer(container);
getcheckedCheckBoxes();
return view;
}
void retrieveQuestion()
{
//Open database
db.open();
Log.e("inside","retrieve question");
//Fetching value of question and section id
Cursor questioncursor=db.getQuestion(username,surveyName,selectedQues,question_no);
int length=questioncursor.getCount();
Log.e("length",""+length);
//Getting question and section id
if(questioncursor.moveToFirst())
{
//Getting column number
int indexquestion=questioncursor.getColumnIndex("question");
Log.e("index",""+indexquestion);
//Getting value of question and section id
question1= questioncursor.getString(indexquestion);
sectionids=questioncursor.getString(questioncursor.getColumnIndex("ques_id"));
//Setting question
ques.setText(question1);
Log.e("question",question1);
//Setting section id
sectionidtext.setText("Q."+sectionids);
}
//Closing cursor
questioncursor.close();
}
void getAnswer(ViewGroup container)
{
//Open database
db.open();
Log.e("inside","answer question");
//Fetching answers
Cursor answergettingcursor=db. getAnswer(username,surveyName,selectedQues,question_no);
//Declaring variable
int i=0;
//Getting answer value
while(answergettingcursor.moveToPosition(i))
{
//Getting column number
int indexanswer=answergettingcursor.getColumnIndex("answer");
//creating check boxes
answercheckbox[i] = new CheckBox(container.getContext());
//Setting id of check boxes
answercheckbox[i].setId(id);
//Adding check boxes in layout
answersettinglayout.addView(answercheckbox[i]);
//Setting answer value
answercheckbox[i].setText(answergettingcursor.getString(indexanswer));
//Setting text color
answercheckbox[i].setTextColor(Color.RED);
int rid=answercheckbox[i].getId();
Log.e("rid",""+rid);
//Incrementing value
id++;
i++;
}
//Closing cursor
answergettingcursor.close();
}
void getcheckedCheckBoxes()
{
Log.e("id",""+id);
Log.e("count",""+answersettinglayout.getChildCount());
//Fetching value of minimum and maximum characters
Cursor checkcondition=db.getmultiselecttabledata(username, surveyName, selectedQues, question_no);
//For Conditions
if(checkcondition.moveToFirst())
{
//Getting column number
int indexmin_answers=checkcondition.getColumnIndex("min_answers");
int indexmax_answers=checkcondition.getColumnIndex("max_answers");
Log.e("indexanswer",""+indexmin_answers);
Log.e("indexanswer1",""+indexmax_answers);
//Getting value of minimum and maximum characters and instructions
min_answers=checkcondition.getInt(indexmin_answers);
max_answers=checkcondition.getInt(indexmax_answers);
instructionset=checkcondition.getString(checkcondition.getColumnIndex("instructions"));
Log.e("texttableview",""+min_answers);
Log.e("texttableview",""+max_answers);
//Setting value of instructions
instructions.setText(instructionset);
//For answers
for(int k=0;k<answersettinglayout.getChildCount();k++)
{
//Whether check box checked or not
answercheckbox[k].setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
//If check box checked
if(((CheckBox) v).isChecked())
{
//Incrementing value of count
count++;
Log.e("count",""+count);
//Getting value of checked check box
answertext=((CheckBox) v).getText().toString();
Log.e("checkbox",""+answertext);
//Checking min and max character conditions
if(count>=min_answers)
{
if(count>max_answers)
{
//Setting text
condition.setText("Selected answers exceeds maximum length");
//Setting text color
condition.setTextColor(Color.RED);
//Setting value of limit
limit="max";
}
else
{
//Setting text
condition.setText("");
//Setting value of limit
limit="proper";
}
}
else
{
//Setting text
condition.setText("Please select more answers");
//Setting text color
condition.setTextColor(Color.RED);
//Setting value of limit
limit="min";
}
//Inserting answers
db.insertAnswer(userid,username,surveyName,selectedQues,question_no,question1,answertext,rating,input_answer,limit,date,time,sectionids,tablename);
}
//if unchecked check box
else
{
//Decreasing count value
count--;
Log.e("count",""+count);
//Getting value of checked check box
answertext=((CheckBox) v).getText().toString();
Log.e("checkboxdelete",""+answertext);
//Deleting unchecked check box value
db.deleteQuesMultiselect(userid,username, surveyName, selectedQues, question_no,answertext);
//Checking min and max character conditions
if(count>=min_answers)
{
if(count>max_answers)
{
//Setting text
condition.setText("Selected answers exceeds maximum length");
//Setting text color
condition.setTextColor(Color.RED);
}
else
{
//Setting text
condition.setText("");
}
}
else
{
//Setting text
condition.setText("Please select more answers");
//Setting text color
condition.setTextColor(Color.RED);
}
}
}
});
}
//Closing cursor
checkcondition.close();
}
}
}

ASP.NET: How to persist Page State accross Pages?

I need a way to save and load the Page State in a persistent manner (Session). The Project i need this for is an Intranet Web Application which has several Configuration Pages and some of them need a Confirmation if they are about to be saved. The Confirmation Page has to be a seperate Page. The use of JavaScript is not possible due to limitations i am bound to. This is what i could come up with so far:
ConfirmationRequest:
[Serializable]
public class ConfirmationRequest
{
private Uri _url;
public Uri Url
{ get { return _url; } }
private byte[] _data;
public byte[] Data
{ get { return _data; } }
public ConfirmationRequest(Uri url, byte[] data)
{
_url = url;
_data = data;
}
}
ConfirmationResponse:
[Serializable]
public class ConfirmationResponse
{
private ConfirmationRequest _request;
public ConfirmationRequest Request
{ get { return _request; } }
private ConfirmationResult _result = ConfirmationResult.None;
public ConfirmationResult Result
{ get { return _result; } }
public ConfirmationResponse(ConfirmationRequest request, ConfirmationResult result)
{
_request = request;
_result = result;
}
}
public enum ConfirmationResult { Denied = -1, None = 0, Granted = 1 }
Confirmation.aspx:
protected void Page_Load(object sender, EventArgs e)
{
if (Request.UrlReferrer != null)
{
string key = "Confirmation:" + Request.UrlReferrer.PathAndQuery;
if (Session[key] != null)
{
ConfirmationRequest confirmationRequest = Session[key] as ConfirmationRequest;
if (confirmationRequest != null)
{
Session[key] = new ConfirmationResponse(confirmationRequest, ConfirmationResult.Granted);
Response.Redirect(confirmationRequest.Url.PathAndQuery, false);
}
}
}
}
PageToConfirm.aspx:
private bool _confirmationRequired = false;
protected void btnSave_Click(object sender, EventArgs e)
{
_confirmationRequired = true;
Response.Redirect("Confirmation.aspx", false);
}
protected override void SavePageStateToPersistenceMedium(object state)
{
if (_confirmationRequired)
{
using (MemoryStream stream = new MemoryStream())
{
LosFormatter formatter = new LosFormatter();
formatter.Serialize(stream, state);
stream.Flush();
Session["Confirmation:" + Request.UrlReferrer.PathAndQuery] = new ConfirmationRequest(Request.UrlReferrer, stream.ToArray());
}
}
base.SavePageStateToPersistenceMedium(state);
}
I can't seem to find a way to load the Page State after being redirected from the Confirmation.aspx to the PageToConfirm.aspx, can anyone help me out on this one?
If you mean view state, try using Server.Transfer instead of Response.Redirect.
If you set the preserveForm parameter
to true, the target page will be able
to access the view state of the
previous page by using the
PreviousPage property.
use this code this works fine form me
public class BasePage
{
protected override PageStatePersister PageStatePersister
{
get
{
return new SessionPageStatePersister(this);
}
}
protected void Page_PreRender(object sender, EventArgs e)
{
//Save the last search and if there is no new search parameter
//Load the old viewstate
try
{ //Define name of the pages for u wanted to maintain page state.
List<string> pageList = new List<string> { "Page1", "Page2"
};
bool IsPageAvailbleInList = false;
foreach (string page in pageList)
{
if (this.Title.Equals(page))
{
IsPageAvailbleInList = true;
break;
}
}
if (!IsPostBack && Session[this + "State"] != null)
{
if (IsPageAvailbleInList)
{
NameValueCollection formValues = (NameValueCollection)Session[this + "State"];
String[] keysArray = formValues.AllKeys;
if (keysArray.Length > 0)
{
for (int i = 0; i < keysArray.Length; i++)
{
Control currentControl = new Control();
currentControl = Page.FindControl(keysArray[i]);
if (currentControl != null)
{
if (currentControl.GetType() == typeof(System.Web.UI.WebControls.TextBox))
((TextBox)currentControl).Text = formValues[keysArray[i]];
else if (currentControl.GetType() == typeof(System.Web.UI.WebControls.DropDownList))
((DropDownList)currentControl).SelectedValue = formValues[keysArray[i]].Trim();
else if (currentControl.GetType() == typeof(System.Web.UI.WebControls.CheckBox))
{
if (formValues[keysArray[i]].Equals("on"))
((CheckBox)currentControl).Checked = true;
}
}
}
}
}
}
if (Page.IsPostBack && IsPageAvailbleInList)
{
Session[this + "State"] = Request.Form;
}
}
catch (Exception ex)
{
LogHelper.PrintError(string.Format("Error occured while loading {0}", this), ex);
Master.ShowMessageBox(enMessageType.Error, ErrorMessage.GENERIC_MESSAGE);
}
}
}

Resources