I'm trying to remove a model from database using ModelService in my groovy script but it doesn't remove.
import de.hybris.platform.core.model.order.OrderModel
import de.hybris.platform.ordersplitting.model.ConsignmentModel
List<String> orderList = new ArrayList<>()
orderList.add("P000015003")
OrderModel orderModel = flexibleSearchService.search(String.format("SELECT {PK} FROM {AbstractOrder} WHERE {code} = '%s'", "P000015003")).result.get(0)
ConsignmentModel consignment = orderModel.getConsignments().iterator().next()
ModelService modelService = (ModelService) spring.getBean("modelService");
modelService.remove(consignment)
println("Removed")
Have you checked if the 'commit' mode is ON as shown in the image below?
You could use transaction to perform commit operation:
import de.hybris.platform.core.model.order.OrderModel
import de.hybris.platform.ordersplitting.model.ConsignmentModel
def tx = de.hybris.platform.tx.Transaction.current()
tx.begin()
List<String> orderList = new ArrayList<>()
orderList.add("P000015003")
OrderModel orderModel = flexibleSearchService.search(String.format("SELECT {PK} FROM {AbstractOrder} WHERE {code} = '%s'", "P000015003")).result.get(0)
ConsignmentModel consignment = orderModel.getConsignments().iterator().next()
ModelService modelService = (ModelService) spring.getBean("modelService");
modelService.remove(consignment)
println("Removed")
tx.commit()
Related
I am trying to run a filter in MongoDB Compass and it returns all rows instead of the row that I am looking for. I can run the filter on example databases that are similar to my database without any problem.
https://i.stack.imgur.com/IBivJ.png
Here is the code that I am using to add records and select from them.
public class NoSQLDataAccess
{
// Create an instance of data factory
public NoSQLDataFactory noSQLDataFactory;
public List<dynamic> DocumentDetails { get; set; }
private IMongoCollection<dynamic> collection;
private BsonDocument bsonDocument = new BsonDocument();
public NoSQLDataAccess() { }
public void TestNoSQL()
{
MongoClient client;
IMongoDatabase database;
string connectionString = ConfigurationManager.AppSettings["NoSQLConnectionString"];
client = new MongoClient(connectionString);
database = client.GetDatabase("TestDatabase");
collection = database.GetCollection<dynamic>("TestCollection");
// Insert
List<Layer> layers = new List<Layer>();
layers.Add(new Layer { LayerId = 117368, Description = "BOOTHLAYER" });
layers.Add(new Layer { LayerId = 117369, Description = "DRAWINGLAYER" });
layers.Add(new Layer { LayerId = 117370, Description = "LAYER3" });
List<Element> elements = new List<Element>();
elements.Add(new Element { ElementId = 9250122, Type = "polyline" });
elements.Add(new Element { ElementId = 9250123, Type = "polyline" });
List<dynamic> documentDetails = new List<dynamic>();
documentDetails.Add(new DrawingDTO { Layers = layers, Elements = elements });
collection.InsertMany(documentDetails);
List<FilterDetails> filterDetails = new List<FilterDetails>();
filterDetails.Add(new FilterDetails { Type = "layers.id", Value = "117368" });
foreach (FilterDetails detail in filterDetails)
{
bsonDocument.Add(new BsonElement(detail.Type, detail.Value));
}
List<dynamic> results = collection.Find(bsonDocument.ToBsonDocument()).ToList();
}
}
I have been able to get the result I need with MongoDB shell but I have not been able to replicate the results in C#.
Here is the solution in MongoDB shell:
db.TestCollection.find({"layers.id": 117368}, {_id:0, layers: {$elemMatch: {id: 117368}}}).pretty();
I have found a post that is similar to my question that works for them. The C# code that I attached is how I will access it after I get it working properly. I use MongoDB Compass to test finds/inserts/updates/deletes.
Retrieve only the queried element in an object array in MongoDB collection
I am tying like this , I want to use same method for inserting and updating, also same form to insert and update. please help me.. this is my controller, it is working fine if I choose new image while updating but if I didnot select image while updating and only update other details then image updated to null in database..
public ModelAndView addOrUpdateFoodItems(#RequestParam(name = "file")CommonsMultipartFile file,
#RequestParam(name = "food_name")String food_name,
#RequestParam(name = "food_type")String food_type,
#RequestParam(name = "food_tags")String food_tags,
#RequestParam(name = "food_desription")String food_desription,
#RequestParam(name = "protein_intake")String protein_intake,
#RequestParam(name = "calorie_intake")String calorie_intake,
#RequestParam(name = "carbs_intake")String carbs_intake,ModelAndView model, HttpServletRequest request){
FoodItemDetails foodItemDetails;
foodItemDetails= (FoodItemDetails) request.getSession().getAttribute("FoodItemDetails");
if(foodItemDetails==null){
foodItemDetails=new FoodItemDetails();
}else{
System.out.println(foodItemDetails.getFood_name());
}
foodItemDetails.setFood_name(food_name);
foodItemDetails.setFood_type(food_type);
foodItemDetails.setFood_tags(food_tags);
foodItemDetails.setFood_desription(food_desription);
foodItemDetails.setProtein_intake(protein_intake);
foodItemDetails.setCalorie_intake(calorie_intake);
foodItemDetails.setCarbs_intake(carbs_intake);
if(file.getOriginalFilename()!=null){
foodItemDetails.setFood_item_image(file.getBytes());
foodItemDetails.setFood_item_image_name(file.getOriginalFilename());}
else{
foodItemDetails.setFood_item_image_name(foodItemDetails.getFood_item_image_name());
foodItemDetails.setFood_item_image(foodItemDetails.getFood_item_image());
}
boolean done= trainerService.saveOrUpdateFoodItems(foodItemDetails);
model.setViewName("redirect:/trainer/addFoodItems");
return model;
}
I tried to add attachment in ics file but it not showing in outlook when open it. I am trying to add attachment like when we send meeting request and add attachment in that from outlook, that attachment can view from calendar as well. This is my ics file :
BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//appform.com//NONSGML kigkonsult.se iCalcreator 2.18//
METHOD:PUBLISH
X-WR-TIMEZONE:UTC
X-MS-OLK-FORCEINSPECTOROPEN:TRUE
BEGIN:VEVENT
UID:20160719T144014-694839744#appform.com
DTSTAMP:20160719T124014Z
ATTACH;FMTTYPE="application/msword; charset=binary";FILENAME=1468827330fCrj
O.doc:/var/www/html/basearch.appform.com/application/../public/uploads/146
8827330fCrjO.doc
ATTENDEE;RSVP=TRUE;SENT-BY="MAILTO:sajal#mailinator.com";CN=satyendra#hirest
orm.com;DIR="/var/www/html/app/application/../public/uplo
ads/1468827330fCrjO.doc";LANGUAGE=us-EN;X-AGENDA=Interview;X-LENGTH=30 min
:MAILTO:satyendra#mailinator.com
DESCRIPTION:Name: Dean Nestle Jones G\nVacancy: test\nEmployer: Zend\nDate:
Wednesday\, 20thJuly 2016\nTime: 1430 to 1500\n\nSubmit Feedback : http:/
/hirestorm.com/tms/a/Mg==/appid/NDU4/vacid/MTY4/candid/MTY=\n\nCandida
te CV : https://f12b1a775b358d1fc463-637e94f874af614e321f6.ssl.
cf2.rackcdn.com/1468827330fCrjO.doc\nOther Documents : https://f12b1a775
b358d1fc463-637e94f874af614cdn.com/146297361
8PwEwE.jpeg\n
DTSTART:20160720T090000Z
DTEND:20160720T093000Z
LOCATION:1 2 Elmshorn Schleswig-Holstein Germany
SEQUENCE:0
SUMMARY:New Interview Confirmed: Dean Nestle Jones G for test
BEGIN:VALARM
ACTION:PROCEDURE
DESCRIPTION:Name: Dean Nestle Jones G\nVacancy: test\nEmployer: Zend\nDate:
Wednesday\, 20thJuly 2016\nTime: 1430 to 1500\n\nSubmit Feedback : http:/
/hirestorm.com/tms/a/Mg==/appid/NDU4/vacid/MTY4/candid/MTY=\n\nCandida
te CV : https://f12b1a775b358d1fc463-637e94f874af614ce048a5e321d7d0f6.ssl.
cf2.rackcdn.com/1468827330fCrjO.doc\nOther Documents : https://f12b1a775
b358d1fc463-637e94f874af614ce048a5e32cdn.com/146297361
8PwEwE.jpeg\n
TRIGGER:-PT0H15M0S
END:VALARM
END:VEVENT
END:VCALENDAR
Your iCalendar file contains a reference to :
/var/www/html/basearch.appform.com/application/../public/uploads/1468827330fCrjO.doc
This would obviously be something on your machine. You're not embedding any file, you're just pasting a local path. Unless you have Outlook running on linux there's no way it can find that path.
I tried to do it in a simple java
import java.io.IOException;
import java.net.URI;
import java.text.ParseException;
import java.util.HashMap;
import javax.activation.DataHandler;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.util.ByteArrayDataSource;
import com.tba.readProps.Constants;
import com.tba.readProps.ReadProps;
import net.fortuna.ical4j.model.Calendar;
import net.fortuna.ical4j.model.DateTime;
import net.fortuna.ical4j.model.Period;
import net.fortuna.ical4j.model.component.VEvent;
import net.fortuna.ical4j.model.parameter.Cn;
import net.fortuna.ical4j.model.parameter.Role;
import net.fortuna.ical4j.model.property.Attendee;
import net.fortuna.ical4j.model.property.CalScale;
import net.fortuna.ical4j.model.property.ProdId;
import net.fortuna.ical4j.model.property.Uid;
import net.fortuna.ical4j.model.property.Version;
import net.fortuna.ical4j.util.RandomUidGenerator;
import net.fortuna.ical4j.util.UidGenerator;
public class EmailWithCalendar{
/**
* #param emailAddr
* #param subject
* #param message
*/
public static void sendHtmlEmail(String emailAddr, String subject, String message){
HashMap propertyValues = null;
String smtpHost = "";
try {
propertyValues = ReadProps.initializeProperties();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
smtpHost = (String) propertyValues.get(Constants.SMTP_HOST);
//ManagerPropertiesBean mgrProps = new ManagerPropertiesBean();
//String smtpHost = mgrProps.getMgrProperty("smtpHost");
try {
// start a session with given properties
java.util.Properties props = new java.util.Properties();
props.put("mail.smtp.host", smtpHost);
Session mailSession = Session.getDefaultInstance(props, null);
String fromAddress = null;
fromAddress = (String) propertyValues.get(Constants.FROM_ADDRESS);
if(!"undefined".equals(fromAddress)){
InternetAddress fromAddr = new InternetAddress("test#test.com");
InternetAddress toAddr = new InternetAddress(emailAddr);
MimeMessage myMessage = new MimeMessage(mailSession);
String replyToAddress = null;
replyToAddress = (String) propertyValues.get(Constants.REPLY_ADDRESS);
InternetAddress replyToAddr[] = new InternetAddress[1];
if(!"undefined".equals(replyToAddress))
replyToAddr[0] = new InternetAddress(replyToAddress);
boolean isfromValid = true;
boolean isToValid = true;
boolean emailDomainCheck = true;
MimeBodyPart messageBodyPart =new MimeBodyPart();
messageBodyPart.setContent(message ,"text/html" );
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
myMessage.setContent(multipart);
if(emailDomainCheck==true)
{
myMessage.addRecipient(javax.mail.Message.RecipientType.TO, toAddr);
myMessage.setReplyTo(replyToAddr);
}
else
{
myMessage.setFrom(fromAddr);
myMessage.addRecipient(javax.mail.Message.RecipientType.TO, toAddr);
if(!"undefined".equals(replyToAddress))
myMessage.setReplyTo(replyToAddr);
}
myMessage.setSentDate(new java.util.Date());
myMessage.setSubject(subject);
messageBodyPart.setDataHandler(new DataHandler(
new ByteArrayDataSource(createEvent().toString(), "text/calendar")));// very important
//myMessage.setText(message);
// now send the message!
if(emailDomainCheck==true)
{
if(isfromValid==true && isToValid==true)
{
Transport.send(myMessage);
}
}
else
{
Transport.send(myMessage);
}
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("Error occurred in ManagerEmailBean.sendHtmlEmail()");
}
}
private static Calendar createEvent() throws ParseException {
// Create the event
String eventName = "Progress Meeting";
//DateTime start = new DateTime(startDate.getTime());
//DateTime end = new DateTime(endDate.getTime());
// Create the date range which is desired.
DateTime start = new DateTime("20100101T070000Z");
DateTime end = new DateTime("20100201T070000Z");;
Period period = new Period(start, end);
VEvent meeting = new VEvent(start, end, eventName);
// add timezone info..
//meeting.getProperties().add(tz.getTimeZoneId());
// generate unique identifier..
UidGenerator ug = new RandomUidGenerator();
Uid uid = ug.generateUid();
meeting.getProperties().add(uid);
// add attendees..
Attendee dev1 = new Attendee(URI.create("mailto:dev1#test.com"));
dev1.getParameters().add(Role.REQ_PARTICIPANT);
dev1.getParameters().add(new Cn("Developer 1"));
meeting.getProperties().add(dev1);
Attendee dev2 = new Attendee(URI.create("mailto:dev2#test.com"));
dev2.getParameters().add(Role.OPT_PARTICIPANT);
dev2.getParameters().add(new Cn("Developer 2"));
meeting.getProperties().add(dev2);
// Create a calendar
net.fortuna.ical4j.model.Calendar icsCalendar = new net.fortuna.ical4j.model.Calendar();
icsCalendar.getProperties().add(new ProdId("-//Events Calendar//iCal4j 1.0//EN"));
icsCalendar.getProperties().add(Version.VERSION_2_0);
icsCalendar.getProperties().add(CalScale.GREGORIAN);
// Add the event and print
icsCalendar.getComponents().add(meeting);
System.out.println(icsCalendar);
return icsCalendar;
}
public static void main(String[] args) {
sendHtmlEmail("dev.test#gmail.com", "Test", "sjgsfgsf<p>dshdfsdf</p>");
}
}
I'm trying to collect my url and the description of the url stored in a column of a list from sharepoint and i don't know how to collect the URL value.
This is my code :
var queryResultSaleListItems = clientContext.LoadQuery(listData);
clientContext.ExecuteQuery();
//Read the Data into the Object
var TipsList = from Tips in queryResultSaleListItems
select Tips;
ObservableCollection<Tips> colTips = new ObservableCollection<Tips>();
//Read Every List Item and Display Data into the DataGrid
foreach (SPSClient.ListItem item in TipsList)
{
var tips = new Tips();
tips.TitleTip = item.FieldValues.Values.ElementAt(1).ToString();
tips.App = item.FieldValues.Values.ElementAt(4).ToString();
//should collect the url
tips.URL = item.FieldValues.Values.ElementAt(5).ToString();
//should collect the description of the url
tips.URLdesc = item.FieldValues.Values.ElementAt(5).ToString();
colTips.Add(tips);
}
ListboxTips.DataContext = colTips;
In my expression its >
((Microsoft.SharePoint.Client.FieldUrlValue)(item.FieldValues.Values.ElementAt(5))).Url
((Microsoft.SharePoint.Client.FieldUrlValue)(item.FieldValues.Values.ElementAt(5))).Description
Thanks for your help,
Use FieldUrlValue for getting hyperlink field in Client Object Model.
Use Following Code:
string server = "siteURL";
var ctx = new ClientContext(server);
var web = ctx.Web;
var list = web.Lists.GetByTitle("CustomList");
var listItemCollection = list.GetItems(CamlQuery.CreateAllItemsQuery());
ctx.Load(listItemCollection);
ctx.ExecuteQuery();
foreach (Microsoft.SharePoint.Client.ListItem listItem in listItemCollection)
{
string acturlURL = ((FieldUrlValue)(listItem["URL"])).Url.ToString(); // get the Hyperlink field URL value
string actdesc = ((FieldUrlValue)(listItem["URL"])).Description.ToString(); // get the Hyperlink field Description value
}
I wish to have a file upload form that in addition to the file selection input , also has other input fields like textarea, dropdown etc. The problem is that I cannot access any post parameters other than the file in my blobstore upload handler. I am using the following function call to get the parameter name but it always returns an empty screen.
par = self.request.get("par")
I found another question with a similar problem Uploading a video to google app engine blobstore. The answer to that question suggests a workaround solution to set the filename to the parameter you wish to read which is not sufficient for my needs. Is there a way to access other form parameters in the post method of blobstore upload handler?
Did you find the solution?
In my experience, when using form/multipart request doesn't include the other parameters and they have to be dug out manually.
This is how I dig out parameters out of request that is used to send a file.
import java.util.Map;
import java.util.HashMap;
import java.util.Iterator;
import javax.servlet.http.HttpServletRequest;
// for reading form data when posted with multipart/form-data
import java.io.*;
import javax.servlet.ServletException;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import com.google.appengine.api.datastore.Blob;
// Fetch the attributes for a given model using rails conventions.
// We need to do this in Java because getParameterMap uses generics.
// We currently only support one lever: foo[bar] but not foo[bar][baz].
// We currently only pull the first value, so no support for checkboxes
public class ScopedParameterMap {
public static Map params(HttpServletRequest req, String model)
throws ServletException, IOException {
Map<String, Object> scoped = new HashMap<String, Object>();
if (req.getHeader("Content-Type").startsWith("multipart/form-data")) {
try {
ServletFileUpload upload = new ServletFileUpload();
FileItemIterator iterator = upload.getItemIterator(req); // this is used to get those params
while (iterator.hasNext()) {
FileItemStream item = iterator.next();
InputStream stream = item.openStream();
String attr = item.getFieldName();
if (attr.startsWith(model + "[") && attr.endsWith("]")) { // fetches all stuff like article[...], you can modify this to return only one value
int len = 0;
int offset = 0;
byte[] buffer = new byte[8192];
ByteArrayOutputStream file = new ByteArrayOutputStream();
while ((len = stream.read(buffer, 0, buffer.length)) != -1) {
offset += len;
file.write(buffer, 0, len);
}
String key = attr.split("\\[|\\]")[1];
if (item.isFormField()) {
scoped.put(key, file.toString());
} else {
if (file.size() > 0) {
scoped.put(key, file.toByteArray());
}
}
}
}
} catch (Exception ex) {
throw new ServletException(ex);
}
} else {
Map params = req.getParameterMap();
Iterator i = params.keySet().iterator();
while (i.hasNext()) {
String attr = (String) i.next();
if (attr.startsWith(model + "[") && attr.endsWith("]")) {
String key = attr.split("\\[|\\]")[1];
String val = ((String[]) params.get(attr))[0];
scoped.put(key, val);
// TODO: when multiple values, set a List instead
}
}
}
return scoped;
}
}
I hope this speedy answer helps, let me know if you have questions.