modifying a value in viewstate - asp.net

Say I have a property like...
public object MyObject
{
get { return (object)ViewState["myobject"]; }
set { ViewState["myobject"] = value; }
}
I modify the object like so...
object myObjCopy = MyObject;
myObjCopy.ChangeSomething();
MyObject = myObjCopy;
Is this the correct method? It just feels really clunky and I wonder if I'm missing something. Is there some clever paradigm which enables modifying viewstate more intuitively without using temporary copys everywhere in my code.

With the property you have defined, you should not need to do any copying like what you have. I'm not sure what ChangeSomething() does, but you should be able to call it directly on the property. I would normally not pull it out as an object... It's been a while since I did pure webforms development, but my ViewState helper properties usually looked more like:
public string CurrentUsername
{
get
{
if (ViewState["Username"] is string)
return (string)ViewState["Username"];
return null;
}
set { ViewState["Username"] = value; }
}
Edit: Thinking about it, I guess the copy is probably there just to remove the potential performance overhead of casting every time you reference the property. I don't think this is a valid optimization in most cases, but if you feel strongly about it, you could hide it with something like this:
private string m_CurrentUsername;
public string CurrentUsername
{
get
{
if (m_CurrentUsername == null && ViewState["Username"] is string)
m_CurrentUsername = (string)ViewState["Username"];
return m_CurrentUsername;
}
set { ViewState["Username"] = m_CurrentUsername = value; }
}
Like I said though - I wouldn't recommend this.

The correct answer is that you shouldn't be modifying viewstate at all. Your controller should create the models and populate the viewstate only just before returning the view. If you're writing this code in the view, you've got an even bigger problem. in general, the view should contain little (if any) code that changes or does things.
Edit: Oops, I think I just got ViewData (in asp.net mvc) confused with viewdata. sorry ... to answer your real question, yes, that is just about the only way :-) it's not really clunky when you are dealing with a "bag" API like the viewstate is.

Related

How to force Newtonsoft.Json.Net Dictionary to serialize as KeyValuePair

