Entity framework context as static - asp.net

In a web application it would be ok if i declare the context of a entity framework model as static? it would be ok? its not recommended? why?
Thanks!

Almost definitely not.
ObjectContexts get bigger and bigger as more Objects are queried / saved.
Also sharing an ObjectContext between threads, as you would be doing, is not recommended, because of the locking issues and undeterministic side-effects you would have to deal with.
I wrote a tip on this topic a while back.
Tip 18 - How to decide on a lifetime for your ObjectContext

This answer sort of answers your question, so does this one. I certainly wouldn't consider having it as static!
Rick Strahl has an in depth article on the lifecycle management.

I had done this the first time I implemented the entity framework. The problem was that the whole application was getting "completed" events so I had to do a lot of code figuring out where the call came from.
I decided to refactor so each page would have an instance of the context. I like it much better now.
/my experience

Related

What exactly is dynamic data?

What exactly is dynamic data? I saw the term in the ASP.NET Overview on msdn. Is it something that we use all the time thats not really mentioned when working with data?
I've built a few web applications already and never came across this term. Is it something that should be used or maybe considered?
UPDATE: I guess I'm not really sure what it's for. I've never had a problem doing LINQ to SQL or Entity Framework before. What makes using Dynamic Data worth it? Is it simply a pattern?
Dynamic Data was a new project type in VS 2008. It used scaffolding & templates to help code faster.
Two big reasons I saw for its usage:
Stand up an admin back-end really
quickly where doing much on the way
of modifying the front-end may not be
needed.
Quickly stand up CRUD apps that are
simple.
Now, it can be modified very heavily. Check out these links for some work others have done on this.
http://aspnet.codeplex.com/Wiki/View.aspx?title=Dynamic%20Data
Matt Berseth - http://mattberseth.com/blog/dynamic_data/
Stephen Naughton - http://csharpbits.notaclue.net/
http://weblogs.asp.net/craigshoemaker/archive/tags/Dynamic+Data/default.aspx
http://blogs.msdn.com/rickandy/archive/2009/01/08/dynamic-data-faq.aspx
Fast Forward to Today:
As MVC has matured they have introduced many of the ideas that were in Dynamic Data. Scaffolding, templates, etc... to help one quickly get up and running BUT also have the ability to modify more easily and is designed for many other desirable features.
Where does Dynamic Data fit today, especially with Light Switch thrown into the mix? Great question and my only answer at this point is it still fits for the two items originally mentioned but with the advent of MVC having these abilities WITH added capabilities and Light Switch it's going to see minimal usage.
The page you linked to has a link to the ASP.NET Dynamic Data Overview. Is there something on that page you would like explained?
Dynamic Data is a way to have your CRUD data logic written for you automatically using the Database Schema.
Take a look at this walkthrough to give you a quick jist.
It isn't something I use, but I can see where it has merit in a really rapid development scenario. I don't know if it will stand the test of time or prove useful or maintainable.

Singleton pattern with Web application, Not a good idea!

I found something funny, I notice it by luck while I was debugging other thing. I was applying MVP pattern and I made a singleton controller to be shared among all presentations.
Suddenly I figured out that some event is called once at first postback, twice if there is two postback, 100 times if there is 100 postbacks.
because Singleton is based on a static variable which hold the instance, and the static variable live across postbacks, and I wired the event assuming that it will be wired once, and rewired for each postback.
I think we should think twice before applying a singleton in a web application, or I miss something??
thanks
I would think twice about using a Singleton anywhere.
Many consider Singleton an anti-pattern.
Some consider it an anti-pattern, judging that it is overused, introduces unnecessary limitations in situations where a sole instance of a class is not actually required, and introduces global state into an application.
There are lots of references on Wikipedia that discuss this.
It is very rare to need a singleton and personally I hold them in the same light as global variables.
You should think twice any time you are using static objects in a multi-threaded application (not only the singleton pattern) because of the shared state. Proper locking mechanisms should be applied in order to synchronize the access to the shared state. Failing to do so some very difficult to find bugs could appear.
I've been using Singletons in my web apps for quite some time and they have always worked out quite well for me, so to say they're a bad idea is really a pretty difficult claim to believe. The main idea, when using Singletons, is to keep all the session-specific information out of them, and to use them more for global or application data. To avoid them because they are "bad" is really not too smart because they can be very useful when applied correctly.

Clever caching using generics?

Are there any clever layers out there to sit on top of the System.Web.Caching.Cache class to handle simple scenarios to fetch items using generics.
I'd like to maybe provide a delegate function to retrieve an item, and be able to fetch an item with a strongly typed GetItem and a delegate function to retrieve an item if it isnt found.
For instance
CleverCache<K, T>
T GetItem(K)
RegisterDelegate(FetchItemDelegate<K,T>)
I'd also like a nice way to handle a cache that only ever handles a single object.
The ASP.NET Cache object just seems really primitive. It just seems like a hashtable with a timeout. They may as well just call it HashtableWithTimeout for all I care. I want some better astraction. Is this the kind of thing that the caching application block will do for me?
Yes I know this is fairly simple code, i just dont have time for any wheel reinventing right now.
You may want to look into some more sophisticated cache providers that can wrap the ASP.NET cache, such as the Enterprise Library's caching block. It provides a much more robust and rich caching story for object lifecycle, invalidation, retrieval, etc.
The ASP.NET cache deserves more credit than you give it - it's actually a very powerful base. Alone, it doesn't do anything complex as you have pointed out, but it is well-designed and robust enough to support some pretty cool stuff.
You may want to look into SharedCache and Microsoft Velocity as improvements to the basic caching available in ASP.NET. I don't know how extensively strong typing is designed into either - but from the samples and documentation I've seen it's better than the ASP.NET Cache.

