Copy dimensions from a View to another Revit API - c#

I'm trying to create a new plug-in on Revit 2016/2017 with the API.
The idea is to copy a set of element from small revit file to a central one to compile them.
Here is the code I'm using :
FilterableValueProvider provider = new ParameterValueProvider(new ElementId(BuiltInParameter.ALL_MODEL_TYPE_NAME));
FilterRule rule = new FilterStringRule(provider, new FilterStringContains(), "BY_GO", false);
ElementParameterFilter epf = new ElementParameterFilter(rule, true);
ICollection<ElementId> npText = new FilteredElementCollector(secDoc, secView.Id).WherePasses(epf).ToElementIds();
using (TransactionGroup tx = new TransactionGroup(mainDoc, "Insert " + Main._roomFile.Typology))
{
ICollection<ElementId> pastedElements;
tx.Start();
using (Transaction tr = new Transaction(mainDoc, "Copy elements"))
{
tr.Start();
pastedElements = ElementTransformUtils.CopyElements(secView, npText, mainView, null, new CopyPasteOptions());
tr.Commit();
}
using (Transaction tr = new Transaction(mainDoc, "Move elements"))
{
tr.Start();
pastedElements = new FilteredElementCollector(mainDoc, pastedElements).WherePasses(epf).ToElementIds();
XYZ originePoint = new FilteredElementCollector(mainDoc, pastedElements).OfClass(typeof(Floor)).First().get_BoundingBox(null).Min;
XYZ translation = extremitePoint - originePoint;
translation = new XYZ(translation.X, translation.Y, 0);
ElementTransformUtils.MoveElements(mainDoc, pastedElements, translation);
tr.Commit();
}
tx.Assimilate();
}
When I use it, everything is good except the dimensions. They are inside the new document (I can get them with there id and RevitLookup) but they are hidden. If I select on of them and add a witness line the dimension is now visible again.
I tried to close and reopen Revit and place the vien on a sheet bt nothing.
Any idea ?
Thank you !

You need to regenerate the view I believe.
Try adding:
Document.Regenerate();

Here is the answer to the probleme.
It's Autodesk which have to solve it but the workaround is to create Dimensions with the reference of invisible one and then delete them.

Related

LibreOffice Calc C# SDK: program to insert images into cells, stuck trying to create XGraphic

