Ejemplo n.º 1
0
        public override void DoWork(Action <string, double> ReportProgress, Action Done)
        {
            @base = new Base();
            inputData.Keys.ToList().ForEach(key =>
            {
                var value = inputData[key];
                if (value == null)
                {
                }
                else if (value is List <object> list)
                {
                    // Value is a list of items, iterate and convert.
                    var converted = list.Select(item => Utilities.TryConvertItemToSpeckle(item, Converter)).ToList();
                    @base[key]    = converted;
                }
                else
                {
                    // If value is not list, it is a single item.
                    var obj    = Utilities.TryConvertItemToSpeckle(value, Converter);
                    @base[key] = obj;
                }
            });

            Done();
        }
Ejemplo n.º 2
0
        public override void DoWork(Action <string, double> ReportProgress, Action Done)
        {
            Parent.Message = "Receiving...";
            var Converter = (Parent as ReceiveLocalComponent).Converter;
            var @base     = Operations.Receive(localDataId).Result;

            if (Converter.CanConvertToNative(@base))
            {
                var converted = Converter.ConvertToNative(@base);
                data = new GH_Structure <IGH_Goo>();
                data.Append(Utilities.TryConvertItemToNative(converted, Converter));
            }
            else if (@base.GetDynamicMembers().Count() == 1)
            {
                var treeBuilder = new TreeBuilder(Converter);
                var tree        = treeBuilder.Build(@base[@base.GetDynamicMembers().ElementAt(0)]);
                data = tree;
            }
            else
            {
                data = new GH_Structure <IGH_Goo>();
                data.Append(new GH_SpeckleBase(@base));
            }
            Done();
        }
        private bool AssignToObject(Base b, List <string> keys, List <IGH_Goo> values)
        {
            var index     = 0;
            var hasErrors = false;

            keys.ForEach(key =>
            {
                if (b[key] != null)
                {
                    RuntimeMessages.Add((GH_RuntimeMessageLevel.Remark, $"Object {b.id} - Property {key} has been overwritten"));
                }

                try
                {
                    b[key] = Utilities.TryConvertItemToSpeckle(values[index++], Converter);
                }
                catch (Exception e)
                {
                    RuntimeMessages.Add((GH_RuntimeMessageLevel.Error, e.Message));
                    hasErrors = true;
                }
            });

            return(hasErrors);
        }
        public override void DoWork(Action <string, double> ReportProgress, Action Done)
        {
            try
            {
                var acc = Speckle.Core.Credentials.AccountManager.GetDefaultAccount();

                Tracker.TrackPageview(Tracker.RECEIVE_LOCAL);
                Parent.Message = "Receiving...";
                var Converter = (Parent as ReceiveLocalComponent).Converter;

                Base @base = null;

                try
                {
                    @base = Operations.Receive(localDataId, disposeTransports: true).Result;
                }
                catch (Exception e)
                {
                    RuntimeMessages.Add((GH_RuntimeMessageLevel.Warning, "Failed to receive local data."));
                    Done();
                    return;
                }

                data = Utilities.ConvertToTree(Converter, @base);
            }
            catch (Exception e)
            {
                // If we reach this, something happened that we weren't expecting...
                Log.CaptureException(e);
                RuntimeMessages.Add((GH_RuntimeMessageLevel.Error, "Something went terribly wrong... " + e.Message));
                Parent.Message = "Error";
            }
            Done();
        }
