How to cache in ASP.NET? - c#

I have some commonly used data that I would like to load from my database and cache during Application_Start in my global.asax file. I've been reading MSDN's article on caching, but I'm a bit confused on the proper way to do this.
They example they give to insert data into cache is below:
Cache.Insert("CacheItem2", "Cached Item 2");
So I added the following to my global.asax:
using System.Web.Caching;
...
Cache.Insert("audioVariables", audioVariables);
But this throws, An object reference is required..... Ok, fine - so I created an instance of the Cache class like so in Application_start:
Cache c = new Cache();
c.Insert("audioVariables", audioVariables);
When I call Insert it throws a An unhandled exception of type 'System.NullReferenceException' occurred in System.Web.dll error.
What is the proper way for me to insert an object into cache on Application_Start?
UPDATE:
Stack trace -
[NullReferenceException: Object reference not set to an instance of an
object.] System.Web.Caching.Cache.Insert(String key, Object value)
+66 MyVerbalInk.MvcApplication.Application_Start() in c:\inetpub\VerbalInk2.0\MyVerbalInk\Global.asax.cs:26
[HttpException (0x80004005): Object reference not set to an instance
of an object.]
System.Web.HttpApplicationFactory.EnsureAppStartCalledForIntegratedMode(HttpContext
context, HttpApplication app) +9935033
System.Web.HttpApplication.RegisterEventSubscriptionsWithIIS(IntPtr
appContext, HttpContext context, MethodInfo[] handlers) +118
System.Web.HttpApplication.InitSpecial(HttpApplicationState state,
MethodInfo[] handlers, IntPtr appContext, HttpContext context) +172
System.Web.HttpApplicationFactory.GetSpecialApplicationInstance(IntPtr
appContext, HttpContext context) +336
System.Web.Hosting.PipelineRuntime.InitializeApplication(IntPtr
appContext) +296
[HttpException (0x80004005): Object reference not set to an instance
of an object.] System.Web.HttpRuntime.FirstRequestInit(HttpContext
context) +9913572
System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context)
+101 System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest
wr, HttpContext context) +254

You probably want to have a read of this article:
http://www.asp.net/web-forms/overview/data-access/caching-data/caching-data-at-application-startup-cs
However, the gist of the problem is that in II7 or greater running in Integrated mode, there is no HttpContext available in Application_Start(). You have to use `HttpRuntime.Cache.Insert()' rather than Cache, or HttpContext.Current.Cache

Related

Webapi call is throwing an exception

I have hosted an asp.net webapi project in IIS.The api calls to this project throws an error as mentioned below. The same webapi call works fine when the project is hosted into IIS of another webserver.
[RoutePrefix("api/datacc")]
public class DataAccessController : ApiController
{
[HttpGet]
[Route("")]
public int HeartBeat()
{
return 1;
}
}
Error
*[ReflectionTypeLoadException: Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.]
System.Reflection.RuntimeModule.GetTypes(RuntimeModule module) +0
System.Reflection.RuntimeModule.GetTypes() +9
System.Reflection.Assembly.GetTypes() +61
FluentNHibernate.AssemblyTypeSource.GetTypes() in c:\work\coding\fluentNhibernate\src\FluentNHibernate\AssemblyTypeSource.cs:27
FluentNHibernate.PersistenceModel.AddMappingsFromSource(ITypeSource source) in c:\work\coding\fluentNhibernate\src\FluentNHibernate\PersistenceModel.cs:80
FluentNHibernate.Cfg.FluentMappingsContainer.Apply(PersistenceModel model) in c:\work\coding\fluentNhibernate\src\FluentNHibernate\Cfg\FluentMappingsContainer.cs:122
FluentNHibernate.Cfg.MappingConfiguration.Apply(Configuration cfg) in c:\work\coding\fluentNhibernate\src\FluentNHibernate\Cfg\MappingConfiguration.cs:80
FluentNHibernate.Cfg.FluentConfiguration.BuildConfiguration() in c:\work\coding\fluentNhibernate\src\FluentNHibernate\Cfg\FluentConfiguration.cs:249
[FluentConfigurationException: An invalid or incomplete configuration was used while creating a SessionFactory. Check PotentialReasons collection, and InnerException for more detail.
]
ProjectName2.Data.UnitOfWork..ctor(String databaseConnectionString) in C:\agent\_work\5\s\.....\ProjectName\UnitOfWork.cs:169
ProjectName.WebApiConfig.Register(HttpConfiguration config) in C:\agent\_work\5\s\.....\ProjectName\App_Start\WebApiConfig.cs:66
System.Web.Http.GlobalConfiguration.Configure(Action`1 configurationCallback) +27
ProjectName.WebApiApplication.Application_Start() in C:\agent\_work\5\s\....\ProjectName\Global.asax.cs:18
[HttpException (0x80004005): An invalid or incomplete configuration was used while creating a SessionFactory. Check PotentialReasons collection, and InnerException for more detail.
]
System.Web.HttpApplicationFactory.EnsureAppStartCalledForIntegratedMode(HttpContext context, HttpApplication app) +10093921
System.Web.HttpApplication.RegisterEventSubscriptionsWithIIS(IntPtr appContext, HttpContext context, MethodInfo[] handlers) +118
System.Web.HttpApplication.InitSpecial(HttpApplicationState state, MethodInfo[] handlers, IntPtr appContext, HttpContext context) +173
System.Web.HttpApplicationFactory.GetSpecialApplicationInstance(IntPtr appContext, HttpContext context) +218
System.Web.Hosting.PipelineRuntime.InitializeApplication(IntPtr appContext) +296
[HttpException (0x80004005): An invalid or incomplete configuration was used while creating a SessionFactory. Check PotentialReasons collection, and InnerException for more detail.
]
System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +10075124
System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +95
System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +254*
I'd bet there is a problem connecting to the database from the new IIS server you are having problems with. This is coming from NHibernate, so it is an issue with the database; however, if it works from one server then it's probably configured correctly. Verify that you can access the database directly from the new IIS server.