Is it possible to get Json.Net 4.5+ to serialize my Dictionary<,> as this;
{
dic:[
{k:"apples",v:2},
{k:"pears",v:43}
]
}
as opposed to;
{
dic:{
"apples":2,
"pears":43,
}
}
Whilst the latter is a great default, and looking at the SO posts almost everyone wanted this when it wasn't the default, but I have one specific case when I actually want it the other (former) way instead. I tried adding the following to the dictionary class or member;
[JsonProperty(ItemConverterType=typeof(DictionaryArrayConverter)]
But that just causes it to barf on a null in the serialization stack.

Can somebody please explain this common binding pitfall to me? (using the wrong bindable event name)

I refer to this site link text
Using the wrong event name in the
[Bindable] tag can cause your
application to not bind your property,
and you will not even know why. When
you use the [Bindable] tag with a
custom name, the example below looks
like a good idea:
public static const EVENT_CHANGED_CONST:String = "eventChangedConst";
private var _number:Number = 0;
[Bindable(event=EVENT_CHANGED_CONST)]
public function get number():Number
{
return _number;
}
public function set number(value:Number) : void
{
_number = value;
dispatchEvent(new Event(EVENT_CHANGED_CONST));
}
The code above assigns a static
property to the event name, and then
uses the same assignment to dispatch
the event. However, when the value
changes, the binding does not appear
to work. The reason is that the event
name will be EVENT_CHANGED_CONST and
not the value of the variable.
The code should have been written as
follows:
public static const EVENT_CHANGED_CONST:String = "eventChangedConst";
private var _number:Number = 0;
[Bindable(event="eventChangedConst")]
public function get number():Number
{
return _number;
}
public function set number(value:Number) : void
{
_number = value;
dispatchEvent(new Event(EVENT_CHANGED_CONST));
}
I agree, the wrong example does look like a good idea and I would do it that way because I think it's the right way and avoids the possibility of a typing error. Why is the name of the constant used instead of it's value? Surely this can't be right?
I appreciate your insights
Because the standard Flex compiler isn't that clever at times... and I feel your pain! I've complained about this exact problem more than a few times.
If I remember correctly, it's because the compiler does multiple passes. One of the early passes changes the Metadata into AS code. At this point in the compiler it hasn't parsed the rest of the AS code, so its not capable of parsing Constants or references to static variables in other files.
The only thing I can suggest is sign up to the Adobe JIRA, vote for the bug, and hope that the compiler fixes in 4.5 bring some relief.

strongly typed sessions in asp.net

Pardon me if this question has already been asked. HttpContext.Current.Session["key"] returns an object and we would have to cast it to that particular Type before we could use it. I was looking at various implementations of typed sessions
http://www.codeproject.com/KB/aspnet/typedsessionstate.aspx
http://weblogs.asp.net/cstewart/archive/2008/01/09/strongly-typed-session-in-asp-net.aspx
http://geekswithblogs.net/dlussier/archive/2007/12/24/117961.aspx
and I felt that we needed to add some more code (correct me if I was wrong) to the SessionManager if we wanted to add a new Type of object into session, either as a method or as a separate wrapper. I thought we could use generics
public static class SessionManager<T> where T:class
{
public void SetSession(string key,object objToStore)
{
HttpContext.Current.Session[key] = objToStore;
}
public T GetSession(string key)
{
return HttpContext.Current.Session[key] as T;
}
}
Is there any inherent advantage in
using
SessionManager<ClassType>.GetSession("sessionString")
than using
HttpContext.Current.Session["sessionString"] as ClassType
I was also thinking it would be nice
to have something like
SessionManager["sessionString"] = objToStoreInSession,
but found that a static class cannot have an indexer. Is there any other way to achieve this ?
My thought was create a SessionObject which would store the Type and the object, then add this object to Session (using a SessionManager), with the key. When retrieving, cast all objects to SessionObject ,get the type (say t) and the Object (say obj) and cast obj as t and return it.
public class SessionObject { public Type type {get;set;} public Object obj{get;set;} }
this would not work as well (as the return signature would be the same, but the return types will be different).
Is there any other elegant way of saving/retrieving objects in session in a more type safe way
For a very clean, maintainable, and slick way of dealing with Session, look at this post. You'll be surprised how simple it can be.
A downside of the technique is that consuming code needs to be aware of what keys to use for storage and retrieval. This can be error prone, as the key needs to be exactly correct, or else you risk storing in the wrong place, or getting a null value back.
I actually use the strong-typed variation, since I know what I need to have in the session, and can thus set up the wrapping class to suit. I've rather have the extra code in the session class, and not have to worry about the key strings anywhere else.
You can simply use a singleton pattern for your session object. That way you can model your entire session from a single composite structure object. This post refers to what I'm talking about and discusses the Session object as a weakly typed object: http://allthingscs.blogspot.com/2011/03/documenting-software-architectural.html
Actually, if you were looking to type objects, place the type at the method level like:
public T GetValue<T>(string sessionKey)
{
}
Class level is more if you have the same object in session, but session can expand to multiple types. I don't know that I would worry about controlling the session; I would just let it do what it's done for a while, and simply provide a means to extract and save information in a more strongly-typed fashion (at least to the consumer).
Yes, indexes wouldn't work; you could create it as an instance instead, and make it static by:
public class SessionManager
{
private static SessionManager _instance = null;
public static SessionManager Create()
{
if (_instance != null)
return _instance;
//Should use a lock when creating the instance
//create object for _instance
return _instance;
}
public object this[string key] { get { .. } }
}
And so this is the static factory implementation, but it also maintains a single point of contact via a static reference to the session manager class internally. Each method in sessionmanager could wrap the existing ASP.NET session, or use your own internal storage.
I posted a solution on the StackOverflow question is it a good idea to create an enum for the key names of session values?
I think it is really slick and contains very little code to make it happen. It needs .NET 4.5 to be the slickest, but is still possible with older versions.
It allows:
int myInt = SessionVars.MyInt;
SessionVars.MyInt = 3;
to work exactly like:
int myInt = (int)Session["MyInt"];
Session["MyInt"] = 3;

Testing an object's state at save

I'm looking to write unit tests for a method such as this one:
public override bool ChangePasswordQuestionAndAnswer(string username, string password, string newPasswordQuestion, string newPasswordAnswer)
{
ISPMembershipUserDao userDao = GetISPMembershipUserDao();
if (ValidateUser(username, password))
{
SPMembershipUser user = userDao.GetUserByUserName(username);
user.PasswordQuestion = newPasswordQuestion;
user.PasswordAnswer = newPasswordAnswer;
userDao.Save(user);
return true;
}
return false;
}
It's a fairly straight-forward method to test. I'm using the Rhino Mocks framework. But one aspect has me questioning myself. I stub the DAO object and its save method, and I'm wondering how deeply I should test that user object that is passed to the save method. Should I assert that every property of that object is as I expect it to be? Or should I only assert that the PasswordQuestion and PasswordAnswer properites have the correct values? The former seems right to me, as I should make sure that only those two properties have been modified, and the others haven't been touched.
I was hoping some people could give their opinions on this. Is there a rule of thumb or pattern to keep in mind for these types of situations?
Warning: personal opinion ahead
Ok, now that that's out of the way.... for me, it comes down to what I need to do to feel that my code properly implements the needed logic. In this case? I'd have two test cases:
Dealing with ValidateUser returning false
Should return false
Save should not have been called
Dealing with ValidateUser returning true
Should return true
Save should have been called
Object passed to save has the modified question and answer
No checks of other properties on user object
However, if/when I got a bug filed that affected this part of the code, I'd add whatever (initially failing) tests were needed to cover the bug, fix the bug, and leave the tests.
Since it's so easy to set up a constraint here, why not test it to ensure there are no side-effects to your method?
stubbedUserDao.AssertWasCalled(x => x.Save(null), o => {
o.IgnoreArguments();
o.Constraints(Property.AllPropertiesMatch(expectedMatchingUser));
});

How to know if an object is dynamic in AS3

In Action Script 3, you can write a class that defines a dynamic object (MovieClip and Object are two examples), this objects can be modified in run-time. What I want to know if is there some way (in run-time, of course) to know if certain object is dynamic or not.
PS: Without making something like this:
function isDynamic(object) {
try {
object.newProperty = 'someValue'
} catch (e) {
return false
}
return true
}
CookieOfFortune has the right idea, but unfortunately the code itself has problems, isDynamic is an attribute, and the returned value will be a XMLList with a value of a String that reflects a true or false value, not a child node that directly returns a Boolean. It should look more like this:
function isDynamic(object) : Boolean
{
var type:XML = describeType(object);
return type.#isDynamic.toString() == "true";
}
Be careful!
Anytime you want to use the describeType() function, please please please use the variation:
import mx.utils.DescribeTypeCache;
var typeDesc:XML = DescribeTypeCache.describeType(object).typeDescription;
Performance of making repeated calls to the runtime reflective machinery will absolutely suck. That's why Adobe invented the DescribeTypeCache class.
You can use describeType from flash.utils to describe the object in XML form. Here's the reference to the API: flash.utils.describeType
function isDynamic(object) {
var type:XML = describeType(object);
if (type.#isDynamic == "true") return true;
return false;
}
This is a very old post, but I'll add an option for those future searchers.
AS3 has a built in way of doing this:
mx.utils.ObjectUtil.isDynamicObject(yourObject);
Read more about it here.

Resources