session abandon is not working in ASP.NET - c#

I have developed a web site and I store data in session.If a user abondan the session,I have to set the data in session.
Logout.aspx :
protected void Page_Load(object sender, EventArgs e)
{
try
{
WebUser user = (WebUser)Session["User"];
Session["User"] = null;
Session.Abandon();
if (user != null)
SentiWordnetUtils.LogYaz(user.uAdi + "\t Çıkış Yaptı");
if ((Request.Cookies["OturumRef"] != null))
Response.Cookies["OturumRef"].Value = string.Empty;
Response.Redirect("Login.aspx");
}
catch (Exception ex)
{
LogYaz( "Oturum Sonlandırma Hatası "+ex.Message.ToString());
}
}
session_end function in global.asax :
void Session_End(object sender, EventArgs e)
{
List<TBL_SentiWordNet> tempList = (List<TBL_SentiWordNet>)Session["listProcess"];
if (tempList == null)
return;
using (DataClassesDataContext dc = new DataClassesDataContext())
{
foreach (TBL_SentiWordNet word in tempList)
{
var a = (from i in dc.TBL_SentiWordNets where i.id == word.id select i).FirstOrDefault();
a.state = 0;
}
dc.SubmitChanges();
}
Session["listProcess"]= null;
Session["User"] = null;
}
This code is working on local but isn't working on IIS. a.state never isn't 0
web.config:
<?xml version="1.0" encoding="UTF-8"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=169433
-->
<configuration>
<system.web>
<sessionState mode="InProc" timeout="30" />
<compilation debug="true" targetFramework="4.0">
<assemblies>
<add assembly="System.Transactions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" />
<add assembly="System.Data.Linq, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" />
</assemblies>
</compilation>
</system.web>
<connectionStrings>
<add name="myconnectionstring" connectionString="Data Source=127.0.0.1;Initial Catalog=mydb;Persist Security Info=True;User ID=userID;Password=password" providerName="System.Data.SqlClient" />
</connectionStrings>
<system.webServer>
<defaultDocument>
<files>
<clear />
<add value="default.aspx" />
<add value="Default.htm" />
<add value="Default.asp" />
<add value="index.htm" />
<add value="index.html" />
<add value="iisstart.htm" />
</files>
</defaultDocument>
</system.webServer>
</configuration>

Session End never truly fires, because when it does execute, it's after the page request is complete and the request has already been sent to the client.
You'll need to do the session_end code in your page, or in a base page class (very handy for this sort of thing).
See the following S.O. links:
Session_End does not fire?
What is the difference between Session.Abandon() and Session.Clear()

Related

Custom Authorization for all requests to sub-folder in ASP.NET website

