Forms Session
One of the
difficulties when dealing with SAP B1 is the “stateless”
condition that object have between events fired on the UI.
If one creates
a class that handles the events for a given form then just creating a
simple static variable would solve the “stateless” problem, but
when you wish to have more then one instance of the form then this
approach does not work.
To work around
this I came up with the class below, which uses the FormUID (the
unique identifier of the form) to identify the object that belongs to
it. Meaning that you create your object and store it by using the
FormUID as the key.
When an event
gets fired you simply ask the FormsSession object to return you the
object stored for the FormUID. This takes care of both problems, the
“stateless” condition and the single class object.
One thing not
to forget is to remove the object from the Session when the form
closes (or like I intent to do, improve this class to auto-register
to the close event and remove the stored object automatically).
public
class
FormsSession<T>
where
T : class,
new()
{
private
static
Dictionary<string,
T> _container = new
Dictionary<string,
T>();
public
void
Add(string
FormUID, T FormObject)
{
if
(_container.ContainsKey(FormUID))
_container[FormUID]
= FormObject;
else
_container.Add(FormUID,
FormObject);
}
public
T Get(string
FormUID)
{
if
(!_container.ContainsKey(FormUID))
_container.Add(FormUID,
new
T());
return
_container[FormUID];
}
public
void
Remove(string
FormUID)
{
if
(_container.ContainsKey(FormUID))
_container.Remove(FormUID);
}
}