Can't use Session in InitializeCulture - c#

When I try to use a Session veriable in InitializeCulture, I get the folowing error:
Session state can only be used when enableSessionState is set to true, either in a configuration file or in the Page directive. Please also make sure that System.Web.SessionStateModule or a custom session state module is included in the \\ section in the application configuration.
This is the code where the error is thrown
public class BasePage : Page
{
public string Lang { get; set; }
protected override void InitializeCulture()
{
if (!Page.IsPostBack)
{
if (!string.IsNullOrEmpty(Request.QueryString["lang"]))
{
Session["lang"] = Request.QueryString["lang"].ToLower();
}
if (Session["lang"] != null && !string.IsNullOrEmpty((string)Session["lang"]))
{
Lang = (string)Session["lang"];
string selectedCulture = Lang == "nl" ? "nl-BE" : "fr-BE";
UICulture = selectedCulture;
Culture = selectedCulture;
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(selectedCulture);
Thread.CurrentThread.CurrentUICulture = new CultureInfo(selectedCulture);
}
base.InitializeCulture();
}
}
}
I changed my Web.Config, as sugested in the error. But It keeps throwing the same error.
<pages enableSessionState="true">
<controls>
<add tagPrefix="asp" namespace="System.Web.UI" assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
<add tagPrefix="asp" namespace="System.Web.UI.WebControls" assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
</controls>
</pages>
<httpModules>
<remove name="Session" />
<add name="Session" type="System.Web.SessionStateModule" />
<add type="Intelligencia.UrlRewriter.RewriterHttpModule, Intelligencia.UrlRewriter" name="UrlRewriter"/>
<add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
</httpModules>
Does anyone has a solution? Thanks!!!

Try to set enableSessionState=true in the pages section.
<system.web>
<pages enableSessionState="true">
</system.web>
Also, if you're using IIS7 on Windows 2008, your modules should be inside the <system.webServer> section, instead of <system.web>.

Related

httpModule in App_code will not load when debugging locally

I have a simple .net web application and implemented a class based off of IHttp. I copied the example directly from Microsoft documentation. The class is located in the app_code directory.
The problem is that whenever I run the application I get the following error:
HttpException (0x80004005): Could not load type 'httpModuleEx.App_Code.HelloWorldClass'
Here is my web.config entry to register the new class:
<system.webServer>
<validation validateIntegratedModeConfiguration="false"/>
<modules>
<remove name="ApplicationInsightsWebTracking"/>
<remove name="HelloWorldClass"/>
<add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web"
preCondition="managedHandler"/>
<add name="HelloWorldClass" type="httpModuleEx.App_Code.HelloWorldClass"/>
</modules>
</system.webServer>
I have tried many variations on referencing the HelloWorldClass here but none worked for me.
I also tried making the build action of the HelloWorldClass.cs file (located under the app_code directory) "compile".
Below is the code from the HelloWorldClass.cs file:
using System;
using System.Web;
namespace httpModuleEx.App_Code
{
public class HelloWordClass : IHttpModule
{
// In the Init function, register for HttpApplication
// events by adding your handlers.
public void Init(HttpApplication application)
{
application.BeginRequest += (new EventHandler(this.Application_BeginRequest));
application.EndRequest += (new EventHandler(this.Application_EndRequest));
}
private void Application_BeginRequest(Object source, EventArgs args)
{
HttpApplication application = (HttpApplication)source;
HttpContext context = application.Context;
string filePath = context.Request.FilePath;
string fileExtension =
VirtualPathUtility.GetExtension(filePath);
if (fileExtension.Equals(".aspx"))
{
context.Response.Write("<h1><font color=red>" +
"HelloWorldModule: Beginning of Request" +
"</font></h1><hr>");
}
}
private void Application_EndRequest(Object source, EventArgs args)
{
HttpApplication application = (HttpApplication)source;
HttpContext context = application.Context;
string filePath = context.Request.FilePath;
string fileExtension =
VirtualPathUtility.GetExtension(filePath);
if (fileExtension.Equals(".aspx"))
{
context.Response.Write("<hr><h1><font color=red>" +
"HelloWorldModule: End of Request</font></h1>");
}
}
public void Dispose()
{
}
}
}
Any help would be greatly appreciated.
Could it be because you've spelled World as Word in your code :)
Yes. Thank you! Also I changed the web.config to:
<system.webServer>
<validation validateIntegratedModeConfiguration="false"/>
<modules>
<remove name="ApplicationInsightsWebTracking"/>
<remove name="HelloWorldClass"/>
<add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web"
preCondition="managedHandler"/>
<add name="HelloWorldClass" type="httpModuleEx.App_Code.HelloWorldClass, httpModuleEx"/>
</modules>
</system.webServer>