I have a ASP.NET 4.0 website which contains a sub-folder with multimedia files like JPG, PNG, MP4, MP3, etc.
Currently, any user with the full link to the files is able to access the multimedia files without any restriction. I want to find the currently logged in user who is making the request and after checking their permissions from DB allow/disallow them to access the file requested.
I have tried implementing a Custom HttpModule for this purpose but I am not able to find the current user making the request. Below is my code:
public class CustomHttpModule : IHttpModule
{
private const string URL_TO_LOOK_FOR = "/MultiMediaFiles/";
public CustomHttpModule()
{ }
public void Init(HttpApplication app)
{
app.AuthenticateRequest += CustomAuthenticateRequest;
//app.EndRequest += CustomAuthenticateRequest;
}
void CustomAuthenticateRequest(object source, EventArgs e)
{
HttpApplication app = (HttpApplication)source;
HttpContext context = app.Context;
Uri url = context.Request.Url;
if (url.AbsolutePath.StartsWith(URL_TO_LOOK_FOR, StringComparison.OrdinalIgnoreCase))
{
var response = context.Response;
response.Clear();
response.Write("app.Context.User :");
if (context.User == null || context.User.Identity == null || context.User.Identity.Name == null)
{
response.Write("No user");
}
else
{
response.Write(context.User.Identity.Name);
}
response.End();
response.Flush();
response.Close();
}
}
public void Dispose()
{ }
}
I tried attaching to events: BeginRequest, AuthenticateRequest, PostAuthenticateRequest and even EndRequest, but in each case context.User is always null even after I have logged in to my website.
EDIT:
I am using the FormsAuthentication and my web.config contains:
<system.web>
<authentication mode="Forms">
<forms name="MyWebFORMAUTH" timeout="60"
loginUrl="~/web/logon/default.aspx" cookieless="UseCookies"
defaultUrl="~/web/logon/default.aspx"
slidingExpiration="true" />
</authentication>
</system.web>
<system.webServer>
<modules>
<add name="CustomHttpModule" type="CustomHttpModule"/>
</modules>
<system.webServer>
NOTE: I cannot modify the links to multimedia files.
Please HELP.
UPDATE:
You would also need to tell ASP.NET that you don't want to execute static content handler for certain file types in certain directory.
Here is the updated version of web.config file:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0" />
<httpRuntime />
<authentication mode="Forms">
<forms name="MyWebFORMAUTH" timeout="60"
loginUrl="~/web/logon/default.aspx" cookieless="UseCookies"
defaultUrl="~/web/logon/default.aspx"
slidingExpiration="true" />
</authentication>
</system.web>
<system.webServer>
<modules>
<add name="CustomHttpModule" type="CustomHttpModule" />
</modules>
<defaultDocument>
<files>
<clear />
<add value="Default.aspx" />
</files>
</defaultDocument>
</system.webServer>
<location path="MultiMediaFiles">
<system.webServer>
<handlers>
<!-- This line tells ASP.NET to skip the processing of PNG files
by default static content handler. -->
<add name="SkipStaticPng" path="*.png" verb="GET"
type="System.Web.Handlers.TransferRequestHandler"
preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
</system.webServer>
</location>
</configuration>
Your code should work. Here is the example:
Default.aspx:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebForm" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Test</title>
</head>
<body>
<form id="form1" runat="server">
<asp:Label ID="CurrentUserLabel" runat="server" />
<br />
<asp:Button ID="LoginButton" runat="server" OnClick="LoginButton_Click" Text="Login" />
</form>
</body>
</html>
Default.aspx.cs:
using System;
using System.Security.Principal;
using System.Web.Security;
public partial class WebForm : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
PopulateCurrentUserName();
}
protected void LoginButton_Click(object sender, EventArgs e)
{
FormsAuthentication.SetAuthCookie("test_user", false);
Response.Redirect(Request.Url.AbsoluteUri);
}
private void PopulateCurrentUserName()
{
IPrincipal user = Request.RequestContext.HttpContext.User;
if (user != null && user.Identity != null && !String.IsNullOrEmpty(user.Identity.Name))
CurrentUserLabel.Text = user.Identity.Name;
else
CurrentUserLabel.Text = "(null)";
}
}
CustomHttpModule.cs:
using System;
using System.Web;
public class CustomHttpModule : IHttpModule
{
private const string URL_TO_LOOK_FOR = "/MultiMediaFiles/";
public CustomHttpModule()
{
}
public void Init(HttpApplication app)
{
app.AuthenticateRequest += CustomAuthenticateRequest;
}
void CustomAuthenticateRequest(object source, EventArgs e)
{
HttpApplication app = (HttpApplication)source;
HttpContext context = app.Context;
Uri url = context.Request.Url;
if (url.AbsolutePath.StartsWith(URL_TO_LOOK_FOR, StringComparison.OrdinalIgnoreCase))
{
var response = context.Response;
response.Clear();
response.Write("app.Context.User :");
if (context.User == null || context.User.Identity == null || context.User.Identity.Name == null)
{
response.Write("No user");
}
else
{
response.Write(context.User.Identity.Name);
}
response.End();
response.Flush();
response.Close();
}
}
public void Dispose()
{
}
}
web.config:
<?xml version="1.0"?>
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0"/>
<httpRuntime/>
<authentication mode="Forms">
<forms name="MyWebFORMAUTH" timeout="60"
loginUrl="~/web/logon/default.aspx" cookieless="UseCookies"
defaultUrl="~/web/logon/default.aspx"
slidingExpiration="true" />
</authentication>
</system.web>
<system.webServer>
<modules>
<add name="CustomHttpModule" type="CustomHttpModule"/>
</modules>
<defaultDocument>
<files>
<clear/>
<add value="Default.aspx"/>
</files>
</defaultDocument>
</system.webServer>
</configuration>
And here is the test scenario:
Clear the cookies in your browser.
Navigate to the start page (let's say it is http://localhost).
You will see that current user is (null).
Open http://localhost/MultiMediaFiles/ in the second tab.
You will see the "app.Context.User :No user" message.
Switch back to the previous tab and click "Login" button.
You will see that current user now is "test_user".
Switch to the second tab and refresh the page.
If everything is correct then the "app.Context.User :test_user" message should be displayed.

Updating a config file in c#

I am creating an update to my companies system that will be running on several clients and I have two config files, the old config file and the newer version.
Is there any way that I can compare the both files and check the differences to add to the older file what I have new in the first one?
Keep in mind that the files may have different info and the only thing that I need to add/change is the keys. For example, if a key is different change the older to that new "version", if a key doesn’t exist in the older files add it.
they keys will have the exact same name but may have different values. Plus there could be a new key that doesnt exist in the older file and I need to add it
I will leave an example of the files for you to see,
Any help would be appreciated.
<configuration>
<appSettings>
<add key="ORCASRV1" value="ORCA30|tcp://127.0.0.1:9001" />
<add key="ORCASRV2" value="REORCA30|tcp://127.0.0.1:9001" />
<add key="ServidorEmail" value="xxx" />
<add key="SqlTrans" value="1" />
<add key="RemoteType" value="0" />
<add key="LocalPort" value="9002" />
<add key="LocalMsgStore" value="1" />
<add key="sqlCHAR_TO_DATA" value="CONVERT(datetime, '#MM#/#DD#/#YYYY#')" />
<add key="sqlDATA_TO_CHAR" value="CONVERT(char(30), #CAMPO#)" />
<add key="sqlDATAPARTE" value="LTRIM(STR(DATEPART(#PARTE, #CAMPO#)))" />
<add key="sqlNUM_TO_CHAR" value="LTRIM(STR(#VALOR#))" />
<add key="sqlSYSDATE" value=" GetDate() " />
<add key="sqlALIAS" value=" As " />
<add key="sqlCONCATENAR" value="+" /> <add key="sqlNULL" value="IsNull(#CAMPO#,#VALOR#)" />
<add key="sqlROUND" value="ROUND(#CAMPO#,#PARTE#)" />
<add key="sqlLPAD" value="RIGTH(REPLICATE('#CHAR#',#VEZES#)+#CAMPO#,#VEZES#)" />
<add key="oraCHAR_TO_DATA" value="TO_DATE('#MM#/#DD#/#YYYY#','MM/DD/YYYY')" />
<add key="oraDATA_TO_CHAR" value="TO_CHAR(#CAMPO#, 'DD/MM/YYYY')" />
<add key="oraDATAPARTE" value="TO_CHAR(#PARTE#, #CAMPO#)" />
<add key="oraNUM_TO_CHAR" value="TO_CHAR(#VALOR#)" />
<add key="oraSYSDATE" value=" SYSDATE " />
<add key="oraALIAS" value=" " />
<add key="oraCONCATENAR" value="||" />
<add key="oraNULL" value="NVL(#CAMPO#,#VALOR#)" />
<add key="oraROUND" value="ROUND(#CAMPO#,#PARTE#)" />
<add key="oraLPAD" value="LPAD(#CAMPO#,#VEZES#,#CHAR#)" />
<add key="EmailCDP" value="antonio.santos#cdp-si.pt" />
<add key="EmailCliente" value="xxx" />
<add key="RPT_PATH1" value="C:\PROD\ORCAREPORT\" />
<add key="StartPage_Height" value="90" />
<add key="StartPage_Margem" value="220" />
<add key="StartPage_Espaco" value="5" />
<add key="StartPage_Intervalo" value="2" />
<add key="StartPage_Mais" value="35" />
<add key="HelpExec" value="WINHLP32.EXE" />
<add key="HelpFile" value="ORCA.HLP" />
<add key="LogLevel" value="0" />
<add key="LogSqlClient" value="0" />
<add key="LogFile" value="C:\cdpsi\logs" />
</appSettings>
<system.runtime.remoting>
<application>
<channels>
<channel ref="tcp" port="9002">
<clientProviders>
<formatter ref="binary" /> <provider type="CdpCompress.CompressionClientSinkProvider, CdpCompress" />
</clientProviders>
</channel>
</channels>
</application>
</system.runtime.remoting>
</configuration>
Code went like this and it works like a charm:
public void UpdateService(string FilePathOld, string FilePathNew, string LatestVersion)
{
Dictionary<string, string> Old = new Dictionary<string, string>();
Dictionary<string, string> New = new Dictionary<string, string>();
if (ExisteFicheiro(FilePathNew) == true && ExisteFicheiro(FilePathOld) == true)
{
ExeConfigurationFileMap configOld = new ExeConfigurationFileMap();
configOld.ExeConfigFilename = FilePathOld;
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(configOld, ConfigurationUserLevel.None);
ExeConfigurationFileMap configNew = new ExeConfigurationFileMap();
configNew.ExeConfigFilename = FilePathNew;
Configuration config2 = ConfigurationManager.OpenMappedExeConfiguration(configNew, ConfigurationUserLevel.None);
KeyValueConfigurationCollection settings = config.AppSettings.Settings;
Old = settings.AllKeys.ToDictionary(key => key, key => settings[key].Value);
KeyValueConfigurationCollection settings2 = config2.AppSettings.Settings;
New = settings2.AllKeys.ToDictionary(key => key, key => settings2[key].Value);
foreach (var NewKey in New)
{
string value;
if (Old.TryGetValue(NewKey.Key, out value))
{
if (value != NewKey.Value)
{
//if (ExistsKey(NewKey.Key, false) == true)
Old[NewKey.Key] = NewKey.Value;
}
}
else
{
Old.Add(NewKey.Key, NewKey.Value);
}
}
foreach (var NewKey in Old)
{
string key = NewKey.Key;
string value = NewKey.Value;
if (config.AppSettings.Settings[key] != null)
{
config.AppSettings.Settings[key].Value = value;
if (key == "Version")
config.AppSettings.Settings[key].Value = LatestVersion;
}
else
{
config.AppSettings.Settings.Add(key, value);
}
if (config.AppSettings.Settings["Version"] == null)
{
config.AppSettings.Settings.Add("Version", LatestVersion);
}
}
config.Save();
}
else
{
Erro NovoErro = new Erro();
Global.Erro = "O ficheiro \"OrcaService.exe.config\" ou o ficheiro \"Orca.exe.config\" não existem nos caminhos especificados!";
}
}

Using WF to send message to Windows Server ServiceBus

I'm trying to send messages to a local Topic created in Windows Server ServiceBus.
I started from examples by Roman Kiss and Paolo salvatori.
I'm stuck with the following exception:
Service namespace cannot be null or empty.
Parameter name: serviceNamespace
This is the service:
[ServiceContract]
public interface INotificationService
{
[OperationContract(Action = "*", IsOneWay = true)]
void Process(string notification);
}
My config file looks like this:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.1" />
</startup>
<system.serviceModel>
<extensions>
<!-- In this extension section we are introducing all known service bus extensions. User can remove the ones they don't need. -->
<behaviorExtensions>
<add name="connectionStatusBehavior" type="Microsoft.ServiceBus.Configuration.ConnectionStatusElement, Microsoft.ServiceBus, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
<add name="transportClientEndpointBehavior" type="Microsoft.ServiceBus.Configuration.TransportClientEndpointBehaviorElement, Microsoft.ServiceBus, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
<add name="serviceRegistrySettings" type="Microsoft.ServiceBus.Configuration.ServiceRegistrySettingsElement, Microsoft.ServiceBus, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
</behaviorExtensions>
<bindingElementExtensions>
<add name="netMessagingTransport" type="Microsoft.ServiceBus.Messaging.Configuration.NetMessagingTransportExtensionElement, Microsoft.ServiceBus, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
<add name="tcpRelayTransport" type="Microsoft.ServiceBus.Configuration.TcpRelayTransportElement, Microsoft.ServiceBus, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
<add name="httpRelayTransport" type="Microsoft.ServiceBus.Configuration.HttpRelayTransportElement, Microsoft.ServiceBus, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
<add name="httpsRelayTransport" type="Microsoft.ServiceBus.Configuration.HttpsRelayTransportElement, Microsoft.ServiceBus, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
<add name="onewayRelayTransport" type="Microsoft.ServiceBus.Configuration.RelayedOnewayTransportElement, Microsoft.ServiceBus, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
</bindingElementExtensions>
<bindingExtensions>
<add name="basicHttpRelayBinding" type="Microsoft.ServiceBus.Configuration.BasicHttpRelayBindingCollectionElement, Microsoft.ServiceBus, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
<add name="webHttpRelayBinding" type="Microsoft.ServiceBus.Configuration.WebHttpRelayBindingCollectionElement, Microsoft.ServiceBus, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
<add name="ws2007HttpRelayBinding" type="Microsoft.ServiceBus.Configuration.WS2007HttpRelayBindingCollectionElement, Microsoft.ServiceBus, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
<add name="netTcpRelayBinding" type="Microsoft.ServiceBus.Configuration.NetTcpRelayBindingCollectionElement, Microsoft.ServiceBus, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
<add name="netOnewayRelayBinding" type="Microsoft.ServiceBus.Configuration.NetOnewayRelayBindingCollectionElement, Microsoft.ServiceBus, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
<add name="netEventRelayBinding" type="Microsoft.ServiceBus.Configuration.NetEventRelayBindingCollectionElement, Microsoft.ServiceBus, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
<add name="netMessagingBinding" type="Microsoft.ServiceBus.Messaging.Configuration.NetMessagingBindingCollectionElement, Microsoft.ServiceBus, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
</bindingExtensions>
</extensions>
<behaviors>
<endpointBehaviors>
<behavior name="sharedSecretCredentials">
<transportClientEndpointBehavior>
<tokenProvider>
<sharedSecret
issuerName="ServiceBusDefaultNamespace"
issuerSecret="--PrimarySymmetricKey retrieved with Get-SBNamespace--" />
</tokenProvider>
</transportClientEndpointBehavior>
</behavior>
</endpointBehaviors>
</behaviors>
<client>
<endpoint name="TopicPublisher"
address="sb://[machinename]/ServiceBusDefaultNamespace/NotificationService"
binding="netMessagingBinding"
contract="INotificationService"
behaviorConfiguration="sharedSecretCredentials" />
</client>
</system.serviceModel><appSettings>
<!-- Service Bus specific app setings for messaging connections -->
<!--<add key="Microsoft.ServiceBus.ConnectionString" value="Endpoint=sb://[your namespace].servicebus.windows.net;SharedSecretIssuer=owner;SharedSecretValue=[your secret]" />-->
</appSettings>
</configuration>
This is my ServiceBus.config file (required to avoid a "The Uri provided [machinename] does not match Service Bus domain: servicebus.windows.net." Exception, look here):
<?xml version="1.0" encoding="utf-8"?> <!-- the root web configuration file -->
<configuration>
<Microsoft.ServiceBus>
<relayHostName>[machinename]</relayHostName>
<stsHostName>[machinename]</stsHostName>
<acmHostName>[machinename]</acmHostName>
</Microsoft.ServiceBus>
</configuration>
This is the very simple workflow:
And finally this is the console:
class Program
{
static void Main(string[] args)
{
Activity publisher = new Publisher();
while (true)
{
Console.WriteLine("Type ctrl+q to exit or enter to insert a notification");
var key = Console.ReadKey();
if (key.Key == ConsoleKey.Q && key.Modifiers == ConsoleModifiers.Control)
{
break;
}
Console.WriteLine();
if (key.Key == ConsoleKey.Enter)
{
Console.WriteLine("Please enter the notification");
}
else
{
Console.WriteLine("Sorry, I didn't understand!");
continue;
}
var notification = Console.ReadLine();
var notificationMessage = new BrokeredMessage(notification);
var inputs = new Dictionary<string, object> { { "Notification", notificationMessage } };
try
{
WorkflowInvoker.Invoke(publisher, inputs);
}
catch (Exception exception)
{
Console.WriteLine("Error: " + exception);
}
}
}
}
I created the NotificationService Topic using Service Bus Explorer 2.1.
The Azure SDK version is 2.1.4 installed via NuGet and I'm using Service Bus for Windows Server 1.1

Session getting lost after publishing (works on dev machine)

I'm working on a Holiday Tracker application and one specific thing is killing the whole "page life cycle".
In my User Scheduler, where every user can insert his vacation, sometimes it's working (and so he can insert/delete/edit and view his vacation). There is also a Vacation page (same story there, just with a grid).
But sometimes the session that is set is getting lost. If I'm debugging with Visual Studio 2012, it's working. But if I publish the application, it's not working. It just gets lost somehow
Code in Global.asax.cs
void Session_Start(object sender, EventArgs e) {
// Code that runs when a new session is started
if (HttpContext.Current.User != null && HttpContext.Current.User is HtUser)
{
HtUser user = (HtUser)HttpContext.Current.User;
Session["UserId"] = user.UserId;
if(user.HtDepartments.Any() && user.HtDepartments.First().HtBusinessUnit != null){
int BusinessUnitId = user.HtDepartments.First().HtBusinessUnit.BusinessUnitId;
Session["BusinessUnitId"] = BusinessUnitId;
}
}
}
I think that maybe the error is there.
Scheduler:
<%--<telerik:RadAjaxPanel ID="RadAjaxPanel1" runat="server" LoadingPanelID="RadAjaxLoadingPanel1">--%>
<div style="float: left; margin-right: 20px; margin-bottom: 10px;">
<asp:Label runat="server" Text="Unbooked vacation:"></asp:Label>
<asp:Label ID="lblBookedVacation" runat="server" Text=""></asp:Label>
</div>
<div style="float: right; margin-right: 20px; margin-bottom: 10px;">
<asp:Button runat="server" ID="btnExport" Text="Export to Lotus Notes" OnClientClick="Export(this, event); return false;" OnClick="btnExport_Click"></asp:Button>
</div>
<div style="clear: both;" />
<div>
<telerik:RadScheduler runat="server" ID="RadScheduler1" Width="750px" Height="700px"
DayStartTime="07:00:00" DayEndTime="18:00:00" SelectedView="WeekView" DataSourceID="dsVactationDays"
DataKeyField="VacationDayId" DataSubjectField="Title" DataStartField="FromDate" DataEndField="ToDate" OnAppointmentUpdate="RadScheduler1_AppointmentUpdate"
OnAppointmentInsert="RadScheduler1_AppointmentInsert"
OnRecurrenceExceptionCreated="RadScheduler1_RecurrenceExceptionCreated" OnTimeSlotCreated="RadScheduler1_TimeSlotCreated" OnAppointmentDataBound="RadScheduler1_AppointmentDataBound">
<AdvancedForm Modal="true"></AdvancedForm>
<TimelineView UserSelectable="false"></TimelineView>
<TimeSlotContextMenuSettings EnableDefault="true"></TimeSlotContextMenuSettings>
<AppointmentContextMenuSettings EnableDefault="true"></AppointmentContextMenuSettings>
</telerik:RadScheduler>
</div>
<asp:TextBox ID="txtID" runat="server"></asp:TextBox>
<asp:DataGrid runat="server" DataSourceID="dsVactationDays" AutoGenerateColumns="true"></asp:DataGrid>
<asp:EntityDataSource ID="dsVactationDays" runat="server" ConnectionString="name=HolidayTrackerEntities" DefaultContainerName="HolidayTrackerEntities"
EnableDelete="True" EnableFlattening="False" EnableInsert="True" EnableUpdate="True" EntitySetName="HtVacationDays"
Where="it.UserId == #UserId">
<WhereParameters>
<asp:SessionParameter DbType="Int32" Name="UserId" SessionField="UserId" />
</WhereParameters>
</asp:EntityDataSource>
<%--</telerik:RadAjaxPanel>--%>
Code behind
private const int AppointmentsLimit = 1;
// private HtUser paramUser;
private HtUser user;
private HtUser User
{
get
{
if (user == null)
{
user = HtUser.INIT_USER(this.Page, false);
}
return user;
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack) {
if (this.User != null) {
updateUnbookedVacationNotification();
}
}
txtID.Text = Session["UserId"] != null ? Session["UserId"].ToString() : "FUUUUU";
}
private void updateUnbookedVacationNotification() {
double avAmount = User.GetAnnualVacationAmountByYear(this.RadScheduler1.SelectedDate.Year);
double bookedAmount = User.GetBookedVacation(this.RadScheduler1.SelectedDate.Year);
this.lblBookedVacation.Text = (avAmount - bookedAmount).ToString();
}
//private void getParameters()
//{
// if (Page.Request["UserId"] != null)
// {
// int userId = Constants.TryConvert(Page.Request["userId"], this.Page);
// this.paramUser = HtUser.GetById(userId);
// }
//}
private bool ExceedsLimit(Appointment apt)
{
int appointmentsCount = 0;
foreach (Appointment existingApt in RadScheduler1.Appointments.GetAppointmentsInRange(apt.Start, apt.End))
{
if (existingApt.Visible)
appointmentsCount++;
}
return (appointmentsCount > AppointmentsLimit - 1);
}
private bool AppointmentsOverlap(Appointment appointment)
{
if (ExceedsLimit(appointment))
{
foreach (Appointment a in RadScheduler1.Appointments.GetAppointmentsInRange(appointment.Start, appointment.End))
{
if (a.ID != appointment.ID)
{
return true;
}
}
}
return false;
}
private void RegisterScript()
{
Label1.Text = "Invalid move! There are appointments arranged for this time period.";
ScriptManager.RegisterClientScriptBlock(this, GetType(), "LabelUpdated",
"$telerik.$('.lblError').show().animate({ opacity: 0.9 }, 2000).fadeOut('slow');", true);
}
protected void RadScheduler1_AppointmentInsert(object sender, SchedulerCancelEventArgs e)
{
if (ExceedsLimit(e.Appointment))
{
e.Cancel = true;
RegisterScript();
}
else
{
int id = HtUser.GetUserIdByLogin(Page.User.Identity.Name);
e.Appointment.Attributes.Add("UserId", id.ToString());
}
}
Login Part
Global.asax.cs
protected void WindowsAuthentication_OnAuthenticate(Object source, WindowsAuthenticationEventArgs e)
{
if (Request.Cookies.Get(Constants.AUTHORIZATION_COOKIE_NAME) != null)
return;
String strUserIdentity;
FormsAuthenticationTicket formsAuthTicket;
HttpCookie httpCook;
String strEncryptedTicket;
AdLookup adLookup = new AdLookup();
strUserIdentity = e.Identity.Name;
bool loggedIn = false;
String email = null;
String role = null;
email = strUserIdentity;
HtUser userInfo = null;
if (email != null && email != "")
{
userInfo = HtUser.GetByLogin(e.Identity, email);
if (userInfo != null && userInfo.UserName.Length > 0)
{
loggedIn = true;
role = HtUser.GetUserRoleString(userInfo);
}
//Checks if user is in domain
else
{
userInfo = adLookup.GetAdUserByUsername(HtUser.getUserNameFromDomainString(email));
if (userInfo != null && userInfo.UserName.Length > 0)
{
loggedIn = true;
role = UserRoles.User;
}
}
}
//}
if (loggedIn)
{
formsAuthTicket = new FormsAuthenticationTicket(1, email, DateTime.Now,
DateTime.Now.AddMinutes(60), false, role);
strEncryptedTicket = FormsAuthentication.Encrypt(formsAuthTicket);
httpCook = new HttpCookie(Constants.AUTHORIZATION_COOKIE_NAME, strEncryptedTicket);
Response.Cookies.Add(httpCook);
HttpContext.Current.User = userInfo;
}
else
{
HttpContext.Current.User = null;
}
Web.Config
<?xml version="1.0" encoding="utf-8"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=169433
-->
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=4.4.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<connectionStrings>
<add name="ApplicationServices" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnetdb.mdf;User Instance=true" providerName="System.Data.SqlClient" />
<add name="ConnectionString" connectionString="Data Source=ch-s-0008086;Initial Catalog=HolidayTracker;Persist Security Info=True;User ID=sa;Password=123.;MultipleActiveResultSets=True" providerName="System.Data.SqlClient" />
<add name="HolidayTrackerConnectionString" connectionString="Data Source=ch-s-0008086;Initial Catalog=HolidayTracker;User ID=sa;Password=123." providerName="System.Data.SqlClient" />
<add name="HolidayTrackerEntities" connectionString="metadata=res://*/Model.HolidayTracker.csdl|res://*/Model.HolidayTracker.ssdl|res://*/Model.HolidayTracker.msl;provider=System.Data.SqlClient;provider connection string="Data Source=ch-s-0008086;Initial Catalog=HolidayTracker;Persist Security Info=True;User ID=sa;Password=123.;MultipleActiveResultSets=True"" providerName="System.Data.EntityClient" />
<add name="HolidayTrackerEntities1" connectionString="metadata=res://*/DAL.HTTracker.csdl|res://*/DAL.HTTracker.ssdl|res://*/DAL.HTTracker.msl;provider=System.Data.SqlClient;provider connection string="data source=ch-s-0008086;initial catalog=HolidayTracker;user id=sa;password=123.;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
<appSettings>
<add key="LDAP_SERVER_NAME" value="asdasdasd" />
<add key="LDAP_USERNAME" value="asdasdas" />
<add key="LDAP_PASSWORD" value="asdasdasd" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.0">
<assemblies>
<add assembly="System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A" />
<add assembly="System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" />
<add assembly="System.Speech, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" />
<add assembly="System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<add assembly="System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Runtime.Serialization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" />
<add assembly="System.ServiceModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" />
<add assembly="System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" />
<add assembly="System.Xml.Linq, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" />
<add assembly="System.Data.DataSetExtensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" />
<add assembly="System.Web.Extensions.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
</assemblies>
</compilation>
<customErrors mode="Off" />
<authentication mode="Windows" />
<identity impersonate="false" />
<httpHandlers>
<add path="ChartImage.axd" type="Telerik.Web.UI.ChartHttpHandler" verb="*" validate="false" />
<add path="Telerik.Web.UI.SpellCheckHandler.axd" type="Telerik.Web.UI.SpellCheckHandler" verb="*" validate="false" />
<add path="Telerik.Web.UI.DialogHandler.aspx" type="Telerik.Web.UI.DialogHandler" verb="*" validate="false" />
<add path="Telerik.RadUploadProgressHandler.ashx" type="Telerik.Web.UI.RadUploadProgressHandler" verb="*" validate="false" />
<add path="Telerik.Web.UI.WebResource.axd" type="Telerik.Web.UI.WebResource" verb="*" validate="false" />
</httpHandlers>
<pages>
<controls>
<add tagPrefix="telerik" namespace="Telerik.Web.UI" assembly="Telerik.Web.UI" />
</controls>
</pages>
<httpModules>
<add name="RadUploadModule" type="Telerik.Web.UI.RadUploadHttpModule" />
<add name="RadCompression" type="Telerik.Web.UI.RadCompression" /></httpModules>
</system.web>
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<modules runAllManagedModulesForAllRequests="true">
<remove name="RadUploadModule" />
<remove name="RadCompression" /><add name="RadUploadModule" type="Telerik.Web.UI.RadUploadHttpModule" preCondition="integratedMode" />
<add name="RadCompression" type="Telerik.Web.UI.RadCompression" preCondition="integratedMode" /></modules>
<handlers>
<remove name="ChartImage_axd" />
<remove name="Telerik_Web_UI_SpellCheckHandler_axd" />
<remove name="Telerik_Web_UI_DialogHandler_aspx" />
<remove name="Telerik_RadUploadProgressHandler_ashx" />
<remove name="Telerik_Web_UI_WebResource_axd" />
<add name="ChartImage_axd" path="ChartImage.axd" type="Telerik.Web.UI.ChartHttpHandler" verb="*" preCondition="integratedMode" />
<add name="Telerik_Web_UI_SpellCheckHandler_axd" path="Telerik.Web.UI.SpellCheckHandler.axd" type="Telerik.Web.UI.SpellCheckHandler" verb="*" preCondition="integratedMode" />
<add name="Telerik_Web_UI_DialogHandler_aspx" path="Telerik.Web.UI.DialogHandler.aspx" type="Telerik.Web.UI.DialogHandler" verb="*" preCondition="integratedMode" />
<add name="Telerik_RadUploadProgressHandler_ashx" path="Telerik.RadUploadProgressHandler.ashx" type="Telerik.Web.UI.RadUploadProgressHandler" verb="*" preCondition="integratedMode" />
<add name="Telerik_Web_UI_WebResource_axd" path="Telerik.Web.UI.WebResource.axd" type="Telerik.Web.UI.WebResource" verb="*" preCondition="integratedMode" />
</handlers>
<directoryBrowse enabled="true" />
</system.webServer>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="v11.0" />
</parameters>
</defaultConnectionFactory>
</entityFramework>
</configuration>
If you need something more, just let me know.
If you are using InProc session storage and publish your application, the application pool gets recycled by the IIS and the w3wp.exe process respawns. Your session data is then lost immediately.
If that is the problem you're having, and you want to avoid it, there are options for storing your session elsewhere (such as in a database). See the MSDN article on ASP.NET Session-State Modes for more information.

FormsAuthentication and Roles problems

What is this garbage in the URL? After login I am directed to:
http://localhost:1337/%28F%2883mI1fhnT6Sm1XopiPcErGYaqCafgnoSL_hgFJi9u7MwncoR98KOirf8GuqRVFfAbZN9mR1IH6W8LQQIeHTd4NcR5BKHAVvZrmcIoDTGTf01%29%29/
When I debug I see that in Global.asax as well as AccountController my userRoles/accessLevel are correctly being found and inserted as part of the authentication ticket. My attributes set required roles to view the action. GET loads and when I save POST prompts for login which continually loops. Any idea what's goin on? Also, when I output my authTicket.UserData I see my roles (Author|Admin) yet HttpContext.User.IsInRole("Author"); && HttpContext.User.IsInRole("Author"); return false. Do I need roleManager enabled in web.config? And what do I set it to given me placing this info in the ticket?
SpotlightsController.cs:
// GET: /Spotlights/Edit/5
[Authorize(Roles="Author,Admin")]
public ActionResult Edit(int id)
{
Spotlight spotlight = spotlightRepository.GetSpotlight(id);
return View(new SpotlightFormViewModel(spotlight));
}
//
// POST: /Spotlights/Edit/5
[Authorize(Roles="Author,Admin"), HttpPost]
public ActionResult Edit(int id, FormCollection collection)
{
Spotlight spotlight = spotlightRepository.GetSpotlight(id);
try
{
spotlight.ModifiedDate = DateTimeOffset.Now;
UpdateModel(spotlight);
spotlightRepository.Save();
return RedirectToAction("Details", new { id = spotlight.SpotlightID });
}
catch
{
ModelState.AddRuleViolations(spotlight.GetRuleViolations());
return View(new SpotlightFormViewModel(spotlight));
}
}
Global.asax.cs:
protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
//Fires upon attempting to authenticate the use
if (!(HttpContext.Current.User == null) &&
HttpContext.Current.User.Identity.IsAuthenticated &&
HttpContext.Current.User.Identity.GetType() == typeof(FormsIdentity))
{
HttpCookie authCookie = Context.Request.Cookies[FormsAuthentication.FormsCookieName];
FormsIdentity userIdentity = (FormsIdentity)HttpContext.Current.User.Identity;
FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
String[] userRoles = authTicket.UserData.Split('|');
HttpContext.Current.User = new GenericPrincipal(userIdentity, userRoles);
}
}
AccountController.cs:
[HttpPost]
public ActionResult LogOn(LogOnModel model, string returnUrl)
{
if (ModelState.IsValid)
{
if (MembershipService.ValidateUser(model.UserName, model.Password))
{
//string accessLevel = userRepository.FindUserByCWID(model.UserName).AccessLevel.LevelName;
string accessLevel = userRepository.FindUserByCWID(model.UserName).Roles;
FormsAuthenticationTicket authTicket = new
FormsAuthenticationTicket(1, //version
model.UserName, // user name
DateTime.Now, //creation
DateTime.Now.AddMinutes(30), //Expiration
model.RememberMe, //Persistent
accessLevel); // add roles?
string encTicket = FormsAuthentication.Encrypt(authTicket);
this.Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encTicket));
FormsService.SignIn(model.UserName, model.RememberMe);
if (!String.IsNullOrEmpty(returnUrl))
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction("Index", "Home");
}
}
else
{
ModelState.AddModelError("", "The user name or password provided is incorrect.");
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
Web.config:
<?xml version="1.0"?>
<configuration>
<connectionStrings>
<add name="ApplicationServices" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true"
providerName="System.Data.SqlClient" />
<add name="devConnectionString" snip"
providerName="System.Data.SqlClient" />
<add name="ADConnectionString" connectionString="LDAP://my.domain/DC=my,DC=domain"/>
</connectionStrings>
<system.web>
<compilation debug="true" targetFramework="4.0">
<assemblies>
<add assembly="System.Web.Abstractions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Routing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<add assembly="System.Web.Mvc, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
</assemblies>
</compilation>
<authentication mode="Forms">
<forms loginUrl="~/Account/LogOn" timeout="2880" />
</authentication>
<membership defaultProvider="MyADMembershipProvider">
<providers>
<clear/>
<add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="ApplicationServices"
enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false"
maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10"
applicationName="/" />
<add name="MyADMembershipProvider"
type="System.Web.Security.ActiveDirectoryMembershipProvider" connectionStringName="ADConnectionString"
attributeMapUsername="sAMAccountName" connectionProtection="Secure"
enablePasswordReset="false" maxInvalidPasswordAttempts="1" passwordAttemptWindow="15"
passwordAnswerAttemptLockoutDuration="1" minRequiredNonalphanumericCharacters="0" attributeMapEmail="mail"
/>
</providers>
</membership>
<profile>
<providers>
<clear/>
<add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="ApplicationServices" applicationName="/" />
</providers>
</profile>
<roleManager enabled="false" defaultProvider="MySqlRoleProvider">
<providers>
<clear/>
<add name="MySqlRoleProvider" type="System.Web.Security.SqlRoleProvider" connectionStringName="ApplicationServices" applicationName="myApp" />
<add name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider" applicationName="/" />
</providers>
</roleManager>
<pages>
<namespaces>
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Routing" />
</namespaces>
</pages>
</system.web>
<system.webServer>
<validation validateIntegratedModeConfiguration="false"/>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0" newVersion="2.0.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>
Cookies were not being used for some reason. Set cookieless="UseCookies" in web.config and all is working :)

Categories