After changing linestyle in revit api cant find new linestyle in object styles - categories

I am creating a category in a Revit family that is a linestyle and after i set it, it exists but i just cant find it in the family and yet i f try to recreate it revit creates an error that it already exists. i tried using regeneration and this doesnt work.
ElementId solidLineId = LinePatternElement.GetSolidPatternId();
// The new linestyle will be a subcategory of the Lines category
Categories categories = doc.Settings.Categories;
Category lineCat = categories.get_Item(BuiltInCategory.OST_Lines);
using (Transaction t = new Transaction(doc, "Create LineStyle"))
{
t.Start();
Category newLineStyleCat = categories.NewSubcategory(lineCat, "Black-01-Solid");
newLineStyleCat.SetLineWeight(1, GraphicsStyleType.Projection);
newLineStyleCat.LineColor = new Color(28,28, 28);
newLineStyleCat.SetLinePatternId(solidLineId, GraphicsStyleType.Projection);
t.Commit();
}

This is how new linestyles can be created
Category cat = famDoc.OwnerFamily.FamilyCategory;
Category newSubCat = null;
if (!cat.SubCategories.Contains(subCatToAdd))
{
using (Transaction t = new Transaction(famDoc, "Add new or find existing subcategory"))
{
t.Start();
newSubCat = famDoc.Settings.Categories.NewSubcategory(cat, subCatToAdd);
GraphicsStyleType gst = GraphicsStyleType.Projection;
GraphicsStyle gs = newSubCat.GetGraphicsStyle(gst);
newSubCat.SetLineWeight(lineWeight, gst);
t.Commit();
}
}

Related

Updating column in tableviwer

I have retrieved data from database and i am able to show it in Table of the Table Viewer but my task is on click of a row the data should be appear in another form from where i can edit it and on click of update the view should be updated with the new values.I am using viewer.addSelectionChangedListener to retrieve the selected row but i am not getting how to update the table .Please suggest me few ideas
I have written the below code in the constructor of my class so whenever object is created Table is generated and l1 is list of data which i am passing to another UI
input[i] = new MyModel(persons[i].getDateOfRegistration(), persons[i].getFirstName(),
persons[i].getMiddleName(), persons[i].getLastName(), persons[i].getGender(),
persons[i].getDob(), persons[i].getContactNumber(), persons[i].getMaritalStatus(),
persons[i].getAddress(), persons[i].getCountry(), persons[i].getBloodGroup(),
persons[i].getInsuranceDetails().getPolicyHolderName(),
persons[i].getInsuranceDetails().getPolicyNumber(),
persons[i].getInsuranceDetails().getSubscriberName(),
persons[i].getInsuranceDetails().getRelationshipToPatient());
viewer.setInput(input);
table.setHeaderVisible(true);
table.setLinesVisible(true);
GridData gridData = new GridData();
gridData.verticalAlignment = GridData.FILL;
gridData.horizontalSpan = 2;
gridData.grabExcessHorizontalSpace = true;
gridData.grabExcessVerticalSpace = true;
gridData.horizontalAlignment = GridData.FILL;
viewer.getControl().setLayoutData(gridData);
viewer.addSelectionChangedListener(new ISelectionChangedListener() {
public void selectionChanged(SelectionChangedEvent event) {
IStructuredSelection selection = (IStructuredSelection) event.getSelection();
StringBuffer sb = new StringBuffer("Selection - ");
int j = 0;
String[] s;
for (Iterator iterator = selection.iterator(); iterator.hasNext();) {
sb.append(iterator.next() + ", ");
System.out.println("Testing::" + sb);
}
System.out.println(sb);
String result[] = new String[18];
List l1 = new ArrayList(100);
String[] parts = sb.toString().split("=");
for (int i = 0; i < parts.length; i++) {
System.out.println("s" + parts[i]);
String[] s1 = parts[i].split(",");
l1.add(s1[0]);
}
SWTPatientRegistrationUpdatePageEventView swtPatientRegistrationUpdatePageEventView = new SWTPatientRegistrationUpdatePageEventView();
swtPatientRegistrationUpdatePageEventView.openParentUpdateShell(l1);
// viewer.refresh();
//flag=false;
//refreshingData(list);
}
});
Make sure we will follow table viewer MVC architecture all the time. Steps we can do to resolve your issue isas follow:
Create proper datastructure(Model Class) to hold the data. and use the same in array which you set in viewer.setInput()
When you click/double click on table row, fetch the data and save it in datastructure created(with new object).
Pass that data structure to your form dialog.
when you are done with update in form. Fill the updated data in new Model object again.
And after form close, pass that model object back to parent.
updated the corresponding array element with object received from Form Dialog and just refresh the tableviewer.
Please let me know if you need some code module. Thanks

