Create Product in MS Dynamics CRM 2011 via SOAP/Java - java

I generated all required java classes from crm.dynamics.com/XRMServices/2011/Discovery.svc?wsdl and crm.dynamics.com/XRMServices/2011/Organization.svc?wsdl schemas.
I authenticated in CRM with LiveId.
Now i need to create Product in Product Catalog. Here is code for this:
Entity newEntryInfo = new Entity();
AttributeCollection collection = new AttributeCollection();
addAttribute(collection, "name", "Tama Starclassic Performer");
addAttribute(collection, "productnumber", "1");
addAttribute(collection, "price", createMoney("100.0"));
addAttribute(collection, "isstockitem", Boolean.TRUE);
addAttribute(collection, "statuscode", 1);
newEntryInfo.setAttributes(collection);
newEntryInfo.setLogicalName("product");
Guid productGuid = serviceStub.create(newEntryInfo);
private void addAttribute(AttributeCollection collection, String key, Object value) {
KeyValuePairOfstringanyType values = new KeyValuePairOfstringanyType();
values.setKey(key);
values.setValue(value);
collection.addKeyValuePairOfstringanyType(values);
}
Execution shows error "The unit schedule id is missing."
Looks like i need to provide "Unit Group" and "Default Unit" for new product.
Question: How can i set those values? Should i use RelatedEntities (how create it) or Attributes (how create it)

