Call a function in Global.asax - asp.net-mvc

Is it possible to call a function in Global.asax from a class libray project which is present in the same solution?

To access the app settings in web.config from your code, just add the following code:
using System.Configuration;
...
string appVersion = ConfigurationManager.AppSettings["AppVersion"];
It assumes, your web.config contains the following section:
<appSettings>
<add key="AppVersion" value="1.0.1"/>
</appSettings>
If the System.Configuration namespace is not known, then you have to add a reference to System.Configuration.

Related

Session Variable not accessible in a partial class

I have a asp.net mvc application and everything seems to be working fine on my Development machine however when I try to deploy and run the application on a server it gives me the following error:
System.NullReferenceException: Object reference not set to an instance of an object.
This happens on this line of code. All I am trying to do is set a value in the session.
I have this code inside a partial class of the Controller.
public partial class HomeController : BaseController
{
public ActionResult Index(string Value)
{
System.Web.HttpContext.Current.Session["Test"] = "world";
return View();
}
}
Thanks that led me to find solution here:
Solution 1 from ASP.NET MVC - Session is null worked for me.
"
Solution 1:
Link: HttpContext.Current.Session is null when routing requests
Got it. Quite stupid, actually. It worked after I removed & added the SessionStateModule like so:
<configuration>
...
<system.webServer>
...
<modules>
<remove name="Session" />
<add name="Session" type="System.Web.SessionState.SessionStateModule"/>
...
</modules>
</system.webServer>
</configuration>
Simply adding it won't work since "Session" should have already been defined in the machine.config.
Now, I wonder if that is the usual thing to do. It surely doesn't seem so since it seems so crude..."

HttpHandler not working

I am trying to integrate the FileUpload project from vid.ly to my web application which is in MVC ASP .NET 4 framework using Razor engine.
I have an HttpHandler under App_Code.
Progress.cs
public class Progress : IHttpHandler
{
...
}
I added this in RegisterRoutes() called from Globals.asax:
routes.IgnoreRoute("Progress.progress");
And added these lines in system.web section in web.config:
<httpHandlers>
<add verb="*" path="*.progress" type="MyNamespace.Progress"/>
</httpHandlers>
When I try to open http://localhost:39234/Progress.progress, I get a HTTP Error 404.0 - Not Found error with below detailed information:
Requested URL http://localhost:39234/Progress.progress
Physical Path c:\users\xxxxx\documents\visual studio 2012\Projects\SolutionName\ProjectName\Progress.progress
Seems like something is wrong with the mapping. Does anyone have any idea what I'm missing?
I finally figured out what the problem was. I had to put the mappings in system.webServer section in this format:
<add name="Progress" verb="*" path="*.progress" type="MyNamespace.Progress,MyNamespace"/>
Or, set the Action Build Path to "Content" for the Progress.cs files so that it doesn't get compiled in the MyNamespace.dll

SignalR error with MVC

I have a class called Startup
this is the class
[assembly: OwinStartup(typeof(MyApp.Startup))]
namespace MyApp
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.MapSignalR();
}
}
}
but it never runs and always give me this error
The following errors occurred while attempting to load the app.
- No assembly found containing an OwinStartupAttribute.
- No assembly found containing a Startup or [AssemblyName].Startup class.
To disable OWIN startup discovery, add the appSetting owin:AutomaticAppStartup with a value of "false" in your web.config.
To specify the OWIN startup Assembly, Class, or Method, add the appSetting owin:AppStartup with the fully qualified startup class or configuration method name in your web.config.
I have also tried to add these values in web.config but it still gives me erorr
<appSettings>
<add key="owin:AppStartup" value="MyApp.Startup, MyApp" />
<add key="owin:AutomaticAppStartup" value="true" />
</appSettings>
Please check the Startup.cs property whether is content type or compile type. The code which you have given should work fine. Just right click the file in visual studio and check properties for compile or content type. Also let me know if you are getting any compile time error.

ASP.NET MVC IgnoreRoute method doesn't work correctly when URL starts with "/Views/"

