Using Multiple Config files for a shared MVC Project - asp.net

I have an MVC application that consists of a directory with all the necessary files to run except the css and master view. In IIS, I have several sites set up that all use the same directory, but then have virtual directories set up for each site's unique css and template. This works very well, although I am now wanting to have a separate config for each unique site (for basic settings like site id to query my db, etc). I created new virtual directories for each site and added a config.xml in each, added the following to my global.asax.cs file in the application start method:
protected void Application_Start()
{
RegisterRoutes(RouteTable.Routes);
//read in all the application variables from the config file on startup
XmlDocument Doc = new XmlDocument();
Doc.Load(Server.MapPath("/Config/Config.xml"));
XmlNodeList VarLst = Doc.DocumentElement.SelectNodes("//AppVars/*");
foreach (XmlNode VarNod in VarLst)
{
RecursiveDescent(VarNod, "");
}
string[] AppVars = new string[Application.Count];
AppVars = Application.AllKeys;
//How do I now use Application.AllKeys from a controller?
}
Now, I have my keys, but can't seem to figure out how to use them in a controller. Normally, if I was using the app settings in the web config and wanted to set my siteId, I'd just use:
int siteId = Convert.ToInt16(WebConfigurationManager.AppSettings["SiteId"]);
but now I want to use
Application["SiteId"];
but it's not like a webforms code behind that inherits from the page class and I'm not getting the concept on how to get the Applications settings in an MVC controller.

As per this other question: Access "Application" object in ASP.Net MVC to store application wide variables
this.HttpContext.Application["SiteId"]

Related

Keep URL extensions

I know that removing URL extensions is the new model for website programming. Unfortunately, my site is hosted on a hybrid server configuration. The call to my site goes into an Apache server that recognizes that my call is for a .aspx page, and passes the call along to an IIS server to complete the call. This complicates my website at this point because I am coding in Visual Studio 2015, and it models after the new rules of removing the extensions, and the call is never passed along to the IIS server.
I am not a big HTML guy, and I cannot find anything to place in web.config or my global.asax file for code to tell the system to overwrite the rule of removing the extension, and to keep my extensions. I have seen several posts here to remove the extensions, but nothing to keep them.
Basically, when I call www.mysite.com/Default.aspx, the current config removes the .aspx extension, and the call is for www.mysite.com/Default. I want to KEEP the .aspx extension on the call to the site so that it passes through the Apache server and to the IIS server. Any help would be greatly appreciated.
Have a look in your App_Start directory for a class called RouteConfig.cs and disable AutoRedirectMode using this line of code
settings.AutoRedirectMode = RedirectMode.Off;
This is what automatically removes extensions from your web pages.
Full example below...
public static class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
var settings = new FriendlyUrlSettings();
settings.AutoRedirectMode = RedirectMode.Off;
routes.EnableFriendlyUrls(settings);
}
}

Dynamically created css not working on Azure website