Ejemplo n.º 5
0
        public override void DoWork(Action <string, double> ReportProgress, Action Done)
        {
            if (CancellationToken.IsCancellationRequested)
            {
                return;
            }

            int branchIndex = 0, completed = 0;

            foreach (var list in Objects.Branches)
            {
                var path = Objects.Paths[branchIndex];
                foreach (var item in list)
                {
                    if (CancellationToken.IsCancellationRequested)
                    {
                        return;
                    }

                    var converted = Utilities.TryConvertItemToNative(item?.Value, Converter);
                    ConvertedObjects.Append(new GH_ObjectWrapper()
                    {
                        Value = converted
                    }, path);
                    ReportProgress(Id, (completed++ + 1) / (double)Objects.Count());
                }

                branchIndex++;
            }

            Done();
        }
        public override void DoWork(Action <string, double> ReportProgress, Action Done)
        {
            Parent.Message = "Extending...";
            var path = new GH_Path(iteration);

            if (valueTree.PathExists(path))
            {
                var values = valueTree.get_Branch(path) as List <IGH_Goo>;
                // Input is a list of values. Assign them directly
                if (keys.Count != values?.Count)
                {
                    Parent.AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Key and Value lists are not the same length.");
                    Done();
                }

                AssignToObject(@base, keys, values);
            }
            else if (valueTree.Branches.Count == 1)
            {
                var values = valueTree.Branches[0];
                if (keys.Count != values.Count)
                {
                    Parent.AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Key and Value lists are not the same length.");
                    Done();
                }

                // Input is just one list, so use it.
                AssignToObject(@base, keys, values);
            }
            else
            {
                // Input is a tree, meaning it's values are either lists or trees.
                var subTree = Utilities.GetSubTree(valueTree, path);
                var index   = 0;
                keys.ForEach(key =>
                {
                    var subPath = new GH_Path(index);
                    if (subTree.PathExists(subPath))
                    {
                        // Value is a list, convert and assign.
                        var list = subTree.get_Branch(subPath) as List <IGH_Goo>;
                        if (list?.Count > 0)
                        {
                            @base[key] = list.Select(goo => Utilities.TryConvertItemToSpeckle(goo, Converter)).ToList();
                        }
                        ;
                    }
                    else
                    {
                        // TODO: Handle tree conversions
                        Parent.AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Cannot handle trees yet");
                    }

                    index++;
                });
            }

            Done();
        }
        private Dictionary <string, object> CreateOutputDictionary(Base @base)
        {
            // Create empty data tree placeholders for output.
            var outputDict = new Dictionary <string, object>();

            // Assign all values to it's corresponding dictionary entry and branch path.
            var obj = @base;

            if (obj == null)
            {
                return(new Dictionary <string, object>());
            }
            foreach (var prop in obj.GetMembers())
            {
                // Convert and add to corresponding output structure
                var value = prop.Value;
                //if (!outputDict.ContainsKey(prop.Key)) continue;
                switch (value)
                {
                case null:
                    outputDict[prop.Key] = null;
                    break;

                case System.Collections.IList list:
                    var result = new List <IGH_Goo>();
                    foreach (var x in list)
                    {
                        var wrapper = Utilities.TryConvertItemToNative(x, Converter);
                        result.Add(wrapper);
                    }
                    outputDict[prop.Key] = result;

                    break;

                // TODO: Not clear how we handle "tree" inner props. They can only be set by sender components,
                // so perhaps this is not an issue. Below a simple stopgap so we can actually see what data is
                // inside a sender-created object.
                case Dictionary <string, List <Base> > dict:
                    foreach (var kvp in dict)
                    {
                        IGH_Goo wrapper = new GH_ObjectWrapper();
                        foreach (var b in kvp.Value)
                        {
                            wrapper = Utilities.TryConvertItemToNative(b, Converter);
                        }

                        outputDict[prop.Key] = wrapper;
                    }

                    break;

                default:
                    outputDict[prop.Key] = Utilities.TryConvertItemToNative(obj[prop.Key], Converter);
                    break;
                }
            }

            return(outputDict);
        }
Ejemplo n.º 8
0
        private void AssignToObject(Base b, List <string> keys, List <IGH_Goo> values)
        {
            var index = 0;

            keys.ForEach(key =>
            {
                if (b[key] != null)
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, $"Object {b.id} - Property {key} has been overwritten");
                }
                b[key] = Utilities.TryConvertItemToSpeckle(values[index++], Converter);
            });
        }
        public override void DoWork(Action <string, double> ReportProgress, Action Done)
        {
            try
            {
                if (CancellationToken.IsCancellationRequested)
                {
                    return;
                }

                int branchIndex = 0, completed = 0;
                foreach (var list in Objects.Branches)
                {
                    var path = Objects.Paths[branchIndex];
                    foreach (var item in list)
                    {
                        if (CancellationToken.IsCancellationRequested)
                        {
                            return;
                        }

                        var converted = Utilities.TryConvertItemToSpeckle(item, Converter, true);
                        if (converted == null)
                        {
                            RuntimeMessages.Add((GH_RuntimeMessageLevel.Warning, $"Cannot convert item at {path}[{list.IndexOf(item)}] to Speckle."));
                        }
                        else if (converted.GetType().IsSimpleType())
                        {
                            ConvertedObjects.Append(new GH_ObjectWrapper(converted));
                        }
                        else
                        {
                            ConvertedObjects.Append(new GH_SpeckleBase {
                                Value = converted as Base
                            }, Objects.Paths[branchIndex]);
                        }
                        ReportProgress(Id, Math.Round((completed++ + 1) / (double)Objects.Count(), 2));
                    }

                    branchIndex++;
                }
            }
            catch (Exception e)
            {
                // If we reach this, something happened that we weren't expecting...
                Log.CaptureException(e);
                RuntimeMessages.Add((GH_RuntimeMessageLevel.Error, "Something went terribly wrong... " + e.Message));
                Parent.Message = "Error";
            }

            Done();
        }
        public override void DoWork(Action <string, double> ReportProgress, Action Done)
        {
            try
            {
                Parent.Message = "Receiving...";
                var Converter = (Parent as ReceiveLocalComponent).Converter;

                Base @base = null;

                try
                {
                    @base = Operations.Receive(localDataId).Result;
                }
                catch (Exception e)
                {
                    RuntimeMessages.Add((GH_RuntimeMessageLevel.Warning, "Failed to receive local data."));
                    Done();
                    return;
                }

                if (Converter.CanConvertToNative(@base))
                {
                    var converted = Converter.ConvertToNative(@base);
                    data = new GH_Structure <IGH_Goo>();
                    data.Append(Utilities.TryConvertItemToNative(converted, Converter));
                }
                else if (@base.GetDynamicMembers().Count() == 1)
                {
                    var treeBuilder = new TreeBuilder(Converter);
                    var tree        = treeBuilder.Build(@base[@base.GetDynamicMembers().ElementAt(0)]);
                    data = tree;
                }
                else
                {
                    data = new GH_Structure <IGH_Goo>();
                    data.Append(new GH_SpeckleBase(@base));
                }
            }
            catch (Exception e)
            {
                // If we reach this, something happened that we weren't expecting...
                Log.CaptureException(e);
                RuntimeMessages.Add((GH_RuntimeMessageLevel.Error, "Something went terribly wrong... " + e.Message));
                Parent.Message = "Error";
            }
            Done();
        }