As it is a lookup on the form, you should be able to set the value with an EntityReference.
Using your methods that would be:
addAttribute(collection, "fieldName", new EntityReference("entityName", new Guid("id"))
Where:
fieldName is the schema name of the field you want to populate
entityName is the schema name of the entity you want to populate the field with
id is the Guid of a record which is the same type as entityName.
To put that into a context (where I happen to know the schema names off the top of my head).
//Create a new contact first
Entity contact = new Entity("contact");
contact["lastname"] = "Wood";
Guid contactId = service.Create(contact);
//Create an incident/case which links to that new contact
Entity incident = new Entity("incident");
incident["customerid"] = new EntityReference("contact", contactId)
service.Create(incident)
As a side is there a particular reason you are using a such a long winded code style? The entity class has an index which links to underlying attribute dictionary. Its a bit more straight forward.
If you are looking for more examples check out: Use the Late Bound Entity Class in Code

Related

DocuSign's Java SDK: Add 'Recipient Company Name' to Signer/Recipient

DocuSigns' report section includes tables containing the column name Recipient Company Name
I had a look through all DocuSign models inside the SDK, but I couldn't find any way to fill this column. Is there a way to do so using the SDK?
This can only be filled if the recipient is either a :
Saved contact in your DocuSign account.
Has their own DocuSign account.
If your recipient is just a random email/name you added to a one-time envelope - there's no way to enter the company information.
You can update contacts in your account and add the company name, see this article I wrote about how to do that in 6 languages including Java:
(note the "Organization" field which is the compan)
// You will need to obtain an access token using your chosen authentication flow
Configuration config = new Configuration(new ApiClient(basePath));
config.addDefaultHeader("Authorization", "Bearer " + accessToken);
UsersApi usersApi = new UsersApi(config);
UserProfile userProfile = new UserProfile();
Contact contact = new Contact();
contact.setName("Inbar Gazit");
contact.setEmails(new java.util.ArrayList<String>());
contact.getEmails().add("inbar.gazit#docusign.com");
contact.setOrganization("DocuSign");
ContactPhoneNumber contactPhoneNumber = new ContactPhoneNumber();
contactPhoneNumber.setPhoneNumber("212-555-1234");
contactPhoneNumber.setPhoneType("mobile");
contact.setContactPhoneNumbers(new java.util.ArrayList<ContactPhoneNumber>());
contact.getContactPhoneNumbers().add(contactPhoneNumber);
ContactModRequest contactModificationRequest = new ContactModRequest();
contactModificationRequest.setContactList(new java.util.ArrayList<Contact>());
contactModificationRequest.getContactList().add(contact);
usersApi.postContacts(accountId, contactModificationRequest);

aem 6.1 extend user properties

Printscreen additional fields useradmin
How can I add some new User Properties to the CQ Users?
I found an solution but it don't work --> http://experience-aem.blogspot.ch/2014/01/aem-cq-56-extend-useradmin-add-new-user.html
I tried to manipulate in CRX the UserProperties.js with new Properties, I see them in useradmin but if I try to add the new propertie in Java Code (not via useradmin) I can save it without error, but the value is empty in useradmin.
And if I try to add some value via useradmin for the new propertie, all user gets the same value.
How can I add new User Properties, that I can set the Value via Java code like the standard properties.
user = userManager.createUser(username, password);
ValueFactory valueFactory = session.getValueFactory();
emailValue = valueFactory.createValue(email);
givennameValue = valueFactory.createValue(givenname);
nameValue = valueFactory.createValue(name);
//User class just accepts Value Object
user.setProperty("profile/" + UserProperties.EMAIL, emailValue);
user.setProperty("profile/" + UserProperties.FAMILY_NAME, nameValue);
user.setProperty("profile/" + UserProperties.GIVEN_NAME, givennameValue);
I found an solution.
Go to crx /libs/cq/security/widgets/source/widgets/security/UserProperties.js
add the fields you need in the items array of the user (Caution - there are items for user and items for groups in the same place)
in the loadRecord method of your JS, you have to add each new field to the "record" object
"items":[{
"xtype":"textfield",
"fieldLabel":CQ.I18n.getMessage("Mail"),
"anchor":"100%",
"vtype":"email",
"msgTarget":"under",
"name":"email"
},{
"xtype":"textfield",
"fieldLabel":CQ.I18n.getMessage("My Field"),
"anchor":"100%",
"msgTarget":"under",
"name":"myfield"
},{
"xtype":"textarea",
"fieldLabel":CQ.I18n.getMessage("About"),
"anchor":"100% -155",
"name":"aboutMe"
}],
loadRecord: function(rec) {
this.enableUserSaveButton(false);
this.enableGroupSaveButton(false);
var type = rec.get("type");
if (type=="user") {
this.activeForm = this.userForm;
this.hiddenForm = this.groupForm;
if (rec.id==CQ.security.UserProperties.ADMIN_ID) {
this.pwdButtons.each(function(bt) {bt.hide(); return true;} )
} else {
this.pwdButtons.each(function(bt) {bt.show(); return true;} )
}
} else {
this.activeForm = this.groupForm;
this.hiddenForm = this.userForm;
}
//is loading additional property from json and show it in formular
rec.data["myfield"] = rec.json["myfield"];
this.activeForm.getForm().loadRecord(rec);
In the java code you can then add the new properties via the "user" object to the new properties. Note that the properties are put into the subfolder "profile".
user.setProperty("profile/" + "myfield", myFieldValue);
Did you try the second approach, posted by "pedro" in the link you've posted?
It probably has to do with pushing the new field to the record:
http://experience-aem.blogspot.com/2014/01/aem-cq-56-extend-useradmin-add-new-user.html?showComment=1390804750445#c2823498719990547675
i hope this may helps you the file exist on http://[host name]:[port]/crx/de/index.jsp#/libs/cq/security/widgets/source/widgets/security/UserProperties.js
and you will have two major properties the first one is for the user this.userForm the other one is this.groupForm for groups.

MongoTemplate upsert - easy way to make Update from pojo (which user has editted)?

Here is a simple pojo:
public class Description {
private String code;
private String name;
private String norwegian;
private String english;
}
And please see the following code to apply an upsert to MongoDb via spring MongoTemplate:
Query query = new Query(Criteria.where("code").is(description.getCode()));
Update update = new Update().set("name", description.getName()).set("norwegian", description.getNorwegian()).set("english", description.getEnglish());
mongoTemplate.upsert(query, update, "descriptions");
The line to generate the Update object specifies every field of the Item class manually.
But if my Item object changes then my Dao layer breaks.
So is there a way to avoid doing this, so that all fields from my Item class are applied automatically to the update?
E.g.
Update update = new Update().fromObject(item);
Note that my pojo does not extend DBObject.
I found a pretty good solution for this question
//make a new description here
Description d = new Description();
d.setCode("no");
d.setName("norwegian");
d.setNorwegian("norwegian");
d.setEnglish("english");
//build query
Query query = new Query(Criteria.where("code").is(description.getCode()));
//build update
DBObject dbDoc = new BasicDBObject();
mongoTemplate.getConverter().write(d, dbDoc); //it is the one spring use for convertions.
Update update = Update.fromDBObject(dbDoc);
//run it!
mongoTemplate.upsert(query, update, "descriptions");
Plz note that Update.fromDBObject return an update object with all fields in dbDoc. If you just want to update non-null fields, you should code a new method to exclude null fields.
For example, the front-end post a doc like below:
//make a new description here
Description d = new Description();
d.setCode("no");
d.setEnglish("norwegian");
We only need to update the field 'language':
//return Update object
public static Update fromDBObjectExcludeNullFields(DBObject object) {
Update update = new Update();
for (String key : object.keySet()) {
Object value = object.get(key);
if(value!=null){
update.set(key, value);
}
}
return update;
}
//build udpate
Update update = fromDBObjectExcludeNullFields(dbDoc);
The solution for a new spring-data-mongodb version 2.X.X.
The API has evolved, since 2.X.X version there is:
Update.fromDocument(org.bson.Document object, String... exclude)
instead of (1.X.X):
Update.fromDBObject(com.mongodb.DBObject object, String... exclude)
The full solution:
//make a new description here
Description d = new Description();
d.setCode("no");
d.setName("norwegian");
d.setNorwegian("norwegian");
d.setEnglish("english");
Query query = new Query(Criteria.where("code").is(description.getCode()));
Document doc = new Document(); // org.bson.Document
mongoTemplate.getConverter().write(item, doc);
Update update = Update.fromDocument(doc);
mongoTemplate.upsert(query, update, "descriptions");
It works!
you can use save : (if non exist = insert else = upsert)
save(Object objectToSave, String collectionName)
read : javadoc
Just like previous answers said, use mongoTemplate.getConverter().write() and Update.fromDocument() functions. But i found Update.fromDocument() won't add "$set" key and won't work directly, the solution is to add "$set" yourself, like below (PS: I'm using 2.2.1.RELEASE version):
public static Update updateFromObject(Object object, MongoTemplate mongoTemplate) {
Document doc = new Document();
mongoTemplate.getConverter().write(object, doc);
return Update.fromDocument(new Document("$set", doc));
}
If you want to upsert Pojos incl. property String id; you have to exclude the _id field in the fromDBObject method Update.fromDBObject(dbDoc,"_id").
Otherwise you get the Exception:
org.springframework.dao.DuplicateKeyException: { "serverUsed" : "127.0.0.1:27017" , "ok" : 1 , "n" : 0 , "updatedExisting" : false , "err" : "E11000 duplicate key error collection: db.description index: _id_ dup key: { : null }" , "code" : 11000}; nested exception is com.mongodb.MongoException$DuplicateKey: { "serverUsed" : "127.0.0.1:27017" , "ok" : 1 , "n" : 0 , "updatedExisting" : false , "err" : "E11000 duplicate key error collection: db.description index: _id_ dup key: { : null }" , "code" : 11000}
because the _id field of the first is null
{
"_id" : null,
...
}
Fullcode based on #PaniniGelato answer would be
public class Description(){
public String id;
...
}
Description d = new Description();
d.setCode("no");
d.setName("norwegian");
d.setNorwegian("norwegian");
d.setEnglish("english");
//build query
Query query = new Query(Criteria.where("code").is(description.getCode()));
//build update
DBObject dbDoc = new BasicDBObject();
mongoTemplate.getConverter().write(d, dbDoc); //it is the one spring use for convertions.
Update update = Update.fromDBObject(dbDoc, "_id");
//run it!
mongoTemplate.upsert(query, update, "descriptions");
Then the upsert is working in the cases of insert and update. Corrections & thoughts are welcome ;)
This is what I am doing for the time being. Not so much elegant way to do it, but it does save a precious DB call:
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;
import com.mongodb.util.JSON;
/**
* Perform an upsert operation to update ALL FIELDS in an object using native mongo driver's methods
* since mongoTemplate's upsert method doesn't allow it
* #param upsertQuery
* #param object
* #param collectionName
*/
private void performUpsert(Query upsertQuery, Object object, String collectionName){
ObjectMapper mapper = new ObjectMapper();
try {
String jsonStr = mapper.writeValueAsString(object);
DB db = mongoTemplate.getDb();
DBCollection collection = db.getCollection(collectionName);
DBObject query = upsertQuery.getQueryObject();
DBObject update = new BasicDBObject("$set", JSON.parse(jsonStr));
collection.update(query, update, true, false);
} catch (IOException e) {
LOGGER.error("Unable to persist the metrics in DB. Error while parsing object: {}", e);
}
}
There are two cases here that need to be distinguished:
Update an item that was previously fetched from the DB.
Update or insert (upsert) an item you created by code.
In Case 1) You can simply use mongoTemplate.save(pojo, "collection"), because your POJO will already have a filled ObjectID in its id field.
In case 2) You have to explain to mongo what "already exists" means in case of your domain model: By default the mongoTemplate.save() method updates an existing item, if there is one with that same ObjectId. But with a newly instantiated POJO you do not have that id. Therefore the mongoTemplate.upsert() method has a query parameter that you can create like this:
MyDomainClass pojo = new MyDomainClass(...);
Query query = Query.query(Criteria.where("email").is("user1#domain.com"));
DBObject dbDoc = new BasicDBObject();
mongoTemplate.getConverter().write(pojo, dbDoc); //it is the one spring use for convertions.
dbDoc.removeField("_id"); // just to be sure to not create any duplicates
Update update = Update.fromDBObject(dbDoc);
WriteResult writeResult = mongoTemplate.upsert(query, update, UserModel.class);
I ran into the same problem. In het current Spring Data MongoDB version no such thing is available. You have to update the seperate fields by hand.
However it is possible with another framework: Morphia.
This framework has a wrapper for DAO functionality: https://github.com/mongodb/morphia/wiki/DAOSupport
You can use the DAO API to do things like this:
SomePojo pojo = daoInstance.findOne("some-field", "some-value");
pojo.setAProperty("changing this property");
daoInstance.save(pojo);
I think that:
Description add a property
#Id
private String id;
then get a document by the query condition,set Description's id by document's id.
and save
Just use ReflectionDBObject - if you make Description extend it, you should just get your object's fields transferred to Update reflectively, automagically. The note from above about null fields included in the update still holds true.
public void saveOrUpdate(String json) {
try {
JSONObject jsonObject = new JSONObject(json);
DBObject update1 = new BasicDBObject("$set", JSON.parse(json));
mongoTemplate.getCollection("collectionName").update(new Query(Criteria.where("name").is(jsonObject.getString("name"))).getQueryObject(), update1, true, false);
} catch (Exception e) {
throw new GenericServiceException("Error while save/udpate. Error msg: " + e.getMessage(), e);
}
}
this is very simple way to save json string into collection using mongodb
and spring.
This method can be override to use as JSONObject.
#Override
public void updateInfo(UpdateObject algorithm) {
Document document = new Document();
mongoTemplate.getConverter().write(algorithm, document);
Update update = Update.fromDocument(document);
mongoTemplate.updateFirst(query(where("_id").is(algorithm.get_id())), update, UpdateObject.class);
}
After upsert, I was Tring to fetch same record but it was given me the old one.
But in dB I am having new records.