Activation error when using Prism and Unity container

I have the following console program in which I attempt to apply the SOLID principles, dependency injection with Unity and Prism 6 modularity:
Main program:
UnityContainer container = new UnityContainer();
container.RegisterInstance<IServiceLocator>(new UnityServiceLocator(container));
container.RegisterType<IModuleInitializer, ModuleInitializer>();
TextLogger logger = new TextLogger();
container.RegisterInstance<ILoggerFacade>(logger);
ConfigurationModuleCatalog catalog = new ConfigurationModuleCatalog();
container.RegisterInstance<IModuleCatalog>(catalog);
container.RegisterType<IModuleManager, ModuleManager>();
IModuleManager manager = container.Resolve<IModuleManager>();
manager.Run();
App config file:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="modules" type="Prism.Modularity.ModulesConfigurationSection, Prism.Wpf" />
</configSections>
<modules>
<module assemblyFile="CalcCommandParsingLib.dll" moduleType="CalcCommandParsingLib.CalculatorCommandParsingModule, CalcCommandParsingLib, Version=1.0.0.0, Culture = neutral, PublicKeyToken=null" moduleName="Parsing" />
<module assemblyFile="CalculatorLibrary.dll" moduleType="CalculatorLibrary.CalculatorModule, CalculatorLibrary, Version=1.0.0.0, Culture = neutral, PublicKeyToken=null" moduleName="Calculator" />
<module assemblyFile="InputOutputLibrary.dll" moduleType="InputOutputLibrary.InputOutputModule, InputOutputLibrary, Version=1.0.0.0, Culture = neutral, PublicKeyToken=null" moduleName="InputOutput" />
<module assemblyFile="MainModuleLibrary.dll" moduleType="MainModuleLibrary.MainModule, MainModuleLibrary, Version=1.0.0.0, Culture = neutral, PublicKeyToken=null" moduleName="Main" >
<dependencies>
<dependency moduleName="Calculator" />
<dependency moduleName="Parsing" />
<dependency moduleName="InputOutput" />
</dependencies>
</module>
</modules>
</configuration>
And one of the four modules which causes the error:
public class MainModule : IModule
{
IServiceLocator serviceLocator;
public MainModule(IServiceLocator serviceLocator)
{
this.serviceLocator = serviceLocator;
}
public void Initialize()
{
ICalculatorReplLoop loop = serviceLocator.GetInstance<ICalculatorReplLoop>();
loop.Run();
}
}
The error occurs on this line:
ICalculatorReplLoop loop = serviceLocator.GetInstance<ICalculatorReplLoop>();
and it is:
An exception of type
'Microsoft.Practices.ServiceLocation.ActivationException' occurred in
Microsoft.Practices.ServiceLocation.dll but was not handled in user
code
Additional information: Activation error occurred while trying to get
instance of type ICalculatorReplLoop, key ""
Can somebody help me with this please?
I think that there are at least 2 things to change:
You should also register ICalculatorReplLoop
container.RegisterType<ICalculatorReplLoop, CalculatorReplLoop>();
It would make more sense for me to inject directly the needed interface, then to resolve it via serviceLocator so:
public MainModule(ICalculatorReplLoop calc)
{
this.calc= calc;
}

Asp.net - Remove Folder Structure From My URL