Ejemplo n.º 11
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            // Initialize local variables
            var speckleObj = new GH_SpeckleBase();
            var key        = "";

            // Get data from inputs
            if (!DA.GetData(0, ref speckleObj))
            {
                return;
            }
            if (!DA.GetData(1, ref key))
            {
                return;
            }

            var b = speckleObj.Value;

            if (b == null)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Object is not a Speckle object");
                return;
            }
            // Get the value and output.
            var value = b[key] ?? b["@" + key];

            switch (value)
            {
            case null:
                AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Key not found in object: " + key);
                return;

            case List <object> list:
            {
                var converted = list.Select(
                    item => new GH_ObjectWrapper(Utilities.TryConvertItemToNative(item, Converter)));
                DA.SetDataList(0, converted);
                break;
            }

            default:
                DA.SetData(0, new GH_ObjectWrapper(Utilities.TryConvertItemToNative(value, Converter)));
                break;
            }
        }
        public override void DoWork(Action <string, double> ReportProgress, Action Done)
        {
            RuntimeMessages.Add((GH_RuntimeMessageLevel.Remark, $"Base count: {bases.Count}"));
            RuntimeMessages.Add((GH_RuntimeMessageLevel.Remark, $"Keys count: {keys.Count}"));
            RuntimeMessages.Add((GH_RuntimeMessageLevel.Remark, $"Vals count: {values.Count}"));

            int max = bases.Count;

            if (max < values.Count)
            {
                max = values.Count;
            }
            if (max < keys.Count)
            {
                max = keys.Count;
            }

            for (int i = 0; i < max; i++)
            {
                var @base = i < bases.Count ? bases[i] : bases[bases.Count - 1];
                var key   = i < keys.Count ? keys[i] : keys[keys.Count - 1];
                var value = i < values.Count ? values[i] : values[values.Count - 1];
                try
                {
                    if (Converter != null)
                    {
                        @base[key] = Utilities.TryConvertItemToSpeckle(value, Converter);
                    }
                    else
                    {
                        @base[key] = value;
                    }
                } catch (Exception e)
                {
                    RuntimeMessages.Add((GH_RuntimeMessageLevel.Warning, $"Failed to set prop {key}: {e.Message}"));
                }
            }

            Done();
        }
        private object DoWork(Base @base, string key, CancellationToken token)
        {
            object value = null;

            try
            {
                if (token.IsCancellationRequested)
                {
                    return(null);
                }

                var obj = @base[key] ?? @base["@" + key];

                switch (obj)
                {
                case null:
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Key not found in object: " + key);
                    break;

                case List <object> list:
                {
                    value = list.Select(
                        item => Converter != null ? Utilities.TryConvertItemToNative(item, Converter) : item).ToList();
                    break;
                }

                default:
                    value = Converter != null?Utilities.TryConvertItemToNative(obj, Converter) : obj;

                    break;
                }
            }
            catch (Exception e)
            {
                // If we reach this, something happened that we weren't expecting...
                Log.CaptureException(e);
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Something went terribly wrong... " + e.Message);
            }
            return(value);
        }
Ejemplo n.º 14
0
        public override void DoWork(Action <string, double> ReportProgress, Action Done)
        {
            try
            {
                if (CancellationToken.IsCancellationRequested)
                {
                    return;
                }

                int branchIndex = 0, completed = 0;
                foreach (var list in Objects.Branches)
                {
                    var path = Objects.Paths[branchIndex];
                    foreach (var item in list)
                    {
                        if (CancellationToken.IsCancellationRequested)
                        {
                            return;
                        }

                        var converted = Utilities.TryConvertItemToSpeckle(item, Converter) as Base;
                        ConvertedObjects.Append(new GH_SpeckleBase {
                            Value = converted
                        }, Objects.Paths[branchIndex]);
                        ReportProgress(Id, ((completed++ + 1) / (double)Objects.Count()));
                    }

                    branchIndex++;
                }

                Done();
            }
            catch (Exception e)
            {
                // If we reach this, something happened that we weren't expecting...
                Log.CaptureException(e);
                Parent.AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Something went terribly wrong... " + e.Message);
                Parent.Message = "Error";
            }
        }
        public override void DoWork(Action <string, double> ReportProgress, Action Done)
        {
            try
            {
                Parent.Message = "Creating...";
                @base          = new Base();
                var hasErrors = false;
                if (inputData == null)
                {
                    @base = null;
                }

                inputData?.Keys.ToList().ForEach(key =>
                {
                    var value = inputData[key];


                    if (value is List <object> list)
                    {
                        // Value is a list of items, iterate and convert.
                        List <object> converted = null;
                        try
                        {
                            converted = list.Select(item =>
                            {
                                return(Converter != null ? Utilities.TryConvertItemToSpeckle(item, Converter) : item);
                            }).ToList();
                        }
                        catch (Exception e)
                        {
                            Log.CaptureException(e);
                            RuntimeMessages.Add((GH_RuntimeMessageLevel.Warning, $"{e.Message}"));
                            hasErrors = true;
                        }
                        try
                        {
                            @base[key] = converted;
                        }
                        catch (Exception e)
                        {
                            Log.CaptureException(e);
                            RuntimeMessages.Add((GH_RuntimeMessageLevel.Error, $"{e.Message}"));
                            hasErrors = true;
                        }
                    }
                    else
                    {
                        // If value is not list, it is a single item.

                        try
                        {
                            if (Converter != null)
                            {
                                @base[key] = value == null ? null : Utilities.TryConvertItemToSpeckle(value, Converter);
                            }
                            else
                            {
                                @base[key] = value;
                            }
                        }
                        catch (Exception e)
                        {
                            Log.CaptureException(e);
                            RuntimeMessages.Add((GH_RuntimeMessageLevel.Error, $"{e.Message}"));
                            hasErrors = true;
                        }
                    }
                });

                if (hasErrors)
                {
                    @base = null;
                }
            }
            catch (Exception e)
            {
                // If we reach this, something happened that we weren't expecting...
                Log.CaptureException(e);
                RuntimeMessages.Add((GH_RuntimeMessageLevel.Error, "Something went terribly wrong... " + e.Message));
                Parent.Message = "Error";
            }

            // Let's always call done!
            Done();
        }
