I have a HTTP Handler which does not fire. i just noticed that adding a break to my code.
The strange thing is the page where the handler is called and the HTTPhandler have the same namespaces ...
I really don't understand why ....
Did anyone face that lately ?
thanks in advance
EDIT:
My ImageHandler.ashx.cs:
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Services;
namespace Actilog.Parametre.Famille
{
/// <summary>
/// Summary description for $codebehindclassname$
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class ImageHandler : IHttpHandler
{
string strcon = ConfigurationManager.AppSettings["DB_CRACQConnectionString"].ToString();
public void ProcessRequest(HttpContext context)
{
string imageid = context.Request.QueryString["ImID"];
SqlConnection connection = new SqlConnection(strcon);
connection.Open();
SqlCommand command = new SqlCommand("select Image from Table_test where ImageID=" + imageid, connection);
SqlDataReader dr = command.ExecuteReader();
dr.Read();
context.Response.BinaryWrite((Byte[])dr[0]);
connection.Close();
context.Response.End();
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
the page where i call it:
<asp:GridView ID="gvImages" runat="server" AutoGenerateColumns="False"
CssClass="Gridview" HeaderStyle-BackColor="#7779AF"
HeaderStyle-ForeColor="white">
<Columns>
<asp:BoundField DataField="ImageName" HeaderText="Image Name" />
<asp:TemplateField HeaderText="Image">
<ItemTemplate>
<asp:Image ID="Image1" runat="server" Height="150px"
ImageUrl='<%# "ImageHandler.ashx?ImID="+ Eval("ImageID") %>' Width="150px" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
my Web.config part:
<httpHandlers>
<add path="Telerik.Web.UI.WebResource.axd" type="Telerik.Web.UI.WebResource" verb="*" validate="false" />
<remove verb="*" path="*.asmx" />
<add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
<add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
<add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
validate="false" />
<!-- ******* Register the RadUploadProgressHandler for IIS prior to v.7 ****** -->
<add path="Telerik.RadUploadProgressHandler.ashx" type="Telerik.Web.UI.RadUploadProgressHandler"
verb="*" validate="false" />
</httpHandlers>
In your web.config you should add:
<httpHandlers>
...
<add path="ImageHandler.ashx" type="Actilog.Parametre.Famille.ImageHandler"
verb="*" validate="false" />
...
</httpHandlers>
To allow Asp.Net to manage every requests containig "ImageHandler.ashx" with the correct IHttpHandler class. And remember to add:
<system.webServer>
<handlers>
...
<add name="ImageHandler" path="ImageHandler.ashx" type="Actilog.Parametre.Famille.ImageHandler"
verb="*" validate="false" />
...
</handlers>
</system.webServer>
In your production environment (if your using IIS7+).
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'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
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 :)