Skip to content

Instantly share code, notes, and snippets.

@danielpinheiros
Last active February 21, 2023 16:09
Show Gist options
  • Save danielpinheiros/c238810967df51187d0ef78c926fb663 to your computer and use it in GitHub Desktop.
Save danielpinheiros/c238810967df51187d0ef78c926fb663 to your computer and use it in GitHub Desktop.
External Command for Revit to Neo4j add-in sampe from e-verse
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Windows;
using Neo4j.Driver;
namespace Neo4j.ClientConnection
{
public class Program : IDisposable
{
private bool _disposed = false;
private readonly IDriver _driver;
~Program() => Dispose(false);
public Program(string uri, string user, string password)
{
_driver = GraphDatabase.Driver(uri, AuthTokens.Basic(user, password));
}
public async Task CreateRelationship(string room1Name, string room2Name)
{
// To learn more about the Cypher syntax, see https://neo4j.com/docs/cypher-manual/current/
// The Reference Card is also a good resource for keywords https://neo4j.com/docs/cypher-refcard/current/
var query = @"
MERGE (p1:Room { name: $room1Name })
MERGE (p2:Room { name: $room2Name })
MERGE (p1)-[:CONNECTS {score: 1}]->(p2)
RETURN p1, p2";
using (var session = _driver.AsyncSession(configBuilder => configBuilder.WithDatabase("neo4j")))
{
try
{
// Write transactions allow the driver to handle retries and transient error
var writeResults = await session.ExecuteWriteAsync(async tx =>
{
var result = await tx.RunAsync(query, new { room1Name, room2Name });
return await result.ToListAsync();
});
foreach (var result in writeResults)
{
var person1 = result["p1"].As<INode>().Properties["name"];
var person2 = result["p2"].As<INode>().Properties["name"];
Console.WriteLine($"Created friendship between: {person1}, {person2}");
}
}
// Capture any errors along with the query and data for traceability
catch (Neo4jException ex)
{
Console.WriteLine($"{query} - {ex}");
throw;
}
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (_disposed)
return;
if (disposing)
{
_driver?.Dispose();
}
_disposed = true;
}
public static async Task Export(Dictionary<string, List<string>> keyValuePairs)
{
try
{
// Aura queries use an encrypted connection using the "neo4j+s" protocol
var uri = "<URI>";
var user = "<USER>";
var password = "<PASSWORD>";
using (var client = new Program(uri, user, password))
{
foreach (var dict in keyValuePairs)
{
foreach (var value in dict.Value)
{
await client.CreateRelationship(dict.Key, value);
}
}
}
MessageBox.Show("Exported Successfully!");
}
catch (Exception ex)
{
MessageBox.Show("debug", ex.StackTrace);
}
}
}
}
using System.Collections.Generic;
using System.Linq;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.DB.Architecture;
using Autodesk.Revit.UI;
namespace Neo4j.Common
{
[Regeneration(RegenerationOption.Manual)]
[Transaction(TransactionMode.Manual)]
public class RevitToNeo4j : IExternalCommand
{
private static List<Room> Rooms = new List<Room>();
private static List<FamilyInstance> Doors = new List<FamilyInstance>();
private static Dictionary<string, List<string>> ConnectedRooms = new Dictionary<string, List<string>>();
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
{
UIApplication uiapp = commandData.Application;
UIDocument uidoc = uiapp.ActiveUIDocument;
Document doc = uidoc.Document;
ParseRooms(doc);
_ = ClientConnection.Program.Export(ConnectedRooms);
return Result.Succeeded;
}
private static void ParseRooms(Document doc)
{
Doors = GetDoors(doc);
Rooms = GetRooms(doc);
ConnectedRooms = new Dictionary<string, List<string>>();
foreach (var room in Rooms)
{
var toRoomDoors = Doors.Where(a => a.ToRoom != null && a.ToRoom.Id == room.Id).ToList();
var connectedRooms = toRoomDoors.Where(a => a.FromRoom != null).Select(a => a.FromRoom.Name).ToList();
ConnectedRooms.Add(room.Name, connectedRooms);
}
}
private static List<Room> GetRooms(Document doc)
{
using (FilteredElementCollector col = new FilteredElementCollector(doc))
{
return col
.WhereElementIsNotElementType()
.OfCategory(BuiltInCategory.OST_Rooms)
.Cast<Room>()
.ToList();
}
}
private static List<FamilyInstance> GetDoors(Document doc)
{
using (FilteredElementCollector col = new FilteredElementCollector(doc))
{
return col
.WhereElementIsNotElementType()
.OfCategory(BuiltInCategory.OST_Doors)
.Cast<FamilyInstance>()
.ToList();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment