Access Session In Global.asax Methods in MVC3 Environment [duplicate] - asp.net-mvc-3

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Why HttpContext.Current.Session is null in Global.asax?
I am developing a MVC3 project (Razor).
I added a variable to my session in some Controller/Action (different per user).
I want to access this variable in Application_AuthenticateRequest method (global.asax).
This exception happened:
Session state is not available in this context.
Sample Project

For startes, see https://stackoverflow.com/a/4185982/717732
The whole point is that Session is not available and simply will never be available at this point of time: and by 'time' I mean 'when this event is fired'.
Read the lifecycle for example at devproconnections.com/article/aspnet2/
The Session object is prepared much later: during the AcquireRequestState event. This is the first 'time' when you can access the Session statebag and investigate it.

Thanks quetzalcoatl,
This is true.
try
{
if (Session != null)
{
if (Session["mys"] != null)
{
//Error
string s = HttpContext.Current.Session["mys"].ToString();
}
else
{
Response.Redirect("~/Home/Index");
Response.End();
}
}
}
catch {
Response.Redirect("~/Home/Index");
Response.End();
}

Related

Avoiding If statement to check if object is Null [duplicate]

This question already has answers here:
Avoiding NullPointerException in Java
(66 answers)
Closed 3 years ago.
I'm using Lombok S1F4j to log my data and In order to avoid logging empty data , I check if the object is null or not . I want avoid this guys so my code is more robuste and so easy to test .
This is an example :
if (object != null)
{
log.info("lalalalal", object)
object1.set(object) }
Is there anyway to avoid checking null and not logging if object is null ?
You can create a wrapper function something like:
public static void log_info(Logger logger, Object obj) {
if (obj != null) {
logger.info(obj);
}
}
And, use this wrapper method in place of logging methods.
you can add a question mark before calling any functions or data fields of an object. That will only call the function if the object is not null
object?.function()

Can't create handler inside thread which has not called Looper.prepare() [xamarin]

So i don't actually have a question because i've already solved it, but in case someone else runs into this issue it's always nice to have a neat solution.
And while there is a plentitude of "Can't create handler inside thread which has not called Looper.prepare()" - questions there is none tagged with xamarin. (so theirs is all java and i had 0 matches for "Can't create handler inside thread which has not called Looper.prepare() [xamarin]")
The issue is generated because You tried to do work on UI from other thread. If you want to change UI, Must call UI changes from UI thread.
Xamarin Android:
activity.RunOnUiThread(() =>
{
// Write your code here
});
Xamarin IOS:
nsObject.BeginInvokeOnMainThread(() =>
{
// Write your code here
});
Xamarin Forms:
Device.BeginInvokeOnMainThread(() =>
{
// Write your code here
});
public static class PageExtensions
{
public static Task<bool> DisplayAlertOnUi(this Page source, string title, string message, string accept, string cancel)
{
TaskCompletionSource<bool> doneSource = new TaskCompletionSource<bool>();
Device.BeginInvokeOnMainThread(async () =>
{
try
{
var result = await source.DisplayAlert(title, message, accept, cancel);
doneSource.SetResult(result);
}
catch (Exception ex)
{
doneSource.SetException(ex);
}
});
return doneSource.Task;
}
}
Finally i had a case for using TaskCompletionSource to solve an issue.
Very similar actually happend to me. Previous evening I was developing and testing my app. Next morning, from other computer I got the exception you described. I was remembered from a official Xamarin.Forms documentation that sometimes a bin and obj folder removal solves lot of issues.
I did exactly the same, removed my bin and obj folder from my shared Xamarin.Forms library and also from Xamarin.Android library.
The strange exception disappeared.

ViewModels and IsolatedStorageSettings

