Response GZIP Compression not working .net - c#

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>

Related

WCF - 'System.IO.Compression.GZipStream' cannot be serialized

I am using a WCF cloud service (Azure) to accept a compressed (GZIP) JSON POST request.
My class
[DataContract]
[ServiceBehavior(AddressFilterMode = AddressFilterMode.Any)]
public class Omni : IOmnivore
{
public async Task<System.Net.HttpStatusCode> GetOmnisJson(GZipStream inputJsonStream)
{
JsonSerializer ser = new JsonSerializer();
using (var decompressor = new GZipStream(inputJsonStream, CompressionMode.Decompress))
using (var sr = new StreamReader(decompressor))
using (var jsonTextReader = new JsonTextReader(sr))
{
JObject jsonObj = (JObject)ser.Deserialize(jsonTextReader);
// extract necessary info
string dataType = (string)jsonObj["data_type"];
string dataTypeEvent = (string)jsonObj["event"];
My interface
[ServiceContract]
public interface IOmnivore
{
[OperationContract]
[WebInvoke(UriTemplate = "/PostOmnis",
Method = "POST",
BodyStyle = WebMessageBodyStyle.Bare,
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json)]
Task<System.Net.HttpStatusCode> GetOmnisJson(GZipStream json);
My web.config (HTTP compression part)
Not sure this is really needed in the web.config. This is WCF hosted on Azure, not sure about the dll part under <httpCompression><scheme dll> part..:
<system.webServer>
<httpCompression>
<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/json" 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>
<urlCompression doStaticCompression="true" doDynamicCompression="true" />
Having an argument of GZipStream type (since the input JSON is GZIPPed) gives a runtime error:
'System.IO.Compression.GZipStream' cannot be serialized. Consider
marking it with the DataContractAttribute attribute.
My class is already marked as a [DataContract] but I see no different outcome.
Any ideas?
This issue is because the GZipStream class is not marked as Serializable or with a DataContractAttribute.
Unless you have access to & can modify the source of the GZipStream class, you will not be able to pass any instance of the GZipStream class to a WCF ServiceContract.

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!";
}
}

URL Rewriting is showing 404 Error after Upgrading Framework from 2.0 to 4.0

I have just change framework of my website from 2.0 to 4.0. And I am getting error HTTP Error 404.0 - Not Found whenever I try to open URL Rewriting webpage.
It was working fine at a time of Framework 2.0, don't know what is the wrong now. I have google many things but din't get any proper solution.
Please help me to solve the problem.
My Code is as below :
http://www.theprojectjugaad.com/PlacementAssistance.html -> Not Working
http://www.theprojectjugaad.com/PlacementAssistance.aspx -> Working
Global.asax :
void Application_Start(object sender, EventArgs e)
{
RegisterRoutes();
}
void Application_BeginRequest(object sender, EventArgs ex)
{
if (!Request.Url.Host.Equals("localhost")
&& !Request.Url.Host.ToString().Contains("www.theprojectjugaad.com")
&& Request.Url.Host.ToString().Contains("theprojectjugaad.com"))
{
string Result = string.Concat(
"http://",
Request.Url.Authority.Replace("theprojectjugaad.com", "www.theprojectjugaad.com"),
HttpContext.Current.Response.ApplyAppPathModifier(Request.Path),
Request.Url.Query);
HttpContext.Current.Response.Redirect(Result, true);
}
}
private static void RegisterRoutes()
{
System.Web.Routing.RouteTable.Routes.Add(
"PlacementAssistance", new System.Web.Routing.Route("PlacementAssistance.html",
new RouteHandler("~/PlacementAssistance.aspx")));
}
RouteHandler.cs :
public RouteHandler(string virtualPath)
{
_virtualPath = virtualPath;
}
public IHttpHandler GetHttpHandler(RequestContext requestContext)
{
var display = BuildManager.CreateInstanceFromVirtualPath(
_virtualPath, typeof(Page)) as IDisplay;
return display;
}
string _virtualPath;
IDisplay.cs :
public interface IDisplay : IHttpHandler
{
}
web.config :
<system.webServer>
<modules runAllManagedModulesForAllRequests="true">
<remove name="Session" />
<add name="Session" type="System.Web.SessionState.SessionStateModule" preCondition="" />
</modules>
<validation validateIntegratedModeConfiguration="false" />
<handlers>
<remove name="UrlRoutingHandler" />
</handlers>
<rewrite>
<rules>
<remove name="Plesk. SEO-safe redirect for http://www.theprojectjugaad.com" />
<rule name="Plesk. SEO-safe redirect for http://www.theprojectjugaad.com" enabled="false" patternSyntax="Wildcard" stopProcessing="true">
<match url="*" />
<conditions>
<add input="{HTTP_HOST}" pattern="www.theprojectjugaad.com" />
<add input="{HTTPS}" pattern="OFF" />
</conditions>
<serverVariables />
<action type="Redirect" url="http://theprojectjugaad.com/{R:1}" />
</rule>
</rules>
</rewrite>
</system.webServer>
What is the URL that is not working?
What I see is you've corrected the URL from .html to .aspx and it works.

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