Exemplo n.º 1
0
            /// <summary>
            /// Get all of the dependencies from a workspace
            /// </summary>
            /// <param name="workspace">The workspace to read the dependencies from</param>
            /// <param name="customNodeManager">A custom node manager to look up dependencies</param>
            /// <returns>A WorkspaceDependencies object containing the workspace and its CustomNodeWorkspaceModel dependencies</returns>
            public static WorkspaceDependencies Collect(HomeWorkspaceModel workspace, ICustomNodeManager customNodeManager)
            {
                if (workspace == null) throw new ArgumentNullException("workspace");
                if (customNodeManager == null) throw new ArgumentNullException("customNodeManager");

                // collect all dependencies
                var dependencies = new HashSet<CustomNodeDefinition>();
                foreach (var node in workspace.Nodes.OfType<Function>())
                {
                    dependencies.Add(node.Definition);
                    foreach (var dep in node.Definition.Dependencies)
                    {
                        dependencies.Add(dep);
                    }
                }

                var customNodeWorkspaces = new List<ICustomNodeWorkspaceModel>();
                foreach (var dependency in dependencies)
                {
                    ICustomNodeWorkspaceModel customNodeWs;
                    var workspaceExists = customNodeManager.TryGetFunctionWorkspace(dependency.FunctionId, false, out customNodeWs);

                    if (!workspaceExists)
                    {
                        throw new InvalidOperationException(String.Format(Resources.CustomNodeDefinitionNotFoundErrorMessage, dependency.FunctionName));
                    }

                    if (!customNodeWorkspaces.Contains(customNodeWs))
                    {
                        customNodeWorkspaces.Add(customNodeWs);
                    }
                }

                return new WorkspaceDependencies(workspace, customNodeWorkspaces);
            }
        public string GetName(Type type)
        {
            string name = string.Empty;
            var excludedTypeNames = new List<string>() { "Code Block", "Custom Node", "Compose Functions", "List.ForEach", "Build Sublists", "Apply Function" };

            var attribs = type.GetCustomAttributes(typeof(NodeNameAttribute), false);
            var attrs = type.GetCustomAttributes(typeof(IsVisibleInDynamoLibraryAttribute), true);
            if (attribs.Length > 0)
            {
                if (!excludedTypeNames.Contains((attribs[0] as NodeNameAttribute).Name))
                    name = (attribs[0] as NodeNameAttribute).Name;

                if ((attrs != null) && attrs.Any())
                {
                    var isVisibleAttr = attrs[0] as IsVisibleInDynamoLibraryAttribute;
                    if (null != isVisibleAttr && isVisibleAttr.Visible == false)
                    {
                        name = string.Empty;
                    }
                }
            }

            return name;
        }
Exemplo n.º 3
0
        /// <summary>
        /// Sends workspace and its' dependencies to Flood.
        /// </summary>
        /// <returns>String which is response from server.</returns>
        internal string Send(IEnumerable<IWorkspaceModel> workspaces, WorkspaceProperties workspaceProperties = null)
        {
            if (String.IsNullOrWhiteSpace(serverUrl))
            {
                Error = UploadErrorType.ServerNotFound;
                return Resources.FailedMessage;
            }

            if (String.IsNullOrWhiteSpace(authenticationProvider.Username))
            {
                Error = UploadErrorType.AuthenticationFailed;
                return Resources.FailedMessage;
            }

            if (authenticationProvider == null)
            {
                Error = UploadErrorType.AuthProviderNotFound;
                return Resources.FailedMessage;
            }

            if (reachClient == null)
                reachClient = new WorkspaceStorageClient(authenticationProvider, serverUrl);

            HomeWorkspace = workspaces.OfType<HomeWorkspaceModel>().First();
            var functionNodes = HomeWorkspace.Nodes.OfType<Function>();

            List<CustomNodeDefinition> dependencies = new List<CustomNodeDefinition>();
            foreach (var node in functionNodes)
            {
                dependencies.AddRange(node.Definition.Dependencies);
            }

            CustomNodeWorkspaces = new List<ICustomNodeWorkspaceModel>();
            foreach (var dependency in dependencies)
            {
                ICustomNodeWorkspaceModel customNodeWs;
                var isWorkspaceCreated = customNodeManager.TryGetFunctionWorkspace(dependency.FunctionId, false, out customNodeWs);
                if (isWorkspaceCreated && !CustomNodeWorkspaces.Contains(customNodeWs))
                    CustomNodeWorkspaces.Add(customNodeWs);
            }

            string result;
            try
            {
                result = reachClient.Send(
                    HomeWorkspace,
                    CustomNodeWorkspaces.OfType<CustomNodeWorkspaceModel>(), 
                    workspaceProperties);
                InvalidNodeNames = null;
            }
            catch (InvalidNodesException ex)
            {
                InvalidNodeNames = ex.InvalidNodeNames;
                result = Resources.FailedMessage;
            }
            catch
            {
                result = Resources.FailedMessage;
            }

            return result;
        }
Exemplo n.º 4
0
 void onSuccessfulDelete(List<ElementId> deleted)
 {
     foreach (var els in elements)
         els.RemoveAll(x => deleted.Contains(x));
 }