Im working on a MVVM Windows phone app that displays weather info.
When the app loads up it opens MainPage.xaml. It makes a call the the service to get weather info and binds that data to the UI. Both Fahrenheit and Celcius info are returned but only one is displayed.
On the setting page, the user can select to view the temp in either Fahrenheit or Celcius.
The user can change this setting at any time and its stored in IsolatedStorageSettings.
The issue Im having is this:
when the user navigates to the Settings page and changes their preference for either Fahrenheit or Celcius, this change is not reflected on the main page.
This issue started me thinking about this in a broader context. I can see this being an issue in ANY MVVM app where the display depends on some setting in IsolatedStorage. Any time any setting in the IsoStore is updated, how does the ViewModels know this? When I navigate back in the NavigationStack from the settings page back to MainPage how can I force a rebind of the page?
The data in my model hasnt changed, only the data that I want to display has changed.
Am I missing something simple here?
Thanks in advance.
Alex
Probably you have code like this:
public double DisplayTemperature
{
get { return (IsCelsium) ? Celsium : Fahrenheit; }
}
And IsCelsium is:
public double IsCelsium
{
get { return (bool)settings["IsCelsium"]; }
set { settings["IsCelsium"] = value; }
}
So you need to add NotifyPropertyChanged event to notify UI to get new values from DisplayTemperature property:
public double IsCelsium
{
get { return (bool)settings["IsCelsium"]; }
set
{
settings["IsCelsium"] = value;
NotifyPropertyChanged("DisplayTemperature");
}
}
Take a look at Caliburn Micro. You could implement something similar or use CM itself. When using CM I don't even think about this stuff, CM makes it so simple.
When your ViewModel inherits from Screen there are life-cycle events that fire that you can override. For example, OnInitialize fires the very first time the ViewModel is Activated and OnActivate fires every time the VM is activated. There's also OnViewAttached and OnViewLoaded.
These methods are the perfect place to put logic to populate or re-populate data.
CM also has some special built in features for allowing one to easily tombstone a single property or an entire object graph into Iso or phone state.
ok, so Ive come up with a solution. Before I get to it, let me provide some background. The app that Im working on uses both MVVM Light and WP7Contrib. That being the case, I am using Funq for DI and the MVVMLight Toolkit. After I posted my initial question, I gave the question a bit more thought. I remembered a video that I watched a while back from MIX2011 called Deep Dive MVVM with Laurent Bugnion
http://channel9.msdn.com/Events/MIX/MIX11/OPN03
In it, he talks about just this problem (view models not living at the same time) on Windows Phone. The part in question starts around the 19 minute mark.
Anyway, after I remembered that and realized that the ViewModel locator is exposed in App.xaml, this became a trivial problem to solve. When the user changes the Fahrenheit/Celcius option on the setting page, I simply get a reference to the MainViewModel via the ViewModelLocator and reset the collection that is bound to the UI thus causing the bindings to update.
public bool AddOrUpdateValue(string Key, Object value)
{
bool valueChanged = false;
// If the key exists
if (settings.Contains(Key))
{
// If the value has changed
if (settings[Key] != value)
{
// Store the new value
settings[Key] = value;
valueChanged = true;
}
}
// Otherwise create the key.
else
{
settings.Add(Key, value);
valueChanged = true;
}
return valueChanged;
}
public bool ImperialSetting
{
get
{
return GetValueOrDefault<bool>(ImperialSettingKeyName, ImperialSettingDefault);
}
set
{
if (AddOrUpdateValue(ImperialSettingKeyName, value))
{
Save();
RaisePropertyChanged("ImperialSettingText");
var vml = new ViewModelLocator();
vml.MainViewModel.Cities = (App.Current as App).Cities;
}
}
}
It was a mistake on my part not to realize that I could get access to the viewModel via the ViewModelLocator. Hopefully this post saves someone else the time I burned on this issue.

Spring Portal MVC Clear Action Exception going to Render Phase

