How can I reference data from an AppState variable? - c#

The problem is that I can't find a way to test anything stored in AppState["variableName"] (or App.variableName or HttpContext.Current.Application["variableName"], etc.) inside an if condition. (It only ever sees it as an object, even though I can plot it on the page with Razor as the string variable I thought it was)
So, I can't compare them to say an actual string value.
I've tried ToString(), among countless other attempts, to no avail.
My question is: How can I achieve full functionality with the AppState variable in WebMatrix Web-Pages with C#?

The problem here is that casting is needed, without a space between the cast and the AppState variable. At the time that I posted this question, I was still so new (well, still am really) to C# server side programming. An example of what works is:
if ((string)AppState["myVariable"] == "someString")
{
//do some stuff
}
Also, whether many people like the term "global variable" or not, the AppState variable is, in fact, considered a global variable. This is clearly stated in Mike Brind's Mikesdotnetting article "Tranferring Data Between ASP.NET Web Pages" in the very first line under Application Variables:
"Application variables are also known as global variables." --(Mikesdotnetting)
Also, if you (whoever you are) have not read this article and are either new to WebMatrix or want to see all of the options for transferring data between pages in WebMatrix, please do yourself a tremendous favor and read this easy-to-read, well-written, and highly educational article found here:
http://www.mikesdotnetting.com/Article/192/Transferring-Data-Between-ASP.NET-Web-Pages

Related

Optimization: local variables or global variables?

I am developing a silverlight application (C#) in which I use a custom control Square and the following global variables.
Square[,] arrSquare = new Square[customRows,customColumns]
List<Square> lstSelection;
List<Square> lstEditable;
List<Square> lstSetSquares;
List<Square> lstCancelled;
The lists are time and again used for updating purposes.
The arrSquare comes in picture only when I have to update my above segregated lists.
I have two options in my mind:
follow my current architecture of having global variables and not using my primary array arrSquare frequently
Use LINQ (on arrSquare converted to locally declared Lists) in methods so that the local objects get destroyed when method gets completed?
If there is any better way, please suggest that.
Please note, the data that I will be dealing with, will be huge.
The question should not be about global vs local variables, it should rather be phrased as "is it better to keep cached copies of calculations or to produce them on the spot as needed?".
Since your dataset will be huge then obviously performing all calculations on demand is a no-go, so that question is easy to answer.

Share complex objects across many page requests - C# MVC

I've got a search function that on completion, stores data in a generic list (List<ViewModel>). Up until now, I've been assigning the viewmodel value to a static variable to allow me to re-use the data over any page requests that the user may use.
After some reading today though, it seems that the static variable value can be shared across threads, meaning that there is a possibility if I'm viewing the site, that the static variables that contain my search data could be modified by another user.
In the course of my reading I've seen solutions such as adding [ThreadStatic] attribute to the variable, although this not only didn't work, but was roundly dismissed by my further reading as an improper solution.
Others talked about storing variables in HttpContext.Current.Items, but my understanding of that is that it only lasts for a single request.
So, I'm unsure of the best solution here - ideally I 'd rather not make too many fundamental changes to my application, but in short I'd like to be able to share complex objects across many requests? What is the best method of doing this?
Thanks very much
You can store objects that should be persisted in memory for each user individually in a session (HttpContext.Session) object. Your deployment will of course have to support sessions.
Couldn't you just use the OutputCacheAttribute?
Static variable is a bad choise. You can use sessions or ViewState. As for me - the first one is better. As expample
if (Session["tmp"] == null) Session["tmp"]=new DataSet();
DataSet ds = (DataSet)Session["tmp"];
{
...Do something with ds
}
Session["tmp"] = ds;
You can pass this dataset between pages or handlers, but you have to look after the lifetime of your session

Why use a GlobalClass? What are they for?

Why use a GlobalClass? What are they for? I have inherited some code (shown below) and as far as I can see there is no reason why strUserName needs this. What is all for?
public static string strUserName
{
get { return m_globalVar; }
set { m_globalVar = value; }
}
Used later as:
GlobalClass.strUserName
Thanks
You get all the bugs of global state and none of the yucky direct variable access.
If you're going to do it, then your coder implemented it pretty well. He/She probably thought (correctly) that they would be free to swap out an implementation later.
Generally it's viewed as a bad idea since it makes it difficult to test the system as a whole the more globals you have in it.
My 2 cents.
When you want to use a static member of a type, you use it like ClassName.MemberName. If your code snippet is in the same class as the member you're referring (in this example, you're coding in a GlobalClass member, and using strUserName) you can omit the class name. Otherwise, it's required as the compiler wouldn't have any knowledge of what class you're referring to.
This is a common approach when dealing with Context in ASP.Net; however, the implementation would never use a single variable. So if this is a web app I could see this approach being used to indicate who the current user is (Although there are better ways to do this).
I use a simillar approach where I have a MembershipService.CurrentUser property which then pulls a user out from either SessionState or LogicalCallContext (if its a web or client app).
But in these cases these aren't global as they are scoped within narrow confines (Like the http session state).
One case where I have used a global like this would be if I have some data which is static and never changes, and is loaded from the DB (And there's not enough of the data to justify storing it in a cache). You could just store it in a static variable so you don;t have to go back to the DB.
One a side note why was the developer using Hungarian notation to name Properties? even when there was no intellisense and all the goodness our IDEs provide we never used hungarian notation on Properties.
#Jayne, #Josh, it's hard to tell - but the code in the question could also be a static accessor to a static field - somewhat different than #Josh's static helper example (where you use instance or context variables within your helper).
Static Helper methods are a good way to conveniently abstract stateless chunks of functionality. However in the example there is potential for the global variable to be stateful - Demeter's Law guides us that you should only play with state that you own or are given e.g. by parameters.
http://www.c2.com/cgi/wiki?LawOfDemeter
Given the rules there occasional times when it is necessary to break them. You should trade the risk of using global state (primarily the risk of creating state/concurrency bugs) vs. the necessity to use globals.
Well if you want a piece of data to be available to any other class running in the jvm then the Global Class is the way to go.
There are only two slight problems;
One. The implmentation shown is not thread safe. The set... method of any global class should be marked critical or wrapped in a mutex.
Even in the niave example above consider what happens if two threads run simultaniously:
set("Joe") and set("Frederick") could result in "Joederick" or "Fre" or some other permutation.
Two. It doesnt scale well. "Global" refers to a single jvm. A more complex runtime environment like Jboss could be runnning several inter communicating jvms. So the global userid could be 'Joe' or 'Frederick' depending on which jvm your EJB is scheduled.

What are the reasons for these 2 error messages?

First of all, I'd like to say that this site is great!
My question is, what are the reasons for the following 2 error messages?
1) In VB.NET (I know this is a C# forum but my next question is from C# experience), property evaluation failed (I do this when putting a watch on an exception variable).
2) In C#, method or class (Can't remember which) does not have a constructor. I think I got this with HttpContext or HttpApplication, which is a class if I remember correctly? Pretty sure it is as it has its own properties and methods.
Thanks
1) Could be any number of reasons. Some properties just don't work nicely in a debugger. (Imagine watching DateTime.Now for changes!)
2) You're trying to create an instance of a class which doesn't have an appropriate accessible constructor. Usually either the class only has static members, or there's a static member you're meant to use to get an instance. (Having said that, both the classes you've mentioned have public constructors.)
More precise error messages and situation descriptions would be helpful.
I'd probably want to see code snippets to give you real answers, but my psychic detection powers are telling me that #2 is most likely that you are trying to do something like:
HttpContext context = new HttpContext;
This isn't the way you'd approach that. Instead, you would use its built-in factory method to access the current one:
HttpContext context = HttpContext.Current;
(Ditto for HttpApplication.)
I can't help with #1 without seeing some representative code. And don't worry, this isn't a C#-specific forum, it's for all programming languages and platforms. :)
First of all, apologies for making a duplicate thread (couldn't see this one so made another).
1) That makes sense. Watching datetime.now for changes will just display the time # the time of adding a watch, cache that value, and then get the new value (Time) when checking again.
2) John Rudy: you are spot on. That is what I was doing. So HttpContext.Current gives me back the httpcontext object to work with, I see.