Exemplo n.º 5
0
        public override Value Evaluate(FSharpList<Value> args)
        {
            var doc = dynRevitSettings.Doc;
            var refCurveList = ((Value.List)args[0]).Item.Select(
               x => ( ((Value.Container)x).Item is ModelCurve ?
                   ((ModelCurve)((Value.Container)x).Item)
                   : (ModelCurve)(
                                      doc.Document.GetElement(
                                             ((Reference) ((Value.Container)x).Item).ElementId)
                                                             )
                                 )
                   ).ToList();

            ModelCurveArray myModelCurves = new ModelCurveArray();

            //Plane thisPlane = null;
            //Line oneLine = null;

            List<ElementId> refIds = new List<ElementId>();
            XYZ loopStart = new XYZ();
            XYZ otherEnd = new XYZ();
            int index = 0;
            double tolerance = 0.000000001;
            foreach( var refCurve in refCurveList)
            {
                if (index == 0)
                {
                    loopStart = refCurve.GeometryCurve.Evaluate(0.0, true);
                    otherEnd = refCurve.GeometryCurve.Evaluate(1.0, true);
                }
                else //if (index > 0)
                {
                    XYZ startXYZ = refCurve.GeometryCurve.Evaluate(0.0, true);
                    XYZ endXYZ = refCurve.GeometryCurve.Evaluate(1.0, true);
                    if (index == 1)
                    {
                        if (startXYZ.DistanceTo(otherEnd) > tolerance && endXYZ.DistanceTo(otherEnd) > tolerance &&
                            (startXYZ.DistanceTo(loopStart) > tolerance || endXYZ.DistanceTo(loopStart) > tolerance))
                        {
                            XYZ temp = loopStart;
                            loopStart = otherEnd;
                            otherEnd = temp;
                        }
                        if (startXYZ.DistanceTo(otherEnd) > tolerance && endXYZ.DistanceTo(otherEnd) < tolerance)
                            otherEnd = startXYZ;
                        else if (startXYZ.DistanceTo(otherEnd) <tolerance && endXYZ.DistanceTo(otherEnd) >tolerance)
                            otherEnd = endXYZ;
                        else
                            throw new Exception("Gap between curves in chain of reference curves.");
                    }
                }
                /* not needed check
                if (refCurve.GeometryCurve is Line)
                {
                    Line thisLine = refCurve.GeometryCurve as Line;
                    if (thisPlane != null)
                    {
                        if (Math.Abs(thisPlane.Normal.DotProduct(thisLine.Direction)) > tolerance)
                            throw new Exception(" Planar Ref Curve Chain fails: not planar");
                        if (Math.Abs(thisPlane.Normal.DotProduct(thisLine.Origin - thisPlane.Origin)) > tolerance)
                            throw new Exception(" Planar Ref Curve Chain fails: not planar");
                    }
                    else if (oneLine == null)
                        oneLine = thisLine;
                    else
                    {
                        if (Math.Abs(oneLine.Direction.DotProduct(thisLine.Direction)) > 1.0 - tolerance)
                        {
                            double projAdjust = oneLine.Direction.DotProduct(oneLine.Origin - thisLine.Origin);
                            XYZ adjustedOrigin = thisLine.Origin + projAdjust * oneLine.Direction;
                            if (adjustedOrigin.DistanceTo(oneLine.Origin) > tolerance)
                                throw new Exception(" Planar Ref Curve Chain fails: not planar");
                        }
                        else
                        {
                            XYZ norm = oneLine.Direction.CrossProduct(thisLine.Direction);
                            norm = norm.Normalize();
                            thisPlane = new Plane(norm, oneLine.Origin);
                            if (Math.Abs(thisPlane.Normal.DotProduct(thisLine.Origin - thisPlane.Origin)) > tolerance)
                                throw new Exception(" Planar Ref Curve Chain fails: not planar");
                        }

                    }
                }
                else
                {
                    CurveLoop curveLoop = new CurveLoop();
                    curveLoop.Append(refCurve.GeometryCurve);
                    if (!curveLoop.HasPlane())
                        throw new Exception(" Planar Ref Curve Chain fails: curve is not planar.");
                    Plane curvePlane = curveLoop.GetPlane();
                    if (thisPlane == null && oneLine == null)
                        thisPlane = curveLoop.GetPlane();
                    else if (thisPlane != null)
                    {
                        if (Math.Abs(thisPlane.Normal.DotProduct(curvePlane.Normal)) < 1.0 - tolerance)
                            throw new Exception(" Planar Ref Curve Chain fails: not planar");
                        if (Math.Abs(thisPlane.Normal.DotProduct(curvePlane.Origin - thisPlane.Origin)) > tolerance)
                            throw new Exception(" Planar Ref Curve Chain fails: not planar");
                    }
                    else if (oneLine != null)
                    {
                        thisPlane = curvePlane;
                        if (Math.Abs(thisPlane.Normal.DotProduct(oneLine.Direction)) > tolerance)
                            throw new Exception(" Planar Ref Curve Chain fails: not planar");
                        if (Math.Abs(thisPlane.Normal.DotProduct(oneLine.Origin - thisPlane.Origin)) > tolerance)
                            throw new Exception(" Planar Ref Curve Chain fails: not planar");
                    }
                }
                */

                refIds.Add(refCurve.Id);
                myModelCurves.Append(refCurve);
                index++;
            }

            List<ElementId> removeIds = new List<ElementId>();
            foreach (ElementId oldId in this.Elements)
            {
                if (!refIds.Contains(oldId))
                {
                    removeIds.Add(oldId);
                }
            }

            foreach (ElementId removeId in removeIds)
            {
                    this.Elements.Remove(removeId);
            }
            foreach (ElementId newId in refIds)
            {
                if (!this.Elements.Contains(newId))
                    this.Elements.Add(newId);
            }
            //if (!curveLoop.HasPlane())
            //    throw new Exception(" Planar Ref Curve Chain fails: not planar");
            return Value.NewContainer(myModelCurves);
        }
