Problem Using the System.Web.Caching.Cache Class in ASP.NET - asp.net

So I am working on a project which uses ASP.NET. I am trying to call Cache["key"] but the compiler complains about how System.Web.Caching.Cache is "nat valid at this point".
If I call Cache obj = new Cache(); the obj is always null.
I can access HttpContext.Current.Cache - but this doesnt let me specify an absolute expiration and sliding expiration in the Insert() method.
Can someone help me?

You should be able to absolute or sliding expiration calling the insert on HttpRuntime.Cache. It has several overloads. Ex:
HttpRuntime.Cache.Insert("EXAMPLE_KEY",
exampleItem,
Nothing,
DateTime.Now.AddHours(1),
System.Web.Caching.Cache.NoSlidingExpiration);
The exact same code should also work with HttpContext.Current.Cache.

I suggest you to try PCache class under PokeIn library. Even if you use FREE edition of that library, there is no limitation with this class. It has many more functionalities in comparison to ASP.NET Cache class and you dont have to deal with these problems. there is a simple sample project available on the web site.

Related

best approach to implement getRealPath()

I am working on struts 2.0 . I am designing a web application.
I am using Jasper Report in my application. I want to access the *.jrxml files in my action class. I don't want to give hard coded path to the files. So to get the path dynamically I googled it and got the solution that I can get the path using getRealPath() method. But I found two implementation of doing this:
Using HttpSession to get object of ServletContext and using the getRealPath() method of the ServletContext object.
Like this:
HttpSession session = request.getSession();
String realPath = session.getServletContext().getRealPath("/");
The second approach to do it directly using the static method getServletContext() of ServletActionContext. And then we can get the real path of the application using the getRealPath() method.
Like this:
String realPath = ServletActionContext.getServletContext().getRealPath("/");
Please tell me, is there any difference between the above two and also please tell me whether there is any other way to get the path?
Neither is "better", really, and I'd argue that neither is particularly good, either.
I might try getting the context path in an initialization servlet and stick it into the application context, then make your action(s) ApplicationAware and retrieve the value from the map.
This has the added benefit of aiding testability and removing the static references in the action.
That said, I see zero reason to go through the extra mechanics of your first approach: it adds a lot of noise for no perceivable benefit; I'm not even sure why it wuld be considered.
I'd also be a little wary of tying your actions to a path like this unless there's a real need, what's the specific use? In general you shouldn't need to access intra-app resources by their path.

How do I access GetGlobalResourceObject function from a class that is not a page?

I have a class in my asp.net proj, I would like to get access GetGlobalResourceObject (that page exposes), from anywhere in the site, possible?
In other words I wanna access the global resources from a class that is not a page I don't care how.
Answer:
Yes, as following pseudo:
Resources.<The name of the resources file name>.<your resource key>;
Example:
lblTitle.Text = Resources.MySettings.WebsiteTitle;
Resources is an Visual-Studio auto generated namespace that exposes all the global resource classes and props in the project.
You should use
HttpContext.GetGlobalResourceObject("myResourceKey")
...because that way it will still work when using a custom ResourceProvider. The default type-generator for Resource files explicitely uses the Resx provider and won't work if you implement something like a database provider.
On some farms you'll need to wrap the call to
HttpContext.GetGlobalResourceObject("myResourceKey")
inside a try/catch block to get it over the "Could not find any resources appropriate for the specified culture or the neutral culture" error.
If you are in the site you have access to HttpContext and can use:
HttpContext.GetGlobalResourceObject("myResourceKey")
I kinda took this from the resource designer,
ResourceManager temp =
new ResourceManager("Resources.<<resource name>>",
System.Reflection.Assembly.Load("App_GlobalResources"));

Using a dictionary object in application scope in Classic ASP