Overhead for not simplifying names in C#

I am working with a C# windows forms application (I doubt the project type affects answer but there it is anyways) and everything is going good. Code works fine. However Visual studio likes to tell me that Name can be simplified' when I do things like like usingthisin some methods where thethis` may not be needed. Here is an example:
public class xyz
{
string startdate;
string enddate;
private void calculateElapsedTime()
{
var endDate = Convert.ToDateTime(this.enddate).ToUniversalTime();
var startDate = Convert.ToDateTime(this.startdate).ToUniversalTime();
elapsedtime = (decimal)(endDate - startDate).TotalSeconds;
}
}
The names that can be simplified are this.startdateand this.enddate
The code runs fine without the this keyword but personally I like using the 'this' as for me it makes it more clear what is being done.
I tried running tests on memory usage and time if I go through and simplify all places where VS says I should and I ran the same test without simplifying names and got the same results.
So this has lead me to the question, Is there any actual performance hit for not simplifying names or is the hit so small that I just don't see the difference because my program isn't big enough or some third option?
EDIT
Since this is starting to get into a discussion on naming conventions figured I would add this. The above is a just an example of code that has a name that can be simplified not the actual way I write code. The name can be simplified message also would show up if you use the namespaceX.class.functionname in code already x namespace.
Is there any actual performance hit for not simplifying names or is the hit so small that I just don't see the difference because my program isn't big enough or some third option?
Not in the slightest. This is just a style choice that has no impact on the compiled code.
I would pick a different name for your local variables, though. Having the same name with just different casing on one letter makes it hard to distinguish between the local variable and the member name.
There will not be a difference in the performance or memory footprint of the application. Your C# code is translated into IL by the compiler, and that is the code that is executed - since the compiler understands both the version with this and without, the resulting IL will be identical in both cases, and as such so will the performance of the program.
You can like or not qualifying class member access with this, but since in C# is avoidable and one of most important premises in programming is keep as simple as possible, while it's just a coding style issue, it's still interesting that you understand that this in C# is used when you need to disambiguate an access to a local variable and a class member.
There's no performance hit and it's just about that you get used with C# coding style. For example, you use camel-casing on method identifiers while C# coding style says that they should be pascal-cased.
Like any other convention and guideline, it's just there to make your code more predictable to others rather than to yourself (and once you get used with these guidelines, they're also predictable for you too ;)).
BTW - the reason not to use this is because it makes you think that you dont need a naming convention for member variables.
Many people use a convention like
string _enddate
string endate_
string m_endate
that way you can tell by looking at the code that this is a member variable.
Using this.endate also says it is a member variable but the same code compiles if you just say enddate. Now you have code that compiles but you cannot tell at a glance if its a member or not

Categories

Resources