I would like to know whether or not it is possible to clear an exception out of the request when trying to hit the Render Phase after the Action Phase has thrown the exception.
If you look at this code snippet from the doRenderService method of DispatchPortlet.class (a Spring provided class):
PortletSession session = request.getPortletSession(false);
if (session != null) {
if (request.getParameter(ACTION_EXCEPTION_RENDER_PARAMETER) != null) {
Exception ex = (Exception)
session.getAttribute(ACTION_EXCEPTION_SESSION_ATTRIBUTE);
if (ex != null) {
logger.debug("Render phase found exception caught during action phase - rethrowing it");
throw ex;
}
}
else {
session.removeAttribute(ACTION_EXCEPTION_SESSION_ATTRIBUTE);
}
}
You can see here that an exception gets put into the parameter map and there doesn't seem to be any way to clear it out.
What I would like to do is originally catch the Exception (what I am successfully doing), display an "Error Page" (what I am successfully doing), then display a button on that Error Page that allows the user to bring up the "Render Phase" page again so that he/she may be able to try their Action, again.
I've tried to create a filter, interceptor, new controller to clear the parameter, but it seems that the ParameterMap is an UnmodifiableCollection.
Any thoughts?
I actually was able to figure this out by doing the following in a render-phase filter:
session.setAttribute(ACTION_EXCEPTION_SESSION_ATTRIBUTE, null)
You can configure your org.springframework.web.portlet.DispatcherPortlet with setForwardActionException(false). This prevents spring from adding the Exception details in render parameters, or session.

Entlib Cache.Contains NULL problem

I have a combined authorization and menustructure system on our backend.
For performance reasons EntLib caching is used in the frontend client (MVC rel 1.0 website, IIS 5.1 local, IIS 6.0 server, no cluster).
Sometimes 'Cache.Contains' will return true, but the contents of the cache is NULL. I know for certain that I filled it correctly, so what can be the problem here?
EDIT: when I set the cache to 1 minute and add the cacheKey 'A_Key', I will see the key coming back when inspecting the CurrentCacheState. When I view CurrentCacheState after 2 minutes, the key is still there. When I execute 'contains', true is returned. When I execute 'contains' again, the cacheKey is gone!
Synchronization problem??
Regards,
Michel
Excerpt:
if (IntranetCaching.Cache.Contains(cacheKey))
{
menuItems = (List<BoMenuItem>)IntranetCaching.Cache[cacheKey];
}
else
{
using (AuthorizationServiceProxyHelper authorizationServiceProxyHelper = new AuthorizationServiceProxyHelper())
{
menuItems = authorizationServiceProxyHelper.Proxy.SelectMenuByUserAndApplication(APPNAME, userName, AuthorizationType.ENUM_LOGIN);
IntranetCaching.Add(cacheKey, menuItems);
}
}
And the cachehelper:
public static class IntranetCaching
{
public static ICacheManager Cache { get; private set; }
static IntranetCaching()
{
Cache = CacheFactory.GetCacheManager();
}
public static void Add(string key, object value)
{
Cache.Add(
key
, value
, CacheItemPriority.Normal
, null
, new Microsoft.Practices.EnterpriseLibrary.Caching.Expirations.AbsoluteTime(TimeSpan.FromMinutes(10)));
}
}
Thanks Michael for following up your own issue, I have been stuck with this all day identifying that if I try and retrieve an item from Cache this is due to expire (+ 0 up to 25 seconds) I will get a NULL value. Codeplex have posted a workaround (of sorts)as it is in their FAQ:
a. How do I avoid getting a null value from the CacheManager when the item is being refreshed? - Intermittently, you may encounter this situation. To work around this, create your own implementation of an ICacheItemExpiration. In the HasExpired()method, implement a logic that will check whether the item has already expired and will update the item's value if it has expired. This method should always return false for the item to not be tagged as expired. As a result of returning false in the HasExpired() method, the item will not be refreshed and will contain the updated value as implemented in the method.
REF: link
I got the following response from Avanade (creators of Entlib):
Most likely, the BackgroundScheduler
hasn't performed its sweeping yet. If
you're going to examine the source
code, the Contains method only checks
if the specific key is present in the
inmemory cache hashtable while on the
GetData method, the code first checks
if the item has expired, if it has,
the item is removed from the cache.
Sarah Urmeneta Global Technology &
Solutions Avanade, Inc.
entlib.support#avanade.com
That solution is working for me.
Still the question remains why you can use 'Contains' when its outcome cannot be used in a sensible way.
Regards,
M.

Resources