unhandled exception in Azure

I am in way over my head here, trying to program a code to work on a website in Azure. This is just supposed to be a demonstration for a presentation I have in the cloud. I wont be getting marks on this program, but it helps me to display the capabilities offered by Azure.
This may be vague, but if you can take a look at this error message and let me know if there's anything obvious let me know.
[SEHException (0x80004005): External component has thrown an exception.]
RdGetApplicationConfigurationSetting(UInt16* , UInt16** ) +0
RoleEnvironmentGetConfigurationSettingValueW(UInt16* pszName, UInt16* pszDest, UInt32 cchDest, UInt32* pcchRequiredDestSize) +47
Microsoft.WindowsAzure.ServiceRuntime.Internal.InteropRoleManager.GetConfigurationSetting(String name, String& ret) +91
Microsoft.WindowsAzure.ServiceRuntime.RoleEnvironment.GetConfigurationSettingValue(String configurationSettingName) +67
Microsoft.WindowsAzure.ServiceRuntime.RoleEnvironment.GetConfigurationSettingValue(String configurationSettingName) +67
ContosoAdsWeb.MvcApplication.InitializeStorage() in C:\a\src\ContosoAdsWeb\Global.asax.cs:32
ContosoAdsWeb.MvcApplication.Application_Start() in C:\a\src\ContosoAdsWeb\Global.asax.cs:26
[HttpException (0x80004005): External component has thrown an exception.]
System.Web.HttpApplicationFactory.EnsureAppStartCalledForIntegratedMode(HttpContext context, HttpApplication app) +4467101
System.Web.HttpApplication.RegisterEventSubscriptionsWithIIS(IntPtr appContext, HttpContext context, MethodInfo[] handlers) +118
System.Web.HttpApplication.InitSpecial(HttpApplicationState state, MethodInfo[] handlers, IntPtr appContext, HttpContext context) +172
System.Web.HttpApplicationFactory.GetSpecialApplicationInstance(IntPtr appContext, HttpContext context) +364
System.Web.Hosting.PipelineRuntime.InitializeApplication(IntPtr appContext) +290
[HttpException (0x80004005): External component has thrown an exception.]
System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +4531288
System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +94
System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +191
I'm assuming you're using Azure Web Apps (websites). That being the case: Looks like you're making calls to RoleEnvironment, which is specifically for web/worker roles, and not Web Apps.
I posted a similar answer several years ago, with a bit more detail, here.