Background: I'm trying to write a program to insert an image into a cell of a spreadsheet. LibreOffice recently changed how this is done, and all the samples I could find use the old method which no longer works.
Technically I know that you can't "insert" an image into a cell and that such an image is an overlay on a DrawPage that sits on top of the spreadsheet to "decorate" it.
One of the first steps in doing this (the new way) is to create an XGraphic object which contains the image. The process is to create an XGraphicProvider and call it with MediaProperties that specify the image file URL to be loaded. I have a program that is supposed to do this but the resulting XGraphic is null. The LO SDK gives pretty much no information when you do something wrong; it just doesn't work.
Here is the code I have, with all the headers removed:
// addpic
// add picture to spreadsheet - debug version
class OpenOfficeApp {
[STAThread]
static void Main(string[] args) {
bool lreadonly;
string pqfile;
string pqURL;
string pqpic;
pqfile = "file:///D:/Documents/NSexeye/ODS%20File%20Access/"+
"addpix/addpic.ods";
pqpic = "addpic2";
pqURL = pqpic+".jpg";
lreadonly = false;
Console.WriteLine("Using: "+pqfile);
// get the desktop
XComponentContext XCC = uno.util.Bootstrap.bootstrap();
XMultiComponentFactory XMCF =
(XMultiComponentFactory)XCC.getServiceManager();
XMultiServiceFactory XMSF = (XMultiServiceFactory)XCC.getServiceManager();
XComponentLoader XCL =
(XComponentLoader)XMSF.createInstance("com.sun.star.frame.Desktop");
// open the spreadsheet
PropertyValue[] pPV = new PropertyValue[2];
pPV[0] = new PropertyValue();
pPV[0].Name = "Hidden";
pPV[0].Value = new uno.Any(true);
pPV[1] = new PropertyValue();
pPV[1].Name = "ReadOnly";
if (lreadonly) pPV[1].Value = new uno.Any(true);
else pPV[1].Value = new uno.Any(false);
XComponent XCo = XCL.loadComponentFromURL(pqfile,"_blank",0,pPV);
// create graphic object containing image
object oGP = XMCF.createInstanceWithContext(
"com.sun.star.graphic.GraphicProvider",XCC);
if (oGP == null) {
Console.WriteLine("oGP is null. Aborting.");
return;
}
XGraphicProvider XGP = (XGraphicProvider)oGP;
if (XGP == null) {
Console.WriteLine("XGP is null. Aborting.");
return;
}
pPV = new PropertyValue[1];
pPV[0] = new PropertyValue();
pPV[0].Name = "URL";
pPV[0].Value = new uno.Any(pqURL);
Console.WriteLine("Creating XGraphic containing "+pqURL);
XGraphic XG = XGP.queryGraphic(pPV);
// *** XG is null here
if (XG == null) {
Console.WriteLine("XG is null. Aborting.");
return;
}
// ... lots of stuff to be added here
// save and close the spreadsheet
XModifiable XM = (XModifiable)XCo;
XM.setModified(true);
XStorable XSt = (XStorable)XCo;
XSt.store();
XCloseable XCl = (XCloseable)XCo;
XCl.close(true);
// terminate LibreOffice
// *** I want this to not terminate it if something else is open
XDesktop XD = (XDesktop)XCL;
if (XD != null) XD.terminate();
}
}
I get a null for the XGraphic, in the place indicated in the comments. I don't know if the call to create it is failing, or if one of the earlier steps of the process are incorrect.
My goal here, in addition to getting my program working, is to create a sample program showing how to add an image to a Calc spreadsheet cell, and to manipulate such images. There are a fair number of people asking questions about this and none of the examples I've found will work. I think a good working sample will be of value.
I've spent a lot of time searching for information and code samples for this, with nothing that helps. I've tried to find ways to verify the validity of the XGraphicProvider interface with no luck. I've run out of things to try.
I'm hoping someone who knows about the LibreOffice SDK can take a look and maybe see what I'm doing wrong.
Update: I figured out what I was doing wrong: I was passing a bare filename in the "URL" property to XGraphicProvider. It has to be the same format (starting with "file:///") as the spreadsheet's file name specification.
Now I'm stuck with another property problem. The XGraphic has to be specified as a parameter to the GraphicObjectShape's Graphic property, but the setPropertyValue() function requires that it be a uno.Any type. I can't figure out how to specify an interface name like XGraphic as a uno.Any.
Here is the piece of code that won't compile, complaining that it can't convert an XGraphic to a uno.Any, in the first setPropertyValue call:
// set image XGraphic
XPropertySet XPS = (XPropertySet)XS;
XPS.setPropertyValue("Graphic",XG);
XPS.setPropertyValue("Name",new uno.Any(pqpic));
XG is an XGraphic type. Using "new uno.Any(XG)" doesn't work either, giving a similar compiler error.
After trying unsuccessfully for a few hours to get the latest LO SDK up and running, let me offer some untested ideas.
First of all, here is some working Basic code, no doubt similar to what you're translating from. The important line is oShape.Graphic = oProvider.queryGraphic(Props()).
oDoc = ThisComponent
oSheet = oDoc.CurrentController.ActiveSheet
pqURL = "file:///C:/Users/JimK/Desktop/addpic.jpg"
oProvider = createUnoService("com.sun.star.graphic.GraphicProvider")
oShape = oDoc.createInstance("com.sun.star.drawing.GraphicObjectShape")
Dim Props(0) as new com.sun.star.beans.PropertyValue
Props(0).Name= "URL"
Props(0).Value = pqURL
oShape.Graphic = oProvider.queryGraphic(Props())
oCell = oSheet.getCellByPosition(5,5)
oShape.Name = oCell.AbsoluteName + "##" + Props(0).Value
oShape.Anchor = oCell
oSheet.DrawPage.add(oShape)
'Resize
w = oShape.Graphic.Size.Width
h = oShape.Graphic.Size.Height
wcl = oCell.Size.Width
hcl = oCell.Size.Height
If w<>0 and h<>0 then
oCell.String=""
Dim Size as new com.sun.star.awt.Size
Size.Width = wcl
Size.Height = h*wcl/w
If Size.Height > hcl then
Size.Width = hcl*w/h
Size.Height = hcl
Endif
oShape.setSize(Size)
oShape.setPosition(oCell.Position)
erase oShape
Else
oShape.dispose()
Endif
Now, how to translate this to C#? It looks like you may need to explicitly specify the type. In the SDK example, there are calls like this.
xFieldProp.setPropertyValue(
"Orientation",
new uno.Any(
typeof (unoidl.com.sun.star.sheet.DataPilotFieldOrientation),
unoidl.com.sun.star.sheet.DataPilotFieldOrientation.DATA ) );
So in your case, something like this:
XPS.setPropertyValue(
"Graphic"
new uno.Any(
typeof(unoidl.com.sun.star.graphic.XGraphic),
XG));
Alternatively, follow the suggestion here: set GraphicURL, which should load the image and set Graphic for you.

