How to effectively handle session in asp.net - asp.net-3.5

I have one web site with multiple accounts like staff, end user and admin.
However I am creating each session while the user is logged into their account.
if (Page.IsValid)
{
string type_name="";
int returnValue = DatabaseHelper.GetLogin(txtusername.Text.Trim(), txtpassword.Text.Trim(), out type_name);
if (returnValue == 1)
{
if (chk_remember.Checked == true)
{
if (type_name.Trim()=="Admin")
{
Response.Cookies["UName"].Value = txtusername.Text;
Response.Cookies["PWD"].Value = txtpassword.Text;
Response.Cookies["UName"].Expires = DateTime.Now.AddMonths(2);
Response.Cookies["PWD"].Expires = DateTime.Now.AddMonths(2);
Session["username"] = txtusername.Text.Trim();
Response.Redirect("~/Admin/Admin_Landing_page.aspx");
}
else if (type_name.Trim()=="User")
{
Response.Cookies["UName"].Value = txtusername.Text;
Response.Cookies["PWD"].Value = txtpassword.Text;
Response.Cookies["UName"].Expires = DateTime.Now.AddMonths(2);
Response.Cookies["PWD"].Expires = DateTime.Now.AddMonths(2);
Session["username"] = txtusername.Text.Trim();
Response.Redirect("~/EndUser/myhome.aspx");
}
}
else
{
Response.Cookies["UName"].Expires = DateTime.Now.AddMonths(-1);
Response.Cookies["PWD"].Expires = DateTime.Now.AddMonths(-1);
if (type_name.Trim()== "Admin")
{
Session["username"] = txtusername.Text.Trim();
Response.Redirect("~/Admin/Admin_Landing_page.aspx");
}
else if (type_name.Trim()== "User")
{
Session["username"] = txtusername.Text.Trim();
Response.Redirect("~/EndUser/myhome.aspx");
}
}
}
else if (returnValue == -1)
{
ltr_error.Text = "Authentication failed..contact administrator";
}
else
{
ltr_error.Text = "Invalid username or password";
}
}
}
Here, sessions are created but how I handle them for long time as possible in ASP.NET timeout? Is that way to handle them with global.asax file?
Also, how do I redirect the user to login page if no session found in application?
-------------------------------------Updated----------------------------------------
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
public partial class WebUserControl : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected override void OnPreRender(EventArgs e)
{
if (Context.Session != null && Context.Session.IsNewSession)
{
if (this.Page.User != null && this.Page.User.Identity.IsAuthenticated)
{
FormsAuthentication.SignOut();
Response.Redirect("~/Default.aspx");
}
}
base.OnPreRender(e);
}
}

session by default lasts for 20 mins - depending on the setting in IIS and also the web.config.
if session is expires, the Session_End event in the global.asax gets fired. from there, you cannot exactly redirect and would not be the right place to redirect anyway.
you should create a user control for example, which is on every page or even better a master page from which all pages derive from, then you can check on every request if Session is empty. if so, redirect to the logon page.
I have done this many times and works a treat.
I have this on a prerender event in a user control:
if (Context.Session != null && Context.Session.IsNewSession)
{
if (this.Page.User != null && this.Page.User.Identity.IsAuthenticated)
{
FormsAuthentication.SignOut();
Response.Redirect("~/Login.aspx");
}
}

Related

Unity3D Webrequest SSL IOS CertificateHandler

Im trien to have a "Ignore all SSL Certificates" Checkbox for a Webrequest in Unity.
On Android it was working fine, but on IOS, I wasnt able to reset certhandler to default, it always returned true, once it was set. I tried dispose the handler by myself, set it to null and also I tried to clear cache.
Here is my code atm
using UnityEngine.Networking;
internal class AcceptAllCertificatesOrVerify : CertificateHandler
{
Main main = null;
protected override bool ValidateCertificate(byte[] certificateData)
{
if (main == null)
{
GameObject go = GameObject.Find("Main");
if (go != null)
{
main = go.GetComponent<Main>();
}
}
if (main != null && main.currentMandant != null && main.currentMandant.mandantIgnoreSSL)
{
main.ConsoleLog("ValidateCertificate: mandantIgnoreSSL");
return true;
}
else
{
if (main == null)
{
Debug.Log("ValidateCertificate: main null");
}
else
{
if (main.currentMandant == null)
{
main.ConsoleLog("ValidateCertificate: main.currentMandant null");
}
else
{
main.ConsoleLog("ValidateCertificate: main.currentMandant.mandantIgnoreSSL false");
}
}
}
main.ConsoleLog("Default ValidateCertificate");
return base.ValidateCertificate(certificateData);
}
}
it has some debugging activated, but when I check my adb log, I see only "ValidateCertificate: mandantIgnoreSSL". And never one of the other messages.
I also tried to set an remove certificateHandler dynamic like this:
{
webRequest.certificateHandler = new AcceptAllCertificatesOrVerify();
}
else
{
webRequest.certificateHandler = null;
}
But after AcceptAllCertificatesOrVerify was set once, I cant unset.
Is it a unity bug?

