I am trying to clear a HttpContext.Current.Session after User logs out of a Sitefinity page.
I saw in this link that you can check the Request.Url but I'm not exactly sure what the implementation is.
This is my current attempt:
protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
if (((System.Web.HttpApplication)(sender)).Request.Url.ToString() == HttpContext.Current.Server.MapPath("~/Sitefinity/Login/DoLogout"))
{
if (HttpContext.Current.Session["Cart"] != null) HttpContext.Current.Session.Remove("Cart");
HttpContext.Current.Session["Cart"] = new List<IQuoteResult>();
}
}
Please let me know if you have any tips or suggestions, or if I'm completely wrong with my logic.
Thanks in advance.
UPDATE:
protected void Application_PostAcquireRequestState(object sender, EventArgs e)
{
if (((HttpApplication)(sender)).Request.Url.ToString().Contains("sign_out=true"))
{
if (HttpContext.Current.Session["Cart"] != null)
{
HttpContext.Current.Session.Remove("Cart");
HttpContext.Current.Session["Cart"] = new List<IQuoteResult>();
}
}
}
This is my next attempt at completing the same task but I keep receiving a NullReferenceException...
Note: I've also tried this method in the Application_AcquireRequestState method.
Here is the stack:
[NullReferenceException: Object reference not set to an instance of an object.]
SitefinityWebApp.Global1.Application_PostAcquireRequestState(Object sender, EventArgs e) +137
System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +91
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +164
This ended up being my solution:
public bool IsUserLoggingOut { get; set; }
protected void Application_PostAcquireRequestState(object sender, EventArgs e)
{
if (((HttpApplication)(sender)).Request.Url.ToString().Contains("/Sitefinity/SignOut"))
{
IsUserLoggingOut = true;
}
if (IsUserLoggingOut && SystemManager.CurrentHttpContext.Session != null)
{
SystemManager.CurrentHttpContext.Session.Remove("Quote");
IsUserLoggingOut = false;
}
}
Looks like Sitefinity has its own SystemManager to access the http context. It worked perfectly.
That's pretty close to how I would do it. The only change I would make is change your url comparison logic to be something like:
if (((System.Web.HttpApplication)(sender)).Request.Url.ToString().EndsWith("/Sitefinity/Login/DoLogout"))
Or potentially use .Contains() instead of EndsWith() -- not sure if there are any query-string parameters or trailing slashes added on the DoLogout action.
This is because Request.Url returns a URL (ex. https://stackoverflow.com/whatever) whereas Server.MapPath() returns a local path (ex. C:\inetpub\wwwroot\whatever), so you wouldn't be comparing apples to apples if you're comparing the two.
Edit:
Something like this should work, just adding a check to see if the session is null
protected void Application_PostAcquireRequestState(object sender, EventArgs e)
{
if (((HttpApplication)(sender)).Request.Url.ToString().Contains("sign_out=true"))
{
if (HttpContext.Current.Session != null && HttpContext.Current.Session["Cart"] != null)
{
HttpContext.Current.Session.Remove("Cart");
HttpContext.Current.Session["Cart"] = new List<IQuoteResult>();
}
}
}
Related
I'm trying to remove a node from an xml file, everything works, but sometimes it happens that the xml web page does not load. this is my code:
private void HttpsCompleted(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error == null)
{
XDocument xdoc = XDocument.Parse(e.Result, LoadOptions.None);
if (e.Error == null)
{
XDocument doc = XDocument.Parse(e.Result, LoadOptions.None);
var lyric = doc.Descendants(XName.Get("Lyric", "http://api.chartlyrics.com/")).FirstOrDefault();
TextBlock1.Text = lyric.Value;
}
}
}
private void btnLoad_Click(object sender, RoutedEventArgs e)
{
WebClient wc = new WebClient();
wc.DownloadStringCompleted += HttpsCompleted;
wc.DownloadStringAsync(new Uri("http://api.chartlyrics.com/apiv1.asmx/SearchLyricDirect?artist=michael%20jackson&song=bad));
}
I' ve read to use the WebException to handle this "mistake" but I am not able to use it. can someone give me some help?
Have you tried this way?
private void btnLoad_Click(object sender, RoutedEventArgs e)
{
try
{
WebClient wc = new WebClient();
wc.DownloadStringCompleted += HttpsCompleted;
wc.DownloadStringAsync(new Uri("http://api.chartlyrics.com/apiv1.asmx/SearchLyricDirect?artist=michael%20jackson&song=bad"));
}
catch (WebException ex)
{
// Check the exception here
}
}
And check for error in the handler too:
private void HttpsCompleted(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error == null)
{
XDocument xdoc = XDocument.Parse(e.Result, LoadOptions.None);
if (e.Error == null)
{
XDocument doc = XDocument.Parse(e.Result, LoadOptions.None);
var lyric = doc.Descendants(XName.Get("Lyric", "http://api.chartlyrics.com/")).FirstOrDefault();
TextBlock1.Text = lyric.Value;
}
}
else
{
// Check for error here
}
}
I realized it sometimes return Error, and I think the problem is in the server, because if I access it from the web browser, I sometimes get the result, but many times I get an error.
Dont know what to do.
I have all the data i need but dont know how to use it right.
I have started to add a "Service Reference". I added the URL wich is this one: transpawebserviceslive/gateway.asmx
So what i have done now is this. For my click event on my button to verify that the password and username is correct i have done the following and i dont know if i am doing it right here:
private void Button_Click_1(object sender, RoutedEventArgs e)
{
ServiceReference.GatewaySoapClient client = new ServiceReference.GatewaySoapClient();
client.AuthenticateAsync(username.Text,password.Text,sign.Text,password.Text);
client.AuthenticateCompleted += client_AuthenticateCompleted;
}
void client_AuthenticateCompleted(object sender, ServiceReference.AuthenticateCompletedEventArgs e)
{
ServiceReference.AuthenticatedDto test = new ServiceReference.AuthenticatedDto();
if (kund.Text == test.CustomerUser)
{
MessageBoxResult m = MessageBox.Show("Ok", "Ok", MessageBoxButton.OK);
}
else
{
MessageBoxResult m = MessageBox.Show("Wrong", "W", MessageBoxButton.OK);
}
Dont know what i am doing here, whould be nice with some help.
All that you did there is correct. You just have to parse the response and proceed.
void client_AuthenticateCompleted(object sender, ServiceReference.AuthenticateCompletedEventArgs e)
{
if (e.Error == null) //To ensure there is no error in the request
{
if (e.Result.Contains("ERROR"))
MessageBox.Show("Authentication failed", "Ok", MessageBoxButton.OK);
else
MessageBox.Show("Authenticaion success", "Ok", MessageBoxButton.OK);
}
}
public IsolatedStorageSettings appSettings =
IsolatedStorageSettings.ApplicationSettings;
public Settings()
{
InitializeComponent();
this.toggle.Checked += new EventHandler<RoutedEventArgs>(toggle_Checked);
this.toggle.Unchecked += new EventHandler<RoutedEventArgs>(toggle_Unchecked);
this.toggle.Click += new EventHandler<RoutedEventArgs>(toggle_Click);
this.toggle.Indeterminate += new EventHandler<RoutedEventArgs>(toggle_Indeterminate);
`}`
void toggle_Unchecked(object sender, RoutedEventArgs e)
{
this.toggle.Content = "Visibity is off";
this.toggle.SwitchForeground = new SolidColorBrush(Colors.Red);
appSettings.Add("value", "off");
}
void toggle_Checked(object sender, RoutedEventArgs e)
{
this.toggle.Content = "Visibity is on";
this.toggle.SwitchForeground = new SolidColorBrush(Colors.Green);
appSettings.Add("value", "on");
}
void toggle_Indeterminate(object sender, RoutedEventArgs e)
{
//add some content here
}
void toggle_Click(object sender, RoutedEventArgs e)
{
//add some content here
}
by default calling checked method.If a user unchcked the button then again an user logged in app need to show the unchcked because the user previously unchcked the btn.but it's show checked.for that i am saving one value in isolated storage.
can you please tell me where to access the isolated varieable value ?
You can access the isolatedstorage value in any page, in the same way as you created it.
Try to access the value in Settings() constructor after the InitializeComponent();
public Settings()
{
InitializeComponent();
string value;
if (appSettings.Contains("value"))
{
appSettings.TryGetValue("value", out value);
}
and then you can change the value of toggle button based on the 'value'.
It seems that you are not calling the Save method on the ApplicationSettings object.
Please read this guide on how you should work with isolated storage.
To save a setting:
IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;
if (!settings.Contains("userData"))
{
settings.Add("userData", "some value");
}
else
{
settings["userData"] = "some value";
}
settings.Save();
To retrieve a setting:
if (IsolatedStorageSettings.ApplicationSettings.Contains("userData"))
{
string result IsolatedStorageSettings.ApplicationSettings["userData"] as string;
}
So in your case, save the state of the CheckBox in the Checked & UnChecked event, and load the state in the init of the page.
I have made and rss reader and have a listbox with all the feeds in it. When I select one item and want to see the whole article I only get the selectedindex number, 0,1,2 and so on.
Here is my code:
private void feedListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
ListBox listBox = sender as ListBox;
if (listBox != null && listBox.SelectedItem != null)
{
NavigationService.Navigate(new Uri("/DetailsPage.xaml?feeditem=" + listBox.SelectedIndex, UriKind.Relative));
}
}
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
base.OnNavigatedTo(e);
string feeditem = "";
if (NavigationContext.QueryString.TryGetValue("feeditem", out feeditem))
{
this.textBlock1.Text = feeditem;
}
}
What am I missing here?
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
lblPostBack.Text = " Text created first time";
}
else
{
if (Session["Counter"] == null)
{
lblPostBack.Text = "PostBack x however strange becasue if is postback it's mean somebody clicked button and session value has been created";
}
else
{
lblPostBack.Text = "PostBack x should be count here";
}
}
}
protected void cmd_Click(object sender, EventArgs e)
{
int _counter;
if (Session["Counter"] == null)
{
_counter = 1;
}
else
{
_counter = (int)Session["Counter"] + 1;
}
Session["Counter"] = _counter;
lblPostBack.Text += "Counter: " + _counter.ToString();
}
Assuming this is ASP.NET: It's because the Click event on your button fires after the Load event on your page, so the session has not been set.
MSDN on the page lifecycle might be good reading - the button click is a "postback event" in the table in that document.
If I've got the wrong end of the stick, please explain what messages you get after the button clicks, and what you were expecting. Some framework and language tags on the question might not go amiss, either.
Ok it works, just FF mess up
I have added following method and works fine.
private int _counter;
protected void Page_Load(object sender, EventArgs e)
{
(...)
protected void Page_PreRender(Object sender, EventArgs e)
{
Session["Counter"] = _counter;
}