Create a cache dependancy on a folder and its sub-folder - asp.net

In ASP.NET I would like to store an object in the cache which has a dependancy on all the files in specific folder and its sub-folders. Just adding the object with a dependancy on the root folder doesn't work. Is there in any reasonable way to do this other than creating a chain of dependancies on all the files?

I believe you can roll your own cache dependency and use FileSystemMonitor to monitor the filesystem changes.
Update: Sample code below
public class FolderCacheDependency : CacheDependency
{
public FolderCacheDependency(string dirName)
{
FileSystemWatcher watcher = new FileSystemWatcher(dirName);
watcher.Changed += new FileSystemEventHandler(watcher_Changed);
watcher.Deleted += new FileSystemEventHandler(watcher_Changed);
watcher.Created += new FileSystemEventHandler(watcher_Changed);
watcher.Renamed += new RenamedEventHandler(watcher_Renamed);
}
void watcher_Renamed(object sender, RenamedEventArgs e)
{
this.NotifyDependencyChanged(this, e);
}
void watcher_Changed(object sender, FileSystemEventArgs e)
{
this.NotifyDependencyChanged(this, e);
}
}

Related

How to reload apache commons configurations2 properties

can anyone guide me on how to perform a reload of an apache commons configuration2 properties. I'm unable to find any implementation of this anywhere. The apache docs are a bit too abstract. This is what I have so far but it's not working.
CombinedConfiguration cc = new CombinedConfiguration();
Parameters params = new Parameters();
File configFile = new File("config.properties");
File emsFile = new File("anotherconfig.properties");
ReloadingFileBasedConfigurationBuilder<FileBasedConfiguration> configBuilder =
new ReloadingFileBasedConfigurationBuilder<FileBasedConfiguration>(PropertiesConfiguration.class)
.configure(params.fileBased()
.setFile(configFile));
PeriodicReloadingTrigger reloadTrg = new PeriodicReloadingTrigger(configBuilder.getReloadingController(), null, 5, TimeUnit.SECONDS);
reloadTrg.start();
cc.addConfiguration(configBuilder.getConfiguration());
FileBasedConfigurationBuilder<FileBasedConfiguration> emsBuilder =
new FileBasedConfigurationBuilder<FileBasedConfiguration>(PropertiesConfiguration.class)
.configure(params.properties()
.setFile(emsFile));
cc.addConfiguration(emsBuilder.getConfiguration());
DataSource ds = EmsDataSource.getInstance().getDatasource(this);
BasicConfigurationBuilder<DatabaseConfiguration> dbBuilder =
new BasicConfigurationBuilder<DatabaseConfiguration>(DatabaseConfiguration.class);
dbBuilder.configure(
params.database()
.setDataSource(ds)
.setTable("EMS_CONFIG")
.setKeyColumn("KEY")
.setValueColumn("VALUE")
);
cc.addConfiguration(dbBuilder.getConfiguration());
The configuration obtained from a builder is not updated automatically. You need to get the configuration from the builder every time you read it.
From Automatic Reloading of Configuration Sources:
One important point to keep in mind when using this approach to reloading is that reloads are only functional if the builder is used as central component for accessing configuration data. The configuration instance obtained from the builder will not change automagically! So if an application fetches a configuration object from the builder at startup and then uses it throughout its life time, changes on the external configuration file become never visible. The correct approach is to keep a reference to the builder centrally and obtain the configuration from there every time configuration data is needed.
use following code:
#Component
public class ApplicationProperties {
private PropertiesConfiguration configuration;
#PostConstruct
private void init() {
try {
String filePath = PropertiesConstants.PROPERTIES_FILE_PATH;
System.out.println("Loading the properties file: " + filePath);
configuration = new PropertiesConfiguration(filePath);
//Create new FileChangedReloadingStrategy to reload the properties file based on the given time interval
FileChangedReloadingStrategy fileChangedReloadingStrategy = new FileChangedReloadingStrategy();
fileChangedReloadingStrategy.setRefreshDelay(PropertiesConstants.REFRESH_DELAY);
configuration.setReloadingStrategy(fileChangedReloadingStrategy);
} catch (ConfigurationException e) {
e.printStackTrace();
}
}
public String getProperty(String key) {
return (String) configuration.getProperty(key);
}
public void setProperty(String key, Object value) {
configuration.setProperty(key, value);
}
public void save() {
try {
configuration.save();
} catch (ConfigurationException e) {
e.printStackTrace();
}
}
}

How can I programmatically stop the current website? [duplicate]