Exemplo n.º 6
0
        /// <summary>
        /// Sends workspace and its' dependencies to Flood.
        /// </summary>
        internal void Send(IEnumerable<IWorkspaceModel> workspaces)
        {
            if (String.IsNullOrWhiteSpace(serverUrl) || String.IsNullOrWhiteSpace(authenticationProvider.Username))
                throw new Exception(Resource.ServerErrorMessage);

            if (authenticationProvider == null)
                throw new Exception(Resource.AuthenticationErrorMessage);

            string fullServerAdress = serverUrl + ":" + port;

            if (reachClient == null)
                reachClient = new WorkspaceStorageClient(authenticationProvider, fullServerAdress);

            HomeWorkspace = workspaces.OfType<HomeWorkspaceModel>().First();
            var functionNodes = HomeWorkspace.Nodes.OfType<Function>();

            List<CustomNodeDefinition> dependencies = new List<CustomNodeDefinition>();
            foreach (var node in functionNodes)
            {
                dependencies.AddRange(node.Definition.Dependencies);
            }

            CustomNodeWorkspaces = new List<CustomNodeWorkspaceModel>();
            foreach (var dependency in dependencies)
            {
                CustomNodeWorkspaceModel customNodeWs;
                var isWorkspaceCreated = customNodeManager.TryGetFunctionWorkspace(dependency.FunctionId, false, out customNodeWs);
                if (isWorkspaceCreated && !CustomNodeWorkspaces.Contains(customNodeWs))
                    CustomNodeWorkspaces.Add(customNodeWs);
            }

            var result = reachClient.Send(HomeWorkspace, CustomNodeWorkspaces);
        }
        public static Dictionary<string, object> GetRunIds(int ProjectId)
        {
            // Initiate the Revit Auth
            Helper.InitRevitAuthProvider();

            string requestUri = GBSUri.GBSAPIUri + string.Format(APIV1Uri.GetProjectRunListUri, ProjectId.ToString(), "json");
            HttpWebResponse response = (HttpWebResponse)Helper._CallGetApi(requestUri);
            Stream responseStream = response.GetResponseStream();
            StreamReader reader = new StreamReader(responseStream);
            string projectRunListJson = reader.ReadToEnd();

            //TextWriterTraceListener tr2 = new TextWriterTraceListener(System.IO.File.CreateText("C:\\00_demo\\Output.txt"));
            //Debug.Listeners.Add(tr2);
            Debug.WriteLine(projectRunListJson);
            Debug.Flush();

            List<ProjectRun> projectRuns = Helper.DataContractJsonDeserialize<List<ProjectRun>>(projectRunListJson);

            List<int> runIds = new List<int>();
            List<List<int>> AltRunIds = new List<List<int>>();
            List<List<string>> RunNames = new List<List<string>>();

            //
            foreach (var run in projectRuns)
            {
                if (!runIds.Contains(run.runId))
                {
                    runIds.Add(run.runId);
                }
            }

            // Foreach runId Linq query on Projects Run
            foreach (var runId in runIds)
            {
                //Local variables
                List<int> altRunIds = new List<int>();
                List<string> Names = new List<string>();

                //linq query
                var runs = from run in projectRuns
                           where run.runId == runId
                           select run;

                foreach (var item in runs)
                {
                    altRunIds.Add(item.altRunId);
                    Names.Add(item.name);
                }

                AltRunIds.Add(altRunIds);
                RunNames.Add(Names);
            }

            //Populate outputs
            return new Dictionary<string, object>
            {
                { "RunNames", RunNames}, // Array
                { "RunIds", runIds}, // List
                { "ParametricRunIds", AltRunIds}

            };
        }