revit api create sheet - docs - contain deprecated "view3d

I'm working from the docs on trying to create a sheet with a view on it using the Revit API in C#
here is the docs URL link. You can find the code at the bottom in the first C# block.
I get a red squiggly under the view3D.Id:
Viewport.Create(doc, viewSheet.Id, view3D.Id, new XYZ(location.U, location.V, 0));
I can't find that it was deprecated nor can I figure out how to resolve it. I'm a bit confused about why it's trying to grab its own elementID. Also, just getting into the revit-API. it seems like "views" in Revit are called "viewports" in the API. i need to read more on this.
here is the entire code block:
private void CreateSheetView(Autodesk.Revit.DB.Document document, View3D view3D)
{
// Get an available title block from document
FilteredElementCollector collector = new FilteredElementCollector(document);
collector.OfClass(typeof(FamilySymbol));
collector.OfCategory(BuiltInCategory.OST_TitleBlocks);
FamilySymbol fs = collector.FirstElement() as FamilySymbol;
if (fs != null)
{
using (Transaction t = new Transaction(document, "Create a new ViewSheet"))
{
t.Start();
try
{
// Create a sheet view
ViewSheet viewSheet = ViewSheet.Create(document, fs.Id);
if (null == viewSheet)
{
throw new Exception("Failed to create new ViewSheet.");
}
// Add passed in view onto the center of the sheet
UV location = new UV((viewSheet.Outline.Max.U - viewSheet.Outline.Min.U) / 2,
(viewSheet.Outline.Max.V - viewSheet.Outline.Min.V) / 2);
//viewSheet.AddView(view3D, location);
Viewport.Create(document, viewSheet.Id, view3D.Id, new XYZ(location.U, location.V, 0));
^ERROR HAPPENS IN LINE ABOVE AT view3D.Id
// Print the sheet out
if (viewSheet.CanBePrinted)
{
TaskDialog taskDialog = new TaskDialog("Revit");
taskDialog.MainContent = "Print the sheet?";
TaskDialogCommonButtons buttons = TaskDialogCommonButtons.Yes | TaskDialogCommonButtons.No;
taskDialog.CommonButtons = buttons;
TaskDialogResult result = taskDialog.Show();
if (result == TaskDialogResult.Yes)
{
viewSheet.Print();
}
}
t.Commit();
}
catch
{
t.RollBack();
}
}
}
}
The Building Coder discussion of exact viewport positioning includes some woking sample calls to ViewSheet.Create and Viewport.Create.

How to set Publish Date in Word Document using OpenXML