This question already has answers here:
How can I programmatically stop or start a website in IIS (6.0 and 7.0) using MsBuild?
(3 answers)
Closed 7 years ago.
I am using the MVC5 for an web application. The web app runs in IIS7 or greater.
In the Global.asax on application_start, the number of licenses will be set:
protected void Application_Start()
{
try
{
MyApp.cNumberOfLicenses = COM.GetNumberOfLicenses();
}
catch(Exception e)
{
// log exception
// stop web site.
}
}
If any expection will be thrown in this context, the web site should shut down as you can do that in the IIS-Manager:
How can I stop the current web site in my Application_Start ?
You can do it with the help of "Microsoft.Web.Administration.dll"
using Microsoft.Web.Administration;
After adding the reference of "Microsoft.Web.Administration.dll" write below code in Global.asax
protected void Application_Start(object sender, EventArgs e)
{
try
{
MyApp.cNumberOfLicenses = COM.GetNumberOfLicenses();
}
catch (Exception e)
{
// get the web site name
var lWebSiteName = System.Web.Hosting.HostingEnvironment.ApplicationHost.GetSiteName();
// log exception
// stop web site.
using (ServerManager smg = new ServerManager())
{
var site = smg.Sites.FirstOrDefault(s => s.Name == lWebSiteName);
if (site != null)
{
//stop the site...
site.Stop();
}
}
}
}
I will go not with stop it, but to show some message if you do not have license.
This is an example, and an idea.
You can use this code on global.asax where if you do not have licenses the moment you start, you open a flag, and after that you do not allow any page to show, and you send a page that you can keep on an html file.
private static bool fGotLicense = true;
protected void Application_Start()
{
try
{
MyApp.cNumberOfLicenses = COM.GetNumberOfLicenses();
}
catch(Exception e)
{
// log exception
// stop web site.
fGotLicense = false;
}
}
protected void Application_BeginRequest(Object sender, EventArgs e)
{
HttpApplication app = (HttpApplication)sender;
// if not have license - let show some infos
if (!fGotLicens)
{
// the file we look now is the app_offline_alt.htm
string cOffLineFile = HttpRuntime.AppDomainAppPath + "app_offline_alt.htm";
// if exist on root
if (System.IO.File.Exists(cOffLineFile))
{
using (var fp = System.IO.File.OpenText(cOffLineFile))
{
// read it and send it to the browser
app.Response.Write(fp.ReadToEnd());
fp.Close();
}
}
// and stop the rest of processing
app.Response.End();
return;
}
}
You can have a file named app_offline.htm with content say This website is offline now in web server and copy that to root directoy of website you want for any event.
It will directly show that message, but yes, App pool will be still ON, when you need to start , you just need to rename that to something else.

Using custom virtual paths

I'm making a test solution with just 2 or 3 pages organized in folders like this:
And when I run the app I get an url like this:
There is any way to maintain that Physical Path but having a different virtual path like
http://localhost:40300/Index.aspx
without the odd word "Views"?
Take a look at the URL Rewrite module for IIS. As an alternative, you can create a custom HTTP module that will rewrite the virtual path appropriately:
public class MyRewriteHttpModule : IHttpModule
{
// ...
public void Init(HttpApplication app)
{
app.AuthenticateRequest += Application_AuthenticateRequest;
}
private void Application_AuthenticateRequest(object sender, EventArgs e)
{
var app = sender as HttpApplication;
var path = app.Request.Url.PathAndQuery;
if (!path.StartsWith("/Views/", StringComparison.OrdinalIgnoreCase))
app.Context.RewritePath("/Views/" + path);
}
}

Server.MapPath - Could not find a part of the path in ASP.net

I am uploading a file to my server using Server.MapPath
When I run my code I get the following error
Could not find a part of the path
'C:\inetpub\wwwroot\wss\VirtualDirectories\80\SitePages\uploads\ABI
Employee List.xlsx'.
So Yes, I dont have that directory on my server. I only have a directory up to here.
'C:\inetpub\wwwroot\wss\VirtualDirectories\80\
So, I go and create Those directories.
The weird thing is, is that if I create a folder with the name "SitePages" in the above directory, my site doesn't even want to start up? Delete it and it works again. (Image of error below)
I need to create that directory to upload the file to my server, but I can't, since everything breaks. How will i fix this?
create a directory in root eg. 'Foldername' and try the following
DirectoryInfo dir = new DirectoryInfo(HttpContext.Server.MapPath("~/Foldername/"));
if (!dir.Exists)
{
dir.Create();
}
// this makes sure that directory has been created
// do other stuff
You have create one folder name manually in virtual directory and try this code:
public static string GetPath()
{
string Path = string.Empty;
try
{
Path = HttpContext.Current.Server.MapPath("~/FolderName/");
}
catch (Exception _e)
{
}
return Path;
}
try to create the desired folder at runtime.
you can create a directory by
if(!Directory.Exists("YourDirectory"))
{
Directory.CreateDirectory("YourDirectory")
}
create a directory in root eg. 'Images' and try the following
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
FileUpload1.SaveAs(Server.MapPath("~\\Images\\" + FileUpload1.FileName));
}

IIS 6, html file/extension, urlrewriting

I use url rewriting on my site (ASP.NET 4.0 / IIS6), instead of aspx I use html. Everything like described here: IIS 6 executing html as aspx . Problem is that when I have any real .html file (html file exists in the site folder) on the site it doesn't open in web-browser. Is it way to resolve this? Thanks!
You can use a custom httpmodule like this:
public class CheckRealHtmlFile : System.Web.IHttpModule
{
public void Dispose()
{
}
public void Init(System.Web.HttpApplication context)
{
context.BeginRequest += new EventHandler(context_BeginRequest);
}
void context_BeginRequest(object sender, EventArgs e)
{
System.Web.HttpApplication app = sender as System.Web.HttpApplication;
if (app != null)
{
System.Text.RegularExpressions.Regex rHtml = new System.Text.RegularExpressions.Regex(#"\.html$", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
if (rHtml.IsMatch(app.Context.Request.Url.AbsolutePath) && !System.IO.File.Exists(app.Context.Server.MapPath(app.Context.Request.Url.AbsolutePath)))
{
//Execute your html -> aspx logic
}
else
return;
}
else
return;
}
}

Resources