Ejemplo n.º 16
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            // Initialize local variables
            var valueTree = new GH_Structure <IGH_Goo>();
            var keys      = new List <string>();

            // Get data from inputs
            if (!DA.GetDataList(0, keys))
            {
                return;
            }
            if (!DA.GetDataTree(1, out valueTree))
            {
                return;
            }

            // Create a path from the current iteration
            var searchPath = new GH_Path(DA.Iteration);

            // Grab the corresponding subtree from the value input tree.
            var  subTree    = Utilities.GetSubTree(valueTree, searchPath);
            Base speckleObj = new Base();

            // Find the list or subtree belonging to that path
            if (valueTree.PathExists(searchPath) || valueTree.Paths.Count == 1)
            {
                var list = valueTree.Paths.Count == 1 ? valueTree.Branches[0] : valueTree.get_Branch(searchPath);
                // We got a list of values
                var ind = 0;
                keys.ForEach(key =>
                {
                    if (ind < list.Count)
                    {
                        speckleObj[key] = Utilities.TryConvertItemToSpeckle(list[ind], Converter);
                    }
                    ind++;
                });
            }
            else
            {
                // We got a tree of values

                // Create the speckle object with the specified keys
                var index = 0;
                keys.ForEach(key =>
                {
                    var itemPath = new GH_Path(index);
                    //TODO: Grab conversion methods and implement branch handling.
                    var branch = subTree.get_Branch(itemPath);
                    if (branch != null)
                    {
                        List <object> objs = new List <object>();
                        foreach (var goo in branch)
                        {
                            objs.Add(Utilities.TryConvertItemToSpeckle(goo, Converter));
                        }

                        if (objs.Count > 0)
                        {
                            speckleObj[key] = objs;
                        }
                    }

                    index++;
                });
            }

            // Set output
            DA.SetData(0, new GH_SpeckleBase {
                Value = speckleObj
            });
        }
        public Base DoWork(Base @base, List <string> keys, GH_Structure <IGH_Goo> valueTree)
        {
            try
            {
                // 👉 Checking for cancellation!
                if (CancelToken.IsCancellationRequested)
                {
                    return(null);
                }

                // Create a path from the current iteration
                var searchPath = new GH_Path(RunCount - 1);

                // Grab the corresponding subtree from the value input tree.
                var subTree = Utilities.GetSubTree(valueTree, searchPath);
                // Find the list or subtree belonging to that path
                if (valueTree.PathExists(searchPath) || valueTree.Paths.Count == 1)
                {
                    var list = valueTree.Paths.Count == 1 ? valueTree.Branches[0] : valueTree.get_Branch(searchPath);
                    // We got a list of values
                    var ind       = 0;
                    var hasErrors = false;
                    keys.ForEach(key =>
                    {
                        if (ind < list.Count)
                        {
                            try
                            {
                                if (Converter != null)
                                {
                                    @base[key] = Utilities.TryConvertItemToSpeckle(list[ind], Converter);
                                }
                                else
                                {
                                    @base[key] = list[ind];
                                }
                            }
                            catch (Exception e)
                            {
                                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, e.Message);
                                hasErrors = true;
                            }
                        }

                        ind++;
                    });
                    if (hasErrors)
                    {
                        @base = null;
                    }
                }
                else
                {
                    // We got a tree of values

                    // Create the speckle object with the specified keys
                    var index     = 0;
                    var hasErrors = false;
                    keys.ForEach(key =>
                    {
                        var itemPath = new GH_Path(index);

                        var branch = subTree.get_Branch(itemPath);
                        if (branch != null)
                        {
                            var objs = new List <object>();
                            foreach (var goo in branch)
                            {
                                if (Converter != null)
                                {
                                    objs.Add(Utilities.TryConvertItemToSpeckle(goo, Converter));
                                }
                                else
                                {
                                    objs.Add(goo);
                                }
                            }

                            if (objs.Count > 0)
                            {
                                try
                                {
                                    @base[key] = objs;
                                }
                                catch (Exception e)
                                {
                                    AddRuntimeMessage(GH_RuntimeMessageLevel.Error, e.Message);
                                    hasErrors = true;
                                }
                            }
                        }

                        index++;
                    });

                    if (hasErrors)
                    {
                        @base = null;
                    }
                }

                return(@base);
            }
            catch (Exception e)
            {
                // If we reach this, something happened that we weren't expecting...
                Log.CaptureException(e);
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Something went terribly wrong... " + e.Message);
                return(null);
            }
        }
        public override void DoWork(Action <string, double> ReportProgress, Action Done)
        {
            try
            {
                Parent.Message = "Extending...";
                var path = new GH_Path(iteration);
                if (valueTree.PathExists(path))
                {
                    var values = valueTree.get_Branch(path) as List <IGH_Goo>;
                    // Input is a list of values. Assign them directly
                    if (keys.Count != values?.Count)
                    {
                        Parent.AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Key and Value lists are not the same length.");
                        Parent.Message = "Error";
                        return;
                    }

                    AssignToObject(@base, keys, values);
                }
                else if (valueTree.Branches.Count == 1)
                {
                    var values = valueTree.Branches[0];
                    if (keys.Count != values.Count)
                    {
                        Parent.AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Key and Value lists are not the same length.");
                        Parent.Message = "Error";
                        return;
                    }

                    // Input is just one list, so use it.
                    AssignToObject(@base, keys, values);
                }
                else
                {
                    // Input is a tree, meaning it's values are either lists or trees.
                    var subTree   = Utilities.GetSubTree(valueTree, path);
                    var index     = 0;
                    var foundTree = false;
                    keys.ForEach(key =>
                    {
                        var subPath = new GH_Path(index);
                        if (subTree.PathExists(subPath))
                        {
                            // Value is a list, convert and assign.
                            var list = subTree.get_Branch(subPath) as List <IGH_Goo>;
                            if (list?.Count > 0)
                            {
                                try
                                {
                                    @base[key] = list.Select(goo => Utilities.TryConvertItemToSpeckle(goo, Converter)).ToList();
                                }
                                catch (Exception e)
                                {
                                    Console.WriteLine(e);
                                }
                            }
                            ;
                        }
                        else
                        {
                            foundTree = true;
                        }

                        index++;
                    });

                    if (foundTree)
                    {
                        // TODO: Handle tree conversions
                        Parent.AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Cannot handle trees yet");
                        Parent.Message = "Error";
                    }
                }

                Done();
            }
            catch (Exception e)
            {
                // If we reach this, something happened that we weren't expecting...
                Log.CaptureException(e);
                Parent.AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Something went terribly wrong... " + e.Message);
                Parent.Message = "Error";
            }
        }
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            if (readFailed)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error,
                                  "This component has changed or cannot be found, please create a new one");
                return;
            }

            if (SelectedConstructor is null)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "No schema has been selected.");
                return;
            }

            if (DA.Iteration == 0)
            {
                Tracker.TrackPageview("objects", "create", "schema");
            }

            var units = Units.GetUnitsFromString(Rhino.RhinoDoc.ActiveDoc.GetUnitSystemName(true, false, false, false));

            List <object> cParamsValues = new List <object>();
            var           cParams       = SelectedConstructor.GetParameters();
            object        mainSchemaObj = null;

            for (var i = 0; i < cParams.Length; i++)
            {
                var    cParam     = cParams[i];
                var    param      = Params.Input[i];
                object objectProp = null;
                if (param.Access == GH_ParamAccess.list)
                {
                    var inputValues = new List <object>();
                    DA.GetDataList(i, inputValues);
                    if (!inputValues.Any() && !param.Optional)
                    {
                        AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Input list `" + param.Name + "` is empty.");
                        return;
                    }

                    try
                    {
                        inputValues = inputValues.Select(x => ExtractRealInputValue(x)).ToList();
                        objectProp  = GetObjectListProp(param, inputValues, cParam.ParameterType);
                    }
                    catch (Exception e)
                    {
                        AddRuntimeMessage(GH_RuntimeMessageLevel.Error, e.InnerException?.Message ?? e.Message);
                        return;
                    }
                }
                else if (param.Access == GH_ParamAccess.item)
                {
                    object inputValue = null;
                    DA.GetData(i, ref inputValue);
                    var extractRealInputValue = ExtractRealInputValue(inputValue);
                    objectProp = GetObjectProp(param, extractRealInputValue, cParam.ParameterType);
                }

                cParamsValues.Add(objectProp);
                if (CustomAttributeData.GetCustomAttributes(cParam)
                    ?.Where(o => o.AttributeType.IsEquivalentTo(typeof(SchemaMainParam)))?.Count() > 0)
                {
                    mainSchemaObj = objectProp;
                }
            }


            object schemaObject = null;

            try
            {
                schemaObject = SelectedConstructor.Invoke(cParamsValues.ToArray());
                ((Base)schemaObject).applicationId = $"{Seed}-{SelectedConstructor.DeclaringType.FullName}-{DA.Iteration}";
                if (((Base)schemaObject)["units"] == null || ((Base)schemaObject)["units"] == "")
                {
                    ((Base)schemaObject)["units"] = units;
                }
            }
            catch (Exception e)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, e.InnerException?.Message ?? e.Message);
                return;
            }

            // create commit obj from main geometry param and try to attach schema obj. use schema obj if no main geom param was found.
            Base commitObj = (Base)schemaObject;

            if (UseSchemaTag)
            {
                commitObj = commitObj.ShallowCopy();
                try
                {
                    if (mainSchemaObj == null)
                    {
                        UseSchemaTag = false;
                        ((SpeckleBaseParam)Params.Output[0]).UseSchemaTag = UseSchemaTag;
                        throw new Exception("Schema tag is not supported for this object type, will return Schema object instead.");
                    }

                    commitObj = ((Base)mainSchemaObj).ShallowCopy();
                    commitObj["@SpeckleSchema"] = schemaObject;
                    if (commitObj["units"] == null || commitObj["units"] == "")
                    {
                        commitObj["units"] = units;
                    }
                }
                catch (Exception e)
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, e.Message);
                }
            }

            // Finally, add any custom props created by the user.
            for (var j = cParams.Length; j < Params.Input.Count; j++)
            {
                // Additional props added to the object
                var ghParam = Params.Input[j];
                if (ghParam.Access == GH_ParamAccess.item)
                {
                    object input = null;
                    DA.GetData(j, ref input);

                    commitObj[ghParam.Name] = Utilities.TryConvertItemToSpeckle(input, Converter);
                }
                else if (ghParam.Access == GH_ParamAccess.list)
                {
                    List <object> input = new List <object>();
                    DA.GetDataList(j, input);
                    commitObj[ghParam.Name] = input.Select(i => Utilities.TryConvertItemToSpeckle(i, Converter)).ToList();
                }
            }

            DA.SetData(0, new GH_SpeckleBase()
            {
                Value = commitObj
            });
        }
        public override void DoWork(Action <string, double> ReportProgress, Action Done)
        {
            try
            {
                Parent.Message = "Creating...";
                @base          = new Base();
                var hasErrors = false;
                inputData.Keys.ToList().ForEach(key =>
                {
                    var value = inputData[key];
                    if (value == null)
                    {
                        Done();
                    }

                    else if (value is List <object> list)
                    {
                        // Value is a list of items, iterate and convert.
                        var converted = list.Select(item => Utilities.TryConvertItemToSpeckle(item, Converter)).ToList();
                        try
                        {
                            @base[key] = converted;
                        }
                        catch (Exception e)
                        {
                            Log.CaptureException(e);
                            Parent.AddRuntimeMessage(GH_RuntimeMessageLevel.Error, $"{e.Message}");
                            Parent.Message = "Error";
                            RhinoApp.InvokeOnUiThread(new Action(() => Parent.OnDisplayExpired(true)));
                            hasErrors = true;
                        }
                    }
                    else
                    {
                        // If value is not list, it is a single item.
                        try
                        {
                            var obj    = Utilities.TryConvertItemToSpeckle(value, Converter);
                            @base[key] = obj;
                        }
                        catch (Exception e)
                        {
                            Log.CaptureException(e);
                            Parent.AddRuntimeMessage(GH_RuntimeMessageLevel.Error, $"{e.Message}");
                            Parent.Message = "Error";
                            RhinoApp.InvokeOnUiThread(new Action(() => Parent.OnDisplayExpired(true)));
                            hasErrors = true;
                        }
                    }
                });
                if (!hasErrors)
                {
                    Done();
                }
            }
            catch (Exception e)
            {
                // If we reach this, something happened that we weren't expecting...
                Log.CaptureException(e);
                Parent.AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Something went terribly wrong... " + e.Message);
                Parent.Message = "Error";
            }
        }