EF6 update not actually updating the table record?

I'm having to write a app that effectively copies data from one databaseA.table to databaseB.table but there are a few fields in databaseB that aren't in databaseA.
I've come up with basic code below. The insert works and the update doesn't trow an error, however, the update doesn't actually update any records.
I've confirmed that the bcEmployee object in the update has the new values from databaseA like it should. The employee object is the record from databaseA.
Am I missing something to make this update?
BC_employee bcEmployee = new BC_employee();
bcEmployee.emp_id = employee.emp_id;
bcEmployee.emp_firstname = employee.emp_firstname;
bcEmployee.emp_lastname = employee.emp_lastname;
using (BCcontext ctx = new BCcontext())
{
var existBCemployee = ctx.employee.Find(employee.emp_id);
if (existBCemployee == null) //Insert
{
//Set default values that aren't in the original database
bcEmployee.emp_paystat = null;
bcEmployee.password = null;
bcEmployee.enroll_date = null;
ctx.employee.Add(bcEmployee);
}
else
{
ctx.Entry(existBCemployee).CurrentValues.SetValues(bcEmployee);
}
ctx.SaveChanges();
}

PSI update resource custom field with lookup table (Project Server)

Can someone show me a code to update a enterprise resource custom field with lookup table ? Already ran the internet looking for some sample code but did not succeed.
You can create and update a custom field with a lookup table using the below code . But we can not update or delete builtin custom fields
var projContext = new ProjectContext(projectServerUrl);
CustomFieldCollection CustomField = projContext.CustomFields;
EntityTypes Entitytype = projContext.EntityTypes;
LookupTableCollection lookupTables = projContext.LookupTables;
projContext.Load(CustomField);
projContext.Load(Entitytype);
projContext.Load(lookupTables);
projContext.ExecuteQuery();
CustomFieldCreationInformation NewfieldInfo = new CustomFieldCreationInformation();
NewfieldInfo.Id = new Guid();
NewfieldInfo.Name = "The Name";
NewfieldInfo.Description = "The Description";
NewfieldInfo.IsWorkflowControlled = true;
NewfieldInfo.IsRequired = true;
NewfieldInfo.IsEditableInVisibility = false;
NewfieldInfo.IsMultilineText = false;
LookupTable lookuptable = lookupTables.ToList().Find(x => x.Name == "LookupTableName");
projContext.Load(lookuptable);
projContext.ExecuteQuery();
NewfieldInfo.LookupTable = lookuptable;
NewfieldInfo.EntityType = Entitytype.ProjectEntity;
NewfieldInfo.FieldType = CustomFieldType.TEXT;
projContext.CustomFields.Add(NewfieldInfo);
projContext.CustomFields.Update();
projContext.ExecuteQuery();

How to force the Plugin on Post-Operation to Submit?

