Check duplicate key in Hashtable before adding a key - c#-4.0

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
}
}
}

Related

Is it possible to use the Slugger interface other than in a constructor?

I'm looking to use the sluggerInterface in a class. But I want to keep:
public function __construct()
{
}
So I want to use sluggerInterface in my class without adding any argument in my constructor. (this is in order to automatically create 1 slug when creating an object).
So I want a code different from this one:
use Symfony\Component\String\Slugger\SluggerInterface;
class MyService
{
private $slugger;
public function __construct(SluggerInterface $slugger)
{
$this->slugger = $slugger;
}
public function someMethod()
{
$slug = $this->slugger->slug('...');
}
}
Thank you !
You do not want to use autowiring in your constructor ?
You could just create a new slugger, for example with Symfony\Component\String\Slugger\AsciiSlugger;
$slugger = new AsciiSlugger();
$slugger->slug('Please slug this.')->toString();
Or you could also use autowiring with another method using #required annotation (or attribute #[Required] for PHP 8+)
private $slugger;
#[Required]
public function setSlugger(SluggerInterface $slugger): void
{
$this->slugger= $slugger;
}
this is in order to automatically create 1 slug when creating an object
You may also want to look into event listener, using doctrine event prePersist to slug your entity when persisted could be another idea.
Finally, gedmo doctrine-extensions sluggable may interest you as well.

ObjectForKey always returns null 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.

Convert ExpandoObject to anonymous type

Is it possible to convert ExpandoObject to anonymously typed object?
Currently I have HtmlHelper extension that can take HTML attributes as a parameter. The problem is that my extension also needs to add some HTML attributes so I've use ExpandoObject to merge my attributes and attributes that user passes to the function using htmlAttributes parameter. Now I need to pass merged HTML attributes to original HtmlHelper function, and when I send ExpandoObject, nothing happens. So I guess that I need to convert ExpandoObject to anonymously typed object or something similar - any suggestions are welcome.
I don't think that you need to deal with expandos to achieve your goal:
public static class HtmlExtensions
{
public static IHtmlString MyHelper(this HtmlHelper htmlHelper, object htmlAttributes)
{
var builder = new TagBuilder("div");
// define the custom attributes. Of course this dictionary
// could be dynamically built at runtime instead of statically
// initialized as in my example:
builder.MergeAttribute("data-myattribute1", "value1");
builder.MergeAttribute("data-myattribute2", "value2");
// now merge them with the user attributes
// (pass "true" if you want to overwrite existing attributes):
builder.MergeAttributes(new RouteValueDictionary(htmlAttributes), false);
builder.SetInnerText("hello world");
return new HtmlString(builder.ToString());
}
}
and if you wanted to call some of the existing helpers, then a simple foreach loop could do the job:
public static class HtmlExtensions
{
public static IHtmlString MyHelper(this HtmlHelper htmlHelper, object htmlAttributes)
{
// define the custom attributes. Of course this dictionary
// could be dynamically built at runtime instead of statically
// initialized as in my example:
var myAttributes = new Dictionary<string, object>
{
{ "data-myattribute1", "value1" },
{ "data-myattribute2", "value2" }
};
var attributes = new RouteValueDictionary(htmlAttributes);
// now merge them with the user attributes
foreach (var item in attributes)
{
// remove this test if you want to overwrite existing keys
if (!myAttributes.ContainsKey(item.Key))
{
myAttributes[item.Key] = item.Value;
}
}
return htmlHelper.ActionLink("click me", "someaction", null, myAttributes);
}
}
Is it possible to convert ExpandoObject to anonymously typed object?
Only if you generate the anonymous type yourself at execution time.
Anonymous types are normally created by the compiler, at compile-time, and baked into your assembly like any other type. They're not dynamic in any sense. So, you'd have to use CodeDOM or something similar to generate the same kind of code that's used for anonymous type... that's not going to be fun.
I think it's rather more likely that someone else will have created some MVC helper classes which know about ExpandoObject (or can just work with IDictionary<string, object>).

ordering of Hashtable in J2ME

I have some data and I have added them to Hashtable in some orders what I want to do now is to get the data in the same order that I have entered
What is the data type that I can use?
Assuming your key is a String you could add some ordering to it and have a getter method for the sorted data. See example below:
static int order;
Hashtable map = new Hashtable();
void put (String key, Object value) {
map.put(order + key, value);
order++;
}
Enumeration getSorted() {
Enumeration keys = map.keys();
Vector sortedKeys = new Vector();
while (keys.hasMoreElements()) {
String key = (String) keys.nextElement();
insertionSort(key, sortedKeys);
}
Vector sortedData = new Vector();
keys = sortedKeys.elements();
while (keys.hasMoreElements()) {
String key = (String) keys.nextElement();
sortedData.addElement(map.get(key));
}
return sortedData.elements();
}
You can find insertionSort algorithms at http://en.wikipedia.org/wiki/Insertion_sort
A Hashtable does not retain any ordering.
If you need insertion order access see if Linked Hash Map is offered in JavaME
You can download a source code of Java SE and make work LinkedHashMap in J2ME easily by removing generics (but also you might need to perform this on it's parent classes and interfaces).
You can find LinkedHashMap for Java ME here

replace static field

The CountryTagLib provided by Grails has an (out-of-date) list of Countries
class CountryTagLib {
static final ISO3166_3 = [
"scg":"Serbia and Montenegro",
"zmb":"Zambia"
]
}
I want to update this Map to replace the "Serbia and Montenegro" entry with an entry for each of Serbia and Montenegro.
Update
I can't simply update the contents of the Map or use metaprogramming because the contents of ISO3166_3 are copied into other variables in a static initializer
static {
ISO3166_3.each { k, v ->
COUNTRY_CODES_BY_NAME[v] = k
}
}
I need the code that modifies ISO3166_3 to be executed before this static initializer runs. I don't think there's any way I can achieve this, so I'm left with only the unpalatable option of copy-pasting the whole CountryTagLib into a custom taglib and modifying ISO3166_3 therein. I'll also have to change every <g:countrySelect> to use my tag instead. I really don't want to do this....
Why are you not accessing the map directly? The field is final which means you cannot modify the field itself but not its content:
You cannot do:
CountryTagLib.ISO3166_3 = xxxx // this will fail (final)
but this should work:
CountryTagLib.ISO3166_3.remove('scg')
..etc...
Yan's method is the cleanest IMO, but for future reference; one way to chain back to the replaced method in a metaClass override is to store the old method somewhere, then invoke this in the new method:
class CountryTagLib {
static final ISO3166_3 = [
"scg":"Serbia and Montenegro",
"zmb":"Zambia"
]
}
// Get a handle to our old static getISO3166_3 method
def originalGetter = CountryTagLib.metaClass.getStaticMetaMethod( 'getISO3166_3', [] as Object[] )
CountryTagLib.metaClass.static.getISO3166_3 = {
// Call the old method, and manipulate the map it returns
originalGetter.invoke( delegate, null ).with {
remove('scg')
put( 'srb', 'Serbia' )
put( 'mon', 'Montenegro' )
it
}
}

Resources