Appologise if this has already been asked but I have an asp.net website and all my footer pages are stored in Visual Studio under
Views > Footer > [Page Names]
When i click on a footer link, my URL is displaying as:
http://www.mysite.co.uk/Views/Footer/testpage
What i'm after is removing the "/Views/Footer" from the URL so it loks like:
http://www.mysite.co.uk/testpage
I have no idea how to do this. Could someone please give me step by step guide on code to use and where to put it so that it does this.
when ever i try double clicking on my Global.asax file it automatically opens the Global.asax.cs file which i suspect is also wrong
Add reference to system.web.routing to project
add urlroutingmodule to http module in config:
<configuration>
...
<system.web>
...
<httpModules>
...
<add name="UrlRoutingModule" type="System.Web.Routing.UrlRoutingModule, System.Web.Routing, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
</httpModules>
</system.web>
<system.webServer>
<validation validateIntegratedModeConfiguration="false"/>
<modules>
...
<add name="UrlRoutingModule" type="System.Web.Routing.UrlRoutingModule, System.Web.Routing, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
</modules>
<handlers>
...
<add name="UrlRoutingHandler" preCondition="integratedMode" verb="*" path="UrlRouting.axd" type="System.Web.HttpForbiddenHandler, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
</handlers>
...
</system.webServer>
</configuration>
Define routes in global.asax:
void Application_Start(object sender, EventArgs e)
{
RegisterRoutes(RouteTable.Routes);
}
void RegisterRoutes(RouteCollection routes)
{
// Register a route for Categories/All
routes.Add(
"All Categories",
new Route("Categories/All", new CategoryRouteHandler())
);
// Register a route for Categories/{CategoryName}
routes.Add(
"View Category",
new Route("Categories/{*CategoryName}", new CategoryRouteHandler())
);
// Register a route for Products/{ProductName}
routes.Add(
"View Product",
new Route("Products/{ProductName}", new ProductRouteHandler())
);
}
Create route handler classes
public class ProductRouteHandler : IRouteHandler
{
public IHttpHandler GetHttpHandler(RequestContext requestContext)
{
string productName = requestContext.RouteData.Values["ProductName"] as string;
if (string.IsNullOrEmpty(productName))
return Helpers.GetNotFoundHttpHandler();
else
{
// Get information about this product
NorthwindDataContext DataContext = new NorthwindDataContext();
Product product = DataContext.Products.Where(p => p.ProductName == productName).SingleOrDefault();
if (product == null)
return Helpers.GetNotFoundHttpHandler();
else
{
// Store the Product object in the Items collection
HttpContext.Current.Items["Product"] = product;
return BuildManager.CreateInstanceFromVirtualPath("~/ViewProduct.aspx", typeof(Page)) as Page;
}
}
}
}
create asp.net pages that process request:
protected void Page_Load(object sender, EventArgs e)
{
dvProductInfo.DataSource = new Product[] { Product };
dvProductInfo.DataBind();
}
protected Product Product
{
get
{
return HttpContext.Current.Items["Product"] as Product;
}
}
This is a good reference to work off, I have used this in the past on webforms apps and it worked like a charm.
If you're not using MVC, then you can implement an IHttpModule. There are several guides on the Internet on how to do this, such as Scott Guthrie's here: http://weblogs.asp.net/scottgu/tip-trick-url-rewriting-with-asp-net

MVC 5/ReportViewer/ASP.NET client-side AJAX errors

I'm at wits end. I'm trying to load up a ReportViewer with both valid aspx code and ReportViewerForMVC code wind up here. First, the error spread:
Uncaught SyntaxError: Unexpected token < WebResource.axd:1
Uncaught SyntaxError: Unexpected token < GetSysWideQuizReport:67
Uncaught ReferenceError: ReportViewerForMvc is not defined(anonymous
function) # GetSysWideQuizReport:67 Uncaught SyntaxError: Unexpected
token < ScriptResource.axd:1
Uncaught SyntaxError: Unexpected token < ReportViewerWebForm.aspx:40
Uncaught Error: ASP.NET Ajax client-side framework failed to
load.(anonymous function) # ReportViewerWebForm.aspx:40
ScriptResource.axd:1
Uncaught SyntaxError: Unexpected token < ScriptResource.axd:1
Uncaught SyntaxError: Unexpected token <
Reserved.ReportViewerWebControl.axd:1
Uncaught SyntaxError: Unexpected token < ScriptResource.axd:1
Uncaught SyntaxError: Unexpected token < ReportViewerWebForm.aspx:51
Uncaught ReferenceError: Sys is not defined(anonymous function) #
ReportViewerWebForm.aspx:51 ReportViewerWebForm.aspx:114
Uncaught ReferenceError: Sys is not defined ReportViewerWebForm.aspx:114
The View:
#using ReportViewerForMvc;
#using Microsoft.Reporting.WebForms;
#using App.Models;
<style>
iframe{
width:900px;
}
</style>
#{
ViewBag.Title = "LocalReportExample";
}
<h2>Local report example</h2>
#Html.ReportViewer(ViewBag.ReportViewer as Microsoft.Reporting.WebForms.ReportViewer)
Controller:
public ActionResult GetSysWideQuizReport([Bind(Include = "Topic, Date1, Date2")] QuizReporting quizParams)
{
ReportViewer reportViewer = new ReportViewer();
reportViewer.ProcessingMode = ProcessingMode.Local;
reportViewer.SizeToReportContent = true;
reportViewer.Width = Unit.Percentage(100);
reportViewer.Height = Unit.Percentage(100);
reportViewer.LocalReport.ReportPath = Request.MapPath(Request.ApplicationPath) + #"/ReportViews/System Quiz Report.rdlc";
reportViewer.LocalReport.DataSources.Add(new ReportDataSource("DataSet1", QuizData(quizParams)));
ViewBag.ReportViewer = reportViewer;
return View();
}
private DataTable QuizData(QuizReporting quizParams)
{
DataSet ds = new DataSet("DataSet1");
using(SqlConnection connection = new SqlConnection())
{
connection.ConnectionString = GetConnectionString();
SqlCommand cmd = new SqlCommand("SystemQuizReport", connection);
cmd.Parameters.AddWithValue("#TopicID", quizParams.Topic.TopicID);
cmd.Parameters.AddWithValue("#Date1", "2015/04/13");
cmd.Parameters.AddWithValue("#Date2", "2015/04/16");
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
da.Fill(ds);
return ds.Tables[0];
}
}
static private string GetConnectionString()
{
return "Data Source=(localdb)\\v11.0; Initial Catalog=LocalDb-20140822124213; Integrated Security=True;";
}
An excerpt of web.config:
<system.web>
<httpHandlers>
<add path="Reserved.ReportViewerWebControl.axd" verb="*" type="Microsoft.Reporting.WebForms.HttpHandler, Microsoft.ReportViewer.WebForms, Version=11.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" validate="false" />
</httpHandlers>
<authentication mode="None" />
<compilation debug="true" targetFramework="4.5">
<buildProviders>
<add extension=".rdlc" type="Microsoft.Reporting.RdlBuildProvider, Microsoft.ReportViewer.WebForms, Version=11.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" />
</buildProviders>
</compilation>
<httpRuntime targetFramework="4.5" />
<!--<hostingEnvironment shadowCopyBinAssemblies="false" /> -->
</system.web>
<system.webServer>
<modules>
<remove name="FormsAuthentication" />
</modules>
<validation validateIntegratedModeConfiguration="false" />
<handlers>
<add name="ReportViewerWebControlHandler" preCondition="integratedMode" verb="*" path="Reserved.ReportViewerWebControl.axd" type="Microsoft.Reporting.WebForms.HttpHandler, Microsoft.ReportViewer.WebForms, Version=11.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" />
</handlers>
</system.webServer>
I've done the following to fix it:
Made sure all Nuget packages/frameworks are up to date
Examined the console output in Chrome. It looks like the AXD files are trying to render the base home page of my application, and I don't know why.
Disabled all authorization requirements in FilterConfig and this has not worked.
I'm pulling my hair out so much with this so I hope you can help me out!