smartgwt SelectItem with empty value

I have a SelectItem, that fetches data from database. I need to add an emptyField to my select Item.
My code looks like that, and that works great.
SelectItem editor = new SelectItem(...);
editor.setOptionDataSource(new DataAllowableValuesDS('data id for database request'));
but after i've changed it to the code below, start_row and end_row fields in HttpServletRequest have been changed to "-1". How can I solve that?
SelectItem editor = new SelectItem(...);
editor.setAllowEmptyValue(true);
editor.setOptionDataSource(new DataAllowableValuesDS('data id for database request'));
public DataAllowableValuesDS(String id) {
DataSourceField nameField = new DataSourceTextField("name", null, 2000);
nameField.setPrimaryKey(true);
setFields(nameField);
}
Have you set valueField (="name") and displayField for the SelectItem?
Those attributes allow DataSource to map results to the SelectItem.
One thing I noticed in your code is, value passed to 'id' in DataAllowableValuesDS constructor is never used.
Also, results should have both key/value pair.
Try changing SelectItem and DataAllowableValuesDS as
SelectItem editor = new SelectItem(...);
editor.setAllowEmptyValue(true);
editor.setValueField("key");
editor.setDisplayField("value");
public DataAllowableValuesDS(String id) {
DataSourceField keyField = new DataSourceTextField("key", "Key");
DataSourceField valueField = new DataSourceTextField("value", "Value");
setFields(keyField, valueField);
}
Other options
use a DataArrivedHandler to add an empty value
try sending the empty value as part of results from server side
Post your DataAllowableValuesDS code if possible.

how to retrieve ID after object store into database

I am using Java, spring, jpa for our application. I want to retrieve Id of insert row. Basically our ID is generated at the time of storing object into database.
RoleRequest role = new RoleRequest();
roleRequest.setUser(user);
roleRequest.setRole(role);
roleRequest.setRequestDate(new Date());
roleRequest.setStatusCode(Enum.PENDING);
Dao.persist(roleRequest);
So after storing this object, I need new generated id for this object, so that will perform some operation on it.
Dao.persist(roleRequest);
After this line, the id should be set, so you can just do
Long id = roleRequest.getId();
(assuming id as id column and Long as id type)
What about:
oleRequest role = new RoleRequest();
roleRequest.setUser(user);
roleRequest.setRole(role);
roleRequest.setRequestDate(new Date());
roleRequest.setStatusCode(RoleRequestStatusEnum.PENDING);
Dao.persist(roleRequest);
int myId = roleRequest.getId();
You may need to do EntityManager.flush() after EntityManager.persist() (YMMV).

Categories