How to display container contains tablelayout of 7 columns in center of the screen for all resolution screens in code name one - width

Currently we are displaying the container that contains the table layout with 7 columns in center of the screen in the 1280x800 pixels resolution.
But we need the same container displaying in the 1920x1200 pixels resolution in center of the screen.
Actually the container is displayed but the row data is missing. Is anything wrong in my code? Please help me how to resolve this one.
FlowLayout centerLayout = new FlowLayout();
centerLayout.setAlign(Component.CENTER);
centerLayout.setValign(Component.TOP);
Container centerContainer = new Container(centerLayout);
topTabelcontainer = new Container(new TableLayout(7, 1));
commonComponentsForm = new CommonComponentsForm();
eventPostSchedulesForm = commonComponentsForm.setEventPostSchedulesFormHeader(eventPostSchedulesForm, res, workerBreaksPreferences);
topTabelcontainer = commonComponentsForm.getEventInfoHeader(eventPostSchedulesForm, res, topTabelcontainer, "showroster");
filterLayoutContainer = this.getFilterBody();
postScheduleTableContainer = this.getEventPostScheduleTable();
TableLayout.Constraint postScheduleTableConstraint = new TableLayout.Constraint();
postScheduleTableConstraint.setHorizontalAlign(BorderLayout.CENTER_BEHAVIOR_SCALE);
postScheduleTableConstraint.setVerticalAlign(BorderLayout.CENTER_BEHAVIOR_SCALE);
topTabelcontainer.add(filterLayoutContainer);
headerContainer);
topTabelcontainer.add(postScheduleTableConstraint, postScheduleTableContainer);
centerContainer.add(topTabelcontainer);
centerContainer.setScrollableY(Boolean.TRUE);
centerContainer.setTactileTouch(Boolean.TRUE);
centerContainer.addPointerDraggedListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
float val = Display.getInstance().getDragSpeed(false);
boolean upperFlag = false;
if (Display.getInstance().isPortrait()) {
if (portRaitUpperBound < toralRecourdsCount)
upperFlag = true;
} else if (landScapeUpperBound < toralRecourdsCount)
upperFlag = true;
boolean lowerFlag = false;
if (Display.getInstance().isPortrait()) {
if ((portRaitLowerBound > 0 && portRaitLowerBound <= toralRecourdsCount))
lowerFlag = true;
} else if (landScapeLowerBound > 0 && landScapeLowerBound < toralRecourdsCount)
lowerFlag = true;
if (val >= 0.5 && scrollFlag) {
dragFlag = true;
if (upperFlag) {
scrollFlag = false;
setPageUpperAndLowerBound(Constants.NEXTFLAG);
postScheduleTableContainer.removeAll();
setEventPostScheduleTable(postScheduleTableContainer);
eventPostSchedulesForm.revalidate();
}
} else if (val <= -0.5 && scrollFlag) {
dragFlag = true;
if (lowerFlag) {
scrollFlag = false;
setPageUpperAndLowerBound(Constants.PREVIOUSFLAG);
postScheduleTableContainer.removeAll();
setEventPostScheduleTable(postScheduleTableContainer);
eventPostSchedulesForm.revalidate();
}
}
}
});
eventPostSchedulesForm.setUIID("workersListForm");
eventPostSchedulesForm.add(BorderLayout.CENTER, centerContainer);
commonComponentsForm.getFooterTag(eventPostSchedulesForm);
eventPostSchedulesForm.show();
}
public Container getEventPostSchedulesTableHeader(Container postSchedulesTableHeaderContainer) {
Label position = new Label(Constants.POSITION, searchingButtonImage);
Label name = new Label(Constants.NAME, searchingButtonImage);
Label callInOutLabel = new Label(Constants.CALLINOUT);
position.setTextPosition(LEFT);
name.setTextPosition(LEFT);
TextArea actualCallIn1 = null;
Label actualCallIn = null;
TextArea actualCallOut1 = null;
Label actualCallOut = null;
TextArea agencyWorker1 = null;
Label agencyWorker = null;
if (Display.getInstance().isPortrait()) {
actualCallIn1 = new TextArea(Constants.ACTUALCALLIN);
actualCallIn1.setEditable(false);
actualCallIn1.setFocusable(false);
actualCallIn1.setColumns(3);
actualCallIn1.setVerticalAlignment(Component.CENTER);
actualCallOut1 = new TextArea(Constants.ACTUALCALLOUT);
actualCallOut1.setEditable(false);
actualCallOut1.setFocusable(false);
actualCallOut1.setColumns(3);
actualCallOut1.setVerticalAlignment(Component.CENTER);
agencyWorker1 = new TextArea(Constants.AGENCYWORKER);
agencyWorker1.setEditable(false);
agencyWorker1.setFocusable(false);
agencyWorker1.setColumns(3);
agencyWorker1.setVerticalAlignment(Component.CENTER);
} else {
agencyWorker = new Label(Constants.AGENCYWORKER);
actualCallIn = new Label(Constants.ACTUALCALLIN);
actualCallOut = new Label(Constants.ACTUALCALLOUT);
}
Label workerBreak = new Label(" ");
position.setUIID("workerTableHeader");
name.setUIID("workerTableHeader");
callInOutLabel.setUIID("workerTableHeader");
if (Display.getInstance().isPortrait()) {
agencyWorker1.setUIID("workerTableHeader");
actualCallIn1.setUIID("workerTableHeader");
actualCallOut1.setUIID("workerTableHeader");
} else {
agencyWorker.setUIID("workerTableHeader");
actualCallIn.setUIID("workerTableHeader");
actualCallOut.setUIID("workerTableHeader");
}
workerBreak.setUIID("workerTableHeader");
if (Display.getInstance().isPortrait()) {
postSchedulesTableHeaderContainer.addComponent(getTableConstraint(16, 8), position);
postSchedulesTableHeaderContainer.addComponent(getTableConstraint(15, 8), name);
postSchedulesTableHeaderContainer.addComponent(getTableConstraint(24, 8), callInOutLabel);
postSchedulesTableHeaderContainer.addComponent(getTableConstraint(13, 8), actualCallIn1);
postSchedulesTableHeaderContainer.addComponent(getTableConstraint(13, 8), actualCallOut1);
postSchedulesTableHeaderContainer.add(getTableConstraint(13, 8), agencyWorker1);
if (workerBreaksPreferences.getAllowbreaks() != null && !"".equals(workerBreaksPreferences.getAllowbreaks()) && "1".equals(workerBreaksPreferences.getAllowbreaks()))
postSchedulesTableHeaderContainer.addComponent(getTableConstraint(6, 8), workerBreak);
} else {
postSchedulesTableHeaderContainer.addComponent(getTableConstraint(13, 10), position);
postSchedulesTableHeaderContainer.addComponent(getTableConstraint(18, 10), name);
postSchedulesTableHeaderContainer.addComponent(getTableConstraint(20, 10), callInOutLabel);
postSchedulesTableHeaderContainer.addComponent(getTableConstraint(13, 10), actualCallIn);
postSchedulesTableHeaderContainer.addComponent(getTableConstraint(13, 10), actualCallOut);
postSchedulesTableHeaderContainer.addComponent(getTableConstraint(16, 10), agencyWorker);
if (workerBreaksPreferences.getAllowbreaks() != null && !"".equals(workerBreaksPreferences.getAllowbreaks()) && "1".equals(workerBreaksPreferences.getAllowbreaks()))
postSchedulesTableHeaderContainer.addComponent(getTableConstraint(7, 10), workerBreak);
}
return postSchedulesTableHeaderContainer;
}
public Container getEventPostScheduleTable() {
List < WorkerBean > eventPostSchedulesList = null;
roasterDao = RoasterDao.getInstance();
if (Display.getInstance().isPortrait()) {
eventPostSchedulesList = roasterDao.getEventPostSchedulesDetails(positionFilterValue, nameFilterValue, portRaitLowerBound, portRaitPageSize);
} else {
eventPostSchedulesList = roasterDao.getEventPostSchedulesDetails(positionFilterValue, nameFilterValue, landScapeLowerBound, landScapePageSize);
}
int tableRowCount = Constants.INITIALTABLEROWS;
boolean pagingFlag = false;
int eventPostScheduleCount = roasterDao.getEventPostSchedulesCount(positionFilterValue, nameFilterValue);
this.toralRecourdsCount = eventPostScheduleCount;
FlowLayout centerLayout = new FlowLayout();
centerLayout.setAlign(Component.CENTER);
postScheduleTableContainer = new Container(centerLayout);
postScheduleTableContainer.setUIID("tableBodyContainer");
if (eventPostSchedulesList.size() > landScapePageSize) {
tableRowCount = landScapePageSize + 1;
} else {
tableRowCount = eventPostSchedulesList.size() + 1;
}
Container borderTopPagingContainer = new Container(new BorderLayout());
if (eventPostScheduleCount > landScapePageSize) {
pagingFlag = true;
if (Display.getInstance().isPortrait()) {
borderTopPagingContainer = this.setHeaderPaging(eventPostScheduleCount, portRaitLowerBound, portRaitUpperBound, res);
} else {
borderTopPagingContainer = this.setHeaderPaging(eventPostScheduleCount, landScapeLowerBound, landScapeUpperBound, res);
}
}
if (pagingFlag) {
tableRowCount = tableRowCount + 1;
}
int columnCount = 6;
if (workerBreaksPreferences.getAllowbreaks() != null && !"".equals(workerBreaksPreferences.getAllowbreaks()) && "1".equals(workerBreaksPreferences.getAllowbreaks()))
columnCount++;
Container postSchedulesListContainer = new Container(new TableLayout(tableRowCount, columnCount));
if (pagingFlag) {
TableLayout.Constraint postSchedulesListConstraint1 = new TableLayout.Constraint();
postSchedulesListConstraint1.setHorizontalSpan(columnCount);
postSchedulesListContainer.add(postSchedulesListConstraint1, borderTopPagingContainer);
}
postSchedulesListContainer = this.getEventPostSchedulesTableHeader(postSchedulesListContainer);
String callInDBValue = "";
String callOutDBValue = "";
String actCallInDBValue = "";
String actCallOutDBValue = "";
Label position = null;
Label name = null;
Label callInOutLabel = null;
Label actualCallIn = null;
Label actualCallOut = null;
TextField agencyWorker = null;
Label workerBreak = null;
for (WorkerBean eventPostSchedules: eventPostSchedulesList) {
callInDBValue = "";
if (eventPostSchedules != null) {
if (eventPostSchedules.getCallIn().length() > 10)
callInDBValue = eventPostSchedules.getCallIn().substring(10).trim();
else {
if (Constants.PLATFORMNAME.equals(Display.getInstance().getPlatformName()))
callInDBValue = " ";
else
callInDBValue = " ";
}
}
callOutDBValue = "";
if (eventPostSchedules != null) {
if (eventPostSchedules.getCallOut().length() > 10)
callOutDBValue = eventPostSchedules.getCallOut().substring(10).trim();
else {
if (Constants.PLATFORMNAME.equals(Display.getInstance().getPlatformName()))
callOutDBValue = " ";
else
callOutDBValue = " ";
}
}
actCallInDBValue = "";
if (eventPostSchedules != null) {
if (eventPostSchedules.getActCallIn().length() > 10)
actCallInDBValue = eventPostSchedules.getActCallIn().substring(10).trim();
else
actCallInDBValue = eventPostSchedules.getActCallIn().trim();
}
actCallOutDBValue = "";
if (null != eventPostSchedules) {
if (eventPostSchedules.getActCallOut().length() > 10)
actCallOutDBValue = eventPostSchedules.getActCallOut().substring(10).trim();
else
actCallOutDBValue = eventPostSchedules.getActCallOut().trim();
}
callInDBValue = ((callInDBValue.trim().length() < 8) ? " ".concat(callInDBValue) : callInDBValue) + ((callOutDBValue.trim().equals("")) ? callOutDBValue : " - " + callOutDBValue);
position = new Label(eventPostSchedules.getPersonnelType());
name = new Label(eventPostSchedules.getName());
callInOutLabel = new Label(callInDBValue);
actualCallIn = new Label(actCallInDBValue);
actualCallIn.setFocusable(Boolean.TRUE);
actualCallIn.addPointerPressedListener(createActualCallChangeListener(actualCallIn, eventPostSchedules.getSerialId(), Constants.ACTUALCALLINFLAG, eventPostSchedules.getName(), eventPostSchedules.getActCallIn(), eventPostSchedules.getActCallOut(), eventPostSchedules.getActCallIn()));
actualCallOut = new Label(actCallOutDBValue);
actualCallOut.setFocusable(Boolean.TRUE);
actualCallOut.addPointerPressedListener(createActualCallChangeListener(actualCallOut, eventPostSchedules.getSerialId(), Constants.ACTUALCALLOUTFLAG, eventPostSchedules.getName(), eventPostSchedules.getActCallIn(), eventPostSchedules.getActCallOut(), eventPostSchedules.getActCallOut()));
agencyWorker = new TextField(eventPostSchedules.getAgencyWorker(), null, 5, TextArea.ANY);
position.setUIID("workersList");
name.setUIID("workersList");
callInOutLabel.setUIID("workersList");
actualCallIn.setUIID("workersListEditable");
actualCallOut.setUIID("workersListEditable");
agencyWorker.setUIID("workersListEditable");
workerBreak.setUIID("workersList");
if (Display.getInstance().isPortrait()) {
postSchedulesListContainer.addComponent(getTableConstraint(16, 8), position);
postSchedulesListContainer.addComponent(getTableConstraint(15, 8), name);
postSchedulesListContainer.addComponent(getTableConstraint(24, 8), callInOutLabel);
postSchedulesListContainer.addComponent(getTableConstraint(13, 8), actualCallIn);
postSchedulesListContainer.addComponent(getTableConstraint(13, 8), actualCallOut);
postSchedulesListContainer.addComponent(getTableConstraint(13, 8), agencyWorker);
if (workerBreaksPreferences.getAllowbreaks() != null && !"".equals(workerBreaksPreferences.getAllowbreaks()) && "1".equals(workerBreaksPreferences.getAllowbreaks()))
postSchedulesListContainer.addComponent(getTableConstraint(6, 8), workerBreak);
} else {
postSchedulesListContainer.addComponent(getTableConstraint(13, 10), position);
postSchedulesListContainer.addComponent(getTableConstraint(18, 10), name);
postSchedulesListContainer.addComponent(getTableConstraint(20, 10), callInOutLabel);
postSchedulesListContainer.addComponent(getTableConstraint(13, 10), actualCallIn);
postSchedulesListContainer.addComponent(getTableConstraint(13, 10), actualCallOut);
postSchedulesListContainer.addComponent(getTableConstraint(16, 10), agencyWorker);
if (workerBreaksPreferences.getAllowbreaks() != null && !"".equals(workerBreaksPreferences.getAllowbreaks()) && "1".equals(workerBreaksPreferences.getAllowbreaks()))
postSchedulesListContainer.addComponent(getTableConstraint(7, 10), workerBreak);
}
}
postScheduleTableContainer.add(postSchedulesListContainer);
return postScheduleTableContainer;
}
}
}
public TableLayout.Constraint getTableConstraint(int widthPercent, int heightPercent) {
TableLayout.Constraint tableConstraint = new TableLayout.Constraint();
tableConstraint.setWidthPercentage(widthPercent);
tableConstraint.setHeightPercentage(heightPercent);
return tableConstraint;
}
}