Can't login with facebook in Windows Phone App

It was working fine before but It's not working even though I haven't changed anything in my Facebook related code. It is giving this error:
App doesn't give permission to given URL : The settings of app doesn't allow one or more of the given URL's. URLs must be Website's URL or Canvas URL...
Here is my FacebookLoginPage.cs:
namespace MyApp.Pages
{
public partial class FacebookLoginPage : PhoneApplicationPage
{
private string message;
public FacebookLoginPage()
{
InitializeComponent();
message = String.Empty;
this.Loaded += FacebookLoginPage_Loaded;
}
protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
{
NavigationService.GoBack();
base.OnBackKeyPress(e);
}
private async void FacebookLoginPage_Loaded(object sender, RoutedEventArgs e)
{
if (String.IsNullOrEmpty(App.AccessToken))
{
App.isAuthenticated = true;
await Authenticate();
}
}
private FacebookSession session;
private async Task Authenticate()
{
//Facebook logini kontroli eğer login olduysa AccessToken ve bilgileri çeker.
try
{
if (App.FacebookSessionClient.LoginInProgress == true && !String.IsNullOrEmpty(message))
{
App.FacebookSessionClient.LoginInProgress = false;
}
else
{
session = await App.FacebookSessionClient.LoginAsync("user_about_me,read_stream");
App.AccessToken = session.AccessToken;
App.appSettings["accessToken"] = App.AccessToken;
App.appSettings.Save();
App.FacebookId = session.FacebookId;
Dispatcher.BeginInvoke(() => NavigationService.Navigate(new Uri("/Pages/MainPage.xaml?token=" + App.AccessToken, UriKind.Relative)));
}
}
catch (InvalidOperationException)
{
message = "failed";
App.FacebookSessionClient.LoginInProgress = true;
NavigationService.GoBack();
}
}
}
}
What might be the probelm?
When I added facebook.com to Oauth part of Advanced Setting in my Facebook App, the problem solved. Thanks to the following link: Windows Phone 8 Facebook Login Given URL is not allowed by the application

UCMA Generic QuestionAnswer activity

