Example #1
0
        public static Dictionary <string, List <ParameterType> > GroupParameterTypesOnDiscipline()
        {
            Dictionary <string, List <ParameterType> > disciplineToParameterTypes = new Dictionary <string, List <ParameterType> >();

            string oriFile  = ThisApplication.CachedApp.SharedParametersFilename;
            string tempFile = Path.GetTempFileName() + ".txt";

            try
            {
                using (File.Create(tempFile)) { }
                ThisApplication.CachedApp.SharedParametersFilename = tempFile;

                Definitions tempDefinitions = ThisApplication.CachedApp.OpenSharedParameterFile().Groups.Create("TemporaryDefintionGroup").Definitions;
                foreach (ParameterType pt in Enum.GetValues(typeof(ParameterType)))
                {
                    if (pt != ParameterType.Invalid)
                    {
                        ExternalDefinitionCreationOptions op = new ExternalDefinitionCreationOptions(pt.ToString(), pt);
                        Definition def = tempDefinitions.Create(op);
                        UnitGroup  ug  = UnitUtils.GetUnitGroup(def.UnitType);
                        if (disciplineToParameterTypes.ContainsKey(ug.ToString()))
                        {
                            disciplineToParameterTypes[ug.ToString()].Add(pt);
                        }
                        else
                        {
                            disciplineToParameterTypes.Add(ug.ToString(), new List <ParameterType> {
                                pt
                            });
                        }
                    }
                }

                File.Delete(tempFile);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.ToString(), "GroupParameterTypesOnDiscipline");
            }
            finally
            {
                ThisApplication.CachedApp.SharedParametersFilename = oriFile;
            }

            return(disciplineToParameterTypes);
        }