I have a situation where a user can upload a word document which contains placeholders for certain properties (i.e. in MS Word the user has gone to Insert > Quick Parts > Document Properties and chosen a property). The specific properties I want to support are Title, Author, Company and Publish Date.
Title and Author are set as Package Properties, and Company is set as an Extended File Property. These are set with the below code, which works correctly:
private static void SetDocumentProperties(ReportTemplateModel model, WordprocessingDocument wordDocument)
{
//these properties always exist
wordDocument.PackageProperties.Title = model.Title;
wordDocument.PackageProperties.Creator = model.Author;
wordDocument.PackageProperties.Created = DateTime.Now;
wordDocument.PackageProperties.Modified = DateTime.Now;
//these properties can be null
if (wordDocument.ExtendedFilePropertiesPart == null)
{
wordDocument.AddNewPart<ExtendedFilePropertiesPart>();
}
if (wordDocument.ExtendedFilePropertiesPart.Properties == null)
{
wordDocument.ExtendedFilePropertiesPart.Properties = new Properties(new Company(model.SiteName));
}
else
{
wordDocument.ExtendedFilePropertiesPart.Properties.Company = new Company(model.SiteName);
}
}
My problem is that I can't work out how the set the Publish Date property. I have tried adding it as a Custom File Property using the below code (which is adapted from https://www.snip2code.com/Snippet/292005/WDSetCustomProperty), but this does not work. I've read a few things about setting custom properties, but I'm confused how they're meant to work. I'm also unsure if the Publish Date should actually be set as a custom property, or some other type of property.
var customProps = wordDocument.CustomFilePropertiesPart;
if (customProps == null)
{
customProps = wordDocument.AddCustomFilePropertiesPart();
customProps.Properties = new DocumentFormat.OpenXml.CustomProperties.Properties();
}
var properties1 = new DocumentFormat.OpenXml.CustomProperties.Properties();
//I have tried both of these lines, neither worked.
//properties1.AddNamespaceDeclaration("op", "http://schemas.openxmlformats.org/officeDocument/2006/custom-properties");
properties1.AddNamespaceDeclaration("vt", "http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes");
var customDocumentProperty1 = new DocumentFormat.OpenXml.CustomProperties.CustomDocumentProperty()
{
FormatId = "{D5CDD505-2E9C-101B-9397-08002B2CF9AE}",
PropertyId = 2,
Name = "Publish Date"
};
customDocumentProperty1.Append(new DocumentFormat.OpenXml.VariantTypes.VTLPWSTR { Text = DateTime.Today.ToShortDateString() });
properties1.Append(customDocumentProperty1);
part.Properties = properties1;
What type of property should the Publish Date be set as, and what is the right syntax for setting this?
Update: I have found that Publish Date is a CoverPageProperty which can be created using the below snippet, but I still haven't found how to set it correctly within the document.
var coverPageProps = new DocumentFormat.OpenXml.Office.CoverPageProps.CoverPageProperties
{
PublishDate = new PublishDate(DateTime.Today.ToShortDateString())
};
Adding the below code to my SetDocumentProperties method seems to work. I must admit I don't fully understand the below code, so any explanation would still be welcome. Additionally, if anyone has a solution which doesn't include writing XML as a string inside C# I would much prefer to avoid that.
const string publishDatePartId = "publishDatePart";
var publishDateXmlPart = wordDocument.MainDocumentPart.AddNewPart<CustomXmlPart>("application/xml", publishDatePartId);
var writer = new XmlTextWriter(publishDateXmlPart.GetStream(FileMode.Create), System.Text.Encoding.UTF8);
writer.WriteRaw($"<CoverPageProperties xmlns=\"http://schemas.microsoft.com/office/2006/coverPageProps\">" +
$"<PublishDate>{DateTime.Today.ToShortDateString()}</PublishDate>" +
$"</CoverPageProperties>");
writer.Flush();
writer.Close();
var customXmlPropertiesPart = publishDateXmlPart.AddNewPart<CustomXmlPropertiesPart>(publishDatePartId);
customXmlPropertiesPart.DataStoreItem = new DocumentFormat.OpenXml.CustomXmlDataProperties.DataStoreItem()
{
//I don't know what this ID is, but it seems to somehow relate to the Publish Date
ItemId = "{55AF091B-3C7A-41E3-B477-F2FDAA23CFDA}"
};

