I use Xamarin.ios with the below code:
var dict = NSUserDefaults.StandardUserDefaults.DictionaryForKey("TheDictKey");
if (dict == null)
{
dict = new NSDictionary();
NSUserDefaults.StandardUserDefaults.SetValueForKey(dict,(NSString)"TheDictKey");
}
dateTime = dateTime.ToUniversalTime();
dict[(NSString)"ValueKey"] = new NSString("Value"); //<------ throw exception here
The last sentence alway throw exception "NotSupported".
How can I update the dictionary?
Thanks
That is because NSDictionary is immutable. That means that after it is created, you cannot change it. Use NSMutableDictionary for this purpose instead, which is a subclass of NSDictionary.
From Apple's NSDictionary reference:
NSDictionary creates static dictionaries, and NSMutableDictionary creates dynamic dictionaries.
Here: click
Related
java-driver 4.1.10 I've created database named mydatabase1 I've created a graph using Java so my question is that how to set edge label using Java code?
If you mean with "edge label" a field in an edge-document, you can set it when you call insertEdge like in the code below.
ArangoDB arangoDB = new ArangoDB.Builder().build();
// create database
arangoDB.createDatabase("myDatabase");
// create named graph
Set<EdgeDefinition> edgeDefinitions = Collections.singleton(
new EdgeDefinition().collection("myEdgeCollection").from("myVertexCollection").to("myVertexCollection"));
arangoDB.db("myDatabase").createGraph("myGraph", edgeDefinitions);
// create from vertex
BaseDocument from = new BaseDocument("myFromKey");
arangoDB.db("myDatabase").graph("myGraph").vertexCollection("myVertexCollection").insertVertex(from);
// create to vertex
BaseDocument to = new BaseDocument("myToKey");
arangoDB.db("myDatabase").graph("myGraph").vertexCollection("myVertexCollection").insertVertex(to);
// create edge
BaseEdgeDocument edge = new BaseEdgeDocument("myVertexCollection/myFromKey",
"myVertexCollection/myToKey");
edge.addAttribute("label", "value");
edge.addAttribute("whatever", 42);
arangoDB.db("myDatabase").graph("myGraph").edgeCollection("myEdgeCollection").insertEdge(edge);
Instead of using BaseEdgeDocument you can also use Map<String, Object>
Map<String, Object> edge = new HashMap<String, Object>();
edge.put("_from", "myVertexCollection/myFromKey");
edge.put("_to", "myVertexCollection/myToKey");
edge.put("label", "value");
edge.put("whatever", 42);
arangoDB.db("myDatabase").graph("myGraph").edgeCollection("myEdgeCollection").in sertEdge(edge);
or create your own POJO representing your edge. The edge needs at least the fields _from and _to. If you don't want to name the fields in your POJO _from and _to, you can use the annotation DocumentField with the values Type.FROM and Type.TO on two String fields of your choice.
public class MyEdge {
#DocumentField(Type.FROM)
private String from;
#DocumentField(Type.TO)
private String to;
public MyEdge() {}
..setter & getter
}
There are several reasons why somebody wants to merge multiple NSManagedObjectModel's. If you search the web, all responses are that it is not possible or that it is only possible for two unrelated entities that share one or more relationships. See this and this link for example.
However with a bit or more work it is (I think) possible to merge NSManagedObjectModels, even if the entities are related (as in parent-child) or if the attributes are spread out across multiple models.
Though it will not show as readily in the Xcode model editor and out-of-box transitions (probably) won't work.
In the answer below my observations about core data and my code on merging several models. If you find any bugs or have suggestions for improvements, please respond here.
Some things I noticed:
Copying a NSPropertyDescription (attribute, relationship) copies all its values, but not the entity to which it belongs. Same for the destinationEntity and inverseRelationship.
Thus a copied NSPropertyDescription should be added to an entity. As a result, all the children entities of that entity automatically get the property as well.
Copying a NSEntityDescription does not include the parent entity. So the tree (of NSManagedObjectEntity) has to rebuild manually.
If you set the parent of an entity, that (child) entity will immediately and automatically inherit all its parent properties. In other words when you ask an entity for its attributes, this entity already knows about all its attributes. It will not first query its parent. (reasonable assumption)
Adding entities to a model fills in the destination entities and inverse relationship descriptions of the relationsDescriptions of the added entities.
if you do not set the name of any entity or property before using it, core data will complain. That is the copy by name instead of value aspect.
Adding a property to an entity which already has a property with the same name (either from itself or inherited from its ancestor) will make core data complain.
This translates into the following code:
extension NSPropertyDescription
{
var isPlaceholder : Bool { return self.userInfo?["isPlaceholder"] != nil }
}
extension NSEntityDescription
{
var isPlaceholder : Bool { return self.userInfo?["isPlaceholder"] != nil }
}
func mergeModels(models: [NSManagedObjectModel]) -> NSManagedObjectModel?
{
var entities : [String : NSEntityDescription] = [:]
//support functions
let makeEntity : String -> NSEntityDescription = { entityName in
let newEntity = NSEntityDescription()
entities[entityName] = newEntity
newEntity.name = entityName
return newEntity
}
let setParent : (String, NSEntityDescription) -> () = { parentName, child in
if let parent = entities[parentName]
{
parent.subentities.append(child)
}
else //parent has not yet been encountered, so generate it
{
let newParentEntity = makeEntity(parentName)
newParentEntity.subentities.append(child)
}
}
//rebuild model: generate new description for each entity and add non-placeholder properties
for model in models
{
for entity in model.entities
{
guard let entityName = entity.name else { fatalError() }
let mergedEntity = entities[entityName] ?? makeEntity(entityName)
//set entity properties
if !entity.isPlaceholder
{
mergedEntity.abstract = entity.abstract
mergedEntity.managedObjectClassName = entity.managedObjectClassName
}
//set parent, if any
if mergedEntity.superentity == nil, //no parent set
let parentName = entity.superentity?.name //but parent is required
{
setParent(parentName, mergedEntity)
}
//set properties
for property in entity.properties
{
if property.isPlaceholder ||
mergedEntity.properties.contains({$0.name == property.name})
{ continue }
let newProperty = property.copy() as! NSPropertyDescription
mergedEntity.properties.append(newProperty)
}
}
}
//generate final model
let mergedModel = NSManagedObjectModel()
mergedModel.entities = Array(entities.values) //sets the destination entity and inverse relationship descriptions
return mergedModel
}
In the managedObjectModel (xcode editor) set the "placeholder" flag in the user info dictionary of the entity and/or the property.
The model generation can be refined by setting additional keys in the user info dictionary to specify which model has the prime entity/attribute/relationship (settings) and appropriately adjusting this code fragment.
However, if you can avoid using multiple models then avoid it. Your life will be much simpler by sticking to the standard single Model approach.
[Disclaimer: as far as I can tell, this code should work. No guarantees though.]
The NSManagedObjectModel class has the following factory methods / constructors
class func mergedModel(from: [Bundle]?)
class func mergedModel(from: [Bundle]?, forStoreMetadata: [String : Any])
init?(byMerging: [NSManagedObjectModel]?)
init?(byMerging: [NSManagedObjectModel], forStoreMetadata: [String : Any])
The optional forStoreMetadata attribute allows to specify the models' version.
see https://developer.apple.com/documentation/coredata/nsmanagedobjectmodel
(I suspect these methods not being available at the time the op asked & answered the question.)
Although there are several questions related to this exception, Folks, this is not a possible duplicate . Iterating through multiple excel sheets using APACHE POI , I have to use JPA to perform a many to one relation
for (int i = 0; i < wb.getNumberOfSheets(); i++) {
HSSFSheet sheet = wb.getSheetAt(i);
....
if(i=0)
{
Baseclass obj = new Baseclass ();
obj.setname("name");
session.save(obj)
session.getTransaction().commit();
}
if(i=3)
{
Foreigclass obj2 = new Foreigclass ();
obj2.setsection("2A");
Baseclass obj = new Baseclass ();
--> obj2.setTransport(obj); // linking foreign keys // error comes here
session.save(obj2)
}
At the marked line, I am getting the following exception:
Exception in thread "main" org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: model.CepTransport
at org.hibernate.engine.internal.ForeignKeys.getEntityIdentifierIfNotUnsaved(ForeignKeys.java:294)
at org.hibernate.type.EntityType.getIdentifier(EntityType.java:537)
at org.hibernate.type.ManyToOneType.isDirty(ManyToOneType.java:311)
at org.hibernate.type.ManyToOneType.isDirty(ManyToOneType.java:321)
at org.hibernate.type.TypeHelper.findDirty(TypeHelper.java:294)
at org.hibernate.persister.entity.AbstractEntityPersister.findDirty(AbstractEntityPersister.java:4243)
at org.hibernate.event.internal.DefaultFlushEntityEventListener.dirtyCheck(DefaultFlushEntityEventListener.java:546)
at org.hibernate.event.internal.DefaultFlushEntityEventListener.isUpdateNecessary(DefaultFlushEntityEventListener.java:232)
Can someone suggest what is wrong here ? The CASCADing properties are fine and everything works fine if data comes from only one excel sheet.
In below code you are creating objects for Foreigclass & Baseclass and trying to save only one:
Foreigclass obj2 = new Foreigclass (); // Created Foreigclass object
obj2.setsection("2A");
Baseclass obj = new Baseclass (); // Created Baseclass object
obj2.setTransport(obj); // linking foreign keys // error comes here
session.save(obj2);
So initially the obj2 and obj are in Transient state, so when you call session.save(obj2) it checks the linked entities and there state before making obj2 to Persistent state. As obj is still in Transient state it complains with error as:
org.hibernate.TransientObjectException: object references an unsaved transient instance
- save the transient instance before flushing: model.CepTransport.
Here I guess CepTransport is same as Baseclass.
To fix this issue, save your Baseclass before saving Foreigclass like this:
session.save(obj);
session.save(obj2);
But if you want to use CASCADE setting then check the settings at Foreigclass and make sure that the CASCADE values are correct.
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
I need help creating a method that allows me to create a bunch of fields during featureactivated. C#. There are about 15 different fields, of varying types, and I'd like to be able to pass in all of the necessary attributes to create each field.
Anyone have any sample code or guidance on this?
Okay I found part of the answer...quite a bit to go though. I found the following utility method here:
public void AddCustomField(SPWeb web, string fieldType, string fieldName, bool isRequired, string defaultValue, string fieldGroup)
{
//Check if the field is there or not already
if (!web.Fields.ContainsField(fieldName))
{
//Initializing a SPField instance
SPField customField;
//Creating a new filed
customField = web.Fields.CreateNewField(fieldType, fieldName);
//Assigning a group
customField.Group = fieldGroup;
//Sets this field is required field
customField.Required = isRequired;
//Assigning a default value
customField.DefaultValue = defaultValue;
//Adding the newly created field to SPweb
web.Fields.Add(customField);
}
}
However, I'm not sure how to call this method, could someone give me an example?