httpModules not working on iis7

I have the following module
public class LowerCaseRequest : IHttpModule {
public void Init(HttpApplication context) {
context.BeginRequest += new EventHandler(this.OnBeginRequest);
}
public void Dispose() { }
public void OnBeginRequest(Object s, EventArgs e) {
HttpApplication app = (HttpApplication)s;
if (app.Context.Request.Url.ToString().ToLower().EndsWith(".aspx")) {
if (app.Context.Request.Url.ToString() != app.Context.Request.Url.ToString().ToLower()) {
HttpResponse response = app.Context.Response;
response.StatusCode = (int)HttpStatusCode.MovedPermanently;
response.Status = "301 Moved Permanently";
response.RedirectLocation = app.Context.Request.Url.ToString().ToLower();
response.SuppressContent = true;
response.End();
}
if (!app.Context.Request.Url.ToString().StartsWith(#"http://zeeprico.com")) {
HttpResponse response = app.Context.Response;
response.StatusCode = (int)HttpStatusCode.MovedPermanently;
response.Status = "301 Moved Permanently";
response.RedirectLocation = app.Context.Request.Url.ToString().ToLower().Replace(#"http://zeeprico.com", #"http://www.zeeprico.com");
response.SuppressContent = true;
response.End();
}
}
}
}
the web.config looks like
<system.web>
<httpModules>
<remove name="WindowsAuthentication" />
<remove name="PassportAuthentication" />
<remove name="AnonymousIdentification" />
<remove name="UrlAuthorization" />
<remove name="FileAuthorization" />
<add name="LowerCaseRequest" type="LowerCaseRequest" />
<add name="UrlRewriter" type="Intelligencia.UrlRewriter.RewriterHttpModule, Intelligencia.UrlRewriter" />
<add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
</httpModules>
</system.web>
It works grate on my PC running XP and IIS 5.1
but on my webserver running IIS7 and WS 2008 dosn't works, please help I don't know how to work this out.
Thanks
On IIS7 and higher use
<configuration>
<system.webServer>
<modules>
<add name="CustomModule" type="Samples.CustomModule" />
</modules>
</system.webServer>
</configuration>
Above is correct for IIS 7.5
<modules>
<add name="CustomModule" type="Samples.CustomModule" />
</modules>
the only problem I got, is that instance of application pool for particular application should be set to managed Pipeline = Integrated, not Classic..
or:
Using Classic Mode
If your application is to use Classic mode, then make sure that your application is configured for that type of pool and your modules are configured in system.web section and not in system.webServer section of web.config file.
In IIS go to feature view select module
double click to module then right click and press (Add Managed Module)
then put name and type as defined in web.config
example:
<httpModules>
<add name="CustomModule" type="WebApplication.Security.CustomModule" />
</httpModules>

Categories