Example #2
0
        void TreeView1DoubleClick(object sender, EventArgs e)
        {
            TreeNode node = treeView1.SelectedNode;

            if (treeView1.SelectedNode.Equals(null))
            {
                return;
            }
            if (node.ForeColor == System.Drawing.Color.Blue)
            {
                return;
            }
            txtName.Text = last_Selected_node = node.Text;
            txtGUID.Text = SP_andItsDetials[node.Text].GUID.ToString();
            //cbGroup.Text = SP_andItsDetials[node.Text].Definition.

            ckbInstance.Checked = SP_andItsDetials[node.Text].IsInstance;
            UnitGroup ug = UnitUtils.GetUnitGroup(SP_andItsDetials[node.Text].Definition.UnitType);

            cbDesc.Text = tmp_s = ug.ToString();
            //txtDes.Text = SP_andItsDetials[node.Text].StorageType.ToString();
            DefinitionFile     deFile = ThisApplication.CachedApp.OpenSharedParameterFile();
            ExternalDefinition ex     = ThisApplication.RawFindExternalDefinition(
                deFile, treeView1.SelectedNode.Text);

            cbGroup.Text  = ex.OwnerGroup.Name;
            lblCount.Text = "This SP founded in " + Globals.SP_andAllItsFiles[node.Text].Count + " file/s";
            cbSPtype.Items.Clear();
            List <ParameterType> tmp = Group_ParameterTypesOn_Discipline[cbDesc.Text];

            foreach (ParameterType p in tmp)
            {
                cbSPtype.Items.Add(p.ToString());
            }
            Globals.parm_to_Replace = txtName.Text;
            cbSPtype.Text           = SP_andItsDetials[node.Text].Definition.ParameterType.ToString();
        }
        // NOTE: This is actually triggered when clicking "Push!"
        // TODO: Orchestration
        // Create buckets, send sequentially, notify ui re upload progress
        // NOTE: Problems with local context and cache: we seem to not sucesffuly pass through it
        // perhaps we're not storing the right sent object (localcontext.addsentobject)
        public override void PushSender(string args)
        {
            var client = JsonConvert.DeserializeObject <dynamic>(args);

            //if it's a category or property filter we need to refresh the list of objects
            //if it's a selection filter just use the objects that were stored previously
            ISelectionFilter            filter  = JsonConvert.DeserializeObject(JsonConvert.SerializeObject(client.filter), GetFilterType(client.filter.Type.ToString()));
            IEnumerable <SpeckleObject> objects = new List <SpeckleObject>();

            objects = GetSelectionFilterObjects(filter, client._id.ToString(), client.streamId.ToString());

            var apiClient = new SpeckleApiClient((string)client.account.RestApi)
            {
                AuthToken = (string)client.account.Token
            };

            var convertedObjects = new List <SpeckleObject>();
            var placeholders     = new List <SpeckleObject>();

            var units = CurrentDoc.Document.GetUnits().GetFormatOptions(UnitType.UT_Length).DisplayUnits.ToString().ToLowerInvariant().Replace("dut_", "");

            InjectScaleInKits(GetScale(units)); // this is used for feet to sane units conversion.

            int  i = 0;
            long currentBucketSize = 0;
            var  errorMsg          = "";
            var  failedToConvert   = 0;
            var  errors            = new List <SpeckleError>();

            foreach (var obj in objects)
            {
                NotifyUi("update-client", JsonConvert.SerializeObject(new
                {
                    _id     = (string)client._id,
                    loading = true,
                    isLoadingIndeterminate = false,
                    loadingProgress        = 1f * i++ / objects.Count() * 100,
                    loadingBlurb           = string.Format("Converting and uploading objects: {0} / {1}", i, objects.Count())
                }));

                var     id           = 0;
                Element revitElement = null;
                try
                {
                    revitElement = CurrentDoc.Document.GetElement((string)obj.Properties["revitUniqueId"]);
                    id           = revitElement.Id.IntegerValue;
                }
                catch (Exception e)
                {
                    errors.Add(new SpeckleError {
                        Message = "Could not retrieve element", Details = e.Message
                    });
                    continue;
                }

                try
                {
                    var conversionResult = SpeckleCore.Converter.Serialise(new List <object>()
                    {
                        revitElement
                    });
                    var byteCount = Converter.getBytes(conversionResult).Length;
                    currentBucketSize += byteCount;

                    if (byteCount > 2e6)
                    {
                        errors.Add(new SpeckleError {
                            Message = "Element is too big to be sent", Details = $"Element {id} is bigger than 2MB, it will be skipped"
                        });
                        continue;
                    }

                    convertedObjects.AddRange(conversionResult);

                    if (currentBucketSize > 5e5 || i >= objects.Count()) // aim for roughly 500kb uncompressed
                    {
                        LocalContext.PruneExistingObjects(convertedObjects, apiClient.BaseUrl);

                        try
                        {
                            var chunkResponse = apiClient.ObjectCreateAsync(convertedObjects).Result.Resources;
                            int m             = 0;
                            foreach (var objConverted in convertedObjects)
                            {
                                objConverted._id = chunkResponse[m++]._id;
                                placeholders.Add(new SpecklePlaceholder()
                                {
                                    _id = objConverted._id
                                });
                                if (objConverted.Type != "Placeholder")
                                {
                                    LocalContext.AddSentObject(objConverted, apiClient.BaseUrl);
                                }
                            }
                        }
                        catch (Exception e)
                        {
                            errors.Add(new SpeckleError {
                                Message = $"Failed to send {convertedObjects.Count} objects", Details = e.Message
                            });
                        }
                        currentBucketSize = 0;
                        convertedObjects  = new List <SpeckleObject>(); // reset the chunkness
                    }
                }
                catch (Exception e)
                {
                    failedToConvert++;
                    errors.Add(new SpeckleError {
                        Message = $"Failed to convert {revitElement.Name}", Details = $"Element id: {id}"
                    });

                    //NotifyUi("update-client", JsonConvert.SerializeObject(new
                    //{
                    //  _id = (string)client._id,
                    //  errors = "Failed to convert " + failedConvert + " objects."
                    //}));
                }
            }

            if (errors.Any())
            {
                if (failedToConvert > 0)
                {
                    errorMsg += string.Format("Failed to convert {0} objects ",
                                              failedToConvert,
                                              failedToConvert == 1 ? "" : "s");
                }
                else
                {
                    errorMsg += string.Format("There {0} {1} error{2} ",
                                              errors.Count() == 1 ? "is" : "are",
                                              errors.Count(),
                                              errors.Count() == 1 ? "" : "s");
                }


                errorMsg += "<nobr>" + Globals.GetRandomSadFace() + "</nobr>";
            }

            var myStream = new SpeckleStream()
            {
                Objects = placeholders
            };

            var ug        = UnitUtils.GetUnitGroup(UnitType.UT_Length);
            var baseProps = new Dictionary <string, object>();

            baseProps["units"] = units;

            baseProps["unitsDictionary"] = GetAndClearUnitDictionary();

            myStream.BaseProperties = baseProps;
            //myStream.BaseProperties =  JsonConvert.SerializeObject(baseProps);

            NotifyUi("update-client", JsonConvert.SerializeObject(new
            {
                _id     = (string)client._id,
                loading = true,
                isLoadingIndeterminate = true,
                loadingBlurb           = "Updating stream."
            }));

            var response = apiClient.StreamUpdateAsync((string)client.streamId, myStream).Result;

            var plural = objects.Count() == 1 ? "" : "s";

            NotifyUi("update-client", JsonConvert.SerializeObject(new
            {
                _id          = (string)client._id,
                loading      = false,
                loadingBlurb = "",
                message      = $"Done sending {objects.Count()} object{plural}.",
                errorMsg,
                errors
            }));

            SpeckleTelemetry.RecordStreamUpdated("Revit");
        }