Don't use flow layout for large dynamic data. You border layout with center constraint or absolute center.
Flow layout is overly simplistic and shouldn't be used for complex structures since Codename One doesn't reflow. There is a big discussion of that in the developer guide.

Related

How to read empty cell in Excel file using POI?

How to read empty cell in excel file using POI?
When I upload Excel file, the empty cell is filled with previous cell.
like this:
this is the sample of excel file
this is the DB that the empty cell be filled with previous cell
POI VERSION
org.apache.poi
poi
4.1.2
org.apache.poi
poi-ooxml
4.1.2
code
#RequestMapping("/mng/mngSaupExcelUpload14.do")
public ModelAndView mngBizApplyExcelUpload14(MultipartHttpServletRequest request, HttpServletResponse response,
HttpSession session, INDEYearVO attach) throws IOException, ParseException {
Iterator<String> iterator = request.getFileNames();
int actResult = 0;
ModelAndView mav = new ModelAndView();
response.setContentType("text/html");
response.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();
MultipartFile mFile = null;
while (iterator.hasNext()) {
String uploadFileName = iterator.next();
mFile = request.getFile(uploadFileName);
// String originFileName = mFile.getOriginalFilename();
// String saveFileName = originFileName;
}
XSSFWorkbook workbook = new XSSFWorkbook(mFile.getInputStream());
for (int sheetNum = 0; sheetNum < workbook.getNumberOfSheets(); sheetNum++) {
XSSFSheet sheet = workbook.getSheetAt(sheetNum);
int rows = sheet.getPhysicalNumberOfRows();
int rowindex = 0;
int columnindex = 0;
if (sheetNum == 0) {
for (rowindex = 1; rowindex < rows; rowindex++) {
sheet = workbook.getSheetAt(0);
XSSFRow row = sheet.getRow(rowindex);
if (row != null) {
int cells = row.getPhysicalNumberOfCells();
for (columnindex = 0; columnindex <= cells; columnindex++) {
XSSFCell cell = row.getCell(columnindex);
String value = "";
if (cell == null) {
continue;
} else {
switch (cell.getCellType()) {
case FORMULA:
value = cell.getCellFormula();
break;
case NUMERIC:
//value = (int)cell.getNumericCellValue() + "";
double cellValue = cell.getNumericCellValue();
if (cellValue == Math.rint(cellValue)) {
value = String.valueOf((int) cellValue);
} else {
value = String.valueOf(cellValue);
}
break;
case STRING:
value = cell.getStringCellValue() + "";
break;
case BLANK:
value = null;
// value = cell.getBooleanCellValue() + "";
break;
case ERROR:
value = cell.getErrorCellValue() + "";
break;
default:
}
if (columnindex == 0) {
attach.setSn(Integer.parseInt(value));
}else if (columnindex == 1) {
attach.setYear(Integer.parseInt(value));
}else if (columnindex == 2) {
attach.setSigngu(value);
} else if (columnindex == 3) {
attach.setJan(Integer.parseInt(value));
} else if (columnindex == 4) {
attach.setFeb(Integer.parseInt(value));
} else if (columnindex == 5) {
attach.setMar(Integer.parseInt(value));
} else if (columnindex == 6) {
attach.setApr(Integer.parseInt(value));
} else if (columnindex == 7) {
attach.setMay(Integer.parseInt(value));
} else if (columnindex == 8) {
attach.setJne(Integer.parseInt(value));
} else if (columnindex == 9) {
attach.setJly(Integer.parseInt(value));
} else if (columnindex == 10) {
attach.setAug(Integer.parseInt(value));
} else if (columnindex == 11) {
attach.setSep(Integer.parseInt(value));
} else if (columnindex == 12) {
attach.setOct(Integer.parseInt(value));
} else if (columnindex == 13) {
attach.setNov(Integer.parseInt(value));
} else if (columnindex == 14) {
if ("false".equals(value) || "".equals(value) || "0".equals(value) || value == null ) {
attach.setDec(Integer.parseInt(""));
} else {
attach.setDec(Integer.parseInt(value));
}
}
}
}
actResult = attachFileService.fileInsertActForExcel14(attach);
}
}
}
}
if (actResult > 0) {
out.println("<script>");
out.println("alert('등록에 성공 하였습니다.');");
out.println("location.replace('" + request.getContextPath() + "attachFile.do');");
out.println("</script>");
out.flush();
out.close();
return null;
} else {
out.println("<script>");
out.println("alert('등록 중 오류가 발생했습니다.');");
out.println("location.replace('" + request.getContextPath() + "attachFile.do');");
out.println("</script>");
out.flush();
out.close();
return null;
}
}
I don't really know why empty cell is filled..
I don't think it's a problem with poi. Also check the db insert code.
And I'm developing a library that might be helpful, so I'd appreciate it if you could watch it.
https://github.com/scndry/jackson-dataformat-spreadsheet