Exemplo n.º 8
0
        /// <summary>
        ///     Deserialize a function definition from a given path.  A side effect of this function is that
        ///     the node is added to the dictionary of loadedNodes.  
        /// </summary>
        /// <param name="funcDefGuid">The function guid we're currently loading</param>
        /// <param name="controller">Reference to the calling controller</param>
        /// <param name="def">The resultant function definition</param>
        /// <returns></returns>
        private bool GetDefinitionFromPath(Guid funcDefGuid, DynamoController controller, out FunctionDefinition def)
        {
            try
            {
                var xmlPath = GetNodePath(funcDefGuid);

                #region read xml file

                var xmlDoc = new XmlDocument();
                xmlDoc.Load(xmlPath);

                string funName = null;
                string category = "";
                double cx = DynamoView.CANVAS_OFFSET_X;
                double cy = DynamoView.CANVAS_OFFSET_Y;
                string id = "";

                // load the header
                foreach (XmlNode node in xmlDoc.GetElementsByTagName("dynWorkspace"))
                {
                    foreach (XmlAttribute att in node.Attributes)
                    {
                        if (att.Name.Equals("X"))
                            cx = Convert.ToDouble(att.Value);
                        else if (att.Name.Equals("Y"))
                            cy = Convert.ToDouble(att.Value);
                        else if (att.Name.Equals("Name"))
                            funName = att.Value;
                        else if (att.Name.Equals("Category"))
                            category = att.Value;
                        else if (att.Name.Equals("ID"))
                        {
                            id = att.Value;
                        }
                    }
                }

                // we have a dyf and it lacks an ID field, we need to assign it
                // a deterministic guid based on its name.  By doing it deterministically,
                // files remain compatible
                if (string.IsNullOrEmpty(id) && !string.IsNullOrEmpty(funName))
                {
                    id = GuidUtility.Create(GuidUtility.UrlNamespace, funName).ToString();
                }

                #endregion

                DynamoCommands.WriteToLogCmd.Execute("Loading node definition for \"" + funName + "\" from: " + xmlPath);

                var workSpace = new FuncWorkspace(
                    funName, category.Length > 0
                    ? category
                    : BuiltinNodeCategories.SCRIPTING_CUSTOMNODES, cx, cy);

                def = new FunctionDefinition(Guid.Parse(id))
                    {
                        Workspace = workSpace
                    };

                // load a dummy version, so any nodes depending on this node
                // will find an (empty) identifier on compilation
                FScheme.Expression dummyExpression = FScheme.Expression.NewNumber_E(0);
                controller.FSchemeEnvironment.DefineSymbol(def.FunctionId.ToString(), dummyExpression);
                this.loadedNodes.Add(def.FunctionId, def);

                dynWorkspaceModel ws = def.Workspace;

                XmlNodeList elNodes = xmlDoc.GetElementsByTagName("dynElements");
                XmlNodeList cNodes = xmlDoc.GetElementsByTagName("dynConnectors");
                XmlNodeList nNodes = xmlDoc.GetElementsByTagName("dynNotes");

                XmlNode elNodesList = elNodes[0];
                XmlNode cNodesList = cNodes[0];
                XmlNode nNodesList = nNodes[0];

                #region instantiate nodes

                List<Guid> badNodes = new List<Guid>();

                foreach (XmlNode elNode in elNodesList.ChildNodes)
                {
                    XmlAttribute typeAttrib = elNode.Attributes[0];
                    XmlAttribute guidAttrib = elNode.Attributes[1];
                    XmlAttribute nicknameAttrib = elNode.Attributes[2];
                    XmlAttribute xAttrib = elNode.Attributes[3];
                    XmlAttribute yAttrib = elNode.Attributes[4];

                    XmlAttribute lacingAttrib = null;
                    if (elNode.Attributes.Count > 5)
                    {
                        lacingAttrib = elNode.Attributes[5];
                    }

                    string typeName = typeAttrib.Value;

                    string oldNamespace = "Dynamo.Elements.";
                    if (typeName.StartsWith(oldNamespace))
                        typeName = "Dynamo.Nodes." + typeName.Remove(0, oldNamespace.Length);

                    //test the GUID to confirm that it is non-zero
                    //if it is zero, then we have to fix it
                    //this will break the connectors, but it won't keep
                    //propagating bad GUIDs
                    var guid = new Guid(guidAttrib.Value);
                    if (guid == Guid.Empty)
                    {
                        guid = Guid.NewGuid();
                    }

                    string nickname = nicknameAttrib.Value;

                    double x = Convert.ToDouble(xAttrib.Value);
                    double y = Convert.ToDouble(yAttrib.Value);

                    //Type t = Type.GetType(typeName);
                    TypeLoadData tData;
                    Type t;

                    if (!controller.BuiltInTypesByName.TryGetValue(typeName, out tData))
                    {
                        //try and get a system type by this name
                        t = Type.GetType(typeName);

                        //if we still can't find the type, try the also known as attributes
                        if (t == null)
                        {
                            //try to get the also known as values
                            foreach (KeyValuePair<string, TypeLoadData> kvp in controller.BuiltInTypesByName)
                            {
                                var akaAttribs = kvp.Value.Type.GetCustomAttributes(typeof(AlsoKnownAsAttribute), false);
                                if (akaAttribs.Count() > 0)
                                {
                                    if ((akaAttribs[0] as AlsoKnownAsAttribute).Values.Contains(typeName))
                                    {
                                        controller.DynamoViewModel.Log(string.Format("Found matching node for {0} also known as {1}", kvp.Key, typeName));
                                        t = kvp.Value.Type;
                                    }
                                }
                            }
                        }

                        if (t == null)
                        {
                            controller.DynamoViewModel.Log("Could not load node of type: " + typeName);
                            controller.DynamoViewModel.Log("Loading will continue but nodes might be missing from your workflow.");

                            //return false;
                            badNodes.Add(guid);
                            continue;
                        }
                    }
                    else
                        t = tData.Type;

                    dynNodeModel el = dynSettings.Controller.DynamoViewModel.CreateNodeInstance(t, nickname, guid);

                    if (lacingAttrib != null)
                    {
                        LacingStrategy lacing = LacingStrategy.First;
                        Enum.TryParse(lacingAttrib.Value, out lacing);
                        el.ArgumentLacing = lacing;
                    }

                    // note - this is because the connectors fail to be created if there's not added
                    // to the canvas
                    ws.Nodes.Add(el);
                    el.WorkSpace = ws;
                    var node = el;

                    node.X = x;
                    node.Y = y;

                    if (el == null)
                        return false;

                    el.DisableReporting();
                    el.LoadElement(elNode); // inject the node properties from the xml

                    // it has no
                    if (el is dynFunction)
                    {
                        var fun = el as dynFunction;

                        // we've found a custom node, we need to attempt to load its guid.
                        // if it doesn't exist (i.e. its a legacy node), we need to assign it one,
                        // deterministically
                        Guid funId;
                        try
                        {
                            funId = Guid.Parse(fun.Symbol);
                        }
                        catch
                        {
                            funId = GuidUtility.Create(GuidUtility.UrlNamespace, nicknameAttrib.Value);
                            fun.Symbol = funId.ToString();
                        }

                        // if it's not a recurisve node and it's not yet loaded, load it
                        if (funcDefGuid != funId && !this.loadedNodes.ContainsKey(funId))
                        {
                            dynSettings.Controller.CustomNodeLoader.GetFunctionDefinition(funId);
                            fun.Definition = this.loadedNodes[funId];
                        }
                        else if ( this.loadedNodes.ContainsKey(funId ))
                        {
                            fun.Definition = this.loadedNodes[funId];
                        }

                    }
                }

                #endregion

                #region instantiate connectors

                foreach (XmlNode connector in cNodesList.ChildNodes)
                {
                    XmlAttribute guidStartAttrib = connector.Attributes[0];
                    XmlAttribute intStartAttrib = connector.Attributes[1];
                    XmlAttribute guidEndAttrib = connector.Attributes[2];
                    XmlAttribute intEndAttrib = connector.Attributes[3];
                    XmlAttribute portTypeAttrib = connector.Attributes[4];

                    var guidStart = new Guid(guidStartAttrib.Value);
                    var guidEnd = new Guid(guidEndAttrib.Value);
                    int startIndex = Convert.ToInt16(intStartAttrib.Value);
                    int endIndex = Convert.ToInt16(intEndAttrib.Value);
                    int portType = Convert.ToInt16(portTypeAttrib.Value);

                    //find the elements to connect
                    dynNodeModel start = null;
                    dynNodeModel end = null;

                    if (badNodes.Contains(guidStart) || badNodes.Contains(guidEnd))
                        continue;

                    foreach (dynNodeModel e in ws.Nodes)
                    {
                        if (e.GUID == guidStart)
                        {
                            start = e;
                        }
                        else if (e.GUID == guidEnd)
                        {
                            end = e;
                        }
                        if (start != null && end != null)
                        {
                            break;
                        }
                    }

                    try
                    {
                        if (start != null && end != null && start != end)
                        {
                            var newConnector = new dynConnectorModel(
                                start, end,
                                startIndex, endIndex,
                                portType, false
                                );

                            ws.Connectors.Add(newConnector);
                        }
                    }
                    catch
                    {
                        DynamoCommands.WriteToLogCmd.Execute(string.Format("ERROR : Could not create connector between {0} and {1}.", start.NickName, end.NickName));
                    }
                }

                #endregion

                #region instantiate notes

                if (nNodesList != null)
                {
                    foreach (XmlNode note in nNodesList.ChildNodes)
                    {
                        XmlAttribute textAttrib = note.Attributes[0];
                        XmlAttribute xAttrib = note.Attributes[1];
                        XmlAttribute yAttrib = note.Attributes[2];

                        string text = textAttrib.Value;
                        double x = Convert.ToDouble(xAttrib.Value);
                        double y = Convert.ToDouble(yAttrib.Value);

                        //dynNoteView n = Bench.AddNote(text, x, y, ws);
                        //Bench.AddNote(text, x, y, ws);

                        var paramDict = new Dictionary<string, object>();
                        paramDict.Add("x", x);
                        paramDict.Add("y", y);
                        paramDict.Add("text", text);
                        paramDict.Add("workspace", ws);
                        dynSettings.Controller.DynamoViewModel.AddNoteCommand.Execute(paramDict);
                    }
                }

                #endregion

                foreach (dynNodeModel e in ws.Nodes)
                    e.EnableReporting();

                ws.FilePath = xmlPath;

                controller.PackageManagerClient.LoadPackageHeader(def, funName);

                var expression = CompileFunction(def);
                controller.FSchemeEnvironment.DefineSymbol(def.FunctionId.ToString(), expression);

            }
            catch (Exception ex)
            {
                DynamoCommands.WriteToLogCmd.Execute("There was an error opening the workbench.");
                DynamoCommands.WriteToLogCmd.Execute(ex);
                def = null;
                return false;
            }

            return true;
        }