I am working on a UCMA 3.0 workflow application and am attempting to generate queries into our client management system allowing end users to obtain data about specific clients via voice or instant message. I was wondering anyone knows how to create a generic questionanswer activity using UCMA that allows generic input. I know that I can set up expected inputs and grammars, but with the bi-capitalization options, and the likelihood that an end user would know the exact client name (or client number for that matter), I would prefer to allow the user to enter part of the name and then search the database for a list of names that might meet the criteria. Does anyone know of a way, and have sample code that might allow me to do this if it is possible?
I had the same problem and had to write a custom activity to capture generic input from a user. This needs some work to make it production ready. Note the classy catching of system.exception in multiple places, as well as throwing an exception if input isn't received within the timeout period instead of reprompting the user. Also no regex on the user input...
The InstanceDependencyProperty is something else that was frustrating about Workflow. Without using InstanceDependencyProperties you won't be able to retrieve any results after the activity is completed.
Hope this helps!
using System;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Threading;
using System.Workflow.Activities;
using System.Workflow.Activities.Rules;
using System.Workflow.ComponentModel;
using System.Workflow.ComponentModel.Design;
using System.Workflow.ComponentModel.Compiler;
using System.Workflow.ComponentModel.Serialization;
using System.Workflow.Runtime;
using Microsoft.Rtc.Collaboration;
using Microsoft.Rtc.Workflow.Activities;
using Microsoft.Rtc.Workflow.Common;
namespace ActivityLibrary
{
public partial class CaptureIMInput : Activity, IInstanceDependencyContainer
{
#region Private member variables
private CallProvider _callProvider;
private Timer _maximumTimer;
private string _imText;
private bool messageReceived = false;
private bool _maximumTimerElapsed = false;
#endregion
public CaptureIMInput()
{
InitializeComponent();
_instanceDependencyProperties = new Dictionary<string, object>();
}
protected override ActivityExecutionStatus Execute(ActivityExecutionContext executionContext)
{
try
{
this._callProvider = Utilities.GetCallProviderFromParent<InstantMessagingCall>(this);
InstantMessagingCall call = (InstantMessagingCall)this._callProvider.Call;
try
{
if (call.State == CallState.Established)
{
call.Flow.EndSendInstantMessage(call.Flow.BeginSendInstantMessage(MainPrompt, null, null));
_maximumTimer = new Timer(new TimerCallback(OnMaximumTimerFired), null, MaximumPrompt, new TimeSpan(0, 0, 0, 0, -1));
call.Flow.MessageReceived += this.InstantMessagingFlow_MessageReceived;
while (!messageReceived)
{
if (_maximumTimerElapsed)
throw new TimeoutException("User input was not detected within alloted time");
}
if (!string.IsNullOrEmpty(_imText))
{
IMText = _imText;
{
this.Stop();
return ActivityExecutionStatus.Closed;
}
}
}
}
catch (Exception ex)
{
throw ex;
}
}
catch (Exception ex)
{
throw ex;
}
return ActivityExecutionStatus.Closed;
}
protected override ActivityExecutionStatus Cancel(ActivityExecutionContext executionContext)
{
this.Stop(); //Clean up timer
return ActivityExecutionStatus.Canceling;
}
private void Stop()
{
if (_maximumTimer != null)
{
_maximumTimer.Dispose();
_maximumTimer = null;
}
}
private void InstantMessagingFlow_MessageReceived(object sender, InstantMessageReceivedEventArgs e)
{
//Can't set dependencyproperties directly from sub-thread
_imText = e.TextBody;
//Mark bool so main while loop exits
messageReceived = true;
}
//Callback to
private void OnMaximumTimerFired(object state)
{
_maximumTimerElapsed = true;
}
#region InstanceDependency dictionary
private Dictionary<string, object> _instanceDependencyProperties;
[Browsable(false)]
public Dictionary<string, object> InstanceDependencyProperties
{
get { return _instanceDependencyProperties; }
}
#endregion
#region Maximum Prompt Timeout
[NonSerialized]
private static readonly InstanceDependencyProperty MaximumPromptProperty = InstanceDependencyProperty.Register("MaximumPrompt", typeof(TimeSpan), typeof(CaptureIMInput), new TimeSpan(0, 0, 30));
[TypeConverter(typeof(TimeSpanConverter))]
public TimeSpan MaximumPrompt
{
get
{
if (base.DesignMode)
return (TimeSpan)InstanceDependencyHelper.GetValue<CaptureIMInput>(this, MaximumPromptProperty);
else
return (TimeSpan)InstanceDependencyHelper.GetValue<CaptureIMInput>(this, this.WorkflowInstanceId, MaximumPromptProperty);
}
set
{
if (base.DesignMode)
InstanceDependencyHelper.SetValue<CaptureIMInput>(this, MaximumPromptProperty, value);
else
InstanceDependencyHelper.SetValue<CaptureIMInput>(this, this.WorkflowInstanceId, MaximumPromptProperty, value);
}
}
#endregion
#region MainPrompt
public static DependencyProperty MainPromptProperty =
DependencyProperty.Register("MainPrompt", typeof(string), typeof(CaptureIMInput));
[ValidationOption(ValidationOption.Required)]
public string MainPrompt
{
get
{
return (string)base.GetValue(MainPromptProperty);
}
set
{
base.SetValue(MainPromptProperty, value);
}
}
#endregion
#region Instant Message Text
public static InstanceDependencyProperty IMTextProperty =
InstanceDependencyProperty.Register("IMText",
typeof(string),
typeof(CaptureIMInput));
[Description("InstantMessaging Text from user")]
[Browsable(true)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
public string IMText
{
get
{
if (base.DesignMode) return ((string)InstanceDependencyHelper.GetValue<CaptureIMInput>(this, CaptureIMInput.IMTextProperty));
else return ((string)(InstanceDependencyHelper.GetValue<CaptureIMInput>(this, this.WorkflowInstanceId, CaptureIMInput.IMTextProperty)));
}
set
{
if (base.DesignMode) InstanceDependencyHelper.SetValue<CaptureIMInput>(this, CaptureIMInput.IMTextProperty, value);
else InstanceDependencyHelper.SetValue<CaptureIMInput>(this, this.WorkflowInstanceId, CaptureIMInput.IMTextProperty, value);
}
}
#endregion
}
}

Prevent sending email and show message via plug-in

I am writing crm2011 plugin in "Email" entity with "Send" Message of Pre_operation. What i want to do is when i click "Send" button in email entity, I do the necessary checking before send. If the checking is not correct, I want to prevent and stop the sending email and show "the alert message" and stop the second plugin(this plugin send email and create the associated entity to convert "Case"). Please give me some suggestion for that plugin?
Should i use pre-Validation stage or Pre_operation state? And how can I return false to stop plugin.
public void Execute(IServiceProvider serviceProvider)
{
try
{
string message = null;
_serviceProvider = serviceProvider;
_context = (IPluginExecutionContext)
serviceProvider.GetService(typeof(IPluginExecutionContext));
_serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
_currentUser = _context.UserId;
message = _context.MessageName.ToLower();
if (message == "send")
{
if (_context.InputParameters != null && _context.InputParameters.Contains("EmailId"))
{
object objEmailId = _context.InputParameters["EmailId"];
if (objEmailId != null)
{
_emailId = new Guid(objEmailId.ToString());
FindEmailInfo();
if (_email != null)
{
if (_email.Attributes.Contains("description") && _email.Attributes["description"] != null)//Email descritpion is not null
{
string emaildescription = StripHTML();
//Find KB Article prefix no in system config entity
serviceguideprefix = "ServiceGuidesPrefix";
QueryByAttribute query = new QueryByAttribute("ppp_systemconfig");
query.ColumnSet = new ColumnSet(true);
query.AddAttributeValue(sysconfig_name, serviceguideprefix);
EntityCollection sysconfig = _service.RetrieveMultiple(query);
if (sysconfig.Entities.Count > 0)
{
Entity e = sysconfig.Entities[0];
if (e.Attributes.Contains("ppp_value"))
{
ppp_value = e.Attributes["ppp_value"].ToString();
}
}
if (ppp_value != null && ppp_value != string.Empty)
{
//var matches = Regex.Matches(emaildescription, #"KBA-\d*-\w*").Cast<Match>().ToArray();
var matches = Regex.Matches(emaildescription, ppp_value + #"-\d*-\w*").Cast<Match>().ToArray();
//ReadKBNo(emaildescription);
foreach (Match kbnumber in matches)
{
EntityCollection kbarticlecol = FindKBArticleIds(kbnumber.ToString());
if (kbarticlecol.Entities.Count > 0)
{
Entity kbariticle = kbarticlecol.Entities[0];
if (kbariticle.Attributes.Contains("mom_internalkm"))
{
bool internalserviceguide = (bool)kbariticle.Attributes["mom_internalkm"];
if (internalserviceguide) found = true;
else found = false;
}
else found = false;
}
}
}
if (found)
{
//-----
}
}
}
}
}
}
}
catch (Exception ex)
{
throw new InvalidPluginExecutionException(ex.Message, ex);
}
}
Well stopping the plugin is dead easy you just throw InvalidPluginException, the message you give it will be shown to the user in a alert window. You will have to do this on the pre of the send. In this case I don't think it will matter if its pre-validation or pre-operation.
Edit:
Yes, you should throw an InvalidPluginException even if no exception has happened in code. I accept this isnt what we would normally do, but its the way its meant to work. Msdn has more details: http://msdn.microsoft.com/en-us/library/gg334685.aspx
So for example the code would look like:
public void Execute(IServiceProvider serviceProvider)
{
try
{
//This is where we validate the email send
if(emailIsOkay)
{
//Do something
}
else if(emailIsNotOkay)
{
//Throw and exception that will stop the plugin and the message will be shown to the user (if its synchronous)
throw new InvalidPluginExecutionException("Hello user, your email is not correct!!");
}
}
catch (InvalidPluginExecutionException invalid)
{
//We dont to catch exception for InvalidPluginExecution, so just throw them on
throw;
}
catch (Exception ex)
{
//This exception catches if something goes wrong in the code, or some other process.
throw new InvalidPluginExecutionException(ex.Message, ex);
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Crm;
using Microsoft.Xrm.Sdk;
using System.ServiceModel;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Crm.Sdk.Messages;
using System.Text.RegularExpressions;
using System.Xml.Linq;
namespace SendEmail
{
public class Email : IPlugin
{
public void Execute(IServiceProvider serviceprovider)
{
IPluginExecutionContext context = (IPluginExecutionContext)serviceprovider.GetService(typeof(IPluginExecutionContext));
if (!(context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity))
return;
//entity
Entity ent = (Entity)context.InputParameters["Target"];
if (ent.LogicalName != "entityName")//EntityName
throw new InvalidPluginExecutionException("Not a Service Request record! ");
//service
IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceprovider.GetService(typeof(IOrganizationServiceFactory));
IOrganizationService _service = serviceFactory.CreateOrganizationService(context.UserId);
string Email="";
if (ent.Contains("emailidfiled"))
Email = (string)ent["emailidfiled"];
#region email template
QueryExpression query = new QueryExpression()
{
EntityName = "template",
Criteria = new FilterExpression(LogicalOperator.And),
ColumnSet = new ColumnSet(true)
};
query.Criteria.AddCondition("title", ConditionOperator.Equal, "templateName");
EntityCollection _coll = _service.RetrieveMultiple(query);
if (_coll.Entities.Count == 0)
throw new InvalidPluginExecutionException("Unable to find the template!");
if (_coll.Entities.Count > 1)
throw new InvalidPluginExecutionException("More than one template found!");
var subjectTemplate = "";
if (_coll[0].Contains("subject"))
{
subjectTemplate = GetDataFromXml(_coll[0]["subject"].ToString(), "match");
}
var bodyTemplate = "";
if (_coll[0].Contains("body"))
{
bodyTemplate = GetDataFromXml(_coll[0]["body"].ToString(), "match");
}
#endregion
#region email prep
Entity email = new Entity("email");
Entity entTo = new Entity("activityparty");
entTo["addressused"] =Email;
Entity entFrom = new Entity("activityparty");
entFrom["partyid"] = "admin#admin.com";
email["to"] = new Entity[] { entTo };
email["from"] = new Entity[] { entFrom };
email["regardingobjectid"] = new EntityReference(ent.LogicalName, ent.Id);
email["subject"] = subjectTemplate;
email["description"] = bodyTemplate;
#endregion
#region email creation & sending
try
{
var emailid = _service.Create(email);
SendEmailRequest req = new SendEmailRequest();
req.EmailId = emailid;
req.IssueSend = true;
GetTrackingTokenEmailRequest wod_GetTrackingTokenEmailRequest = new GetTrackingTokenEmailRequest();
GetTrackingTokenEmailResponse wod_GetTrackingTokenEmailResponse = (GetTrackingTokenEmailResponse)
_service.Execute(wod_GetTrackingTokenEmailRequest);
req.TrackingToken = wod_GetTrackingTokenEmailResponse.TrackingToken;
_service.Execute(req);
}
catch (Exception ex)
{
throw new InvalidPluginExecutionException("Email can't be saved / sent." + Environment.NewLine + "Details: " + ex.Message);
}
#endregion
}
private static string GetDataFromXml(string value, string attributeName)
{
if (string.IsNullOrEmpty(value))
{
return string.Empty;
}
XDocument document = XDocument.Parse(value);
// get the Element with the attribute name specified
XElement element = document.Descendants().Where(ele => ele.Attributes().Any(attr => attr.Name == attributeName)).FirstOrDefault();
return element == null ? string.Empty : element.Value;
}
}
}

Facebook Integration Session Issue

Here is my UserLogin.aspx Page code, which contains authentication of Facebook user, the problem is i am maintaing token in session which i laterly use it on Default.aspx. if you see the line Session["facebook_token"] = authToken;
On my Default.aspx page load i have placed this code, but it gives me null value, when i go to home or default page.
if (Session["facebook_token"] != null)
lblUserName.Text = Session["facebook_token"].ToString();
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SocialMediaModel;
using Facebook.Components;
public partial class UserLogin : System.Web.UI.Page
{
FacebookService _fbService = new FacebookService();
private const string FACEBOOK_API_KEY = "551810942508804";
private const string FACEBOOK_SECRET = "b63b8cca428b42935e6eab59976367b1";
protected void Page_Load(object sender, EventArgs e)
{
// ApplicationKey and Secret are acquired when you sign up for
_fbService.ApplicationKey = FACEBOOK_API_KEY;
_fbService.Secret = FACEBOOK_SECRET;
_fbService.IsDesktopApplication = false;
string sessionKey = Session["facebook_session_key"] as String;
string userId = Session["facebook_userId"] as String;
string authToken = Request.QueryString["auth_token"];
Session["facebook_token"] = authToken;
// We have already established a session on behalf of this user
if (!String.IsNullOrEmpty(sessionKey))
{
_fbService.SessionKey = sessionKey;
_fbService.UserId = userId;
}
// This will be executed when facebook login redirects to our page
else if (!String.IsNullOrEmpty(authToken))
{
_fbService.CreateSession(authToken);
Session["facebook_session_key"] = _fbService.SessionKey;
Session["facebook_userId"] = _fbService.UserId;
Session["facebook_session_expires"] = _fbService.SessionExpires;
}
// Need to login
else
{
Response.Redirect(#"http://www.facebook.com/login.php?api_key=" +
_fbService.ApplicationKey + #"&v=1.0");
}
}
}
string authToken = Request.QueryString["auth_token"];
Session["facebook_token"] = authToken;
Looks like you are executing these lines on every page load(?) – without checking if there even is a GET parameter by this name.