Ejemplo n.º 21
0
        public override void DoWork(Action <string, double> ReportProgress, Action Done)
        {
            try
            {
                // 👉 Checking for cancellation!
                if (CancellationToken.IsCancellationRequested)
                {
                    return;
                }
                Parent.Message = "Creating...";
                // Create a path from the current iteration
                var searchPath = new GH_Path(iteration);

                // Grab the corresponding subtree from the value input tree.
                var subTree = Utilities.GetSubTree(valueTree, searchPath);
                speckleObj = new Base();
                // Find the list or subtree belonging to that path
                if (valueTree.PathExists(searchPath) || valueTree.Paths.Count == 1)
                {
                    var list = valueTree.Paths.Count == 1 ? valueTree.Branches[0] : valueTree.get_Branch(searchPath);
                    // We got a list of values
                    var ind       = 0;
                    var hasErrors = false;
                    keys.ForEach(key =>
                    {
                        if (ind < list.Count)
                        {
                            try
                            {
                                speckleObj[key] = Utilities.TryConvertItemToSpeckle(list[ind], Converter);
                            }
                            catch (Exception e)
                            {
                                Console.WriteLine(e);
                                Parent.AddRuntimeMessage(GH_RuntimeMessageLevel.Error, e.Message);
                                Parent.Message = "Error";
                                hasErrors      = true;
                            }
                        }

                        ind++;
                    });
                    if (hasErrors)
                    {
                        return;
                    }
                }
                else
                {
                    // We got a tree of values

                    // Create the speckle object with the specified keys
                    var index = 0;
                    keys.ForEach(key =>
                    {
                        var itemPath = new GH_Path(index);

                        var branch = subTree.get_Branch(itemPath);
                        if (branch != null)
                        {
                            var objs = new List <object>();
                            foreach (var goo in branch)
                            {
                                objs.Add(Utilities.TryConvertItemToSpeckle(goo, Converter));
                            }

                            if (objs.Count > 0)
                            {
                                try
                                {
                                    speckleObj[key] = objs;
                                }
                                catch (Exception e)
                                {
                                    Console.WriteLine(e);
                                    Parent.AddRuntimeMessage(GH_RuntimeMessageLevel.Error, e.Message);
                                    return;
                                }
                            }
                        }

                        index++;
                    });
                }
                // --> Report progress if necessary
                // ReportProgress(Id, percentage);

                // Call Done() to signal it's finished.
                Done();
            }
            catch (Exception e)
            {
                // If we reach this, something happened that we weren't expecting...
                Log.CaptureException(e);
                Parent.AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Something went terribly wrong... " + e.Message);
                Parent.Message = "Error";
            }
        }