Exemplo n.º 9
0
        public override FScheme.Value Evaluate(FSharpList<FScheme.Value> args)
        {
            var doc = dynRevitSettings.Doc;
            var refCurveList = ((FScheme.Value.List)args[0]).Item.Select(
               x => (((FScheme.Value.Container)x).Item is Autodesk.Revit.DB.ModelCurve ?
                   ((Autodesk.Revit.DB.ModelCurve)((FScheme.Value.Container)x).Item)
                   : (Autodesk.Revit.DB.ModelCurve)(
                                      doc.Document.GetElement(
                                             ((Reference)((FScheme.Value.Container)x).Item).ElementId)
                                                             )
                                 )
                   ).ToList();

            var myModelCurves = new ModelCurveArray();

            //Plane thisPlane = null;
            //Line oneLine = null;

            var refIds = new List<ElementId>();
            var loopStart = new XYZ();
            var otherEnd = new XYZ();
            int index = 0;
            double tolerance = 0.000000001;
            foreach (var refCurve in refCurveList)
            {
                if (index == 0)
                {
                    loopStart = refCurve.GeometryCurve.Evaluate(0.0, true);
                    otherEnd = refCurve.GeometryCurve.Evaluate(1.0, true);
                }
                else //if (index > 0)
                {
                    XYZ startXYZ = refCurve.GeometryCurve.Evaluate(0.0, true);
                    XYZ endXYZ = refCurve.GeometryCurve.Evaluate(1.0, true);
                    if (index == 1)
                    {
                        if (startXYZ.DistanceTo(otherEnd) > tolerance && endXYZ.DistanceTo(otherEnd) > tolerance &&
                            (startXYZ.DistanceTo(loopStart) > tolerance || endXYZ.DistanceTo(loopStart) > tolerance))
                        {
                            XYZ temp = loopStart;
                            loopStart = otherEnd;
                            otherEnd = temp;
                        }
                        if (startXYZ.DistanceTo(otherEnd) > tolerance && endXYZ.DistanceTo(otherEnd) < tolerance)
                            otherEnd = startXYZ;
                        else if (startXYZ.DistanceTo(otherEnd) < tolerance && endXYZ.DistanceTo(otherEnd) > tolerance)
                            otherEnd = endXYZ;
                        else
                            throw new Exception("Gap between curves in chain of reference curves.");
                    }
                }

                refIds.Add(refCurve.Id);
                myModelCurves.Append(refCurve);
                index++;
            }

            List<ElementId> removeIds = new List<ElementId>();
            foreach (ElementId oldId in this.Elements)
            {
                if (!refIds.Contains(oldId))
                {
                    removeIds.Add(oldId);
                }
            }

            foreach (ElementId removeId in removeIds)
            {
                this.Elements.Remove(removeId);
            }
            foreach (ElementId newId in refIds)
            {
                if (!this.Elements.Contains(newId))
                    this.Elements.Add(newId);
            }
            //if (!curveLoop.HasPlane())
            //    throw new Exception(" Planar Ref Curve Chain fails: not planar");
            return FScheme.Value.NewContainer(myModelCurves);
        }