I have a plugin in post-operation witch need to create a folder on sharepoint via webservice, to do that, my plugin calls a webservice to execute a FechXML to get the info from the entity, but the problem is that entity still not exist, and it give me Null.
How do i force the plugin to submit/save the data to my FechXml to work?
PLUGIN CODE:
try
{
Entity entity;
if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
{
entity = (Entity)context.InputParameters["Target"];
if (entity.LogicalName != "fcg_processos")
{
throw new InvalidPluginExecutionException("Ocorreu um erro no PlugIn Create Folder.");
}
}
else
{
throw new InvalidPluginExecutionException("Ocorreu um erro no PlugIn Create Folder.");
}
processosid = (Guid)((Entity)context.InputParameters["Target"])["fcg_processosid"];
string processoid2 = processosid.ToString();
PluginSharepointProcessos.ServiceReference.PrxActivityResult result = log.CreateFolderSP("Processo", processoid2);
string resultado = result.xmlContent;
if (result.retCode > 0)
{
throw new InvalidPluginExecutionException("Ocorreu um erro na criação do Folder do Processo.");
}
WEBSERVICE CODE:
{
//WEBSERVICE TO CALL XML FROM ENTITY
PrxActivityResult Processo = ProcessoFetch2("", "", guid);
string stxml;
stxml = Processo.XmlContent;
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(stxml);
XmlNodeList nodeList = xmlDoc.SelectNodes("resultset/result");
List<string[]> lista = new List<string[]>();
string[] strs = new string[7];
if (nodeList.Count != 0)//verificar o numero de registos
{
foreach (XmlNode xmlnode in nodeList)
{
if (xmlnode.SelectSingleNode("//fcg_numero") != null)
strs[2] = xmlnode.SelectSingleNode("//fcg_numero").InnerText;
else
strs[2] = "";
if (xmlnode.SelectSingleNode("//Concurso.fcg_numero") != null)
strs[3] = xmlnode.SelectSingleNode("//Concurso.fcg_numero").InnerText;
else
strs[3] = "";
}
}
IwsspClient FmwSharepoint = new IwsspClient();
PrxActivityResult folderresult = new PrxActivityResult();
List<ws.fcg.sipp.svc.ServiceReferenceSharePoint.PareChave> arrayfields = new List<ws.fcg.sipp.svc.ServiceReferenceSharePoint.PareChave>();
ws.fcg.sipp.svc.ServiceReferenceSharePoint.PareChave nprocesso = new ws.fcg.sipp.svc.ServiceReferenceSharePoint.PareChave();
nprocesso.Key = "FCG_Numero_Processo";
nprocesso.value = strs[2];
arrayfields.Add(nprocesso);
ws.fcg.sipp.svc.ServiceReferenceSharePoint.PareChave npconcurso = new ws.fcg.sipp.svc.ServiceReferenceSharePoint.PareChave();
npconcurso.Key = "FCG_Numero_Concurso";
npconcurso.value = strs[3];
arrayfields.Add(npconcurso);
ws.fcg.sipp.svc.ServiceReferenceSharePoint.PareChave npguid = new ws.fcg.sipp.svc.ServiceReferenceSharePoint.PareChave();
npguid.Key = "FCG_Guid_CRM";
npguid.value = guid;
arrayfields.Add(npguid);
folderresult = FmwSharepoint.CreateFolder("http://localhost/folder", "Processos", strs[2], arrayfields.ToArray());
res = folderresult;
}
When a plugin runs on the Post-Operation, it is still within the database transaction, and it hasn't actually been committed to the database. Any calls done with the service reference passed in as a part of the Plugin Context will be executed within the context on the database transaction and you will be able to retrieve the newly created/updated values. If you create a brand new OrganizationServiceProxy (Which I'm guessing is what you're doing), it will execute outside of the database transaction, and will not see the newly created / updated values.
As #AndyMeyers suggests in his comment (which really should be an answer IMHO), grabbing the data from the plugin context either via a pre/post image or the target is ideal since it eliminates another database call. If you're having to lookup records that may have been created by another plugin that fired earlier, you'll need to use the IOrganizationService that is included in the plugin context.
I had no option and I used this code to run webservice based on image and forget the FecthXml, as mentioned, i get all info from the Image on the post operation and send back to the WebService. Thanks, here is the code:
entity = (Entity)context.InputParameters["Target"];
concursid = (Guid)entity.Attributes["fcg_concursid"];
guid = concursid.ToString();
string npconcurs = (string)entity.Attributes["fcg_numer"];
nconcurs= npconcurs;
EntityReference nprograma = (EntityReference)entity.Attributes["fcg_unidadeorganica"];
program = nprogram.Name;
if (entity.LogicalName != "fcg_concurs")

Add Hyperlink to Cell in Excel 2007 Using Open XML SDK 2.0

I can't seem to find any documentation or code samples on how to add a hyperlink to a cell in Excel 2007 using the Open XML SDK 2.0. I am using the following code, but is there a step I am missing?
WorksheetPart workSheetPart = ExcelUtilities.GetWorkSheetPart(mWorkBookPart, "Program");
workSheetPart.AddHyperlinkRelationship(new Uri("http://www.google.com", UriKind.Absolute), true);
workSheetPart.Worksheet.Save();
mWorkBookPart.Workbook.Save();
Then when I try and open the Excel document it says the file is corrupted because the Relationship Id for the hyperlink cannot be found. How do you setup or create that Relationship Id?
Another possibility, (which I used), is to use the HYPERLINK formula for Excel. I needed to create individual hyperlinks in each cell, yet the cells had to display different text, (I had to display tracking numbers in the cells yet have a hyperlink for each tracking number to the carrier's site and had to handle multiple carriers).
Once I instantiated an individual cell, the formula was applied in this manner to each cell (there are undoubtedly numerous way):
// ...
Cell cell1 = new Cell(){ CellReference = "A1", StyleIndex = (UInt32Value)1U, DataType = CellValues.InlineString };
CellValue cellValue1 = new CellValue();
CellFormula cellFormula1 = new CellFormula() { Space = SpaceProcessingModeValues.Preserve };
cellFormula1.Text = #"HYPERLINK(""http://www.theclash.com"", ""Radio Clash"")";
cellValue1.Text = "Radio Clash";
cell1.Append(cellFormula1);
cell1.Append(cellValue1);
// append cell, etc.
In this way, I was able to create individual hyperlinks and text for each cell. By the way, the links will appear with the default font color unless you reference a style with blue font.
Hope this helps.
I was able to add a hyperlink to a cell using System.IO.Packaging code:
private void HyperlinkCreate(PackagePart part, XmlNamespaceManager nsm, XmlNode _cellElement, string CellAddress)
{
Uri _hyperlink = new Uri("http://www.yahoo.com");
XmlNode linkParent = _cellElement.OwnerDocument.SelectSingleNode("//d:hyperlinks", nsm);
if (linkParent == null)
{
// create the hyperlinks node
linkParent = _cellElement.OwnerDocument.CreateElement("hyperlinks", #"http://schemas.openxmlformats.org/spreadsheetml/2006/main");
XmlNode prevNode = _cellElement.OwnerDocument.SelectSingleNode("//d:conditionalFormatting", nsm);
if (prevNode == null)
{
prevNode = _cellElement.OwnerDocument.SelectSingleNode("//d:mergeCells", nsm);
if (prevNode == null)
{
prevNode = _cellElement.OwnerDocument.SelectSingleNode("//d:sheetData", nsm);
}
}
_cellElement.OwnerDocument.DocumentElement.InsertAfter(linkParent, prevNode);
}
string searchString = string.Format("./d:hyperlink[#ref = '{0}']", CellAddress);
XmlElement linkNode = (XmlElement)linkParent.SelectSingleNode(searchString, nsm);
XmlAttribute attr;
if (linkNode == null)
{
linkNode = _cellElement.OwnerDocument.CreateElement("hyperlink", #"http://schemas.openxmlformats.org/spreadsheetml/2006/main");
// now add cell address attribute
linkNode.SetAttribute("ref", CellAddress);
linkParent.AppendChild(linkNode);
}
attr = (XmlAttribute)linkNode.Attributes.GetNamedItem("id", #"http://schemas.openxmlformats.org/officeDocument/2006/relationships");
if (attr == null)
{
attr = _cellElement.OwnerDocument.CreateAttribute("r", "id", #"http://schemas.openxmlformats.org/officeDocument/2006/relationships");
linkNode.Attributes.Append(attr);
}
PackageRelationship relationship = null;
string relID = attr.Value;
if (relID == "")
relationship = part.CreateRelationship(_hyperlink, TargetMode.External, #"http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink");
else
{
relationship = part.GetRelationship(relID);
if (relationship.TargetUri != _hyperlink)
relationship = part.CreateRelationship(_hyperlink, TargetMode.External, #"http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink");
}
attr.Value = relationship.Id;
}
I then translated this code using the Open XML SDK 2.0 and it doesn't work. It seems the AddHyperlinkRelationship method doesn't actually add the relationship to the .rels file. I'm not sure why, but it sure seems like a bug to me.
private void HyperlinkCreate(PackagePart part, XmlNamespaceManager nsm, XmlNode _cellElement, string CellAddress)
{
WorksheetPart workSheetPart = ExcelUtilities.GetWorkSheetPart(mWorkBookPart, "Program");
Uri hyperlinkUri = new Uri("http://www.yahoo.com", UriKind.Absolute);
Hyperlinks hyperlinks = workSheetPart.Worksheet.Descendants<Hyperlinks>().FirstOrDefault();
// Check to see if the <x:hyperlinks> element exists; if not figure out
// where to insert it depending on which elements are present in the Worksheet
if (hyperlinks == null)
{
// Create the hyperlinks node
hyperlinks = new Hyperlinks();
OpenXmlCompositeElement prevElement = workSheetPart.Worksheet.Descendants<ConditionalFormatting>().FirstOrDefault();
if (prevElement == null)
{
prevElement = workSheetPart.Worksheet.Descendants<MergeCells>().FirstOrDefault();
if (prevElement == null)
{
// No FirstOrDefault needed since a Worksheet requires SheetData or the excel doc will be corrupt
prevElement = workSheetPart.Worksheet.Descendants<SheetData>().First();
}
}
workSheetPart.Worksheet.InsertAfter(hyperlinks, prevElement);
}
Hyperlink hyperlink = hyperlinks.Descendants<Hyperlink>().Where(r => r.Reference.Equals(CellAddress)).FirstOrDefault();
if (hyperlink == null)
{
hyperlink = new Hyperlink() { Reference = CellAddress, Id = string.Empty };
}
HyperlinkRelationship hyperlinkRelationship = null;
string relId = hyperlink.Id;
if (relId.Equals(string.Empty))
{
hyperlinkRelationship = workSheetPart.AddHyperlinkRelationship(hyperlinkUri, true);
}
else
{
hyperlinkRelationship = workSheetPart.GetReferenceRelationship(relId) as HyperlinkRelationship;
if (!hyperlinkRelationship.Uri.Equals(hyperlinkUri))
{
hyperlinkRelationship = workSheetPart.AddHyperlinkRelationship(hyperlinkUri, true);
}
}
hyperlink.Id = hyperlinkRelationship.Id;
hyperlinks.AppendChild<Hyperlink>(hyperlink);
workSheetPart.Worksheet.Save();
}
You should be adding it to an object that accepts hyperlinks, such as a cell, instead of the worksheet. Something like this should work for you:
using DocumentFormat.OpenXml.Spreadsheet;
using DocumentFormat.OpenXml;
namespace GeneratedCode
{
public class GeneratedClass
{
// Creates an Worksheet instance and adds its children.
public Worksheet GenerateWorksheet()
{
Worksheet worksheet1 = new Worksheet(){ MCAttributes = new MarkupCompatibilityAttributes(){ Ignorable = "x14ac" } };
worksheet1.AddNamespaceDeclaration("r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships");
worksheet1.AddNamespaceDeclaration("mc", "http://schemas.openxmlformats.org/markup-compatibility/2006");
worksheet1.AddNamespaceDeclaration("x14ac", "http://schemas.microsoft.com/office/spreadsheetml/2009/9/ac");
SheetDimension sheetDimension1 = new SheetDimension(){ Reference = "A1" };
SheetViews sheetViews1 = new SheetViews();
SheetView sheetView1 = new SheetView(){ TabSelected = true, WorkbookViewId = (UInt32Value)0U };
sheetViews1.Append(sheetView1);
SheetFormatProperties sheetFormatProperties1 = new SheetFormatProperties(){ DefaultRowHeight = 14.4D, DyDescent = 0.3D };
SheetData sheetData1 = new SheetData();
Row row1 = new Row(){ RowIndex = (UInt32Value)1U, Spans = new ListValue<StringValue>() { InnerText = "1:1" }, DyDescent = 0.3D };
Cell cell1 = new Cell(){ CellReference = "A1", StyleIndex = (UInt32Value)1U, DataType = CellValues.SharedString };
CellValue cellValue1 = new CellValue();
cellValue1.Text = "0";
cell1.Append(cellValue1);
row1.Append(cell1);
sheetData1.Append(row1);
Hyperlinks hyperlinks1 = new Hyperlinks();
Hyperlink hyperlink1 = new Hyperlink(){ Reference = "A1", Id = "rId1" };
hyperlinks1.Append(hyperlink1);
PageMargins pageMargins1 = new PageMargins(){ Left = 0.7D, Right = 0.7D, Top = 0.75D, Bottom = 0.75D, Header = 0.3D, Footer = 0.3D };
worksheet1.Append(sheetDimension1);
worksheet1.Append(sheetViews1);
worksheet1.Append(sheetFormatProperties1);
worksheet1.Append(sheetData1);
worksheet1.Append(hyperlinks1);
worksheet1.Append(pageMargins1);
return worksheet1;
}
}
}
Easiest way is to use the HyperLink formular, but the links aren't blue by default, this is why the styleIndex is set.
private Cell BuildHyperlinkCell(string url) =>
new Cell
{
DataType = new EnumValue<CellValues>(CellValues.String),
CellFormula = new CellFormula($"HyperLink(\"{url}\")"),
StyleIndex = 4u
};
Adding the styling to the workbook:
http://www.dispatchertimer.com/tutorial/how-to-create-an-excel-file-in-net-using-openxml-part-3-add-stylesheet-to-the-spreadsheet/