Ejemplo n.º 22
0
        public override void DoWork(Action <string, double> ReportProgress, Action Done)
        {
            // 👉 Checking for cancellation!
            if (CancellationToken.IsCancellationRequested)
            {
                return;
            }
            Parent.Message = "Creating...";
            // Create a path from the current iteration
            var searchPath = new GH_Path(iteration);

            // Grab the corresponding subtree from the value input tree.
            var subTree = Utilities.GetSubTree(valueTree, searchPath);

            speckleObj = new Base();
            // Find the list or subtree belonging to that path
            if (valueTree.PathExists(searchPath) || valueTree.Paths.Count == 1)
            {
                var list = valueTree.Paths.Count == 1 ? valueTree.Branches[0] : valueTree.get_Branch(searchPath);
                // We got a list of values
                var ind = 0;
                keys.ForEach(key =>
                {
                    if (ind < list.Count)
                    {
                        speckleObj[key] = Utilities.TryConvertItemToSpeckle(list[ind], Converter);
                    }
                    ind++;
                });
            }
            else
            {
                // We got a tree of values

                // Create the speckle object with the specified keys
                var index = 0;
                keys.ForEach(key =>
                {
                    var itemPath = new GH_Path(index);

                    var branch = subTree.get_Branch(itemPath);
                    if (branch != null)
                    {
                        var objs = new List <object>();
                        foreach (var goo in branch)
                        {
                            objs.Add(Utilities.TryConvertItemToSpeckle(goo, Converter));
                        }

                        if (objs.Count > 0)
                        {
                            speckleObj[key] = objs;
                        }
                    }

                    index++;
                });
            }
            // --> Report progress if necessary
            // ReportProgress(Id, percentage);

            // Call Done() to signal it's finished.
            Done();
        }