I am working on Web Form project to deploy on production. In this project, dynamic folder is created on fly and put the new css style as per data configuration from database. This was handled by Handlers in web form. Application works locally without any error. But when I publish on production it does not find the dynamic created css file path. Its not physical exists it creates on fly. So it fails to download css and it missing all images and styles. Another team had developed this application and we are moving this from FireHost to Azure site. It was working on Firehost but no any luck on Azure site yet. I tried to remove manifest file in production by adding remove attributes .manifest in web.config. But no any luck yet. I appreciate your help Thanks
I am getting 404 errors,
Failed to load resource: the server responded with a status of 404 (Not Found)
I have the style css inject this way in site.master page.
<link href="/Styles/Dynamic/CompanySite.css" rel="stylesheet" type="text/css" />
It did not mentioned handlers in web.config. There is separate handlers folders and pages. In pages code behind file look like this in page load method.
StringBuilder sb = new StringBuilder(File.ReadAllText(Server.MapPath("~/Styles/CompanyStyles.css")));
string sPrimaryColor = "#B1D74C";
string sSecondaryColor = "#8BBB29";
string sPrimaryTextColor = "#000";
string sSecondaryTextColor = "#000";
string sBannerId = "1";
try
{
var settings = new CompanySettingDataLogic().Retrieve();
if (settings != null)
{
sPrimaryColor = settings.primary_color_txt;
sSecondaryColor = settings.secondary_color_txt;
sPrimaryTextColor = settings.primary_text_color_txt;
sSecondaryTextColor = settings.secondary_text_color_txt;
}
var BannerId = new CompanyThemeDataLogic().GetBannerId();
if (BannerId.HasValue)
sBannerId = BannerId.Value.ToString();
}
catch (Exception Ex)
{
new Data.Config.ErrorLogDataLogic().LogException(Ex);
}
sb.Replace("#PRIMARY#", sPrimaryColor);
sb.Replace("#SECONDARY#", sSecondaryColor);
sb.Replace("#PRIMARYTEXTCOLOR#", sPrimaryTextColor);
sb.Replace("#SECONDARYTEXTCOLOR#", sSecondaryTextColor);
sb.Replace("#BANNERIMAGEID#", sBannerId);
Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
Response.Cache.SetCacheability(HttpCacheability.Private);
Response.Cache.SetExpires(DateTime.Now.AddDays(2));
Response.ContentType = "text/css";
Response.Write(sb.ToString());
Its not physical exists it creates on fly. So it fails to download css
and it missing all images and styles.
Where have you stored the files after the folder being created? Do you store them in website Azure vm disk? Please note
the VM disk storage is not persistent
if you have >= 2 instances on Azure to host the web app, and then you just created the css/images files on 1 instance (VM), later your end user may hit the other instance that has no such files.
so please store your files in Azure storage - blob and use its url in your project to connect to css/image files

ASP.NET MVC thinks my virtual directory is a controller

I have a virtual directory under my MVC website in IIS called "Files". This directory is at the same level as my Views directory. When I link to a file from my MVC app to a file under my Files directory, I get the following error:
The controller for path
'/Files/Images/1c7f7eb8-5d66-4bca-a73a-4ba6340a7805.JPG'
was not found or does not implement
IController.
It thinks that my Files VD is a controller. How do I access my files like a normal VD without MVC interfering?
Thanks.
When registering routes, try to add the following Ignore rules.
public static void RegisterRoutes(RouteCollection routes)
{
/* Ignore static content, see
http://weblogs.asp.net/rashid/archive/2009/04/03/asp-net-mvc-best-practices-part-2.aspx
*/
routes.RouteExistingFiles = false;
routes.IgnoreRoute("Content/{*pathInfo}");
routes.IgnoreRoute("Scripts/{*pathInfo}");
routes.IgnoreRoute("Styles/{*pathInfo}");
routes.IgnoreRoute("{*favicon}",
new { favicon = #"(.*/)?favicon.([iI][cC][oO]|[gG][iI][fF])(/.*)?" });
//Ignore handlers and resources
routes.IgnoreRoute("{resource}.ashx/{*pathInfo}");
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
// your routes go here
}
ASP.Net looks for the directory first and then tries to match a controller, so what you are doing should work. Are you sure the file with that name exists and is accessible?
I think you'll have to add a call to routes.Ignore() a static route in your Global.asax file so that .NET MVC knows to ignore the request:
RouteCollection.Ignore(String) - MSDN

Configure IIS7 to server static content through ASP.NET Runtime

I searched high an low and still cannot find a definite answer.
How do I configure IIS 7.0 or a Web Application in IIS so that ASP.NET Runtime will handle all requests -- including ones to static files like *.js, *.gif, etc?
What I'm trying to do is as follows.
We have kind of SaaSy site, which we can "brand" for every customer. "Branding" means developing a custom master page and using a bunch of *.css and other images.
Quite naturally, I'm using VirtualPathProvider, which operates like this:
public override System.Web.Hosting.VirtualFile GetFile(string virtualPath)
{
if(PhysicalFileExists(virtualPath))
{
var virtualFile = base.GetFile(virtualPath);
return virtualFile;
}
if(VirtualFileExists(virtualPath))
{
var brandedVirtualPath = GetBrandedVirtualPath(virtualPath);
var absolutePath = HttpContext.Current.Server.MapPath(brandedVirtualPath);
Trace.WriteLine(string.Format("Serving '{0}' from '{1}'",
brandedVirtualPath, absolutePath), "BrandingAwareVirtualPathProvider");
var virtualFile = new VirtualFile(brandedVirtualPath, absolutePath);
return virtualFile;
}
return null;
}
The basic idea is as follows: we have a branding folder inside our webapp, which in turn contains folders for each "brand", with "brand" being equal to host name. That is, requests to http://foo.example.com/ should use static files from branding/foo_example_com, whereas http://bar.example.com/ should use content from branding/bar_example_com.
Now what I want IIS to do is to forward all requests to static files to StaticFileHandler, which would then use this whole "infrastructure" and serve correct files. However, try as I might, I cannot configure IIS to do this.
II7 already does that if the application pool's Managed Pipeline Mode is set to Integrated which is the default. In Integrated mode, ASP.NET handles all requests including those for static objects.
If you have to leave your application pool in Classic Mode then you need to use the same techniques you would use in IIS 6 to explicitly create handlers for the various static extensions.
Additional Information Based on Comments: I think your missing piece is creating an HttpHandler to handle the other extensions (.js, .css, etc.). Without this, then ASP.NET will use the default handling for these types of files. You would create a reference to you handler in your web.config. This article is an example of creating an HttpHandler for static files.
Kudos to everyone, but the problem was in totally different space.
VirtualPathProvider cannot be used in a pre-compiled web site. I'm furious.

How to consume different proxyclass versions (production or test) of ASMX webservice

I've got an ASMX webservice as a separate project in Visual Studio 2005. In pursuit of "assembly separation" per a CODE Magazine tutorial, my proxy class is in a separate class library project containing no code of mine - just a web reference named ASMXproxy with the associated reference.cs, app.config, .disco and .wsdl files. Thus, when compiled I have a FileServiceProxy.dll.
For consuming this WS, I have a web app project called FileServiceDemo in this same solution. It has no web reference but instead a "regular" reference to FileServiceProxy.dll. In my default.aspx.cs file, I gain access to my WS via these snippets:
using FileServiceProxy.ASMXproxy;
public partial class _Default : System.Web.UI.Page
{
ASMXproxy.FileService brokerService;
protected void Page_Load(object sender, EventArgs e)
{
try
{
brokerService = new ASMXproxy.FileService();
So while things work OK this way, I find it awkward when I want to test a deployed version or make changes to a "localhost" version. I can't simply make changes to the app.config:
<applicationSettings>
<FileServiceProxy.Properties.Settings>
<setting name="FileServiceProxy_ASMXproxy_FileService" serializeAs="String">
<value>http://localhost/TRIMBrokerService/FileService.asmx</value>
</setting>
</FileServiceProxy.Properties.Settings>
</applicationSettings>
In short, when I need to publish my web app to another server, I have to change the web reference in proxy class and rebuild it. Then when I want to debug it on my localhost, I have to change the web reference back to localhost (as above).
Ideally, I would like to expose some sort of choice (e.g. radio buttons or a textbox for altering a URL at runtime) in my web app demo project such that I could have a "late binding" of sorts for the desired FileServiceProxy.dll to be used at runtime. Others have sketched proposals "using config files" but I am stuck on how to do that. It appears to me that I would have to have an additional project and hence another DLL - perhaps FileServiceProxyPROD.dll - but this seems awkward and even then I'm not sure what else I'd have to do.
Actually, you can use the same reference. Just change the Url property of the proxy instance:
using (var svc = new WebServiceProxy())
{
svc.Url = realUrl;
var result = svc.ServiceMethod();
}

Resources