REVIT Transfer floor sketch to Void Extrusion in Family

Struggling with some Revit code to copy the profile of a floor and use it as the sketch profile for a void extrusion in a family.
Here is the Full Sharp Development Code. It half works in my custom project template, when I try to use it in an out of the box project generated from revit default template it gives the error "a managed exception was thrown by revit or by one of its external applications"
In my template it cannot properly split the curves into a secondary array. It says the array elements are being changed but when the loop runs again the element i is back to it's original content??? The TaskDialog clearly says the elements have changed, until the loop iterates again.
Full code: To work it requires a generic family with the name "Void - Custom" to be in the project. The "If found" near the bottom last page and a half of code, is where the for loop is not behaving as expected.
/*
* Created by SharpDevelop.
* User: arautio
* Date: 4/30/2019
* Time: 11:10 AM
*
* To change this template use Tools | Options | Coding | Edit Standard Headers.
*/
using System;
using Autodesk.Revit.UI;
using Autodesk.Revit.DB;
using Autodesk.Revit.DB.Architecture;
using Autodesk.Revit.DB.Structure;
using Autodesk.Revit.UI.Selection;
using System.Collections.Generic;
using System.Linq;
using Autodesk.Revit.ApplicationServices;
using Autodesk.Revit.Attributes;
using System.Text;
using System.IO;
using System.Diagnostics;
namespace ARC
{
[Autodesk.Revit.Attributes.Transaction(Autodesk.Revit.Attributes.TransactionMode.Manual)]
[Autodesk.Revit.DB.Macros.AddInId("3411F411-6FC1-4A4D-9CFD-37ABB2028A15")]
public partial class ThisApplication
{
private void Module_Startup(object sender, EventArgs e)
{
}
private void Module_Shutdown(object sender, EventArgs e)
{
}
#region Revit Macros generated code
private void InternalStartup()
{
this.Startup += new System.EventHandler(Module_Startup);
this.Shutdown += new System.EventHandler(Module_Shutdown);
}
#endregion
public void FloorGrating()
{
StringBuilder sb = new StringBuilder();
Dictionary<Floor, List<ModelCurve>> dict_SketchLines = new Dictionary<Floor, List<ModelCurve>>();
UIDocument uidoc = this.ActiveUIDocument;
Document document = uidoc.Document;
View activev = document.ActiveView;
ElementId levelId = null;
levelId = activev.LevelId;
Element levelem = document.GetElement( levelId );
Level lev = document.ActiveView.GenLevel;
Reference refsel = uidoc.Selection.PickObject(ObjectType.Element, "Select Floor to Add Grating To");
Element elem = document.GetElement(refsel.ElementId);
Floor f = elem as Floor;
List<ElementId> _deleted = null;
using (Transaction t = new Transaction(document, "temp"))
{
t.Start();
document.Regenerate();
_deleted = document.Delete(elem.Id).ToList();
t.RollBack();
}
bool SketchLinesFound = false;
List<ModelCurve> _sketchCurves = new List<ModelCurve>();
foreach (var id in _deleted)
{
ModelCurve mc = document.GetElement(id) as ModelCurve;
if (mc != null)
{
_sketchCurves.Add(mc);
SketchLinesFound = true;
}
else
{
if (SketchLinesFound) break;
}
}
dict_SketchLines.Add(f, _sketchCurves);
foreach (Floor key in dict_SketchLines.Keys)
{
List<ModelCurve> _curves = dict_SketchLines[key];
sb.AppendLine(string.Format("floor {0} has sketchlines:", key.Id));
foreach (ModelCurve mc in _curves)
{
sb.AppendLine(string.Format("{0} <{1}>", mc.GetType(), mc.Id));
sb.AppendLine(string.Format("<{0}>", mc.GeometryCurve.IsBound.ToString()));
if (mc.GetType().ToString() == "Autodesk.Revit.DB.ModelArc" && mc.GeometryCurve.IsBound == false)
{
TaskDialog.Show("Revit", "Circle Found");
}
try
{
sb.AppendLine(string.Format("<{0} -- {1}>", mc.GeometryCurve.GetEndPoint(0), mc.GeometryCurve.GetEndPoint(1)));
}
catch
{
}
}
sb.AppendLine();
}
//TaskDialog.Show("debug", sb.ToString());
Document docfamily;
Family fam;
string ftitle = document.Title;
string fpath = document.PathName;
int ftitlelen = ftitle.Length + 4;
int fpathlen = fpath.Length;
int finpathlen = fpathlen - ftitlelen;
string sfinpath = fpath.Substring(0,finpathlen);
string famname = "GratingVoid";
string fext = ".rfa";
int counter = 1;
while (counter < 100)
{
famname = ("GratingVoid" + counter as String);
Family family = FindElementByName(document,typeof(Family),famname)as Family;
if( null == family )
{
sfinpath = (sfinpath + famname + fext);
counter = 1000;
}
counter += 1;
}
FilteredElementCollector collector0 = new FilteredElementCollector(document);
ICollection<Element> collection0 = collector0.WhereElementIsNotElementType().ToElements();
List<FamilySymbol> fsym0 = new FilteredElementCollector(document).OfClass(typeof(FamilySymbol)).Cast<FamilySymbol>().ToList();
FamilySymbol famsymb0 = null;
foreach (FamilySymbol symb in fsym0)
{
if (symb.Name == "Void - Custom")
{
famsymb0 = symb as FamilySymbol;
}
}
fam = famsymb0.Family;
docfamily = document.EditFamily(fam);
try
{
docfamily.SaveAs(#sfinpath);
}
catch
{
TaskDialog.Show("Revit", "Could Not Save Void Family");
}
using (Transaction trans = new Transaction(docfamily))
{
trans.Start("family");
bool circleflag = false;
ElementId delid = null;
FilteredElementCollector collector = new FilteredElementCollector( docfamily );
foreach(Element element in collector.OfClass(typeof(GenericForm)))
{
delid = element.Id;
}
docfamily.Delete(delid);
CurveArray loccurva = new CurveArray();
foreach (Floor key in dict_SketchLines.Keys)
{
List<ModelCurve> _curves = dict_SketchLines[key];
foreach (ModelCurve mc in _curves)
{
if (mc.GetType().ToString() == "Autodesk.Revit.DB.ModelArc" && mc.GeometryCurve.IsBound == false)
{
circleflag = true;
}
LocationCurve lcurve = mc.Location as LocationCurve;
Curve c = lcurve.Curve as Curve;
loccurva.Append(c);
}
}
try
{
if (circleflag == true && loccurva.Size == 2)
{
Curve tempc;
if (loccurva.get_Item(0).GetType().ToString() == "Autodesk.Revit.DB.Arc")
{
tempc = loccurva.get_Item(0);
}
else
{
tempc = loccurva.get_Item(1);
}
loccurva.Clear();
loccurva.Append(tempc);
}
CurveArrArray newcurarr = new CurveArrArray();
newcurarr.Append(loccurva);
SortCurvesContiguousArray(newcurarr);
TaskDialog.Show("Revit CurveArray Array Size" , newcurarr.Size.ToString());
foreach (CurveArray ca in newcurarr)
{
TaskDialog.Show("Revit CurveArray within Array Size" , ca.Size.ToString());
}
// Below is edited for error control - leaving out the secondary loops for now
CurveArrArray switcharr = new CurveArrArray();
//switcharr.Append(newcurarr.get_Item(1));
switcharr.Append(newcurarr.get_Item(0));
//SortCurvesContiguousArray(loccurva);
//CurveArrArray newcurarr = new CurveArrArray();
//newcurarr.Append(loccurva);
double end = 1;
SketchPlane sketch = FindElementByName( docfamily,typeof( SketchPlane ), "Ref. Level" ) as SketchPlane;
docfamily.FamilyCreate.NewExtrusion(false, switcharr, sketch, end);
}
catch
{
TaskDialog.Show("Revit", "Could Not Write to Curve Array or Create Extrusion");
}
trans.Commit();
}
docfamily.Save();
docfamily.LoadFamily(document, new CustomFamilyLoadOption());
docfamily.Close();
File.Delete(sfinpath);
Family familynew = FindElementByName(document,typeof(Family),famname)as Family;
if( null == familynew )
{
TaskDialog.Show("Revit", "Family Does Not Exist");
}
FilteredElementCollector collector1 = new FilteredElementCollector(document);
ICollection<Element> collection = collector1.WhereElementIsNotElementType().ToElements();
List<FamilySymbol> fsym = new FilteredElementCollector(document).OfClass(typeof(FamilySymbol)).Cast<FamilySymbol>().ToList();
FamilySymbol famsymb = null;
foreach (FamilySymbol symb in fsym)
{
if (symb.Name == famname)
{
famsymb = symb as FamilySymbol;
}
}
using (Transaction trans = new Transaction(document))
{
trans.Start("PlaceVoid");
if( ! famsymb.IsActive )
{
famsymb.Activate();
}
XYZ p = new XYZ(0,0,0);
FamilyInstance gratingvoid = document.Create.NewFamilyInstance( p, famsymb, lev, lev, StructuralType.NonStructural );
document.Regenerate();
trans.Commit();
}
}
//--------------------------------------------------------------------------------------------------------------------------------------------------------
static public Element FindElementByName(Document doc,Type targetType,string targetName)
{
return new FilteredElementCollector( doc ).OfClass( targetType ).FirstOrDefault<Element>(e => e.Name.Equals( targetName ) );
}
//--------------------------------------------------------------------------------------------------------------------------------------------------------
public class CustomFamilyLoadOption : IFamilyLoadOptions
{
public bool OnFamilyFound(bool familyInUse, out bool overwriteParameterValues)
{
overwriteParameterValues = true;
return true;
}
public bool OnSharedFamilyFound(Family sharedFamily,bool familyInUse,out FamilySource source, out bool overwriteParameterValues)
{
source = FamilySource.Family;
overwriteParameterValues = true;
return true;
}
}
//--------------------------------------------------------------------------------------------------------------------------------------------------------
const double _inch = 1.0 / 12.0;
const double _sixteenth = _inch / 16.0;
static Curve CreateReversedCurve(Curve orig )
{
//if( !IsSupported( orig ) )
//{
// throw new NotImplementedException("CreateReversedCurve for type " + orig.GetType().Name );
//}
if( orig is Line )
{
//return creapp.NewLineBound(orig.GetEndPoint( 1 ), orig.GetEndPoint( 0 ) );
return Line.CreateBound(orig.GetEndPoint( 1 ), orig.GetEndPoint( 0 ) );
}
else if( orig is Arc )
{
// return creapp.NewArc( orig.GetEndPoint( 1 ), orig.GetEndPoint( 0 ), orig.Evaluate( 0.5, true ) );
return Arc.Create( orig.GetEndPoint( 1 ), orig.GetEndPoint( 0 ), orig.Evaluate( 0.5, true ) );
}
else
{
throw new Exception(
"CreateReversedCurve - Unreachable" );
}
}
public static void SortCurvesContiguousArray(CurveArrArray curvesarr)
{
double _precision1 = 1.0 / 12.0 / 16.0; // around 0.00520833
double _precision2 = 0.001; // limit for CurveLoop.Create(...)
int cn = curvesarr.Size;
int ci = 0;
while (ci < cn)
{
CurveArray curves = curvesarr.get_Item(ci);
ci +=1;
// account for multiple curve loops with secondary array
CurveArray loop1 = new CurveArray();
CurveArray loop2 = new CurveArray();
int n = curves.Size;
int split = 1;
// Walk through each curve (after the first)
// to match up the curves in order
for (int i = 0; i < n; ++i)
{
TaskDialog.Show("Revit I Loop Run", i.ToString());
Curve curve = curves.get_Item(i);
if (curve.GetType().ToString() == "Autodesk.Revit.DB.Arc" && curve.IsBound == false)
{
break;
}
XYZ beginPoint = curve.GetEndPoint(0);
XYZ endPoint = curve.GetEndPoint(1);
XYZ p,q;
// Find curve with start point = end point
bool found = (i + 1 >= n);
for (int j = i + 1; j < n; ++j)
{
p = curves.get_Item(j).GetEndPoint(0);
q = curves.get_Item(j).GetEndPoint(1);
// If there is a match end->start,
// this is the next curve
if (p.DistanceTo(endPoint) < _precision1)
{
if (p.DistanceTo(endPoint) > _precision2)
{
XYZ intermediate = new XYZ((endPoint.X + p.X) / 2.0, (endPoint.Y + p.Y) / 2.0, (endPoint.Z + p.Z) / 2.0);
curves.set_Item(i, Line.CreateBound(beginPoint, intermediate));
curves.set_Item(j, Line.CreateBound(intermediate, q));
}
if (i + 1 != j)
{
Curve tmp = curves.get_Item(i + 1);
curves.set_Item(i + 1, curves.get_Item(j));
curves.set_Item(j, tmp);
}
found = true;
break;
}
// If there is a match end->end,
// reverse the next curve
if (q.DistanceTo(endPoint) < _precision1)
{
if (q.DistanceTo(endPoint) > _precision2)
{
XYZ intermediate = new XYZ((endPoint.X + q.X) / 2.0, (endPoint.Y + q.Y) / 2.0, (endPoint.Z + q.Z) / 2.0);
curves.set_Item(i, Line.CreateBound(beginPoint, intermediate));
curves.set_Item(j, Line.CreateBound(p, intermediate));
}
if (i + 1 == j)
{
curves.set_Item(i + 1, CreateReversedCurve(curves.get_Item(j)));
}
else
{
Curve tmp = curves.get_Item(i + 1);
curves.set_Item(i + 1, CreateReversedCurve(curves.get_Item(j)));
curves.set_Item(j, tmp);
}
found = true;
break;
}
}
if (!found)
{
// if not found, must be part of a new loop - move it to the back and keep going and add to second array
TaskDialog.Show("Revit No Match Found for item", i.ToString());
TaskDialog.Show("Revit", "Moveing it to back of list");
Curve tmp1 = curves.get_Item(i);
TaskDialog.Show("Revit tmp1 Current i item endpt", tmp1.GetEndPoint(0).ToString());
loop2.Append(tmp1);
Curve tmp2 = curves.get_Item(n - split);
TaskDialog.Show("Revit tmp2 Back of list item endpt", tmp2.GetEndPoint(0).ToString());
// set current item to rear
curves.set_Item(i, tmp2);
// set rear item to current
curves.set_Item(n - split, tmp1);
TaskDialog.Show("Revit new item i endpt", curves.get_Item(i).GetEndPoint(0).ToString());
TaskDialog.Show("Revit moved item endpt", curves.get_Item(n - split).GetEndPoint(0).ToString());
// error testing - try to append in a different manner and check values
//curves.set_Item(i, Line.CreateBound(curves.get_Item(i).GetEndPoint(0), curves.get_Item(i).GetEndPoint(1)));
//curves.set_Item(n - split, Line.CreateBound(curves.get_Item(n - split).GetEndPoint(0), curves.get_Item(n - split).GetEndPoint(1)));
//Curve ncurve = Line.CreateBound(curves.get_Item(n - split).GetEndPoint(0), curves.get_Item(n - split).GetEndPoint(1));
//TaskDialog.Show("Revit Appended to Loop2 Endpoint", ncurve.GetEndPoint(0).ToString());
//loop2.Append(ncurve);
//set the split off counter so items not fitting in first loop can be split to new array.
split += 1;
//reset the counter back so item moved from rear can be checked in next run of for loop
i -= 2;
}
//set counter to end for loop when all items that do not fit in first loop are processed
if (i >= n - (split + 1))
{
TaskDialog.Show("Revit", "End Of Looping");
TaskDialog.Show("Revit - The Split Number", split.ToString());
i = n;
}
}
int counter = 0;
// recreate array with only items from first loop found
while (counter <= (n - split))
{
loop1.Append(curves.get_Item(counter));
counter += 1;
}
TaskDialog.Show("Revit loop1 Size", loop1.Size.ToString());
curvesarr.Clear();
curvesarr.Append(loop1);
if (loop2.Size > 0)
{
string stringinfo = "";
// run the loop detection on a second array that was split from the first
TaskDialog.Show("Revit loop2 Size", loop2.Size.ToString());
CurveArrArray tmpcurvesarr = new CurveArrArray();
tmpcurvesarr.Append(loop2);
SortCurvesContiguousArray(tmpcurvesarr);
loop2.Clear();
loop2 = tmpcurvesarr.get_Item(0);
curvesarr.Append(loop2);
foreach (Curve ccc in loop2)
{
stringinfo = (stringinfo + " " + ccc.GetEndPoint(0).ToString() + " - " + ccc.GetEndPoint(1).ToString());
}
TaskDialog.Show("Revit", stringinfo);
}
}
}
}
}
Thanks for any and all help.
Shane

Acumatica - Where is the method that writes to CRRelation?

Can anyone help me find where in the code Acumatica writes to the CRRelation table when createing a Sales Order from an Opportunity? I've done a search for all instances of "CRRelation" but none of them seem to be doing the actual writing to the table.
It is done in the DoCreateSalesOrder(CreateSalesOrderFilter param) method which is called in the CreateSalesOrder action:
public PXAction<CROpportunity> createSalesOrder;
[PXUIField(DisplayName = Messages.CreateSalesOrder, MapEnableRights = PXCacheRights.Update, MapViewRights = PXCacheRights.Select)]
[PXButton(ImageKey = PX.Web.UI.Sprite.Main.DataEntry)]
public virtual IEnumerable CreateSalesOrder(PXAdapter adapter)
{
foreach (CROpportunity opportunity in adapter.Get())
{
Customer customer = (Customer)PXSelect<Customer, Where<Customer.bAccountID, Equal<Current<CROpportunity.bAccountID>>>>
.SelectSingleBound(this, new object[] { opportunity });
if (customer == null)
{
throw new PXException(Messages.ProspectNotCustomer);
}
var products = Products.View.SelectMultiBound(new object[] { opportunity }).RowCast<CROpportunityProducts>();
if (products.Any(_ => _.InventoryID == null) && !products.Any(_ => _.InventoryID != null))
{
throw new PXException(Messages.SalesOrderHasOnlyNonInventoryLines);
}
if (CreateOrderParams.AskExtFullyValid((graph, viewName) => { }, DialogAnswerType.Positive))
{
Save.Press();
PXLongOperation.StartOperation(this, delegate()
{
var grapph = PXGraph.CreateInstance<OpportunityMaint>();
grapph.Opportunity.Current = opportunity;
grapph.CreateOrderParams.Current = CreateOrderParams.Current;
grapph.DoCreateSalesOrder(CreateOrderParams.Current);
});
}
yield return opportunity;
}
}
if we look in that method we can find the following lines which are creating the relation:
var campaignRelation = docgraph.RelationsLink.Insert();
campaignRelation.RefNoteID = doc.NoteID;
campaignRelation.Role = CRRoleTypeList.Source;
campaignRelation.TargetType = CRTargetEntityType.CROpportunity;
campaignRelation.TargetNoteID = opportunity.NoteID;
campaignRelation.DocNoteID = opportunity.NoteID;
campaignRelation.EntityID = opportunity.BAccountID;
campaignRelation.ContactID = opportunity.ContactID;
docgraph.RelationsLink.Update(campaignRelation);
You can find the full code of that method below:
protected virtual void DoCreateSalesOrder(CreateSalesOrderFilter param)
{
bool recalcAny = param.RecalculatePrices == true ||
param.RecalculateDiscounts == true ||
param.OverrideManualDiscounts == true ||
param.OverrideManualDocGroupDiscounts == true ||
param.OverrideManualPrices == true;
var opportunity = this.Opportunity.Current;
Customer customer = (Customer)PXSelect<Customer, Where<Customer.bAccountID, Equal<Current<CROpportunity.bAccountID>>>>.Select(this);
SOOrderEntry docgraph = PXGraph.CreateInstance<SOOrderEntry>();
CurrencyInfo info = PXSelect<CurrencyInfo, Where<CurrencyInfo.curyInfoID, Equal<Current<CROpportunity.curyInfoID>>>>.Select(this);
info.CuryInfoID = null;
info = CurrencyInfo.GetEX(docgraph.currencyinfo.Insert(info.GetCM()));
SOOrder doc = new SOOrder();
doc.OrderType = CreateOrderParams.Current.OrderType ?? SOOrderTypeConstants.SalesOrder;
doc = docgraph.Document.Insert(doc);
doc = PXCache<SOOrder>.CreateCopy(docgraph.Document.Search<SOOrder.orderNbr>(doc.OrderNbr));
doc.CuryInfoID = info.CuryInfoID;
doc = PXCache<SOOrder>.CreateCopy(docgraph.Document.Update(doc));
doc.CuryID = info.CuryID;
doc.OrderDate = Accessinfo.BusinessDate;
doc.OrderDesc = opportunity.Subject;
doc.TermsID = customer.TermsID;
doc.CustomerID = opportunity.BAccountID;
doc.CustomerLocationID = opportunity.LocationID ?? customer.DefLocationID;
if (opportunity.TaxZoneID != null)
{
doc.TaxZoneID = opportunity.TaxZoneID;
if (!recalcAny)
{
SOTaxAttribute.SetTaxCalc<SOLine.taxCategoryID>(docgraph.Transactions.Cache, null, TaxCalc.ManualCalc);
SOTaxAttribute.SetTaxCalc<SOOrder.freightTaxCategoryID>(docgraph.Document.Cache, null,
TaxCalc.ManualCalc);
}
}
doc.ProjectID = opportunity.ProjectID;
doc.BranchID = opportunity.BranchID;
doc = docgraph.Document.Update(doc);
var campaignRelation = docgraph.RelationsLink.Insert();
campaignRelation.RefNoteID = doc.NoteID;
campaignRelation.Role = CRRoleTypeList.Source;
campaignRelation.TargetType = CRTargetEntityType.CROpportunity;
campaignRelation.TargetNoteID = opportunity.NoteID;
campaignRelation.DocNoteID = opportunity.NoteID;
campaignRelation.EntityID = opportunity.BAccountID;
campaignRelation.ContactID = opportunity.ContactID;
docgraph.RelationsLink.Update(campaignRelation);
bool failed = false;
foreach (CROpportunityProducts product in SelectProducts(opportunity.QuoteNoteID))
{
if (product.SiteID == null)
{
InventoryItem item = (InventoryItem)PXSelectorAttribute.Select<CROpportunityProducts.inventoryID>(Products.Cache, product);
if (item != null && item.NonStockShip == true)
{
Products.Cache.RaiseExceptionHandling<CROpportunityProducts.siteID>(product, null,
new PXSetPropertyException(ErrorMessages.FieldIsEmpty, typeof(CROpportunityProducts.siteID).Name));
failed = true;
}
}
SOLine tran = new SOLine();
tran = docgraph.Transactions.Insert(tran);
if (tran != null)
{
tran.InventoryID = product.InventoryID;
tran.SubItemID = product.SubItemID;
tran.TranDesc = product.Descr;
tran.OrderQty = product.Quantity;
tran.UOM = product.UOM;
tran.CuryUnitPrice = product.CuryUnitPrice;
tran.TaxCategoryID = product.TaxCategoryID;
tran.SiteID = product.SiteID;
tran.IsFree = product.IsFree;
tran.ProjectID = product.ProjectID;
tran.TaskID = product.TaskID;
tran.CostCodeID = product.CostCodeID;
tran.ManualPrice = true;
tran.ManualDisc = true;
tran.CuryDiscAmt = product.CuryDiscAmt;
tran.DiscAmt = product.DiscAmt;
tran.DiscPct = product.DiscPct;
tran.POCreate = product.POCreate;
tran.VendorID = product.VendorID;
if (param.RecalculatePrices != true)
{
tran.ManualPrice = true;
}
else
{
if (param.OverrideManualPrices != true)
tran.ManualPrice = product.ManualPrice;
else
tran.ManualPrice = false;
}
if (param.RecalculateDiscounts != true)
{
tran.ManualDisc = true;
}
else
{
if (param.OverrideManualDiscounts != true)
tran.ManualDisc = product.ManualDisc;
else
tran.ManualDisc = false;
}
tran.CuryDiscAmt = product.CuryDiscAmt;
tran.DiscAmt = product.DiscAmt;
tran.DiscPct = product.DiscPct;
}
tran = docgraph.Transactions.Update(tran);
PXNoteAttribute.CopyNoteAndFiles(Products.Cache, product, docgraph.Transactions.Cache, tran,
Setup.Current);
}
PXNoteAttribute.CopyNoteAndFiles(Opportunity.Cache, opportunity, docgraph.Document.Cache, doc, Setup.Current);
if (failed)
throw new PXException(Messages.SiteNotDefined);
//Skip all customer dicounts
if (param.RecalculateDiscounts != true && param.OverrideManualDiscounts != true)
{
var discounts = new Dictionary<string, SOOrderDiscountDetail>();
foreach (SOOrderDiscountDetail discountDetail in docgraph.DiscountDetails.Select())
{
docgraph.DiscountDetails.SetValueExt<SOOrderDiscountDetail.skipDiscount>(discountDetail, true);
string key = discountDetail.Type + ':' + discountDetail.DiscountID + ':' + discountDetail.DiscountSequenceID;
discounts.Add(key, discountDetail);
}
Discount ext = this.GetExtension<Discount>();
foreach (CROpportunityDiscountDetail discountDetail in ext.DiscountDetails.Select())
{
SOOrderDiscountDetail detail;
string key = discountDetail.Type + ':' + discountDetail.DiscountID + ':' + discountDetail.DiscountSequenceID;
if (discounts.TryGetValue(key, out detail))
{
docgraph.DiscountDetails.SetValueExt<SOOrderDiscountDetail.skipDiscount>(detail, false);
if (discountDetail.IsManual == true && discountDetail.Type == DiscountType.Document)
{
docgraph.DiscountDetails.SetValueExt<SOOrderDiscountDetail.extDiscCode>(detail, discountDetail.ExtDiscCode);
docgraph.DiscountDetails.SetValueExt<SOOrderDiscountDetail.description>(detail, discountDetail.Description);
docgraph.DiscountDetails.SetValueExt<SOOrderDiscountDetail.isManual>(detail, discountDetail.IsManual);
docgraph.DiscountDetails.SetValueExt<SOOrderDiscountDetail.curyDiscountAmt>(detail, discountDetail.CuryDiscountAmt);
}
}
else
{
detail = (SOOrderDiscountDetail)docgraph.DiscountDetails.Cache.CreateInstance();
detail.Type = discountDetail.Type;
detail.DiscountID = discountDetail.DiscountID;
detail.DiscountSequenceID = discountDetail.DiscountSequenceID;
detail.ExtDiscCode = discountDetail.ExtDiscCode;
detail.Description = discountDetail.Description;
detail = (SOOrderDiscountDetail)docgraph.DiscountDetails.Cache.Insert(detail);
if (discountDetail.IsManual == true && (discountDetail.Type == DiscountType.Document || discountDetail.Type == DiscountType.ExternalDocument))
{
detail.CuryDiscountAmt = discountDetail.CuryDiscountAmt;
detail.IsManual = discountDetail.IsManual;
docgraph.DiscountDetails.Cache.Update(detail);
}
}
}
SOOrder old_row = PXCache<SOOrder>.CreateCopy(docgraph.Document.Current);
docgraph.Document.Cache.SetValueExt<SOOrder.curyDiscTot>(docgraph.Document.Current, DiscountEngineProvider.GetEngineFor<SOLine, SOOrderDiscountDetail>().GetTotalGroupAndDocumentDiscount(docgraph.DiscountDetails));
docgraph.Document.Cache.RaiseRowUpdated(docgraph.Document.Current, old_row);
}
doc = docgraph.Document.Update(doc);
if (opportunity.TaxZoneID != null && !recalcAny)
{
foreach (CRTaxTran tax in PXSelect<CRTaxTran, Where<CRTaxTran.quoteID, Equal<Current<CROpportunity.quoteNoteID>>>>.Select(this))
{
SOTaxTran newtax = new SOTaxTran();
newtax.LineNbr = int.MaxValue;
newtax.TaxID = tax.TaxID;
newtax = docgraph.Taxes.Insert(newtax);
if (newtax != null)
{
newtax = PXCache<SOTaxTran>.CreateCopy(newtax);
newtax.TaxRate = tax.TaxRate;
newtax.CuryTaxableAmt = tax.CuryTaxableAmt;
newtax.CuryTaxAmt = tax.CuryTaxAmt;
newtax.CuryUnshippedTaxableAmt = tax.CuryTaxableAmt;
newtax.CuryUnshippedTaxAmt = tax.CuryTaxAmt;
newtax.CuryUnbilledTaxableAmt = tax.CuryTaxableAmt;
newtax.CuryUnbilledTaxAmt = tax.CuryTaxAmt;
newtax = docgraph.Taxes.Update(newtax);
}
}
}
if (opportunity.AllowOverrideContactAddress == true)
{
CRContact _CRContact = Opportunity_Contact.SelectSingle();
CRAddress _CRAddress = Opportunity_Address.SelectSingle();
// Insert
if (_CRContact != null)
{
SOBillingContact _billingContact = docgraph.Billing_Contact.Select();
if (_billingContact != null)
{
_billingContact.FullName = _CRContact.FullName;
_billingContact.Salutation = _CRContact.Salutation;
_billingContact.Phone1 = _CRContact.Phone1;
_billingContact.Email = _CRContact.Email;
_billingContact = docgraph.Billing_Contact.Update(_billingContact);
_billingContact.IsDefaultContact = false;
_billingContact = docgraph.Billing_Contact.Update(_billingContact);
}
}
if (_CRAddress != null)
{
SOBillingAddress _billingAddress = docgraph.Billing_Address.Select();
if (_billingAddress != null)
{
_billingAddress.AddressLine1 = _CRAddress.AddressLine1;
_billingAddress.AddressLine2 = _CRAddress.AddressLine2;
_billingAddress.City = _CRAddress.City;
_billingAddress.CountryID = _CRAddress.CountryID;
_billingAddress.State = _CRAddress.State;
_billingAddress.PostalCode = _CRAddress.PostalCode;
_billingAddress = docgraph.Billing_Address.Update(_billingAddress);
_billingAddress.IsDefaultAddress = false;
_billingAddress = docgraph.Billing_Address.Update(_billingAddress);
}
}
}
if (recalcAny)
{
docgraph.recalcdiscountsfilter.Current.OverrideManualPrices = param.OverrideManualPrices == true;
docgraph.recalcdiscountsfilter.Current.RecalcDiscounts = param.RecalculateDiscounts == true;
docgraph.recalcdiscountsfilter.Current.RecalcUnitPrices = param.RecalculatePrices == true;
docgraph.recalcdiscountsfilter.Current.OverrideManualDiscounts = param.OverrideManualDiscounts == true;
docgraph.recalcdiscountsfilter.Current.OverrideManualDocGroupDiscounts = param.OverrideManualDocGroupDiscounts == true;
docgraph.Actions[nameof(Discount.RecalculateDiscountsAction)].Press();
}
if (!this.IsContractBasedAPI)
throw new PXRedirectRequiredException(docgraph, "");
docgraph.Save.Press();
}
NOTE: you can find most part of the sources by the following path in the Acumatica's server folder App_Data\CodeRepository\PX.Objects,App_Data\CodeRepository\PX.Data,App_Data\CodeRepository\PX.Objects.FS

How to detect window state in linux?

I need to find out if a native linux application window is maximized or minimized in a java program.
I tried using X11.XGetWindowProperty() and I get some results also, but I cant make out any useful information in it.
I am using JNA 4.2.1, Java 8 update72 on Ubuntu 14.04 LTS. Any pointers will be very helpful. Thanks in advance to all.
[Edit]
I have the code below which gives me the result I need. But the result is not same for every invocation. The atoms which are returned for the window vary within invocations. Is there any other reliable way to get the window state?
private static X11 x11 = X11.INSTANCE;
private static Display dispy = x11.XOpenDisplay(null);
public static void main(String[] args) {
try {
X11.Atom[] atoms = getAtomProperties(
bytesToInt(getProperty(X11.XA_ATOM, X11.INSTANCE.XInternAtom(dispy, "_NET_WM_STATE", false))));
boolean hidden = false;
boolean vmax = false;
boolean hmax = false;
for (int i = 0; i < atoms.length; i++) {
X11.Atom atom = atoms[i];
if (atom == null)
continue;
String atomName = X11.INSTANCE.XGetAtomName(dispy, atom);
if ("_NET_WM_STATE_HIDDEN".equals(atomName)) {
hidden = true;
} else if ("_NET_WM_STATE_MAXIMIZED_VERT".equals(atomName)) {
vmax = true;
} else if ("_NET_WM_STATE_MAXIMIZED_HORZ".equals(atomName)) {
hmax = true;
}
}
if (hidden)
System.out.println("Window minimized");
else if (vmax && hmax && !hidden)
System.out.println("Window maximized");
else
System.out.println("Window normal");
} catch (X11Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static X11.Atom[] getAtomProperties(int[] ids) {
X11.Atom[] atoms = new X11.Atom[ids.length];
for (int i = 0; i < ids.length; i++) {
if (ids[i] == 0)
continue;
atoms[i] = new X11.Atom(ids[i]);
}
return atoms;
}
private static int[] bytesToInt(byte[] prop) {
if (prop == null)
return null;
int[] res = new int[prop.length / 4];
for (int i = 0; i < res.length; i++) {
res[i] = ((prop[i * 4 + 3] & 0xff) << 24) | ((prop[i * 4 + 2] & 0xff) << 16) | ((prop[i * 4 + 1] & 0xff) << 8)
| ((prop[i * 4 + 0] & 0xff));
if (res[i] != 0)
continue;
}
return res;
}
private static byte[] getProperty(X11.Atom xa_prop_type, X11.Atom xa_prop_name) throws X11Exception {
X11.Window window = new X11.Window(73400355);
X11.AtomByReference xa_ret_type_ref = new X11.AtomByReference();
IntByReference ret_format_ref = new IntByReference();
NativeLongByReference ret_nitems_ref = new NativeLongByReference();
NativeLongByReference ret_bytes_after_ref = new NativeLongByReference();
PointerByReference ret_prop_ref = new PointerByReference();
NativeLong long_offset = new NativeLong(0);
NativeLong long_length = new NativeLong(4096 / 4);
/*
* MAX_PROPERTY_VALUE_LEN / 4 explanation (XGetWindowProperty manpage):
*
* long_length = Specifies the length in 32-bit multiples of the data to be retrieved.
*/
if (x11.XGetWindowProperty(dispy, window, xa_prop_name, long_offset, long_length, false, xa_prop_type, xa_ret_type_ref,
ret_format_ref, ret_nitems_ref, ret_bytes_after_ref, ret_prop_ref) != X11.Success) {
String prop_name = x11.XGetAtomName(dispy, xa_prop_name);
throw new X11Exception("Cannot get " + prop_name + " property.");
}
X11.Atom xa_ret_type = xa_ret_type_ref.getValue();
Pointer ret_prop = ret_prop_ref.getValue();
if (xa_ret_type == null) {
// the specified property does not exist for the specified window
return null;
}
if (xa_ret_type == null || xa_prop_type == null || !xa_ret_type.toNative().equals(xa_prop_type.toNative())) {
x11.XFree(ret_prop);
String prop_name = x11.XGetAtomName(dispy, xa_prop_name);
throw new X11Exception("Invalid type of " + prop_name + " property");
}
int ret_format = ret_format_ref.getValue();
long ret_nitems = ret_nitems_ref.getValue().longValue();
// null terminate the result to make string handling easier
int nbytes;
if (ret_format == 32)
nbytes = Native.LONG_SIZE;
else if (ret_format == 16)
nbytes = Native.LONG_SIZE / 2;
else if (ret_format == 8)
nbytes = 1;
else if (ret_format == 0)
nbytes = 0;
else
throw new X11Exception("Invalid return format");
int length = Math.min((int) ret_nitems * nbytes, 4096);
byte[] ret = ret_prop.getByteArray(0, length);
x11.XFree(ret_prop);
return ret;
}

span insertion logic help

I have a text like this
"You are advised to grant access to these settings only if you are sure you want to allow this program to run automatically when your computer starts. Otherwise it is better to deny access."
and i have 3 selections,
1. StartIndex = 8, Length = 16 // "advised to grant"
2. StartIndex = 16, Length = 33 //"to grant access to these settings"
3. StartIndex = 35, Length = 26 // "these settings only if you"
i need to insert span tags and highlight selections, and intersections of words should be highlighted in different color,
result should be something like this
"You are <span style= 'background-color:#F9DA00'>advised </span> <span id = 'intersection' style= 'background-color:#F9DA00'>to grant </span> <span style= 'background-color:#F9DA00'>advised </span> <span style= 'background-color:#F9DA00'>access to </span>
<span id = 'intersection' style= 'background-color:#F9DA00'>these settings</span>
<span style= 'background-color:#F9DA00'>only if you </span> sure you want to allow this program to run automatically when your computer starts. Otherwise it is better to deny access."
please help me to sort this out, i have been trying to figure-out a logic for a long time now and no luck so far
Markup comment: IDs need to be unique. Make them classes instead: class="intersection".
finally manage to find a solution on my own, hope this help someone also in the future
public enum SortDirection
{
Ascending, Descending
}
public enum SpanType
{
Intersection, InnerSpan, Undefined
}
class Program
{
static void Main(string[] args)
{
string MessageText = #"You are advised to grant access to these settings only if you are sure you want to allow this program to run automatically when your computer starts. Otherwise it is better to deny access.";
List<Span> spanList = new List<Span>();
List<Span> intersectionSpanList = new List<Span>();
spanList.Add(new Span() { SpanID = "span1", Text = "advised to grant", ElementType = SpanType.Undefined, StartIndex = 8, Length = 16 });
spanList.Add(new Span() { SpanID = "span2", Text = "to grant access to these settings", ElementType = SpanType.Undefined, StartIndex = 16, Length = 33 });
spanList.Add(new Span() { SpanID = "span3", Text = "these settings only if you", ElementType = SpanType.Undefined, StartIndex = 35, Length = 26 });
// simple interseciotn
//spanList.Add(new Span() { SpanID = "span1", Text = "advised to grant", ElementType = TagType.Undefined, StartIndex = 8, Length = 16 });
//spanList.Add(new Span() { SpanID = "span2", Text = "to grant access", ElementType = TagType.Undefined, StartIndex = 16, Length = 15 });
// two different spans
//spanList.Add(new Span() { SpanID = "span1", Text = "advised to grant", ElementType = TagType.Undefined, StartIndex = 8, Length = 16 });
//spanList.Add(new Span() { SpanID = "span2", Text = "only if you are ", ElementType = TagType.Undefined, StartIndex = 50, Length = 16 });
// inner span
//spanList.Add(new Span() { SpanID = "span1", Text = "to grant access to these settings", ElementType = TagType.Undefined , StartIndex = 16, Length = 33 });
//spanList.Add(new Span() { SpanID = "span2", Text = "access to these", ElementType = TagType.Undefined, StartIndex = 25, Length = 15 });
// one inner span, and complex
//spanList.Add(new Span() { SpanID = "span1", Text = "to grant access to these settings only ", ElementType = TagType.Undefined, StartIndex = 16, Length = 39 });
//spanList.Add(new Span() { SpanID = "span2", Text = "access to these", ElementType = TagType.Undefined, StartIndex = 25, Length = 15 });
//spanList.Add(new Span() { SpanID = "span3", Text = "only if you are sure", ElementType = TagType.Undefined, StartIndex = 50, Length = 20 });
// one large span, and two intersections
//spanList.Add(new Span() { SpanID = "span1", Text = "grant access to these settings only if you are sure you want to allow this program to run automatically when", ElementType = SpanType.Undefined, StartIndex = 19, Length = 108 });
//spanList.Add(new Span() { SpanID = "span2", Text = "these settings only", ElementType = SpanType.Undefined, StartIndex = 35, Length = 19 });
//spanList.Add(new Span() { SpanID = "span3", Text = "you want to allow this", ElementType = SpanType.Undefined, StartIndex = 71, Length = 22 });
spanList.Sort("StartIndex asc");
foreach (var item in spanList)
item.SplitSpans(ref spanList, ref intersectionSpanList, ref MessageText);
// join intersections with span collection
foreach (var item in intersectionSpanList)
spanList.Add(item);
//remove duplicates
spanList = RemoveDuplicateSpans(spanList);
// sort spans by index ..
spanList.Sort("StartIndex asc"); //desc
foreach (var item in spanList)
{
item.InsertStartSpan(ref spanList, ref MessageText);
}
foreach (var item in spanList)
{
item.InsertEndSpan(ref spanList, ref MessageText);
}
//int count = spanList.Count -1;
//while (count > 0)
//{
// Span currentSpan = spanList[count];
// currentSpan.InsertEndSpan(ref spanList, ref MessageText);
// count--;
//}
}
internal static List<Span> RemoveDuplicateSpans(List<Span> list)
{
List<int> uniqueList = new List<int>();
for (int i = 0; i < list.Count; i++)
{
for (int j = 0; j < list.Count ; j++)
{
if (list[i].SpanID != list[j].SpanID)
{
if (list[i].StartIndex == list[j].StartIndex && list[i].EndPossition == list[j].EndPossition && list[i].ElementType == SpanType.Undefined)
{
uniqueList.Add(i);
}
}
}
}
foreach (var item in uniqueList)
{
list.RemoveAt(item);
}
return list;
}
}
public static class Extensions
{
public static void Sort<T>(this List<T> list, string sortExpression)
{
string[] sortExpressions = sortExpression.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
List<GenericComparer> comparers = new List<GenericComparer>();
foreach (string sortExpress in sortExpressions)
{
string sortProperty = sortExpress.Trim().Split(' ')[0].Trim();
string sortDirection = sortExpress.Trim().Split(' ')[1].Trim();
Type type = typeof(T);
PropertyInfo PropertyInfo = type.GetProperty(sortProperty);
if (PropertyInfo == null)
{
PropertyInfo[] props = type.GetProperties();
foreach (PropertyInfo info in props)
{
if (info.Name.ToString().ToLower() == sortProperty.ToLower())
{
PropertyInfo = info;
break;
}
}
if (PropertyInfo == null)
{
throw new Exception(String.Format("{0} is not a valid property of type: \"{1}\"", sortProperty, type.Name));
}
}
SortDirection SortDirection = SortDirection.Ascending;
if (sortDirection.ToLower() == "asc" || sortDirection.ToLower() == "ascending")
{
SortDirection = SortDirection.Ascending;
}
else if (sortDirection.ToLower() == "desc" || sortDirection.ToLower() == "descending")
{
SortDirection = SortDirection.Descending;
}
else
{
throw new Exception("Valid SortDirections are: asc, ascending, desc and descending");
}
comparers.Add(new GenericComparer { SortDirection = SortDirection, PropertyInfo = PropertyInfo, comparers = comparers });
}
list.Sort(comparers[0].Compare);
}
}
public class GenericComparer
{
public List<GenericComparer> comparers { get; set; }
int level = 0;
public SortDirection SortDirection { get; set; }
public PropertyInfo PropertyInfo { get; set; }
public int Compare<T>(T t1, T t2)
{
int ret = 0;
if (level >= comparers.Count)
return 0;
object t1Value = comparers[level].PropertyInfo.GetValue(t1, null);
object t2Value = comparers[level].PropertyInfo.GetValue(t2, null);
if (t1 == null || t1Value == null)
{
if (t2 == null || t2Value == null)
{
ret = 0;
}
else
{
ret = -1;
}
}
else
{
if (t2 == null || t2Value == null)
{
ret = 1;
}
else
{
ret = ((IComparable)t1Value).CompareTo(((IComparable)t2Value));
}
}
if (ret == 0)
{
level += 1;
ret = Compare(t1, t2);
level -= 1;
}
else
{
if (comparers[level].SortDirection == SortDirection.Descending)
{
ret *= -1;
}
}
return ret;
}
}
public class Span
{
string _Color = "#F9DA00";
public const int SPAN_START_LENGTH = 40;
public const int SPAN_END_LENGTH = 7;
public const int SPAN_TOTAL_LENGTH = 47;
public string Color
{
get
{
return _Color;
}
set
{
_Color = value;
}
}
public string SpanID { get; set; }
public int StartIndex { get; set; }
public int HTMLTagEndPossition { get; set; }
public Span ParentSpan { get; set; }
public int Length { get; set; }
public SpanType ElementType { get; set; }
public string Text { get; set; }
public int EndPossition
{
get
{
return StartIndex + Length;
}
}
public string GetStartSpanHtml()
{
return "<span style= 'background-color:" + Color + "'>" + this.Text;
}
public string GetEndSpanHtml()
{
return "</span>";
}
public bool IsProcessed { get; set; }
internal void PostProcess(Span span, ref List<Span> spanList, ref string MessageText)
{
MessageText = MessageText.Remove(span.StartIndex, span.Length);
MessageText = MessageText.Insert(span.StartIndex, span.GetStartSpanHtml());
int offset = Span.SPAN_TOTAL_LENGTH;
AdjustStartOffsetOfSpans(spanList, span, offset);
}
internal void SplitSpans(ref List<Span> spanList, ref List<Span> intersectionSpanList, ref string MessageText)
{
foreach (var item in spanList)
{
if (this.SpanID == item.SpanID)
continue;
if (this.StartIndex < item.StartIndex && this.EndPossition > item.EndPossition)
{
// inner
int innerSpanLength = this.EndPossition - item.StartIndex;
int innerSpanStartPos = this.StartIndex;
string innerSpanText = MessageText.Substring(item.StartIndex, item.Length);
Span innerSpan = new Span();
innerSpan.SpanID = "innerSpan" + Guid.NewGuid().ToString().Replace("-", "");
innerSpan.ElementType = SpanType.InnerSpan;
innerSpan.Text = innerSpanText;
innerSpan.Length = item.Length;
innerSpan.StartIndex = item.StartIndex;
innerSpan.ParentSpan = this;
intersectionSpanList.Add(innerSpan);
}
if (this.StartIndex < item.StartIndex && item.EndPossition > this.EndPossition && this.EndPossition > item.StartIndex)
{
// end is overlapping
int intersectionLength = this.EndPossition - item.StartIndex;
int intersectionStartPos = item.StartIndex;
string intersectionText = MessageText.Substring(item.StartIndex, intersectionLength);
// Build intersection span
Span intersectonSpan = new Span();
intersectonSpan.SpanID = "intersectonSpan" + Guid.NewGuid().ToString().Replace("-", "");
intersectonSpan.Text = intersectionText;
intersectonSpan.Length = intersectionLength;
intersectonSpan.StartIndex = intersectionStartPos;
intersectonSpan.ElementType = SpanType.Intersection;
intersectionSpanList.Add(intersectonSpan);
// adjust my end pos.
this.Length = this.Length - intersectionLength;
this.Text = this.Text.Substring(0, this.Length);
item.StartIndex += intersectionLength;
item.Length -= intersectionLength;
item.Text = item.Text.Substring(intersectionLength, item.Length);
}
else if (this.StartIndex < item.StartIndex && item.EndPossition > this.EndPossition && this.EndPossition < item.StartIndex)
{
// two spans are not over lapping,
}
//if (this.EndPossition > item.StartIndex && this.EndPossition < item.EndPossition)
//{
// if (item.StartIndex < this.StartIndex && item.EndPossition > this.EndPossition)
// {
// int innerSpanLength = this.EndPossition - this.StartIndex;
// int innerSpanStartPos = this.StartIndex;
// string innerSpanText = MessageText.Substring(this.StartIndex, this.Length);
// // we are dealing with a inner span..
// Span innerSpan = new Span();
// innerSpan.SpanID = "innerSpan";
// innerSpan.Text = innerSpanText;
// innerSpan.Length = innerSpanLength;
// innerSpan.StartIndex = innerSpanStartPos;
// innerSpan.IsIntersection = true;
// intersectionSpanList.Add(innerSpan);
// MessageText = MessageText.Remove(innerSpanStartPos, innerSpanLength);
// MessageText = MessageText.Insert(innerSpanStartPos, innerSpan.GetStartSpanHtml());
// break;
// }
// int intersectionLength = this.EndPossition - item.StartIndex;
// int intersectionStartPos = item.StartIndex;
// string intersectionText = MessageText.Substring(item.StartIndex, intersectionLength);
// // adjust the string.
// if (!this.IsProcessed)
// {
// this.Text = this.Text.Substring(0, this.Length - intersectionLength);
// this.Length = this.Length - intersectionLength;
// MessageText = MessageText.Remove(this.StartIndex, this.Length);
// MessageText = MessageText.Insert(this.StartIndex, this.GetStartSpanHtml());
// // readjust intersection after insertion of the first span..
// intersectionStartPos = Span.SPAN_START_LENGTH + intersectionStartPos;
// }
// // Build intersection span
// Span intersectonSpan = new Span();
// intersectonSpan.SpanID = "intersectonSpan";
// intersectonSpan.Text = intersectionText;
// intersectonSpan.Length = intersectionLength;
// intersectonSpan.StartIndex = intersectionStartPos;
// intersectonSpan.IsIntersection = true;
// intersectionSpanList.Add(intersectonSpan);
// MessageText = MessageText.Remove(intersectionStartPos, intersectionLength);
// MessageText = MessageText.Insert(intersectionStartPos, intersectonSpan.GetStartSpanHtml());
// if (!this.IsProcessed)
// item.StartIndex = item.StartIndex + intersectionLength + Span.SPAN_START_LENGTH + Span.SPAN_START_LENGTH;
// else
// item.StartIndex = item.StartIndex + intersectionLength + Span.SPAN_START_LENGTH;
// item.Length = item.Length - intersectionLength;
// item.Text = item.Text.Substring(intersectionLength, item.Length);
// //MessageText = MessageText.Remove(item.StartIndex, item.Length);
// //MessageText = MessageText.Insert(item.StartIndex, item.GetOuterHtml());
// int offset;
// if (!this.IsProcessed)
// offset = Span.SPAN_START_LENGTH + Span.SPAN_START_LENGTH;
// else
// offset = Span.SPAN_START_LENGTH;
// AdjustOffsetSpans(spanList, item, offset);
// this.IsProcessed = true;
// break;
//}
//else if (item.StartIndex > this.StartIndex && item.EndPossition < this.EndPossition)
//{
// // bigger span, inside there are children span(s)
// MessageText = MessageText.Remove(this.StartIndex, this.Length);
// MessageText = MessageText.Insert(this.StartIndex, this.GetStartSpanHtml());
// // since this span is the big guy.
// AdjustOffsetForInnerSpansAndExternalSpans(spanList, this, this.StartIndex, this.EndPossition);
// this.StartIndex += Span.SPAN_START_LENGTH;
// this.IsProcessed = true;
//}
}
}
//internal static void AdjustOffsetForInnerSpansAndExternalSpans(List<Span> spanList, Span parentSpan, int parentStartIndex, int parentEndIndex)
//{
// bool adjustAfterThisSpan = false;
// foreach (var item in spanList)
// {
// if (item.SpanID == parentSpan.SpanID)
// {
// adjustAfterThisSpan = true;
// continue;
// }
// if (adjustAfterThisSpan)
// {
// // is this span in the middle of the parent ?
// if (item.StartIndex > parentSpan.StartIndex && item.EndPossition < parentSpan.EndPossition)
// {
// item.StartIndex += SPAN_START_LENGTH;
// }
// else
// {
// // after parent tag ?
// item.StartIndex += SPAN_START_LENGTH;
// }
// }
// }
//}
private void AdjustEndOffsetOfSpans(List<Span> spanList, Span span, int SPAN_END_LENGTH)
{
bool adjustAfterThisSpan = false;
foreach (var item in spanList)
{
if (item.SpanID == span.SpanID)
{
adjustAfterThisSpan = true;
continue;
}
if (adjustAfterThisSpan)
{
if (item.ParentSpan == null)
{
item.HTMLTagEndPossition += SPAN_END_LENGTH;
}
else if (span.ParentSpan != null && this.SpanID == item.ParentSpan.SpanID)
{ }
}
}
}
internal static void AdjustStartOffsetOfSpans(List<Span> spanList, Span fromSpan, int offset)
{
bool adjustAfterThisSpan = false;
foreach (var item in spanList)
{
if (item.SpanID == fromSpan.SpanID)
{
adjustAfterThisSpan = true;
continue;
}
if (adjustAfterThisSpan)
item.StartIndex += offset;
}
}
internal void InsertStartSpan(ref List<Span> spanList, ref string MessageText)
{
MessageText = MessageText.Remove(this.StartIndex, this.Length);
MessageText = MessageText.Insert(this.StartIndex, this.GetStartSpanHtml());
AdjustStartOffsetOfSpans(spanList, this, SPAN_START_LENGTH);
// Adjust end element tag
switch (this.ElementType)
{
case SpanType.Intersection:
{
this.HTMLTagEndPossition = this.Length + SPAN_START_LENGTH + this.StartIndex;
break;
}
case SpanType.InnerSpan:
{
this.HTMLTagEndPossition = this.Length + SPAN_START_LENGTH + this.StartIndex;
// increase the parent's tag offset conent length
this.ParentSpan.HTMLTagEndPossition += SPAN_START_LENGTH;
break;
}
case SpanType.Undefined:
{
this.HTMLTagEndPossition = this.Length + SPAN_START_LENGTH + this.StartIndex;
break;
}
default:
break;
}
}
internal void InsertEndSpan(ref List<Span> spanList, ref string MessageText)
{
switch (this.ElementType)
{
case SpanType.Intersection:
{
MessageText = MessageText.Insert(this.HTMLTagEndPossition, this.GetEndSpanHtml());
break;
}
case SpanType.InnerSpan:
{
MessageText = MessageText.Insert(this.HTMLTagEndPossition, this.GetEndSpanHtml());
break;
}
case SpanType.Undefined:
{
MessageText = MessageText.Insert(this.HTMLTagEndPossition, this.GetEndSpanHtml());
break;
}
default:
break;
}
AdjustEndOffsetOfSpans(spanList, this, SPAN_END_LENGTH);
}
}

Resources