I use ASP.NET MVC in my application.
Users can specify their own images, styles, scripts by including them on the page.
But when they specify URL to the file which not exists then routing mechanism tries to find controller and action by URL to image or styles etc.
I've added a method IgnoreRoute and specified there all extensions I don't want to handle by routing.
It works correctly until URL doesn't starts with "Views/...".
In this case URL passes into application and executes error 404 inside of application.
But I want to handle this error with IIS.
This can be tested with empty project.
You can simply use this code for Global.asax.cs file:
using System;
using System.Web.Mvc;
using System.Web.Routing;
namespace MvcApplication1
{
public class MvcApplication : System.Web.HttpApplication
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.IgnoreRoute(
"{*staticfile}",
new { staticfile = #".*\.(jpg|gif|jpeg|png|js|css|htm|html|htc)$" }
);
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = "" } // Parameter defaults
);
}
protected void Application_Start()
{
RegisterRoutes(RouteTable.Routes);
}
void Application_Error(object sender, EventArgs e)
{
}
}
}
Now we need to host this application at IIS, for example at http://localhost/testmvc/
You can place a break-point inside of Application_Error method to see when error executes inside of application
So now open test URL:
http://localhost/testmvc/test.css
We can see that IIS handled that error:
Now we open another test URL with "/Views/..." in the path:
http://localhost/testmvc/Views/test.css
And we see that error was handled by ASP.NET:
So the question is: maybe there exists some setting to tell MVC to not handle URL with "Views" in the path?
MVC by default will not allow you to directly address items under the /Views folder because of the mapping of all file types to the System.Web.HttpNotFoundHandler.
To get around this change your definition in your /Views/web.config to tell it to ignore basically everything else in that location
<add path="*.cshtml" verb="*" type="System.Web.HttpNotFoundHandler"/>
I wrote up a blog entry based on this since IIS 6 is different than 7 if you want to include multiple file types. See:
http://completedevelopment.blogspot.com/2011/06/using-views-outside-of-views-or-other.html
Here are my way :
1- Make a new folder in Views folder, eg. myFolder
2- Add your static page into this new folder, eg. filename.cshtml
3- Copy the web.config file from "Views" folder and paste it to the new folder you just
created (myFolder)
4- In the new web.config Replace
this :
<add path="*.*" verb="*" type="System.Web.HttpNotFoundHandler"/>
with this :
<add path="*.*" verb="*" type="System.Web.DefaultHttpHandler"/>
5- delete these line if you found it :
<remove name="BlockViewHandler"/>
<add name="BlockViewHandler" path="*" verb="*" preCondition="integratedMode" type="System.Web.HttpNotFoundHandler" />
Resault :
Now any file in this folder will work without routing!

MVC view can't find my extension method

I've created an extension method:
namespace MyComp.Web.MVC.Html
{
public static class LinkExtensions
{
public static MvcHtmlString ActionImageLink(this HtmlHelper htmlHelper, string linkText, string imageSource, string actionName)
{
...
}
}
}
I've referenced the assembly from my mvc app, and I've tried importing the namespace in my view:
<%# Import Namespace="MyComp.Web.Mvc.Html" %>
and I've also added it to the web config file:
<pages>
<controls>
...
</controls>
<namespaces>
<add namespace="System.Web.Mvc"/>
<add namespace="System.Web.Mvc.Ajax"/>
<add namespace="System.Web.Mvc.Html"/>
<add namespace="System.Web.Routing"/>
<add namespace="System.Linq"/>
<add namespace="System.Collections.Generic"/>
<add namespace="MyComp.Web.Mvc.Html"/>
</namespaces>
</pages>
In My view if I try to access Html.ActionImageLink I get an error saying that System.Web.Mvc.HtmlHelper does not contain a definition for ActionImageLink accepting a first argument type of System.Web.Mvc.HtmlHelper. I don't see any of the ActionLink extension methods for System.Web.Mvc.HtmlHelper, only for System.Web.Mvc.HtmlHelper, so how does it work for the .net framework, and not for me?
Notice the difference in the case of your namespace when declaring and when importing.
namespace MyComp.Web.MVC.Html
{
}
<%# Import Namespace="MyComp.Web.Mvc.Html" %>
<add namespace="MyComp.Web.Mvc.Html"/>
Namespaces are case-sensitive!
You must add the namespace in the web.config but in the one inside the Views Folder
Try shutting down Visual Studio and opening your Solution again. When things start acting weird, some times this helps.
Close and reopen Visual Studio did the trick!!
Does the VS intellisense autocompletes your extension method? Does it autocompletes standard MVC helpers methods? If not then the view complilation error occured. Make sure you have the proper "Inherits" attribute value in Page tag at the beginning of the view. If you use strongly typed views make sure the "strong type" exists and compiles.
Do you define the extension method in the same project where the view is defined? If not you have to add the reference in the mvc project. Finally check if the assembly with the extension method (MyComp.Web.Mvc.Html.dll?) is in the Bin folder of the application
Try to add the namespace declaration to the pages/namespaces section of the web.config file placed in your Views folder in MVC project (not the main project web.config file).
One of the reasons may be you are returning a MvcHtmlString and not a string.
Include the namespace for class MvcHtmlString. See if it helps.

Resources