Example #4
0
        // TODO: Orchestration
        // Create buckets, send sequentially, notify ui re upload progress
        // NOTE: Problems with local context and cache: we seem to not sucesffuly pass through it
        // perhaps we're not storing the right sent object (localcontext.addsentobject)
        public override void UpdateSender(string args)
        {
            var client    = JsonConvert.DeserializeObject <dynamic>(args);
            var apiClient = new SpeckleApiClient((string)client.account.RestApi)
            {
                AuthToken = (string)client.account.Token
            };

            var convertedObjects = new List <SpeckleObject>();
            var placeholders     = new List <SpeckleObject>();

            var units = CurrentDoc.Document.GetUnits().GetFormatOptions(UnitType.UT_Length).DisplayUnits.ToString().ToLower().Replace("dut_", "");

            InjectScaleInKits(GetScale(units)); // this is used for feet to sane units conversion.

            int  i = 0;
            long currentBucketSize = 0;
            var  errors            = "";
            var  failedSend        = 0;
            var  failedConvert     = 0;

            foreach (var obj in client.objects)
            {
                NotifyUi("update-client", JsonConvert.SerializeObject(new
                {
                    _id     = (string)client._id,
                    loading = true,
                    isLoadingIndeterminate = false,
                    loadingProgress        = 1f * i++ / client.objects.Count * 100,
                    loadingBlurb           = string.Format("Converting and uploading objects: {0} / {1}", i, client.objects.Count)
                }));

                try
                {
                    var revitElement = CurrentDoc.Document.GetElement((string)obj.properties["revitUniqueId"]);

                    var conversionResult = SpeckleCore.Converter.Serialise(new List <object>()
                    {
                        revitElement
                    });
                    var byteCount = Converter.getBytes(conversionResult).Length;
                    currentBucketSize += byteCount;

                    if (byteCount > 2e6)
                    {
                        var problemId = revitElement.Id;
                    }

                    convertedObjects.AddRange(conversionResult);

                    if (currentBucketSize > 5e5 || i >= client.objects.Count) // aim for roughly 500kb uncompressed
                    {
                        LocalContext.PruneExistingObjects(convertedObjects, apiClient.BaseUrl);

                        try
                        {
                            var chunkResponse = apiClient.ObjectCreateAsync(convertedObjects).Result.Resources;
                            int m             = 0;
                            foreach (var objConverted in convertedObjects)
                            {
                                objConverted._id = chunkResponse[m++]._id;
                                placeholders.Add(new SpecklePlaceholder()
                                {
                                    _id = objConverted._id
                                });
                                if (objConverted.Type != "Placeholder")
                                {
                                    LocalContext.AddSentObject(objConverted, apiClient.BaseUrl);
                                }
                            }
                        }
                        catch (Exception e)
                        {
                            failedSend += convertedObjects.Count;
                            NotifyUi("update-client", JsonConvert.SerializeObject(new
                            {
                                _id    = (string)client._id,
                                errors = "Failed to send " + failedSend + " objects."
                            }));
                        }
                        currentBucketSize = 0;
                        convertedObjects  = new List <SpeckleObject>(); // reset the chunkness
                    }
                }
                catch (Exception e)
                {
                    failedConvert++;
                    NotifyUi("update-client", JsonConvert.SerializeObject(new
                    {
                        _id    = (string)client._id,
                        errors = "Failed to convert " + failedConvert + " objects."
                    }));
                }
            }

            if (failedConvert > 0)
            {
                errors += String.Format("Failed to convert a total of {0} objects. ", failedConvert);
            }
            if (failedSend > 0)
            {
                errors += String.Format("Failed to send a total of {0} objects. ", failedSend);
            }

            var myStream = new SpeckleStream()
            {
                Objects = placeholders
            };

            var ug        = UnitUtils.GetUnitGroup(UnitType.UT_Length);
            var baseProps = new Dictionary <string, object>();

            baseProps["units"] = units;

            baseProps["unitsDictionary"] = GetAndClearUnitDictionary();

            myStream.BaseProperties = baseProps;
            //myStream.BaseProperties = JsonConvert.SerializeObject(baseProps);

            NotifyUi("update-client", JsonConvert.SerializeObject(new
            {
                _id     = (string)client._id,
                loading = true,
                isLoadingIndeterminate = true,
                loadingBlurb           = "Updating stream."
            }));

            var response = apiClient.StreamUpdateAsync((string)client.streamId, myStream).Result;

            NotifyUi("update-client", JsonConvert.SerializeObject(new
            {
                _id          = (string)client._id,
                loading      = false,
                loadingBlurb = "Done sending.",
                errors
            }));
        }