Ejemplo n.º 23
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            // Init local variables
            GH_SpeckleBase ghBase = null;
            var            keys   = new List <string>();

            // Grab data from input
            if (!DA.GetData(0, ref ghBase))
            {
                return;
            }
            if (!DA.GetDataList(1, keys))
            {
                return;
            }
            if (!DA.GetDataTree(2, out GH_Structure <IGH_Goo> valueTree))
            {
                return;
            }

            // TODO: Handle data validation
            var b = ghBase.Value.ShallowCopy();

            CleanDeletedKeys(b, keys);
            // Search for the path coinciding with the current iteration.
            var path = new GH_Path(DA.Iteration);

            if (valueTree.PathExists(path))
            {
                var values = valueTree.get_Branch(path) as List <IGH_Goo>;
                // Input is a list of values. Assign them directly
                if (keys.Count != values?.Count)
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Key and Value lists are not the same length.");
                    return;
                }
                AssignToObject(b, keys, values);
            }
            else if (valueTree.Branches.Count == 1)
            {
                var values = valueTree.Branches[0];
                if (keys.Count != values.Count)
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Key and Value lists are not the same length.");
                    return;
                }
                // Input is just one list, so use it.
                AssignToObject(b, keys, values);
            }
            else
            {
                // Input is a tree, meaning it's values are either lists or trees.
                var subTree = Utilities.GetSubTree(valueTree, path);
                int index   = 0;
                keys.ForEach(key =>
                {
                    var subPath = new GH_Path(index);
                    if (subTree.PathExists(subPath))
                    {
                        // Value is a list, convert and assign.
                        var list = subTree.get_Branch(subPath) as List <IGH_Goo>;
                        if (list?.Count > 0)
                        {
                            var converted = list.Select(goo => Utilities.TryConvertItemToSpeckle(goo, Converter)).ToList();
                            b[key]        = converted;
                        }
                    }
                    else
                    {
                        AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Cannot handle trees yet");
                    }
                    index++;
                });
            }

            lastSolutionKeys = keys;
            DA.SetData(0, new GH_SpeckleBase {
                Value = b
            });
        }