Exemplo n.º 10
0
        public bool OpenWorkbench(string xmlPath)
        {
            Log("Opening home workspace " + xmlPath + "...");
            CleanWorkbench();

            try
            {
                #region read xml file

                var xmlDoc = new XmlDocument();
                xmlDoc.Load(xmlPath);

                foreach (XmlNode node in xmlDoc.GetElementsByTagName("dynWorkspace"))
                {
                    foreach (XmlAttribute att in node.Attributes)
                    {
                        if (att.Name.Equals("X"))
                        {
                            _model.CurrentSpace.X = Convert.ToDouble(att.Value);
                        }
                        else if (att.Name.Equals("Y"))
                        {
                            _model.CurrentSpace.Y = Convert.ToDouble(att.Value);
                        }
                    }
                }

                XmlNodeList elNodes = xmlDoc.GetElementsByTagName("dynElements");
                XmlNodeList cNodes = xmlDoc.GetElementsByTagName("dynConnectors");
                XmlNodeList nNodes = xmlDoc.GetElementsByTagName("dynNotes");

                XmlNode elNodesList = elNodes[0];
                XmlNode cNodesList = cNodes[0];
                XmlNode nNodesList = nNodes[0];

                //if there is any problem loading a node, then
                //add the node's guid to the bad nodes collection
                //so we can avoid attempting to make connections to it
                List<Guid> badNodes = new List<Guid>();

                foreach (XmlNode elNode in elNodesList.ChildNodes)
                {
                    XmlAttribute typeAttrib = elNode.Attributes[0];
                    XmlAttribute guidAttrib = elNode.Attributes[1];
                    XmlAttribute nicknameAttrib = elNode.Attributes[2];
                    XmlAttribute xAttrib = elNode.Attributes[3];
                    XmlAttribute yAttrib = elNode.Attributes[4];

                    XmlAttribute lacingAttrib = null;
                    if (elNode.Attributes.Count > 5)
                    {
                        lacingAttrib = elNode.Attributes[5];
                    }

                    string typeName = typeAttrib.Value;

                    //test the GUID to confirm that it is non-zero
                    //if it is zero, then we have to fix it
                    //this will break the connectors, but it won't keep
                    //propagating bad GUIDs
                    var guid = new Guid(guidAttrib.Value);
                    if (guid == Guid.Empty)
                    {
                        guid = Guid.NewGuid();
                    }

                    string nickname = nicknameAttrib.Value;

                    double x = Convert.ToDouble(xAttrib.Value);
                    double y = Convert.ToDouble(yAttrib.Value);

                    if (typeName.StartsWith("Dynamo.Elements."))
                        typeName = "Dynamo.Nodes." + typeName.Remove(0, 16);

                    TypeLoadData tData;
                    Type t;

                    if (!Controller.BuiltInTypesByName.TryGetValue(typeName, out tData))
                    {
                        //try and get a system type by this name
                        t = Type.GetType(typeName);

                        //if we still can't find the type, try the also known as attributes
                        if(t == null)
                        {
                            //try to get the also known as values
                            foreach (KeyValuePair<string, TypeLoadData> kvp in Controller.BuiltInTypesByName)
                            {
                                var akaAttribs = kvp.Value.Type.GetCustomAttributes(typeof(AlsoKnownAsAttribute), false);
                                if (akaAttribs.Count() > 0)
                                {
                                    if ((akaAttribs[0] as AlsoKnownAsAttribute).Values.Contains(typeName))
                                    {
                                        Log(string.Format("Found matching node for {0} also known as {1}", kvp.Key , typeName));
                                        t = kvp.Value.Type;
                                    }
                                }
                            }
                        }

                        if (t == null)
                        {
                            Log("Could not load node of type: " + typeName);
                            Log("Loading will continue but nodes might be missing from your workflow.");

                            //return false;
                            badNodes.Add(guid);
                            continue;
                        }
                    }
                    else
                        t = tData.Type;

                    dynNodeModel el = CreateInstanceAndAddNodeToWorkspace(
                        t, nickname, guid, x, y,
                        _model.CurrentSpace
                        );

                    if (lacingAttrib != null)
                    {
                        LacingStrategy lacing = LacingStrategy.Disabled;
                        Enum.TryParse(lacingAttrib.Value, out lacing);
                        el.ArgumentLacing = lacing;
                    }

                    el.DisableReporting();

                    el.LoadElement(elNode);

                    if (ViewingHomespace)
                        el.SaveResult = true;

                    if (el is dynFunction)
                    {
                        var fun = el as dynFunction;

                        //argument lacing on functions should be set to disabled
                        //by default in the constructor, but for any workflow saved
                        //before this was the case, we need to ensure it here.
                        el.ArgumentLacing = LacingStrategy.Disabled;

                        // we've found a custom node, we need to attempt to load its guid.
                        // if it doesn't exist (i.e. its a legacy node), we need to assign it one,
                        // deterministically
                        Guid funId;
                        try
                        {
                            funId = Guid.Parse(fun.Symbol);
                        }
                        catch
                        {
                            funId = GuidUtility.Create(GuidUtility.UrlNamespace, nicknameAttrib.Value);
                            fun.Symbol = funId.ToString();
                        }

                        fun.Definition = dynSettings.Controller.CustomNodeLoader.GetFunctionDefinition(funId);

                    }
                }

                OnRequestLayoutUpdate(this, EventArgs.Empty);

                foreach (XmlNode connector in cNodesList.ChildNodes)
                {
                    XmlAttribute guidStartAttrib = connector.Attributes[0];
                    XmlAttribute intStartAttrib = connector.Attributes[1];
                    XmlAttribute guidEndAttrib = connector.Attributes[2];
                    XmlAttribute intEndAttrib = connector.Attributes[3];
                    XmlAttribute portTypeAttrib = connector.Attributes[4];

                    var guidStart = new Guid(guidStartAttrib.Value);
                    var guidEnd = new Guid(guidEndAttrib.Value);
                    int startIndex = Convert.ToInt16(intStartAttrib.Value);
                    int endIndex = Convert.ToInt16(intEndAttrib.Value);
                    int portType = Convert.ToInt16(portTypeAttrib.Value);

                    //find the elements to connect
                    dynNodeModel start = null;
                    dynNodeModel end = null;

                    if (badNodes.Contains(guidStart) || badNodes.Contains(guidEnd))
                        continue;

                    foreach (dynNodeModel e in _model.Nodes)
                    {
                        if (e.GUID == guidStart)
                        {
                            start = e;
                        }
                        else if (e.GUID == guidEnd)
                        {
                            end = e;
                        }
                        if (start != null && end != null)
                        {
                            break;
                        }
                    }

                    if (start != null && end != null && start != end)
                    {
                        var newConnector = new dynConnectorModel(start, end,
                                                            startIndex, endIndex, portType);

                        _model.CurrentSpace.Connectors.Add(newConnector);
                    }
                }

                #region instantiate notes

                if (nNodesList != null)
                {
                    foreach (XmlNode note in nNodesList.ChildNodes)
                    {
                        XmlAttribute textAttrib = note.Attributes[0];
                        XmlAttribute xAttrib = note.Attributes[1];
                        XmlAttribute yAttrib = note.Attributes[2];

                        string text = textAttrib.Value;
                        double x = Convert.ToDouble(xAttrib.Value);
                        double y = Convert.ToDouble(yAttrib.Value);

                        //dynNoteView n = Bench.AddNote(text, x, y, this.CurrentSpace);
                        //Bench.AddNote(text, x, y, this.CurrentSpace);

                        var paramDict = new Dictionary<string, object>();
                        paramDict.Add("x", x);
                        paramDict.Add("y", y);
                        paramDict.Add("text", text);
                        paramDict.Add("workspace", _model.CurrentSpace);
                        AddNoteCommand.Execute(paramDict);
                    }
                }

                #endregion

                foreach (dynNodeModel e in _model.CurrentSpace.Nodes)
                    e.EnableReporting();

                #endregion

                _model.HomeSpace.FilePath = xmlPath;
            }
            catch (Exception ex)
            {
                Log("There was an error opening the workbench.");
                Log(ex);
                Debug.WriteLine(ex.Message + ":" + ex.StackTrace);
                CleanWorkbench();
                return false;
            }
            return true;
        }