Following up from my last question does anyone know how I can use a dictionary object in application scope in Classic ASP? You cannot use Scripting.Dictionary - if you try you will see something similar to the following:
Application object error 'ASP 0197 : 80004005'
Disallowed object use /xxx.asp, line 2. Cannot add object with apartment model behavior to the application intrinsic object.
I found this article on (good ol') 4GuysFromRolla but it points to Microsoft's free Lookup Component and a free Dictionary Component from Caprock Consulting - both of which are dead links.
The article clearly explains why you can't use the Scripting.Dictionary in application scope, but I was wondering if anyone knew of a free alternative or where I might find a copy of the old components that 4GuysFromRolla mentioned?
I was able to download the Dictionary Component from Caprock Consulting using this link: http://web.archive.org/web/20000619122506/http://www.caprockconsulting.com/data/CaprockDCT.zip
I have the LookupTable-component and can provide it to you if interested.
However, I have notived that you can use .NET HashTable in application-scope which might be useful for you.
just do this:
<object id="YOUR_VAR_NAME" progid="System.Collections.HashTable" runat="Server" scope="Application"></object>
this will give you a global, application-wide HashTable-object.
Beware of modifying this to heavily though, I have problems with memoryleaks where eventually the applications session-handling gets unreliable (doesn't invoke SessionStart properly)
i had the same issue and ended up feeding the application variable with the content of my dictionary and added
for each obj in application.Contents
if Left(obj,6) = "urlLog" then
application.Contents.Remove(obj)
end if
next
to kill all the application variables in the global.asa on application.end ( you could also use the Application.Contents.RemoveAll but i heard there was som issue with it leaving some variable up and causing memory leak even tho i could net find any solid source to prove it ...
anyway is the Caprock dictionary working for you ?

ASP.NET Localized web site -- updating on the fly

I think I have a solution to this, but is there a better way, or is this going to break on me?
I am constructing a localized web site using global/local resx files. It is a requirement that non-technical users can edit the strings and add new languages through the web app.
This seems easy enough -- I have a form to display strings and the changes are saved with code like this snippet:
string filename = MapPath("App_GlobalResources/strings.hu.resx");
XmlDocument xDoc = new XmlDocument();
XmlNode xNode;
xDoc.Load(filename);
xNode = xDoc.SelectSingleNode("//root/data[#name='PageTitle']/value");
xNode.InnerText = txtNewTitle.Text;
xDoc.Save(filename);
Is this going to cause problems on a busy site? If it causes a momentary delay for recompilation, that's no big deal. And realistically, this form won't see constant, heavy use. What does the community think?
I've used a similar method before for a very basic "CMS". The site wasn't massively used but it didn't cause me any problems.
I don't think changing a resx will cause a recycle.
We did something similar, but used a database to store the user modified values. We then provided a fallback mechanism to serve the overridden value of a localized key.
That said, I think your method should work fine.
Have you considered creating a Resource object? You would need to wrap your settings into a single object that all the client code would use. Something like:
public class GuiResources
{
public string PageTitle
{
get return _pageTitle;
}
// Fired once when the class is first created.
void LoadConfiguration()
{
// Load settings from config section
_pageTitle = // Value from config
}
}
You could make it a singleton or a provider, that way the object is loaded only one time. Also you could make it smart to look at the current thread to get the culture info so you know what language to return.
Then in your web.config file you can create a custom section and set restartOnExternalChanges="true". That way, your app will get the changed when they are made.

Is there any way to use XmlSiteMapProvider within WinForm/Console/VSTest application?

I wonder whether there is a workaround for using the standard XmlSiteMapProvider within a non asp.net application, like WinForm/Console or, in my case, VS Unit Test one.
The following code fails, because it cannot create a path to the .sitemap file inside a private GetConfigDocument method.
XmlSiteMapProvider provider = new XmlSiteMapProvider();
NameValueCollection providerAttributes = new NameValueCollection();
providerAttributes.Add("siteMapFile", "Web.sitemap");
provider.Initialize("XmlSiteMapReader", providerAttributes);
provider.BuildSiteMap();
I feel the right solution is to write another provider.
I do not see why not. It is just a provider that implements an interface. You may not need many of the features, but you can access the API for what it provides you. Your WinForms screens can simply use the Urls for identification so that you can determine your place in the hierarchy.
What you may have to do is create a custom implementation of the provider because it will use the HttpContext to get the Url of the current web request to identify current placement while you will need to get that value differently. That is what could be tricky because your WinForm application could be displaying multiple windows at time. If you know there is only one window showing at a time you could use a static value which is set prior to accessing the SiteMap API.
Now you have to question the value of using an API if you have to do all of the work. There may not be enough benefit to make it worthwhile.

Resources