Using a DataContext static variable

I have recently inherited an ASP.Net app using Linq2SQL. Currently, it has its DataContext objects declared as static in every page, and I create them the first time I find they are null (singleton, sort of).
I need comments if this is good or bad. In situations when I only need to read from the DB and in situations where i need to write as well.
How about having just one DataContext instance for the entire application?
One DataContext per application would perform badly, I'm afraid. The DataContext isn't thread safe, for starters, so even using one as a static member of a page is a bad idea. As asgerhallas mentioned it is ideal to use the context for a unit of work - typically a single request. Anything else and you'll start to find all of your data is in memory and you won't be seeing updates without an explicit refresh. Here are a couple posts that talk to those two subjects: Identity Maps and Units of Work
I use to have one DataContext per request, but it depends on the scenarios you're facing.
I think the point with L2S was to use it with the unit of work pattern, where you have a context per ... well unit of work. But it doesn't work well in larger applications as it's pretty hard to reattach entities to a new context later.
Rick Strahl has a real good introduction to the topic here:
http://www.west-wind.com/weblog/posts/246222.aspx
One thing I can say I have had problems with in the past, is to have one context to both read and write scenarios. The change tracking done in the datacontext is quite an overhead when you are just reading, which is what most webapps tends to do most of the time. You can make the datacontext readonly and it will speed up things quite a bit - but then you'll need another context for writing.

ASP.NET and System.Diagnostics tracing - have I missed something, or is this a bad idea?

For various common reasons I wanted to use tracing for my ASP.NET application. Especially since I found out about the possibility to use the Service Trace Viewer tool which allows you to examine your traces in a powerful way.
Since I had never used this trace thing before, I started stuying it. After a while of Google, SO and MSDN I finally have a good idea of how things work. But I also found one very distrubing thing.
When using trace in ASP.NET applications it makes a lot of sense to group the trace messages together by web requests. Especially since one of the reasons I want to use it is for studying performance problems. The above mentioned tool also supports this by using <Corrleation> tags in the generated XML files. Which in turn come from System.Diagnostics.Trace.CorrelationManager. It also allows other nice features like Activity starting/stopping, which provides an even better grouping of trace messages. Cool, right?
I though so too, until I started inspecting where the CorrelationManager actually lived. After all - it was a static property. After some playing around with Reflector I found out something horrifying - it's stored in CallContext! Which is the kind of thing we shouldn't be using in ASP.NET, right?
So... am I missing something here? Is tracing really fundamentally flawed in ASP.NET?
Added: Emm, I'm kinda on the verge of rewriting this stuff myself. I still want to use the neat tool for exploring the traces. Any reason I shouldn't do this? Perhaps there is something better yet? It would be really nice if I got some answers soon. :)
Added 2: A colleague of mine confirmed that this is not just a theoretical issue. He has observed this in the system he's working on. So it's settled. I'm going to build a new little system that does things just the way I want it to. :)
Added 3: Wow, cool... the guys at Microsoft couldn't find anything wrong with using Correlation Manager in ASP.NET. So apparently we're not getting a fix for this bug after all...
You raise a very interesting question. After looking at Reflector, I also see that CorrelationManager is using the CallContext to store the activity id. I have not worked with tracing much, so I can't really speak on behalf of what types of activities it tracks, but if it tracks a single activity across the entire life cycle of a page request, per the article you referenced above, there is a possibility that the activity id could become disassociated with the actual activity. This activity would appear to die halfway through.
HttpContext would seem ideal for tracking an entire page request from beginning to finish, since it will be carried over even if the execution changes to a different thread. However, the HttpContext will not be transferred to your business objects, where as the CallContext would. On a side note, I saw that CallContext can also be transferred when using remoting between client and server apps which is pretty nifty, but in the case of tracking the website, this would not really be all that useful.
If you haven't already, check out this guy's site. The issue described in this article isn't specifically the same issue that Cup(Of T) article mentioned, but it's still pretty interesting. He also provides several very informative links on the page that describe components of the CorrelateionManager.
Unfortunately, I don't really have an answer to your question, but I definitely find the topic interesting and will continue looking into it. So please update this post as you learn more. I'm curious to see what you or others (hopefully someone out there can shed some light on the topic) find while looking into this.
Anyway, good luck. I'll talk to some of the peeps at my work about this and post more later if I find anything.
Chris
OK, so this is how it ended.
My colleague called Microsoft and reported this bug to them. Being certified partners means we get access to some more prioritized fixing queue or something... don't know that stuff. Anyway, they're working on it. Hopefully we'll see a patch soon. :)
In the mean time I've created my own little tracing class. It doesn't support all the bells and whistles that the default trace framework does, but it's just what I need. :) More specifically:
It writes to the same XML format as the default XmlWriterTraceListener so I can use the tool to analyze the logs.
It has a built in log rotation - something my colleague had to do himself on top of XmlWriterTraceListener.
The actual logging is deferred to another thread so performance can be measured more accurately.
Correlations are now stored in HttpContext.Items so ASP.NET threading peculiarities don't affect it.
Happy end, I hope. :)

Resources