Exemplo n.º 11
0
        // PB: This is deprecated, can't do it now, though...
        internal bool OpenDefinition(
            string xmlPath,
            Dictionary<Guid, HashSet<FunctionDefinition>> children,
            Dictionary<Guid, HashSet<Guid>> parents)
        {
            try
            {
                #region read xml file

                var xmlDoc = new XmlDocument();
                xmlDoc.Load(xmlPath);

                string funName = null;
                string category = "";
                double cx = DynamoView.CANVAS_OFFSET_X;
                double cy = DynamoView.CANVAS_OFFSET_Y;
                string id = "";

                // load the header
                foreach (XmlNode node in xmlDoc.GetElementsByTagName("dynWorkspace"))
                {
                    foreach (XmlAttribute att in node.Attributes)
                    {
                        if (att.Name.Equals("X"))
                            cx = Convert.ToDouble(att.Value);
                        else if (att.Name.Equals("Y"))
                            cy = Convert.ToDouble(att.Value);
                        else if (att.Name.Equals("Name"))
                            funName = att.Value;
                        else if (att.Name.Equals("Category"))
                            category = att.Value;
                        else if (att.Name.Equals("ID"))
                        {
                            id = att.Value;
                        }
                    }
                }

                // we have a dyf and it lacks an ID field, we need to assign it
                // a deterministic guid based on its name.  By doing it deterministically,
                // files remain compatible
                if (string.IsNullOrEmpty(id) && !string.IsNullOrEmpty(funName))
                {
                    id = GuidUtility.Create(GuidUtility.UrlNamespace, funName).ToString();
                }

                #endregion

                //If there is no function name, then we are opening a home definition
                if (funName == null)
                {
                    //View the home workspace, then open the bench file
                    if (!ViewingHomespace)
                        ViewHomeWorkspace(); //TODO: Refactor
                    return OpenWorkbench(xmlPath);
                }
                else if (Controller.CustomNodeLoader.Contains(funName))
                {
                    Log("ERROR: Could not load definition for \"" + funName +
                              "\", a node with this name already exists.");
                    return false;
                }

                Log("Loading node definition for \"" + funName + "\" from: " + xmlPath);

                FunctionDefinition def = NewFunction(
                    Guid.Parse(id),
                    funName,
                    category.Length > 0
                        ? category
                        : BuiltinNodeCategories.SCRIPTING_CUSTOMNODES,
                    false, cx, cy
                    );

                dynWorkspaceModel ws = def.Workspace;

                //this.Log("Opening definition " + xmlPath + "...");

                XmlNodeList elNodes = xmlDoc.GetElementsByTagName("dynElements");
                XmlNodeList cNodes = xmlDoc.GetElementsByTagName("dynConnectors");
                XmlNodeList nNodes = xmlDoc.GetElementsByTagName("dynNotes");

                XmlNode elNodesList = elNodes[0];
                XmlNode cNodesList = cNodes[0];
                XmlNode nNodesList = nNodes[0];

                var dependencies = new Stack<Guid>();

                #region instantiate nodes

                //if there is any problem loading a node, then
                //add the node's guid to the bad nodes collection
                //so we can avoid attempting to make connections to it
                List<Guid> badNodes = new List<Guid>();

                foreach (XmlNode elNode in elNodesList.ChildNodes)
                {
                    XmlAttribute typeAttrib = elNode.Attributes[0];
                    XmlAttribute guidAttrib = elNode.Attributes[1];
                    XmlAttribute nicknameAttrib = elNode.Attributes[2];
                    XmlAttribute xAttrib = elNode.Attributes[3];
                    XmlAttribute yAttrib = elNode.Attributes[4];

                    XmlAttribute lacingAttrib = null;
                    if(elNode.Attributes.Count > 5)
                    {
                         lacingAttrib = elNode.Attributes[5];
                    }

                    string typeName = typeAttrib.Value;

                    string oldNamespace = "Dynamo.Elements.";
                    if (typeName.StartsWith(oldNamespace))
                        typeName = "Dynamo.Nodes." + typeName.Remove(0, oldNamespace.Length);

                    //test the GUID to confirm that it is non-zero
                    //if it is zero, then we have to fix it
                    //this will break the connectors, but it won't keep
                    //propagating bad GUIDs
                    var guid = new Guid(guidAttrib.Value);
                    if (guid == Guid.Empty)
                    {
                        guid = Guid.NewGuid();
                    }

                    string nickname = nicknameAttrib.Value;

                    double x = Convert.ToDouble(xAttrib.Value);
                    double y = Convert.ToDouble(yAttrib.Value);

                    //Type t = Type.GetType(typeName);
                    TypeLoadData tData;
                    Type t;

                    if (!Controller.BuiltInTypesByName.TryGetValue(typeName, out tData))
                    {
                        //try and get a system type by this name
                        t = Type.GetType(typeName);

                        //if we still can't find the type, try the also known as attributes
                        if (t == null)
                        {
                            //try to get the also known as values
                            foreach (KeyValuePair<string, TypeLoadData> kvp in Controller.BuiltInTypesByName)
                            {
                                var akaAttribs = kvp.Value.Type.GetCustomAttributes(typeof(AlsoKnownAsAttribute), false);
                                if (akaAttribs.Count() > 0)
                                {
                                    if ((akaAttribs[0] as AlsoKnownAsAttribute).Values.Contains(typeName))
                                    {
                                        Log(string.Format("Found matching node for {0} also known as {1}", kvp.Key, typeName));
                                        t = kvp.Value.Type;
                                    }
                                }
                            }
                        }

                        if (t == null)
                        {
                            Log("Could not load node of type: " + typeName);
                            Log("Loading will continue but nodes might be missing from your workflow.");

                            //return false;
                            badNodes.Add(guid);
                            continue;
                        }
                    }
                    else
                        t = tData.Type;

                    dynNodeModel el = CreateInstanceAndAddNodeToWorkspace(t, nickname, guid, x, y, ws);

                    if (lacingAttrib != null)
                    {
                        LacingStrategy lacing = LacingStrategy.First;
                        Enum.TryParse(lacingAttrib.Value, out lacing);
                        el.ArgumentLacing = lacing;
                    }

                    if (el == null)
                        return false;

                    el.DisableReporting();
                    el.LoadElement(elNode);

                    if (el is dynFunction)
                    {
                        var fun = el as dynFunction;

                        // we've found a custom node, we need to attempt to load its guid.
                        // if it doesn't exist (i.e. its a legacy node), we need to assign it one,
                        // deterministically
                        Guid funId;
                        try
                        {
                            funId = Guid.Parse(fun.Symbol);
                        }
                        catch
                        {
                            funId = GuidUtility.Create(GuidUtility.UrlNamespace, nicknameAttrib.Value);
                            fun.Symbol = funId.ToString();
                        }

                        if (dynSettings.Controller.CustomNodeLoader.IsInitialized(funId))
                            fun.Definition = dynSettings.Controller.CustomNodeLoader.GetFunctionDefinition(funId);
                        else
                            dependencies.Push(funId);
                    }
                }

                #endregion

                //Bench.WorkBench.UpdateLayout();
                OnRequestLayoutUpdate(this, EventArgs.Empty);

                #region instantiate connectors

                foreach (XmlNode connector in cNodesList.ChildNodes)
                {
                    XmlAttribute guidStartAttrib = connector.Attributes[0];
                    XmlAttribute intStartAttrib = connector.Attributes[1];
                    XmlAttribute guidEndAttrib = connector.Attributes[2];
                    XmlAttribute intEndAttrib = connector.Attributes[3];
                    XmlAttribute portTypeAttrib = connector.Attributes[4];

                    var guidStart = new Guid(guidStartAttrib.Value);
                    var guidEnd = new Guid(guidEndAttrib.Value);
                    int startIndex = Convert.ToInt16(intStartAttrib.Value);
                    int endIndex = Convert.ToInt16(intEndAttrib.Value);
                    int portType = Convert.ToInt16(portTypeAttrib.Value);

                    //find the elements to connect
                    dynNodeModel start = null;
                    dynNodeModel end = null;

                    if (badNodes.Contains(guidStart) || badNodes.Contains(guidEnd))
                        continue;

                    foreach (dynNodeModel e in ws.Nodes)
                    {
                        if (e.GUID == guidStart)
                        {
                            start = e;
                        }
                        else if (e.GUID == guidEnd)
                        {
                            end = e;
                        }
                        if (start != null && end != null)
                        {
                            break;
                        }
                    }

                    try
                    {
                        if (start != null && end != null && start != end)
                        {
                            var newConnector = new dynConnectorModel(
                                start, end,
                                startIndex, endIndex,
                                portType, false
                                );

                            ws.Connectors.Add(newConnector);
                        }
                    }
                    catch
                    {
                        dynSettings.Controller.DynamoViewModel.Log(string.Format("ERROR : Could not create connector between {0} and {1}.", start.GUID, end.GUID));
                    }
                }

                #endregion

                #region instantiate notes

                if (nNodesList != null)
                {
                    foreach (XmlNode note in nNodesList.ChildNodes)
                    {
                        XmlAttribute textAttrib = note.Attributes[0];
                        XmlAttribute xAttrib = note.Attributes[1];
                        XmlAttribute yAttrib = note.Attributes[2];

                        string text = textAttrib.Value;
                        double x = Convert.ToDouble(xAttrib.Value);
                        double y = Convert.ToDouble(yAttrib.Value);

                        var paramDict = new Dictionary<string, object>();
                        paramDict.Add("x", x);
                        paramDict.Add("y", y);
                        paramDict.Add("text", text);
                        paramDict.Add("workspace", ws);
                        //DynamoCommands.AddNoteCmd.Execute(paramDict);
                        dynSettings.Controller.DynamoViewModel.AddNoteCommand.Execute(paramDict);
                    }
                }

                #endregion

                foreach (dynNodeModel e in ws.Nodes)
                    e.EnableReporting();

                //DynamoModel.hideWorkspace(ws);

                ws.FilePath = xmlPath;

                bool canLoad = true;

                //For each node this workspace depends on...
                foreach (Guid dep in dependencies)
                {
                    canLoad = false;
                    //Dep -> Ws
                    if (children.ContainsKey(dep))
                        children[dep].Add(def);
                    else
                        children[dep] = new HashSet<FunctionDefinition> { def };

                    //Ws -> Deps
                    if (parents.ContainsKey(def.FunctionId))
                        parents[def.FunctionId].Add(dep);
                    else
                        parents[def.FunctionId] = new HashSet<Guid> { dep };
                }

                if (canLoad)
                    SaveFunction(def, false);

                Controller.PackageManagerClient.LoadPackageHeader(def, funName);
                nodeWorkspaceWasLoaded(def, children, parents);

            }
            catch (Exception ex)
            {
                Log("There was an error opening the workbench.");
                Log(ex);
                Debug.WriteLine(ex.Message + ":" + ex.StackTrace);
                CleanWorkbench();
                return false;
            }

            return true;
        }
Exemplo n.º 12
0
        protected override void OnRenderPackagesUpdated(NodeModel node,
            IEnumerable<IRenderPackage> renderPackages)
        {
            var updatedNode = model.CurrentWorkspace.Nodes.FirstOrDefault(n => n.GUID == node.GUID);
            if (updatedNode == null) return;

            var visibleUpstream = new List<NodeModel>();
            watchNode.VisibleUpstreamNodes(visibleUpstream);

            if (!visibleUpstream.Contains(updatedNode))
            {
                return;
            }

            base.OnRenderPackagesUpdated(node, renderPackages);
        }