Request is not available in this context Error

On a shared hosting where I uploaded my Application files, I get the aforementioned exception each time I log on to the website. Below is the exception with it's stack trace.
Request is not available in this context
Description: An unhandled exception occurred during the execution of
the current web request. Please review the stack trace for more
information about the error and where it originated in the code.
Exception Details: System.Web.HttpException: Request is not available
in this context
Source Error:
An unhandled exception was generated during the execution of the
current web request. Information regarding the origin and location of
the exception can be identified using the exception stack trace below.
Stack Trace:
[HttpException (0x80004005): Request is not available in this context]
System.Web.HttpContext.get_Request() +8891008
Microsoft.Practices.CompositeWeb.Services.WebConfigModuleInfoStore.GetConfiguration(String
configFilePath) +115
Microsoft.Practices.CompositeWeb.Services.WebConfigModuleInfoStore.PopulateSection(ModulesConfigurationSection
section, String rootDirectory) +186
Microsoft.Practices.CompositeWeb.Services.WebConfigModuleInfoStore.GetModuleConfigurationSection()
+79 Microsoft.Practices.CompositeWeb.Services.WebModuleEnumerator.EnumerateModules()
+173 Microsoft.Practices.CompositeWeb.WebClientApplication.LoadModules()
+216 Microsoft.Practices.CompositeWeb.WebClientApplication.Application_Start(Object
sender, EventArgs e) +149
[HttpException (0x80004005): Request is not available in this context]
System.Web.HttpApplicationFactory.EnsureAppStartCalledForIntegratedMode(HttpContext
context, HttpApplication app) +2761334
System.Web.HttpApplication.RegisterEventSubscriptionsWithIIS(IntPtr
appContext, HttpContext context, MethodInfo[] handlers) +128
System.Web.HttpApplication.InitSpecial(HttpApplicationState state,
MethodInfo[] handlers, IntPtr appContext, HttpContext context) +188
System.Web.HttpApplicationFactory.GetSpecialApplicationInstance(IntPtr
appContext, HttpContext context) +295
System.Web.HttpApplicationFactory.GetPipelineApplicationInstance(IntPtr
appContext, HttpContext context) +56
System.Web.Hosting.PipelineRuntime.InitializeApplication(IntPtr
appContext) +231
[HttpException (0x80004005): Request is not available in this context]
System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +8994307
System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +85
System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest
wr, HttpContext context) +333
I can see it's from Application_Start event from Global.asax. But I don't see what may be causing the exception. Below is the code in the event;
void Application_Start(object sender, EventArgs e)
{
XmlDocument xml = new XmlDocument();
xml.Load(HostingEnvironment.MapPath(#"\Config\tasks.config"));
XmlNodeList nodes = xml.SelectNodes("Tasks/Task");
this._scheduler = new TaskScheduler(nodes);
this._scheduler.StartTasks();
}
What could I be possibly doing wrong here?

Umbraco upgrade issue with RTE & uSync & Forms

I'm pretty new to Umbraco an I've just attempted to upgraded from version 7.1.1 to the latest 7.2.6. I all seemed fine until I noticed that the RTE stopped working. Then I deleted the umbraco.config file and the TEMP folder.
Since then I keep getting this error message:
Cannot insert duplicate key row in object 'dbo.cmsMacroProperty' with unique index 'IX_cmsMacroProperty_Alias'. The duplicate key value is (11, FormGuid).
The statement has been terminated.
[SqlException (0x80131904): Cannot insert duplicate key row in object 'dbo.cmsMacroProperty' with unique index 'IX_cmsMacroProperty_Alias'. The duplicate key value is (11, FormGuid).
The statement has been terminated.]
jumps.umbraco.usync.uSync.RunSync() +687
jumps.umbraco.usync.uSync.DoOnStart() +118
Umbraco.Core.EnumerableExtensions.ForEach(IEnumerable`1 items, Action`1 action) +148
Umbraco.Core.CoreBootManager.Complete(Action`1 afterComplete) +116
Umbraco.Web.WebBootManager.Complete(Action`1 afterComplete) +95
Umbraco.Core.UmbracoApplicationBase.StartApplication(Object sender, EventArgs e) +223
[HttpException (0x80004005): Cannot insert duplicate key row in object 'dbo.cmsMacroProperty' with unique index 'IX_cmsMacroProperty_Alias'. The duplicate key value is (11, FormGuid).
The statement has been terminated.]
System.Web.HttpApplicationFactory.EnsureAppStartCalledForIntegratedMode(HttpContext context, HttpApplication app) +588
System.Web.HttpApplication.RegisterEventSubscriptionsWithIIS(IntPtr appContext, HttpContext context, MethodInfo[] handlers) +181
System.Web.HttpApplication.InitSpecial(HttpApplicationState state, MethodInfo[] handlers, IntPtr appContext, HttpContext context) +322
System.Web.HttpApplicationFactory.GetSpecialApplicationInstance(IntPtr appContext, HttpContext context) +402
System.Web.Hosting.PipelineRuntime.InitializeApplication(IntPtr appContext) +452
[HttpException (0x80004005): Cannot insert duplicate key row in object 'dbo.cmsMacroProperty' with unique index 'IX_cmsMacroProperty_Alias'. The duplicate key value is (11, FormGuid).
The statement has been terminated.]
System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +646
System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +159
System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +778
Being new to Umbraco I find it hard to approach this exception and resolve the issue.
Any help is appreciated!
Looking at the initial error, I think you might need to update to the latest version of uSync. To see if that's the case, remove the uSync DLL from your bin folder and see if everything starts working. If it does, you just need to grab the latest version of uSync and use that instead of the current one!

NullReferenceException:Object reference not set to an instance of an object. SQL Server

i have issue to run this asp.net script on my server,
I get this error :
Server Error in '/' Application.
Object reference not set to an instance of an object.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[NullReferenceException: Object reference not set to an instance of an object.]
Gilass.ApplicationBase.SQLDataProvider.Select(String srcTable, String whereClause, String orderClause, Boolean noSecure) +455
Gilass.ApplicationBase.SQLDataProvider.Select(String srcTable, String whereClause, String orderClause) +19
Gilass.ApplicationBase.HostSettings.Get(String settingName) +79
GilassSocial.Global.Application_Start(Object sender, EventArgs e) +418
[HttpException (`0x80004005`): Object reference not set to an instance of an object.]
System.Web.HttpApplicationFactory.EnsureAppStartCalledForIntegratedMode(HttpContext context, HttpApplication app) `+3985477`
System.Web.HttpApplication.RegisterEventSubscriptionsWithIIS(IntPtr appContext, HttpContext context, MethodInfo[] handlers) +191
System.Web.HttpApplication.InitSpecial(HttpApplicationState state, MethodInfo[] handlers, IntPtr appContext, HttpContext context) +325
System.Web.HttpApplicationFactory.GetSpecialApplicationInstance(IntPtr appContext, HttpContext context) +407
System.Web.Hosting.PipelineRuntime.InitializeApplication(IntPtr appContext) +375
[HttpException (0x80004005): Object reference not set to an instance of an object.]
System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +11524352
System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +141
System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +4782309
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.1
i think i need change something in web.config , this is my web.config information :
<Gilass>
<data defaultProvider="WIN-AK7E554L8NA\SQLEXPRESS">
<providers>
<clear/>
<add name="WIN-AK7E554L8NA\SQLEXPRESS" type="WIN-AK7E554L8NA\SQLEXPRESS" connectionString="Server=127.0.0.1;Database=db_name;uid=gilass;pwd=****;" providerPath="~\" objectQualifier="" databaseOwner="gilass" upgradeConnectionString="" />
</providers>
</data>
</Gilass>
Any advice ?
Thanks in advance

Categories

Resources