Ejemplo n.º 24
0
        private Dictionary <string, GH_Structure <IGH_Goo> > CreateOutputDictionary()
        {
            // Create empty data tree placeholders for output.
            var outputDict = outputList.ToDictionary(outParam => outParam, _ => new GH_Structure <IGH_Goo>());

            // Assign all values to it's corresponding dictionary entry and branch path.
            foreach (var path in speckleObjects.Paths)
            {
                if (speckleObjects.get_Branch(path).Count == 0)
                {
                    continue;
                }
                // Loop through all dynamic properties
                var baseGoo = speckleObjects.get_DataItem(path, 0) as GH_SpeckleBase;
                if (baseGoo == null)
                {
                    continue;
                }
                var obj = baseGoo.Value;
                foreach (var prop in obj.GetMembers())
                {
                    // Convert and add to corresponding output structure
                    var value = prop.Value;
                    if (!outputDict.ContainsKey(prop.Key))
                    {
                        continue;
                    }
                    switch (value)
                    {
                    case null:
                        continue;

                    case System.Collections.IList list:
                        var index = 0;
                        foreach (var x in list)
                        {
                            var wrapper = Utilities.TryConvertItemToNative(x, Converter);
                            outputDict[prop.Key].Append(wrapper, path);
                            index++;
                        }
                        break;

                    // TODO: Not clear how we handle "tree" inner props. They can only be set by sender components,
                    // so perhaps this is not an issue. Below a simple stopgap so we can actually see what data is
                    // inside a sender-created object.
                    case Dictionary <string, List <Base> > dict:
                        foreach (var kvp in dict)
                        {
                            IGH_Goo wrapper = new GH_ObjectWrapper();
                            foreach (var b in kvp.Value)
                            {
                                wrapper = Utilities.TryConvertItemToNative(b, Converter);
                            }
                            outputDict[prop.Key].Append(wrapper, path);
                        }
                        break;

                    default:
                        outputDict[prop.Key].Append(
                            Utilities.TryConvertItemToNative(obj[prop.Key], Converter),
                            path);
                        break;
                    }
                }
            }

            return(outputDict);
        }
Ejemplo n.º 25
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            var res   = new List <string>();
            var @base = new Base();

            for (int i = 0; i < Params.Input.Count; i++)
            {
                var param      = Params.Input[i] as GenericAccessParam;
                var type       = param.Access.ToString();
                var detachable = param.Detachable;

                var key = detachable ? "@" + param.NickName : param.NickName;

                object result = null;

                switch (param.Access)
                {
                case GH_ParamAccess.item:
                    object value = null;
                    DA.GetData(i, ref value);

                    if (value == null)
                    {
                        break;
                    }

                    result = Utilities.TryConvertItemToSpeckle(value, Converter);

                    if (result == null)
                    {
                        AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, $"Data of type {value.GetType().Name} in {param.NickName} could not be converted.");
                    }
                    break;

                case GH_ParamAccess.list:
                    var myList = new List <object>();
                    var values = new List <object>();
                    var j      = 0;
                    DA.GetDataList(i, values);

                    if (values == null)
                    {
                        break;
                    }

                    foreach (var item in values)
                    {
                        var conv = Utilities.TryConvertItemToSpeckle(item, Converter);
                        myList.Add(conv);
                        if (conv == null)
                        {
                            AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, $"Data of type {item.GetType().Name} in {param.NickName} at index {j} could not be converted.");
                        }
                        j++;
                    }

                    result = myList;
                    break;
                }

                res.Add($"{key} ({type}, detach {detachable}) {result?.ToString()} \n");

                if (result != null)
                {
                    @base[key] = result;
                }
            }

            DA.SetData(0, new GH_SpeckleBase()
            {
                Value = @base
            });
        }
        public Base DoWork(Base @base, Dictionary <string, object> inputData)
        {
            try
            {
                var hasErrors = false;

                inputData?.Keys.ToList().ForEach(key =>
                {
                    var value = inputData[key];


                    if (value is List <object> list)
                    {
                        // Value is a list of items, iterate and convert.
                        List <object> converted = null;
                        try
                        {
                            converted = list.Select(item =>
                            {
                                return(Converter != null ? Utilities.TryConvertItemToSpeckle(item, Converter) : item);
                            }).ToList();
                        }
                        catch (Exception e)
                        {
                            Log.CaptureException(e);
                            AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, $"{e.Message}");
                            hasErrors = true;
                        }

                        try
                        {
                            @base[key] = converted;
                        }
                        catch (Exception e)
                        {
                            Log.CaptureException(e);
                            AddRuntimeMessage(GH_RuntimeMessageLevel.Error, $"{e.Message}");
                            hasErrors = true;
                        }
                    }
                    else
                    {
                        // If value is not list, it is a single item.

                        try
                        {
                            if (Converter != null)
                            {
                                @base[key] = value == null ? null : Utilities.TryConvertItemToSpeckle(value, Converter);
                            }
                            else
                            {
                                @base[key] = value;
                            }
                        }
                        catch (Exception e)
                        {
                            Log.CaptureException(e);
                            AddRuntimeMessage(GH_RuntimeMessageLevel.Error, $"{e.Message}");
                            hasErrors = true;
                        }
                    }
                });

                if (hasErrors)
                {
                    @base = null;
                }
            }
            catch (Exception e)
            {
                // If we reach this, something happened that we weren't expecting...
                Log.CaptureException(e);
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "Something went terribly wrong... " + e.Message);
            }

            return(@base);
        }