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());
}
Related
I'm creating an import tool that programatically creates items in Sitecore. The item gets created, but when I view it, it says 'The current item does not have a version in "English : English."' I put in using (new LanguageSwitcher("en-gb")) but that didn't fix it. The way my code works is that it looks for the folder that the item is supposed to be put in (all folders are based on year, e.g. 2016, 2017); if the folder doesn't exist, I create that folder before creating the item. This is my code:
protected void PublishRelease(PressReleaseItem release)
{
using (new LanguageSwitcher("en-gb"))
{
var year = release.ReleaseDate.Year;
// create year folder if it doesn't exist
var folderQuery = String.Format(PressReleaseYearFolderFastQuery, year);
Item folder = _db.SelectItems(folderQuery).ToList().FirstOrDefault();
if (folder == null)
{
var templateId = _templateFactory.GetTemplateId<IPressReleaseYearFolderItem>();
TemplateID pressReleaseFolderTemplateId = new TemplateID(templateId.ToID());
folder = _pressReleaseFolder.Add(year.ToString(), pressReleaseFolderTemplateId);
}
if (folder == null) return;
// add item to folder
var itemTemplateId = _templateFactory.GetTemplateId<IPRNewswirePressReleaseItem>();
TemplateID pressReleaseTemplateId = new TemplateID(itemTemplateId.ToID());
item = folder.Add(SanitizeHeadline(release.Headline), pressReleaseTemplateId);
if (item == null) return;
item.Fields.ReadAll();
item.Editing.BeginEdit();
try
{
item.Fields["External ID"].Value = release.ExternalId;
item.Fields["Active"].Value = release.Active.ToString();
item.Fields["Image Url"].Value = release.ImageUrl;
item.Fields["PDF Url"].Value = release.PdfUrl;
item.Fields["Description"].Value = release.SubHeadline;
item.Fields["Headline"].Value = release.Headline;
item.Fields["Date"].Value = release.ReleaseDate.ToString("d");
item.Fields["Longtext"].Value = release.Body;
item.Fields["Category"].Value = SetReleaseCategories(release.Category);
}
catch (Exception ex)
{
item.Editing.EndEdit();
}
item.Editing.EndEdit();
}
}
When I view the new item in Sitecore, it says it has no version in English; when I click to add a new version, all of the fields are blank.
I would have expected the code you have above to default to creating a new version in the en-GB language. Like Richard mentions, validate if your 'english' is set to 'en' or 'en-gb'. If your default English has a different code, you might have to update your language switcher.
Alternatively, have you tried doing something like below to force a version?
var result = item.Versions.AddVersion();
This would at least allow you to test if the version creation is working at all, though you shouldn't need it for a new item.
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}"
};
in my case i wanted to display items from local SQLite database which i created as shown below:
public string CreateDB() //create database
{
var output = "";
string dbPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "IsoModule.db3");
output = "Database Created";
return output;
}
public string CreateTable() //create table
{
try
{
string dbPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "IsoModule.db3");
var db = new SQLiteConnection(dbPath);
db.CreateTable<UserInfo>();
db.CreateTable<TableInfo>();
string result = "Table(s) created";
return result;
}
catch (Exception ex)
{
return ("Error" + ex.Message);
}
}
and this is my code where i wish to retrieve data
string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "IsoModule.db3");
var tablelistout = new SQLiteConnection(path);
var alltables = tablelistout.Table<TableInfo>();
foreach (var listing in alltables)
{
var from = new string[]
{
listing.tname + " - " + listing.status
};
ListView listtable = (ListView)FindViewById(Resource.Id.listtable);
listtable.Adapter = new ArrayAdapter(this, Android.Resource.Layout.SimpleListItem1, from);
}
the code runs with NO ERROR but it only display last item in the table. it is confusing me, so i would like to ask how can i retrieve all the data from specific table?
or if someone has asked the same question please share me the link. many appreciate.
var alltables = tablelistout.Table<TableInfo>();
var data = new List<string>();
foreach (var listing in alltables)
{
data.Add(listing.tname + " - " + listing.status);
}
ListView listtable = (ListView)FindViewById(Resource.Id.listtable);
listtable.Adapter = new ArrayAdapter(this, Android.Resource.Layout.SimpleListItem1, data.ToArray());
All I did was move 2 things out of the loop. First, I moved out the initialization of the array. Second, I moved out the listView + assignation of the adapter.
Your issue is that in the loop, you were always overriding everything you had done in the previous iteration (leaving you with the last item like you said).
Also, You should take note that it will be important for you to create a custom adapter if you plan on having a decent amount of data. ArrayAdapter is a native Android class which is then wrapped by a C# Xamarin object, meaning you will have both a C# and Java object per row. It adds overhead as both garbage collectors will have work to do and can cause performance issues. Xamarin devs tend to generally avoid it with the exception of quick prototyping.
On another note, I would use the FindViewById<T>(Int32) instead of the FindViewById(Int32) and casting it. FindViewById<ListView>(Resource.Id.listtable) in your case. Just taking advantage of the power of generics.
I am trying to use a filter to show/hide a certain element on the view. The family is from catogary GenericModel. I use the same code snippet that on the help on the autodesk site it works fine in its original state (catogary is walls) but when I changed it to GenericModel I got the following error:
"One of the given rules refers to a parameter that does not apply to this filter's categories."
I suspect that something wrong with the typeOf(FamilyInstance).
The original code on Autodesk site is:
http://help.autodesk.com/view/RVT/2014/ENU/?guid=GUID-B6FB80F2-7A17-4242-9E95-D6056090E85B
and here is my code
Transaction trans = new Transaction(doc);
trans.Start("Hide_or_Unhide");
//
List<ElementId> categories = new List<ElementId>();
categories.Add(new ElementId(BuiltInCategory.OST_GenericModel));
ParameterFilterElement parameterFilterElement = ParameterFilterElement.Create(doc, "elementNo = 102", categories);
FilteredElementCollector parameterCollector = new FilteredElementCollector(doc);
Parameter parameter = parameterCollector.OfClass(typeof(FamilyInstance)).FirstElement().get_Parameter("elementNo");
List<FilterRule> filterRules = new List<FilterRule>();
filterRules.Add(ParameterFilterRuleFactory.CreateEqualsRule(parameter.Id, 102));
try
{
parameterFilterElement.SetRules(filterRules);
}
catch (Exception ex)
{
TaskDialog.Show("", ex.Message);
}
OverrideGraphicSettings filterSettings = new OverrideGraphicSettings();
// outline walls in red
filterSettings.SetProjectionLineColor(new Autodesk.Revit.DB.Color(255, 0, 0));
Autodesk.Revit.DB.View curView = doc.ActiveView;
curView.SetFilterOverrides(parameterFilterElement.Id, filterSettings);
trans.Commit();
I think the problem is that your code which is performing the FilteredElementCollector is not specific enough. In the ADN sample, they're filtering on a type of "Wall" - but you're filtering on a type of FamilyInstance. You're correct on the type, but FamilyInstance covers lots of categories. The FirstElement() is giving the first FamilyInstance in the collector (which is likely not a generic model).
Try this line:
Parameter parameter = parameterCollector.OfClass(typeof(FamilyInstance)).OfCategory(BuiltInCategory.OST_GenericModel).FirstElement().get_Parameter("elementNo");
That way, you should get the first element that is both a family instance AND a GenericModel.
Good Luck,
Matt
We have a large public contacts folder in Outlook called Global Contacts, I'd like to be able to search through it and return a number of results that match certain criteria, ideally wildcard-style.
E.g. if someone puts "je" in the 'name' textbox, it will return all contacts whose names contain 'je'. This may be coupled as an AND with a companyname textbox.
Most of the examples I've seen are either in VB, or are concerned with doing this form a web app - I'm doing a winforms app, and every machine has Outlook 2002 installed (yeah, I know, update long overdue).
Can anyone point me in the right direction? Some code would be nice as a place to start.
Cheers
I ended up doing this:
Microsoft.Office.Interop.Outlook._Application objOutlook; //declare Outlook application
objOutlook = new Microsoft.Office.Interop.Outlook.Application(); //create it
Microsoft.Office.Interop.Outlook._NameSpace objNS = objOutlook.Session; //create new session
Microsoft.Office.Interop.Outlook.MAPIFolder oAllPublicFolders; //what it says on the tin
Microsoft.Office.Interop.Outlook.MAPIFolder oPublicFolders; // as above
Microsoft.Office.Interop.Outlook.MAPIFolder objContacts; //as above
Microsoft.Office.Interop.Outlook.Items itmsFiltered; //the filtered items list
oPublicFolders = objNS.Folders["Public Folders"];
oAllPublicFolders = oPublicFolders.Folders["All Public Folders"];
objContacts = oAllPublicFolders.Folders["Global Contacts"];
itmsFiltered = objContacts.Items.Restrict(strFilter);//restrict the search to our filter terms
Then just looping through itmsFiltered to add it to an ObjectListView. Hopefully this will be of use to someone else looking to do the same - it took me a while to cobble this together from various sources.
to find contacts folder you can iterate items of olFolderContacts. Here is the code
using System;
using Microsoft.Office.Interop.Outlook;
using Application = Microsoft.Office.Interop.Outlook.Application;
namespace RyanCore
{
public class Loader
{
public static ContactsViewModel LoadModel(Application objOutlook)
{
var viewModel = new ContactsViewModel();
MAPIFolder fldContacts = objOutlook.Session.GetDefaultFolder(OlDefaultFolders.olFolderContacts);
foreach (object obj in fldContacts.Items)
{
if (obj is _ContactItem)
{
var contact = (_ContactItem) obj;
viewModel.Contacts.Add(new Contact(contact.FirstName + " " + contact.LastName, contact.Email1Address));
}
else if (obj is DistListItem)
{
var distListItem = (DistListItem) obj;
var contactGroup = new ContactGroup(distListItem.Subject);
viewModel.Groups.Add(contactGroup);
for (Int32 i = 1; i <= distListItem.MemberCount; i++)
{
Recipient subMember = distListItem.GetMember(i);
contactGroup.Contacts.Add(new Contact(subMember.Name, subMember.AddressEntry.Address));
}
}
}
return viewModel;
}
}
}