ObjectForKey always returns null xamarin.ios - xamarin.ios

I have tried to set string into the cache using NSCache in Xamarin.iOS setting id done without problem, but when tries to get this cached value always return null, any one can help, please?
/*set*/
public static void AddCachedString(NSString key, NSString Value)
{
cacheProvider.SetObjectforKey(key, Value);
}
/*get*/
public static NSString GetCachedString(NSString key)
{
return (NSString)cacheProvider.ObjectForKey(key);
}

The method public virtual void SetObjectforKey(NSObject obj, NSObject key); has two parameters value and key, you just made a mistake in the order. The second parameter is the key.
You should modify your own method like:
cacheProvider.SetObjectforKey(Value, key);
In this way you can get this value with the correct key string. Moreover please pay attention to the Apple Documentation NSCache:
You typically use NSCache objects to temporarily store objects with
transient data that are expensive to create. However, the objects are not critical to the application and can be discarded if memory is tight.
If you want to persists the data, you can try NSUserDefaults.

Related

o:graphicImage caching possible?

In my topbar I have a <o:graphicImage> to show picture from my user.
<o:graphicImage dataURI="true" height="32" width="32" styleClass="img-circle"
value="#{employeeProfileMenuPictureRequestController.getPicture_32_32(loginBean.currentEmployee)}"
lastModified="#{employeeProfileMenuPictureRequestController.lastUpdate}" />
My backend bean is the following:
#GraphicImageBean
public class EmployeeProfileMenuPictureRequestController implements Serializable {
private Date lastUpdate = new Date();
public byte[] getPicture_32_32(Employee employee) throws StorageAttachmentNotFoundException, IOException {
try {
String path = employeeProfilePictureService.findProfileImageByEmployee(employee, FileSizeType.SIZE_32_32.toString());
if (employee == null || path == null || path.isEmpty()) {
return Utils.toByteArray(Faces.getResourceAsStream("/resources/images/no-photo-icon.png"));
}
Path fileLocation = Paths.get(path);
byte[] data = Files.readAllBytes(fileLocation);
LOGGER.info("END getPicture_32_32");
return data;
catch (Exception e) {
LOGGER.error(ExceptionUtils.getFullStackTrace(e));
}
return Utils.toByteArray(Faces.getResourceAsStream("/resources/images/no-photo-icon.png"));
}
public Date getLastUpdate() {
return lastUpdate;
}
}
Unfortunatelly the getPicture_32_32(Employee) is called for every page request / page navigation. This means it´s also everytime a request against the database, which takes time.
I´ve tried already to add lastModified to the <o:graphicImage>, but the function is called also everytime for each page request.
Can anybody help me to solve this?
According to <o:graphicImage> documentation:
Data URI
[...]
This approach is however not recommended for "permanent" and/or "large" images as it doesn't offer the browser any opportunity to cache the images for reuse, ~10KB would typically be the max even less so if there are more such images on the same page.
So, it does not support caching at all. The technical reason is that it basically embeds whole contents of the image in the HTML output. It does not embed an URL to the image. The lastModified is basically ignored. I should probably better document that. At least, you should absolutely remove the dataURI attribute. It's only useful for e.g. preview of an uploaded image.
And,
Image streaming
[...]
In case the property is a method expression taking arguments, each of those arguments will be converted to a string HTTP request parameter and back to actual objects using the converters registered by class as available via Application.createConverter(Class). So, most of standard types like Long are already implicitly supported. In case you need to supply a custom object as argument for some reason, you need to explicitly register a converter for it yourself via #FacesConverter(forClass).
So, because your method take a Employee argument, you basically need to have a #FacesConverter(forClass=Employee.class) so that JSF can automatically convert it from and to String. How to create converters can be found here: Conversion Error setting value for 'null Converter' - Why do I need a Converter in JSF?
You should end up with something like this:
#FacesConverter(forClass=Employee.class)
public class EmployeeConverter implements Converter {
#Override
public String getAsString(FacesContext context, UIComponent component, Object modelValue) {
// Write code here which converts Employee to its unique String representation.
}
#Override
public Object getAsObject(FacesContext context, UIComponent component, String submittedValue) {
// Write code here which coverts the Employee unique String representation
// as created in above method back to the original Employee object.
}
}
An alternative is to adjust your getPicture_32_32() method to take employee ID as e.g. Long instead of employee. Then you don't need a custom converter. JSF has already a built-in converter for Long.
public byte[] getPicture_32_32(Long employeeId) {
// ...
}
<o:graphicImage
value="#{employeeProfileMenuPictureRequestController.getPicture_32_32(loginBean.currentEmployee.id)}" />
Coming back to caching, the documentation says this:
Caching
[...]
When unspecified, then the "default resource maximum age" as set in either the Mojarra specific context parameter com.sun.faces.defaultResourceMaxAge or MyFaces specific context parameter org.apache.myfaces.RESOURCE_MAX_TIME_EXPIRES will be used, else a default of 1 week will be assumed.
So, when you have no resource age settings, it's already by default cached for 1 week. The lastModified is thus optional and only useful when you actually track a timestamp in the same database or filesystem when the image is actually changed. You should then really use that instead for most optimal caching. A "random" date is absolutely not the correct way.

Check duplicate key in Hashtable before adding a key

I have a Hashtable and I want to put check whether the Hashtable has key or not before adding a key in Hashtable. As adding a duplicate key in Hashtable throwing exception.
Basically I want to override Hashtable's virtual 'Add' method and put a check in it. I dont know how can I override Add method.
Please help me to write override method.
You can use ContainsKey.
Another way is to use the Item indexer-property which adds new keys and updates existing.
var ht = new System.Collections.Hashtable();
ht["test"] = "foo"; // added
ht["test"] = "bah"; // updated
However, you should consider to replace your old and redundant Hashtable with a generic Dictionary<Tkey, Tval>. Why?
The Add method of the Hashtable class is overridable. So try this:
class MyHashTable : Hashtable
{
public override void Add(object key, object value)
{
try
{
base.Add(key, value);
}
catch
{
// whatever
}
}
}

GXT Grid ValueProvider / PropertyAccess for a Map<K,V> Datastore?

Rather than using Bean model objects, my data model is built on Key-Value pairs in a HashMap container.
Does anyone have an example of the GXT's Grid ValueProvider and PropertyAccess that will work with a underlying Map?
It doesn't have one built in, but it is easy to build your own. Check out this blog post for a similar way of thinking, especially the ValueProvider section: http://www.sencha.com/blog/building-gxt-charts
The purpose of a ValueProvider is to be a simple reflection-like mechanism to read and write values in some object. The purpose of PropertyAccess<T> then is to autogenerate some of these value/modelkey/label provider instances based on getters and setters as are found on Java Beans, a very common use case. It doesn't have much more complexity than that, it is just a way to simply ask the compiler to do some very easy boilerplate code for you.
As that blog post shows, you can very easily build a ValueProvider just by implementing the interface. Here's a quick example of how you could make one that reads a Map<String, Object>. When you create each instance, you tell it which key are you working off of, and the type of data it should find when it reads out that value:
public class MapValueProvider<T> implements
ValueProvider<Map<String, Object>, T> {
private final String key;
public MapValueProvider(String key) {
this.key = key;
}
public T getValue(Map<String, Object> object) {
return (T) object.get(key);
}
public void setValue(Map<String, Object> object, T value) {
object.put(key, value);
}
public String getPath() {
return key;
}
}
You then build one of these for each key you want to read out, and can pass it along to ColumnConfig instances or whatever else might be expecting them.
The main point though is that ValueProvider is just an interface, and can be implemented any way you like.

Locking to modify static value-type member. Is it necessary?

I have a CacheHelper class to facilitate interaction with the cache. I want to use a static int field to specify my cache timeout. The field is initially set to a const default value but I want to provide a way for the application to change the default timeout value.
Do you need to lock when modifying a static value type? Is the lock in the setter necessary? Are there any other problems you can see here? Sorry, I'm still pretty dumb when it comes to multithreading.
Thanks.
public static class CacheHelper
{
private static object _SyncRoot;
private static int _TimeoutInMinutes = CacheDefaults.TimeoutInMinutes;
public static int TimeoutInMinutes
{
get
{
return _TimeoutInMinutes;
}
set
{
lock (_SyncRoot)
{
if (_TimeoutInMinutes != value)
{
_TimeoutInMinutes = value;
}
}
}
}
public static void Insert(string key, Object data)
{
if (HttpContext.Current != null && data != null)
{
HttpContext.Current.Cache.Insert(key, data, null, Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(CacheHelper.TimeoutInMinutes));
}
}
}
You could use a volatile variable instead... but you need something, otherwise it's possible that a value written by one thread would never be seen by another.
Note that for "larger" types such as double or long you really should use a lock or the Interlocked class, as modifications to those values may not be atomic.
You don't need to lock here if the client of CacheHelper does somthing like
CacheHelper.TimeoutInMinutes = input.Value;
Since it doesn't rely on the previous value.
If your client does something like
CacheHelper.TimeoutInMinutes += input.Value;
Then you'll need to do some locking
.

Custom getEntityNameSelectList() fails

Writing a simple JSF application I've some across the following Problem:
My entities.controller.EntityNameManager class contains a method getEntityNameSelectList() which I can use to populate a ComboBox with. This works and shows all Entities, since the Method to retrieve the Entities does not have a where clause.
This Method was automatically created.
Now I want to have a second similar Method, that filters the options based on a variable in the sessionscope. To do this I copied the original Method, renamed it to getEntityNameSelectListByUser(User theUser) and changed the Method that queries the database to one that does indeed filter by UserId.
However, when trying to load the page in the browser, I get an error stating that the controller class does not have a "EntityNameSelectListByUser" property. I assume that since my new method expects a parameter it can't be found. Is there a way I can make it aware of the Parameter or the Sessionscope userid?
Support for parameters in EL is slated for the next maintenance release of JSR 245 (announcement here; implementation here).
Assuming you don't want to wait for JEE6, you have several ways to overcome this limitation. These approached are defined in terms of POJO managed beans, so adapt them to your EJBs as appropriate.
1.
Do the session lookup and function call in a backing bean:
public String getFoo() {
FacesContext context = FacesContext
.getCurrentInstance();
ExternalContext ext = context.getExternalContext();
String bar = (String) ext.getSessionMap().get("bar");
return getFoo(bar);
}
Example binding:
#{paramBean.foo}
2.
Use an EL function (defined in a TLD, mapped to a public static method):
public static String getFoo(ParamBean bean, String bar) {
return bean.getFoo(bar);
}
Example binding:
#{baz:getFoo(paramBean, bar)}
3.
Subvert the Map class to call the function (a bit of a hack and limited to one parameter):
public Map<String, String> getFooMap() {
return new HashMap<String, String>() {
#Override
public String get(Object key) {
return getFoo((String) key);
}
};
}
Example binding:
#{paramBean.fooMap[bar]}

Resources