I have an MVC4 application with the models and the migrations in a separate project, which is a class library.
I have this in my seed method:
protected override void Seed(BDOleoTorres.Models.OleoTorresContext context)
{
if (!Roles.RoleExists("Admin"))
Roles.CreateRole("Admin");
//[Authorize(Roles = "Admin,Vendedor,Administrativo")]
if (!WebSecurity.UserExists("Administrador"))
WebSecurity.CreateUserAndAccount(
"Administrador",
"Admin123.",
new { NrVendedor = 1, DataHoraCriacao = DateTime.Now, NomeHumano = "Sr Administrador", TipoUser="Geral" });
if (!Roles.GetRolesForUser("Administrador").Contains("Admin"))
Roles.AddUsersToRole(new string[] { "Administrador" }, "Admin");
}
And this in my web.config (other project):
<system.web>
<roleManager enabled="true" defaultProvider="SimpleRoleProvider">
<providers>
<clear />
<add name="SimpleRoleProvider" type="WebMatrix.WebData.SimpleRoleProvider, WebMatrix.WebData" />
</providers>
</roleManager>
<membership defaultProvider="SimpleMembershipProvider">
<providers>
<clear />
<add name="SimpleMembershipProvider" type="WebMatrix.WebData.SimpleMembershipProvider, WebMatrix.WebData" />
</providers>
</membership>
I do correctly migration, but when do update-database -verbose have the error:
The Role Manager feature has not been enabled.
Related
I need to compress json response, I have tried IIS dynamic compression and used below code to compress but compression is not working it always Content-Type:application/json; charset=utf-8, Gzip headers are properly send to server. I have tried the code below.There is nothing in failed request tracing. Please suggest a solution.
class CompressFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
HttpRequestBase request = filterContext.HttpContext.Request;
string acceptEncoding = request.Headers["Accept-Encoding"];
if (string.IsNullOrEmpty(acceptEncoding)) return;
acceptEncoding = acceptEncoding.ToUpperInvariant();
HttpResponseBase response = filterContext.HttpContext.Response;
if (acceptEncoding.Contains("GZIP"))
{
response.AppendHeader("Content-encoding", "gzip");
response.Filter = new GZipStream(response.Filter, CompressionMode.Compress,true);
}
else if (acceptEncoding.Contains("DEFLATE"))
{
response.AppendHeader("Content-encoding", "deflate");
response.Filter = new DeflateStream(response.Filter, CompressionMode.Compress);
}
}
}
I have this settings in web.config file
<httpCompression directory="%SystemDrive%\inetpub\temp\IIS Temporary Compressed Files">
<scheme name="gzip" dll="%Windir%\system32\inetsrv\gzip.dll" staticCompressionLevel="9" />
<dynamicTypes>
<add mimeType="text/*" enabled="true" />
<add mimeType="message/*" enabled="true" />
<add mimeType="application/x-javascript" enabled="true" />
<add mimeType="application/javascript" enabled="true" />
<add mimeType="application/javascript; charset=utf-8" enabled="true" />
<add mimeType="application/json" enabled="true" />
<add mimeType="application/json; charset=utf-8" enabled="true" />
<add mimeType="*/*" enabled="false" />
</dynamicTypes>
<staticTypes>
<add mimeType="text/*" enabled="true" />
<add mimeType="message/*" enabled="true" />
<add mimeType="application/x-javascript" enabled="true" />
<add mimeType="application/atom+xml" enabled="true" />
<add mimeType="application/xaml+xml" enabled="true" />
<add mimeType="*/*" enabled="false" />
</staticTypes>
</httpCompression>
I am working on a c# project to register a new user in visual studio and using toad for database.The code to conect to database is:
protected void New_User(object sender, EventArgs e)
{
OleDbConnection conn;
OleDbDataAdapter OledbAdapter = new OleDbDataAdapter();
String sql = "";
conn = new OleDbConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString);
sql = "INSERT INTO USER_DETAIL VALUES('" + TextBoxUN.Text + "','" +TextBoxPass.Text+ "', '" + TextBoxEmail.Text + "','" + TextBoxmobileno.Text +"')";
try
{
conn.Open();
OledbAdapter.InsertCommand = new OleDbCommand(sql, conn);
OledbAdapter.InsertCommand.ExecuteNonQuery();
Label_success.Text = "Successfully inserted into database";
}
catch (Exception ex)
{
Label_success.Text = "Error" + ex.ToString();
}
finally
{
conn.Close();
}
}
and my web.config file is:
<?xml version="1.0"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=169433
-->
<configuration>
<connectionStrings>
<add name="ConnString" connectionString="Provider=MSDAORA;Data Source=TRGDB;Persist Security Info=True;Password=pass;User ID=TRAINEE01" providerName="System.Data.OleDb"/>
<add name="ApplicationServices"
connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnetdb.mdf;User Instance=true"
providerName="System.Data.SqlClient" />
</connectionStrings>
<system.web>
<compilation debug="true" targetFramework="4.0" />
<authentication mode="Forms">
<forms loginUrl="~/Account/Login.aspx" timeout="2880" />
</authentication>
<membership>
<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="/" />
</providers>
</membership>
<profile>
<providers>
<clear/>
<add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="ApplicationServices" applicationName="/"/>
</providers>
</profile>
<roleManager enabled="false">
<providers>
<clear/>
<add name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider" connectionStringName="ApplicationServices" applicationName="/" />
<add name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider" applicationName="/" />
</providers>
</roleManager>
</system.web>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
</configuration>
But i am getting the following error:
ErrorSystem.Data.OleDb.OleDbException (0x80004005): ORA-12504: TNS:listener was not given the SERVICE_NAME in CONNECT_DATA at System.Data.OleDb.OleDbConnectionInternal..ctor(OleDbConnectionString constr, OleDbConnection connection) at System.Data.OleDb.OleDbConnectionFactory.CreateConnection(DbConnectionOptions options, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningObject) at System.Data.ProviderBase.DbConnectionFactory.CreateNonPooledConnection(DbConnection owningConnection, DbConnectionPoolGroup poolGroup) at System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection owningConnection) at System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory) at System.Data.OleDb.OleDbConnection.Open() at Project._Default.New_User(Object sender, EventArgs e) in c:\documents and settings\admin\my documents\visual studio 2010\Projects\Project\Project\Default.aspx.cs:line 26
Your connectionstring should be like this :
Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=MyHost)(PORT=MyPort))(CONNECT_DATA=(SERVICE_NAME=MyOracleSID)));
User Id=myUsername;Password=myPassword;
Please refer : http://www.connectionstrings.com/oracle/
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.
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()
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 :)