Create a New SubCategory LineStyle in Revit

I have created code that gathers a list of the existing "Line Styles" in Revit.
List<Category> All_Categories = doc.Settings.Categories.Cast<Category>().ToList();
Category Line_Category = All_Categories[1];
foreach (Category one_cat in All_Categories) { if (one_cat.Name == "Lines") { Line_Category = one_cat;} }
if (Line_Category.CanAddSubcategory)
{
CategoryNameMap All_Styles = Line_Category.SubCategories; List<string> Line_Styles = new List<string>();
foreach (Category one_category in All_Styles) { if (one_category.Name.Contains("CO_NAME")) {Line_Styles.Add(one_category.Name); } }
TaskDialog.Show(Line_Styles.Count.ToString() + " Current Line Styles", List_To_Dialog(Line_Styles));
}
This gets the list of line styles, but when I try:
Category New_Line_Style = Line_Category.NewSubCategory....
Visual Studio tells me there is no definition for NewSubCategory
Can anyone tell me how to make a new SubCategory of "Lines", or what I'm doing wrong in the above code?
NOTE: I discovered the main issue. I was attempting to add the sub category to my variable Line_Category (which is itself a category, which should be a parent). I had also attempted adding the sub category to All_Categories (which had been cast as a list and not a CategoryNameMap).
When I added a variable that was not cast, NewSubCategory became available. However, now I am unable to see how to set the line pattern associated with my new style -- the only example I've found online suggests using New_Line_Style.LinePatternId, but that is not in the list of available options on my new SubCategory. Is there some way to set the default pattern to be used when creating a new SubCategory?
Jeremy Tammik wrote a post about retrieving all the linestyles here: http://thebuildingcoder.typepad.com/blog/2013/08/retrieving-all-available-line-styles.html. That might help explain some of the linestyle category stuff in more detail.
Here's another good link asking the same question and how it was solved using VB: http://thebuildingcoder.typepad.com/blog/2013/08/retrieving-all-available-line-styles.html. Here's a C# version of the VB code that worked for a new linestyle:
UIApplication app = commandData.Application;
UIDocument uidoc = app.ActiveUIDocument;
Document ptr2Doc = uidoc.Document;
Category lineCat = ptr2Doc.Settings.Categories.get_Item(BuiltInCategory.OST_Lines);
Category lineSubCat;
string newSubCatName = "NewLineStyle";
Color newSubCatColor = new Color(255, 0, 0); //Red
try
{
using (Transaction docTransaction = new Transaction(ptr2Doc, "hatch22 - Create SubCategory"))
{
docTransaction.Start();
lineSubCat = ptr2Doc.Settings.Categories.NewSubcategory(lineCat, newSubCatName);
lineSubCat.LineColor = newSubCatColor;
docTransaction.Commit();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}

Creating an Ektron Smart Form Definition via the API

I've been trying to create a smart form definition from another application. The app successfully creates the smart form, but I'm unable to get the FieldList, DisplayXSLT or Schema fields to populate.
This leaves me with a blank smart form definition (less that ideal).
Here's the code I have to perform the action. Any ideas?
// form is a simple POCO with values copied from an existing SmartForm Definition
var config = new SmartFormConfigurationData();
config.SmartformTitle = form.Name;
config.SmartformDescription = form.Description;
config.XmlSchema = form.Schema;
config.PackageDisplayXslt = form.Xslt;
config.FieldList = form.FieldList;
config.Type = EkEnumeration.XmlConfigType.Content;
var api = new SmartFormConfigurationManager(ApiAccessMode.Admin);
api.RequestInformation.ServicesPath = this.EktronServiceHost;
api.RequestInformation.AuthenticationToken = this.GetAdminAuthToken();
api.Add(config);
Update:
I heard back from Ektron Support on this issue. It's not so much a "bug" per-se... It's more a case of this API class looking very similar to the ContentManager but not behaving like it. I expected that since it looked so similar to ContentManager and many of the other classes, I would be able to call Add() and it would just magically work. It turns out the solution is a little more complicated.
Adding a smartform is a two-step process: first Add(), then Update().
The Add method doesn't set all of the fields and in fact passes in NULL for a few of the parameters on the stored procedure that creates the entry in xml_collection_tbl.
The real fun comes in step 2. Basically, you start with the SmartForm's HTML -- the stuff you see when you're in the "Data Design" view for editing the smart form definition and you click that <> button ("HTML") at the bottom of the editor. You run that through a whole bunch of XSLTs that are burried in the WorkArea folder to construct the missing fields, and then you call update. Here's the code that worked for me:
var sfManager = new SmartFormConfigurationManager();
var data = sfManager.GetItem(12);
if (data == null) return;
var sfcData = new SmartFormConfigurationData();
sfcData.Type = EkEnumeration.XmlConfigType.Content;
sfcData.SmartformTitle = "SmartForm12 copy";
sfcData.SmartformDescription = "SmartForm12 copy";
sfcData.XmlSchema = "";
sfcData.PackageDisplayXslt = data.PackageDisplayXslt;
sfcData.FieldList = data.FieldList;
sfcData = sfManager.Add(sfcData);
Response.Write("SmartForm added with id: " + sfcData.Id);
var design = System.IO.File.ReadAllText(Server.MapPath("~/NewsArticleSmartForm.html"));
var contentApi = new ContentAPI();
var schema = contentApi.TransformXsltPackage(design, Server.MapPath("~/WorkArea/ContentDesigner/DesignToSchema.xslt"), true);
var fieldList = contentApi.TransformXsltPackage(design, Server.MapPath("~/WorkArea/ContentDesigner/DesignToFieldList.xslt"), true);
var viewEntryXslt = contentApi.TransformXsltPackage(design, Server.MapPath("~/WorkArea/ContentDesigner/DesignToEntryXSLT.xslt"), true);
var xsltArgs = new XsltArgumentList();
xsltArgs.AddParam("srcPath", "", "/WorkArea/ContentDesigner/");
var viewXsltSource = string.Concat("<root>", design, "<ektdesignpackage_list>", fieldList, "</ektdesignpackage_list></root>");
var viewXslt = contentApi.XSLTransform(viewXsltSource, Server.MapPath("~/WorkArea/ContentDesigner/DesignToViewXSLT.xslt"), true, false, xsltArgs, false);
var initialDocument = contentApi.TransformXsltPackage(design, Server.MapPath("~/WorkArea/ContentDesigner/PresentationToData.xslt"), true);
var sbPackage = new StringBuilder("<ektdesignpackage_forms><ektdesignpackage_form><ektdesignpackage_designs><ektdesignpackage_design>");
sbPackage.Append(design);
sbPackage.Append("</ektdesignpackage_design></ektdesignpackage_designs><ektdesignpackage_schemas><ektdesignpackage_schema>");
sbPackage.Append(schema);
sbPackage.Append("</ektdesignpackage_schema></ektdesignpackage_schemas><ektdesignpackage_lists><ektdesignpackage_list>");
sbPackage.Append(fieldList);
sbPackage.Append("</ektdesignpackage_list></ektdesignpackage_lists><ektdesignpackage_views><ektdesignpackage_view>");
sbPackage.Append(viewEntryXslt);
sbPackage.Append("</ektdesignpackage_view><ektdesignpackage_view>");
sbPackage.Append(viewXslt);
sbPackage.Append("</ektdesignpackage_view></ektdesignpackage_views><ektdesignpackage_initialDocuments><ektdesignpackage_initialDocument>");
sbPackage.Append(initialDocument);
sbPackage.Append("</ektdesignpackage_initialDocument></ektdesignpackage_initialDocuments></ektdesignpackage_form></ektdesignpackage_forms>");
sfcData.PackageXslt = sbPackage.ToString();
sfcData.FieldList = fieldList;
var baseFilename = "SmartForm" + sfcData.Id;
var schemaFilename = "/" + baseFilename + "Schema.xsd";
var xsltFilename = "/" + baseFilename + "Xslt.xslt";
sfcData.XmlSchema = schemaFilename; // The file will be prefixed with /XmlFiles
var unPackDisplayXslt = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\"><xsl:output method=\"xml\" version=\"1.0\" encoding=\"UTF-8\" indent=\"yes\"/><xsl:template match=\"/\"><xsl:choose><xsl:when test=\"ektdesignpackage_forms/ektdesignpackage_form[1]/ektdesignpackage_views/ektdesignpackage_view[2]\"><xsl:copy-of select=\"ektdesignpackage_forms/ektdesignpackage_form[1]/ektdesignpackage_views/ektdesignpackage_view[2]/node()\"/></xsl:when><xsl:otherwise><xsl:copy-of select=\"ektdesignpackage_forms/ektdesignpackage_form[1]/ektdesignpackage_views/ektdesignpackage_view[1]/node()\"/></xsl:otherwise></xsl:choose></xsl:template></xsl:stylesheet>";
var displayXslt = contentApi.TransformXsltPackage(sbPackage.ToString(), unPackDisplayXslt, false);
System.IO.File.WriteAllText(Server.MapPath("~/XmlFiles" + xsltFilename), displayXslt);
sfcData.Xslt1 = xsltFilename; // The file will be prefixed with /XmlFiles
sfcData.DefaultXslt = 1;
sfManager.Update(sfcData);
I extracted the HTML for my existing smart form and saved in the root of my site as NewsArticleSmartForm.html. Here's what my file looked like:
<p>Author: <input type="text" name="Author" id="Author" ektdesignns_caption="Author" ektdesignns_name="Author" title="Author" ektdesignns_indexed="false" ektdesignns_nodetype="element" size="24" class="design_textfield" /></p>
<p> </p>
<p>Article Summary: <textarea name="Summary" id="Summary" ektdesignns_caption="Summary" ektdesignns_name="Summary" title="Summary" ektdesignns_indexed="false" ektdesignns_nodetype="element" cols="40" rows="3" class="design_textfield"></textarea>
</p>
<p> </p>
<p>Article Body:</p>
<p> </p>
<ektdesignns_richarea id="Body" name="Body" ektdesignns_caption="Body" ektdesignns_name="Body" title="Body" ektdesignns_indexed="false" ektdesignns_nodetype="element"> </ektdesignns_richarea>
<p> </p>
Good luck!
Original Answer:
Creating a copy of a SmartForm configuration should be fairly straight-forward. The SmartFormConfigurationData object has a Clone() method on it which makes it really easy to create a copy of an existing SmartForm. I say "should be" because it doesn't work.
I had an answer all typed out ready to post; I tried some code and it appeared to work. The new smartform was listed in the workarea, but when I clicked on that new smartform to view its details, I realized something was wrong.
I tried the following code:
var sfManager = new SmartFormConfigurationManager();
var config = sfManager.GetItem(7);
if (config == null) return;
var newSmartForm = config.Clone();
newSmartForm.SmartformTitle += " copy";
sfManager.Add(newSmartForm);
Here are the details from the original smartform:
And here's what the new smartform looked like -- the one I created with the frameworkAPI:
I did find one API method that successfully created a copy of an existing smartform:
var sfApi = new Ektron.Cms.ContentAPI();
var newId = sfApi.ReplicateXmlConfiguration(7, "copied sf title");
The problem with that method is that the smartform must exist on your system and you can only change the title. So, I went digging into the database to see what was happening. It turns out that after calling this ReplicateXmlConfiguration() method, the two database records are identical (except for the expected LastUpdated type of fields).
After calling the frameworkAPI's Update() method (same holds true when calling Add()), the "updated" record is clearly different.
I think we've got a genuine bug here. This happens both in v8.7 sp2 and v9.0 sp1. I've opened a case with Ektron support, and I'll update my answer as I hear back. They have always been very responsive when I've dealt with them in the past.

Categories

Resources