//[TestCase(GSATargetLayer.Analysis, "S5pNxjmUH.json")]
        public void ReceiverTestForDebug(GSATargetLayer layer, string fileName)
        {
            var json = Helper.ReadFile(fileName, TestDataDirectory);

            var mockGsaCom = SetupMockGsaCom();

            Initialiser.AppResources.Proxy.OpenFile("", false, mockGsaCom.Object);

            var receiverProcessor = new ReceiverProcessor(TestDataDirectory);

            //Run conversion to GWA keywords
            Assert.IsTrue(receiverProcessor.JsonSpeckleStreamsToGwaRecords(new[] { fileName }, out var actualGwaRecords, layer));
            Assert.IsNotNull(actualGwaRecords);
            Assert.IsNotEmpty(actualGwaRecords);

            var TypePrerequisites = Initialiser.GsaKit.RxTypeDependencies;
            var keywords          = TypePrerequisites.Select(i => i.Key.GetGSAKeyword()).Distinct().ToList();

            //Log outcome to file

            foreach (var keyword in keywords)
            {
                var actualGwaRecordsForKeyword = new List <GwaRecord>();
                for (var i = 0; i < actualGwaRecords.Count(); i++)
                {
                    GSAProxy.ParseGeneralGwa(actualGwaRecords[i].GwaCommand, out var recordKeyword, out var foundIndex, out var foundStreamId, out string foundApplicationId, out var gwaWithoutSet, out var gwaSetCommandType);
                    if (recordKeyword.Equals(keyword, StringComparison.InvariantCultureIgnoreCase))
                    {
                        actualGwaRecordsForKeyword.Add(actualGwaRecords[i]);
                    }
                }

                var actualUniqueApplicationIds = actualGwaRecordsForKeyword.Where(r => !string.IsNullOrEmpty(r.ApplicationId)).Select(r => r.ApplicationId).Distinct();
            }
        }
Example #2
0
        //Copied and modified from Receiver in SpeckleGSA - the Speckle object isn't copied to the cache here because that's only used for merging
        public static bool GwaToCache(string gwaCommand, string streamId)
        {
            var lines = gwaCommand.Split(new[] { '\n' }).Where(l => !string.IsNullOrEmpty(l)).ToList();

            foreach (var l in lines)
            {
                //At this point the SID will be filled with the application ID
                GSAProxy.ParseGeneralGwa(l, out var keyword, out var foundIndex,
                                         out var foundStreamId, out var foundApplicationId, out var gwaWithoutSet, out var gwaSetCommandType);

                var originalSid = Initialiser.AppResources.Proxy.FormatSidTags(foundStreamId, foundApplicationId);
                var newSid      = Initialiser.AppResources.Proxy.FormatSidTags(streamId, foundApplicationId);

                //If the SID tag has been set then update it with the stream
                gwaWithoutSet = (string.IsNullOrEmpty(originalSid))
            ? gwaWithoutSet.Replace(keyword, keyword + ":" + newSid)
            : gwaWithoutSet.Replace(originalSid, newSid);

                if (!Initialiser.AppResources.Cache.Upsert(keyword, foundIndex.Value, gwaWithoutSet, streamId, foundApplicationId, gwaSetCommandType.Value))
                {
                    return(false);
                }
            }
            return(true);
        }
Example #3
0
    private bool GwaToCache(string gwaCommand, string streamId, SpeckleObject targetObject)
    {
      //At this point the SID will be filled with the application ID
      GSAProxy.ParseGeneralGwa(gwaCommand, out string keyword, out int? foundIndex, out string foundStreamId, out string foundApplicationId, out string gwaWithoutSet, out GwaSetCommandType? gwaSetCommandType, true);

      var originalSid = GSA.App.Proxy.FormatSidTags(foundStreamId, foundApplicationId);
      var newSid = GSA.App.Proxy.FormatSidTags(streamId, foundApplicationId);

      //If the SID tag has been set then update it with the stream
      if (string.IsNullOrEmpty(originalSid))
      {
        gwaWithoutSet = gwaWithoutSet.Replace(keyword, keyword + ":" + newSid);
      }
      else
      {
        gwaWithoutSet = gwaWithoutSet.Replace(originalSid, newSid);
      }

      //Only cache the object against, the top-level GWA command, not the sub-commands - this is what the SID value comparision is there for
      return GSA.App.LocalCache.Upsert(keyword.Split('.').First(),
        foundIndex.Value,
        gwaWithoutSet,
        foundApplicationId,
        so: (foundApplicationId != null
          && targetObject.ApplicationId != null
          && targetObject.ApplicationId.EqualsWithoutSpaces(foundApplicationId))
            ? targetObject
            : null,
        gwaSetCommandType: gwaSetCommandType ?? GwaSetCommandType.Set,
        streamId: streamId);
    }
Example #4
0
        public bool JsonSpeckleStreamsToGwaRecords(IEnumerable <string> savedJsonFileNames, out List <GwaRecord> gwaRecords, GSATargetLayer layer)
        {
            Initialiser.AppResources.Settings.TargetLayer = layer;

            gwaRecords = new List <GwaRecord>();

            receivedObjects = JsonSpeckleStreamsToSpeckleObjects(savedJsonFileNames);

            if (receivedObjects == null || !ScaleObjects())
            {
                return(false);
            }

            if (!ConvertSpeckleObjectsToGsaInterfacerCache(layer))
            {
                return(false);
            }

            //var gwaCommands = ((IGSACacheForTesting) this.appResources.Cache).GetGwaSetCommands();
            var gwaCommands = ((IGSACacheForTesting)Initialiser.AppResources.Cache).GetGwaSetCommands();

            foreach (var gwaC in gwaCommands)
            {
                GSAProxy.ParseGeneralGwa(gwaC, out var keyword, out int?index, out var streamId, out var applicationId, out var gwaWithoutSet, out GwaSetCommandType? gwaSetType);
                gwaRecords.Add(new GwaRecord(string.IsNullOrEmpty(applicationId) ? null : applicationId, gwaC));
            }
            return(true);
        }
Example #5
0
 public void SetupContext(string gsaFileName)
 {
     gsaInterfacer         = new GSAProxy();
     gsaCache              = new GSACache();
     Initialiser.Interface = gsaInterfacer;
     Initialiser.Cache     = gsaCache;
     Initialiser.Settings  = new Settings();
     gsaInterfacer.OpenFile(Helper.ResolveFullPath(gsaFileName, TestDataDirectory));
 }
        public void SetupContext()
        {
            gsaInterfacer = new GSAProxy();
            gsaCache      = new GSACache();

            Initialiser.Cache     = gsaCache;
            Initialiser.Interface = gsaInterfacer;
            Initialiser.Settings  = new Settings();
        }
Example #7
0
        public void SetupTests()
        {
            //This uses the installed SpeckleKits - when SpeckleStructural is built, the built files are copied into the
            // %LocalAppData%\SpeckleKits directory, so therefore this project doesn't need to reference the projects within in this solution
            SpeckleInitializer.Initialize();
            gsaInterfacer = new GSAProxy();
            gsaCache      = new GSACache();

            Initialiser.Cache     = gsaCache;
            Initialiser.Interface = gsaInterfacer;
            Initialiser.Settings  = new Settings();
        }
Example #8
0
        public void SetupTests()
        {
            //This uses the installed SpeckleKits - when SpeckleStructural is built, the built files are copied into the
            // %LocalAppData%\SpeckleKits directory, so therefore this project doesn't need to reference the projects within in this solution

            //If this isn't called, then the GetObjectSubtypeBetter method in SpeckleCore will cause a {"Value cannot be null.\r\nParameter name: source"} message
            SpeckleInitializer.Initialize();
            gsaInterfacer = new GSAProxy();
            gsaCache      = new GSACache();

            Initialiser.Cache     = gsaCache;
            Initialiser.Interface = gsaInterfacer;
            Initialiser.Settings  = new Settings();
        }
Example #9
0
        public SenderProcessor(string directory, GSAProxy gsaInterfacer, GSACache gsaCache, GSATargetLayer layer, bool embedResults, string[] cases = null, string[] resultsToSend = null) : base(directory)
        {
            GSAInterfacer = gsaInterfacer;
            Initialiser.Settings.TargetLayer = layer;

            Initialiser.Settings.EmbedResults = embedResults;
            if (cases != null)
            {
                Initialiser.Settings.ResultCases = cases.ToList();
            }
            if (resultsToSend != null)
            {
                processResultLabels(resultsToSend);
            }
        }
        public void ReceiverTestLoadRelated(GSATargetLayer layer, string fileName,
                                            int expectedNum0DLoads, int expectedNum2DBeamLoads, int expectedNum2dFaceLoads, int expectedNumLoadTasks, int expectedLoadCombos)
        {
            var json = Helper.ReadFile(fileName, TestDataDirectory);

            var mockGsaCom = SetupMockGsaCom();

            Initialiser.AppResources.Proxy.OpenFile("", false, mockGsaCom.Object);


            var receiverProcessor = new ReceiverProcessor(TestDataDirectory);

            //Run conversion to GWA keywords
            Assert.IsTrue(receiverProcessor.JsonSpeckleStreamsToGwaRecords(new[] { fileName }, out var actualGwaRecords, layer));
            Assert.IsNotNull(actualGwaRecords);
            Assert.IsNotEmpty(actualGwaRecords);

            var TypePrerequisites = Initialiser.GsaKit.RxTypeDependencies;
            var keywords          = TypePrerequisites.Select(i => i.Key.GetGSAKeyword()).Distinct().ToList();

            //Log outcome to file

            var actualGwaRecordsForKeyword = new Dictionary <string, List <string> >();

            for (var i = 0; i < actualGwaRecords.Count(); i++)
            {
                GSAProxy.ParseGeneralGwa(actualGwaRecords[i].GwaCommand, out var recordKeyword, out var foundIndex, out var foundStreamId, out string foundApplicationId, out var gwaWithoutSet, out var gwaSetCommandType);
                if (!actualGwaRecordsForKeyword.ContainsKey(recordKeyword))
                {
                    actualGwaRecordsForKeyword.Add(recordKeyword, new List <string>());
                }
                actualGwaRecordsForKeyword[recordKeyword].Add(actualGwaRecords[i].GwaCommand);
            }

            Assert.AreEqual(expectedNum0DLoads, actualGwaRecords.Where(r => r.GwaCommand.Contains("LOAD_NODE")).Count());
            Assert.AreEqual(expectedNum2DBeamLoads, actualGwaRecords.Where(r => r.GwaCommand.Contains("LOAD_BEAM_UDL")).Count());
            Assert.AreEqual(expectedNum2dFaceLoads, actualGwaRecords.Where(r => r.GwaCommand.Contains("LOAD_2D_FACE")).Count());
            Assert.AreEqual(expectedNumLoadTasks, actualGwaRecords.Where(r => r.GwaCommand.Contains("TASK")).Count());
            Assert.AreEqual(expectedLoadCombos, actualGwaRecords.Where(r => r.GwaCommand.Contains("COMBINATION")).Count());

            /*
             * Assert.AreEqual(expectedNum2DBeamLoads, actualGwaRecordsForKeyword["LOAD_BEAM_UDL.2"].Distinct().Count());
             * Assert.AreEqual(expectedNum2dFaceLoads, actualGwaRecordsForKeyword["LOAD_2D_FACE.2"].Distinct().Count());
             * Assert.AreEqual(expectedNumLoadTasks, actualGwaRecordsForKeyword["TASK.1"].Distinct().Count());
             * Assert.AreEqual(expectedLoadCombos, actualGwaRecordsForKeyword["COMBINATION.1"].Distinct().Count());
             */
        }
Example #11
0
        public void StreamInfoSidStorage()
        {
            var server   = "https://australia.speckle.arup.com/api";
            var filePath = HelperFunctions.GetFullPath(sendGsaFileRelativePath);

            var gsaProxy = new GSAProxy();

            gsaProxy.OpenFile(filePath, true);

            var wroteOne = HelperFunctions.SetSidSpeckleRecords("*****@*****.**", server, gsaProxy,
                                                                new List <SidSpeckleRecord>()
            {
                new SidSpeckleRecord("Rec-01", null, "Client-01")
            },
                                                                null);
            var wroteTwo = HelperFunctions.SetSidSpeckleRecords(email, server, gsaProxy,
                                                                new List <SidSpeckleRecord>()
            {
                new SidSpeckleRecord(testRecStreamId, null, "Client-02")
            },
                                                                new List <SidSpeckleRecord>()
            {
                new SidSpeckleRecord(testSenBucketStreamIds["model"], "model", "Client-02"), new SidSpeckleRecord(testSenBucketStreamIds["results"], "results", "Client-02")
            });

            //The first record is just for context, to add basic complexity
            var readOne = HelperFunctions.GetSidSpeckleRecords("*****@*****.**", server, gsaProxy, out var recOne, out var senOne) && recOne.Count() == 1 && senOne.Count() == 0;
            var readTwo = HelperFunctions.GetSidSpeckleRecords(email, server, gsaProxy, out var recTwo, out var senTwo) && recTwo.Count() == 1 && senTwo.Count() == 2;

            if (wroteOne && wroteTwo && readOne && readTwo)
            {
                gsaProxy.SaveAs(filePath);
            }
            gsaProxy.Close();

            Assert.IsTrue(wroteOne);
            Assert.IsTrue(wroteTwo);
            Assert.IsTrue(readOne);
            Assert.IsTrue(readTwo);
        }
 public ReceiverProcessor(string directory, GSAProxy gsaInterfacer, GSACache gsaCache, GSATargetLayer layer = GSATargetLayer.Design) : base(directory)
 {
     GSAInterfacer = gsaInterfacer;
     GSACache      = gsaCache;
     Initialiser.Settings.TargetLayer = layer;
 }
Example #13
0
        public bool RunCLI(params string[] args)
        {
            CultureInfo.DefaultThreadCurrentCulture   = CultureInfo.InvariantCulture;
            CultureInfo.DefaultThreadCurrentUICulture = CultureInfo.InvariantCulture;

            cliMode = args[0];
            if (cliMode == "-h")
            {
                Console.WriteLine("\n");
                Console.WriteLine("Usage: SpeckleGSAUI.exe <command>\n\n" +
                                  "where <command> is one of: receiver, sender\n\n");
                Console.Write("SpeckleGSAUI.exe <command> -h\thelp on <command>\n");
                return(true);
            }
            if (cliMode != "receiver" && cliMode != "sender")
            {
                Console.WriteLine("Unable to parse command");
                return(false);
            }

            for (int index = 1; index < args.Length; index += 2)
            {
                string arg = args[index].Replace("-", "");
                if (args.Length <= index + 1 || args[index + 1].StartsWith("-"))
                {
                    arguments.Add(arg, "true");
                    index--;
                }
                else
                {
                    arguments.Add(arg, args[index + 1].Trim(new char[] { '"' }));
                }
            }

            if (cliMode == "receiver" && arguments.ContainsKey("h"))
            {
                Console.WriteLine("\n");
                Console.WriteLine("Usage: SpeckleGSAUI.exe receiver\n");
                Console.WriteLine("\n");
                Console.Write("Required arguments:\n");
                Console.Write("--server <server>\t\tAddress of Speckle server\n");
                Console.Write("--email <email>\t\t\tEmail of account\n");
                Console.Write("--token <token>\t\tJWT token\n");
                Console.Write("--file <path>\t\t\tFile to save to. If file does not exist, a new one will be created\n");
                Console.Write("--streamIDs <streamIDs>\t\tComma-delimited ID of streams to be received\n");
                Console.WriteLine("\n");
                Console.Write("Optional arguments:\n");
                Console.Write("--layer [analysis|design]\tSet which layer to write to. Default is design layer\n");
                Console.Write("--nodeAllowance <distance>\tMax distance before nodes are not merged\n");
                return(true);
            }
            else if (cliMode == "sender" && arguments.ContainsKey("h"))
            {
                Console.WriteLine("\n");
                Console.WriteLine("Usage: SpeckleGSAUI.exe sender\n");
                Console.WriteLine("\n");
                Console.Write("Required arguments:\n");
                Console.Write("--server <server>\t\tAddress of Speckle server\n");
                Console.Write("--email <email>\t\t\tEmail of account\n");
                Console.Write("--token <token>\t\tJWT token\n");
                Console.Write("--file <path>\t\t\tFile to open. If file does not exist, a new one will be created\n");
                Console.WriteLine("\n");
                Console.Write("Optional arguments:\n");
                Console.Write("--layer [analysis|design]\tSet which layer to write to. Default is design layer\n");
                Console.Write("--sendAllNodes\t\t\tSend all nodes in model. Default is to send only 'meaningful' nodes\n");
                Console.Write("--separateStreams\t\tSeparate model into different streams\n");
                Console.Write("--result <options>\t\tType of result to send. Each input should be in quotation marks. Comma-delimited\n");
                Console.Write("--resultCases <cases>\t\tCases to extract results from. Comma-delimited\n");
                Console.Write("--resultOnly\t\t\tSend only results\n");
                Console.Write("--resultUnembedded\t\tSend results as separate objects\n");
                Console.Write("--resultInLocalAxis\t\tSend results calculated at the local axis. Default is global\n");
                Console.Write("--result1DNumPosition <num>\tNumber of additional result points within 1D elements\n");
                return(true);
            }

            string[] neededArgs = new string[] { "server", "email", "token", "file" };

            foreach (string a in neededArgs)
            {
                if (!arguments.ContainsKey(a))
                {
                    Console.WriteLine("Missing -" + a + " argument");
                    return(false);
                }
            }

            // Login
            EmailAddress = arguments["email"];
            RestApi      = arguments["server"];
            ApiToken     = arguments["token"];

            //This will create the logger
            GSA.App.LocalSettings.LoggingMinimumLevel = 4; //Debug
            GSA.App.Settings.TargetLayer = (arguments.ContainsKey("layer") && (arguments["layer"].ToLower() == "analysis")) ? GSATargetLayer.Analysis : GSATargetLayer.Design;

            //This ensures that if multiple CLI calls are made sequentially from any process, that there is no carry over of static variable values
            //from previous calls
            GSA.Reset();

            GSA.Init(getRunningVersion().ToString());
            GSA.App.LocalMessenger.MessageAdded += this.ProcessMessage;
            SpeckleCore.SpeckleInitializer.Initialize();

            List <SidSpeckleRecord> receiverStreamInfo;
            List <SidSpeckleRecord> senderStreamInfo;

            var fileArg  = arguments["file"];
            var filePath = fileArg.StartsWith(".") ? Path.Combine(AssemblyDirectory, fileArg) : fileArg;

            // GSA File
            if (File.Exists(filePath))
            {
                OpenFile(filePath, EmailAddress, RestApi, out receiverStreamInfo, out senderStreamInfo, false);
            }
            else if (cliMode == "sender")
            {
                Console.WriteLine("Could not locate file: " + filePath);
                //sending needs the file to exist
                return(false);
            }
            else
            {
                receiverStreamInfo = new List <SidSpeckleRecord>();
                senderStreamInfo   = new List <SidSpeckleRecord>();
                GSA.App.Proxy.NewFile(false);

                GSA.App.Messenger.Message(SpeckleGSAInterfaces.MessageIntent.Display, SpeckleGSAInterfaces.MessageLevel.Information, "Created new file.");

                //Ensure this new file has a file name
                GSA.App.Proxy.SaveAs(filePath);
            }

            var calibrateNodeAtTask = Task.Run(() => GSAProxy.CalibrateNodeAt());

            calibrateNodeAtTask.Wait();

            if (cliMode == "receiver")
            {
                if (!arguments.ContainsKey("streamIDs"))
                {
                    Console.WriteLine("Missing -streamIDs argument");
                    return(false);
                }
                //There seem to be some issues with HTTP requests down the line if this is run on the initial (UI) thread, so this ensures it runs on another thread
                return(Task.Run(() => CLIReceiver(receiverStreamInfo)).Result);
            }
            else if (cliMode == "sender")
            {
                //There seem to be some issues with HTTP requests down the line if this is run on the initial (UI) thread, so this ensures it runs on another thread
                return(Task.Run(() => CLISender(senderStreamInfo)).Result);
            }
            return(true);
        }
        private void RunReceiverTest(string[] savedJsonFileNames, string expectedGwaPerIdsFile, string subdir, GSATargetLayer layer)
        {
            var dir = System.IO.Path.Combine(TestDataDirectory, subdir) + "\\";

            var expectedJson       = Helper.ReadFile(expectedGwaPerIdsFile, dir);
            var expectedGwaRecords = Helper.DeserialiseJson <List <GwaRecord> >(expectedJson);

            var mockGsaCom = SetupMockGsaCom();

            Initialiser.AppResources.Proxy.NewFile(false, mockGsaCom.Object);

            var receiverProcessor = new ReceiverProcessor(dir);

            //Run conversion to GWA keywords
            Assert.IsTrue(receiverProcessor.JsonSpeckleStreamsToGwaRecords(savedJsonFileNames, out var actualGwaRecords, layer));
            Assert.IsNotNull(actualGwaRecords);
            Assert.IsNotEmpty(actualGwaRecords);

            var TypePrerequisites = Initialiser.GsaKit.RxTypeDependencies;
            var keywords          = TypePrerequisites.Select(i => i.Key.GetGSAKeyword()).Distinct().ToList();

            //Log outcome to file

            foreach (var keyword in keywords)
            {
                var expectedGwaRecordsForKeyword = new List <GwaRecord>();
                for (var i = 0; i < expectedGwaRecords.Count(); i++)
                {
                    GSAProxy.ParseGeneralGwa(expectedGwaRecords[i].GwaCommand, out var recordKeyword, out var foundIndex, out var foundStreamId, out string foundApplicationId, out var gwaWithoutSet, out var gwaSetCommandType);
                    if (recordKeyword.Equals(keyword, StringComparison.InvariantCultureIgnoreCase))
                    {
                        expectedGwaRecordsForKeyword.Add(expectedGwaRecords[i]);
                    }
                }

                var actualGwaRecordsForKeyword = new List <GwaRecord>();
                for (var i = 0; i < actualGwaRecords.Count(); i++)
                {
                    GSAProxy.ParseGeneralGwa(actualGwaRecords[i].GwaCommand, out var recordKeyword, out var foundIndex, out var foundStreamId, out string foundApplicationId, out var gwaWithoutSet, out var gwaSetCommandType);
                    if (recordKeyword.Equals(keyword, StringComparison.InvariantCultureIgnoreCase))
                    {
                        actualGwaRecordsForKeyword.Add(actualGwaRecords[i]);
                    }
                }

                if (expectedGwaRecordsForKeyword.Count() == 0)
                {
                    continue;
                }

                Assert.GreaterOrEqual(actualGwaRecordsForKeyword.Count(), expectedGwaRecordsForKeyword.Count(), "Number of GWA records don't match");

                var actualUniqueApplicationIds   = actualGwaRecordsForKeyword.Where(r => !string.IsNullOrEmpty(r.ApplicationId)).Select(r => r.ApplicationId).Distinct();
                var expectedUniqueApplicationIds = expectedGwaRecordsForKeyword.Where(r => !string.IsNullOrEmpty(r.ApplicationId)).Select(r => r.ApplicationId).Distinct();
                Assert.AreEqual(expectedUniqueApplicationIds.Count(), actualUniqueApplicationIds.Count());

                //Check for any actual records missing from expected
                Assert.IsTrue(actualUniqueApplicationIds.All(a => expectedUniqueApplicationIds.Contains(a)));

                //Check any expected records missing in actual
                Assert.IsTrue(expectedUniqueApplicationIds.All(a => actualUniqueApplicationIds.Contains(a)));

                //Check each actual record has match in expected
                foreach (var actualGwaRecord in actualGwaRecordsForKeyword)
                {
                    Assert.GreaterOrEqual(1,
                                          expectedGwaRecordsForKeyword.Count(er => er.ApplicationId == actualGwaRecord.ApplicationId && er.GwaCommand.Equals(actualGwaRecord.GwaCommand, StringComparison.InvariantCultureIgnoreCase)),
                                          "Expected record not found in actual records");
                }
            }
        }
Example #15
0
        private void ReceiverGsaValidation(string subdir, string[] jsonFiles, GSATargetLayer layer)
        {
            // Takes a saved Speckle stream with structural objects
            // converts to GWA and sends to GSA
            // then reads the data back out of GSA
            // and compares the two sets of GWA
            // if successful then there will be the same number
            // of each of the keywords in as out

            SpeckleInitializer.Initialize();
            Initialiser.AppResources = new MockGSAApp(proxy: new GSAProxy());
            Initialiser.GsaKit.Clear();
            ((MockSettings)Initialiser.AppResources.Settings).TargetLayer = layer;
            Initialiser.AppResources.Proxy.NewFile(false);

            var dir = TestDataDirectory;

            if (subdir != String.Empty)
            {
                dir = Path.Combine(TestDataDirectory, subdir);
                dir = dir + @"\"; // TestDataDirectory setup unconvetionally with trailing seperator - follow suit
            }

            var receiverProcessor = new ReceiverProcessor(dir);

            // Run conversion to GWA keywords
            // Note that it can be one model split over several json files
            Assert.IsTrue(receiverProcessor.JsonSpeckleStreamsToGwaRecords(jsonFiles, out var gwaRecordsFromFile, layer));

            //Run conversion to GWA keywords
            Assert.IsNotNull(gwaRecordsFromFile);
            Assert.IsNotEmpty(gwaRecordsFromFile);

            var typeHierarchy = Initialiser.GsaKit.RxTypeDependencies;
            var keywords      = typeHierarchy.Select(i => i.Key.GetGSAKeyword()).ToList();

            keywords.AddRange(typeHierarchy.SelectMany(i => i.Key.GetSubGSAKeyword()));
            keywords = keywords.Where(k => k.Length > 0).Select(k => Helper.RemoveVersionFromKeyword(k)).Distinct().ToList();

            Initialiser.AppResources.Proxy.Sync();                                        // send GWA to GSA

            var retrievedGwa = Initialiser.AppResources.Proxy.GetGwaData(keywords, true); // read GWA from GSA

            var retrievedDict = new Dictionary <string, List <string> >();

            foreach (var gwa in retrievedGwa)
            {
                GSAProxy.ParseGeneralGwa(gwa.GwaWithoutSet, out string keyword, out _, out _, out _, out _, out _);
                if (!retrievedDict.ContainsKey(keyword))
                {
                    retrievedDict.Add(keyword, new List <string>());
                }
                retrievedDict[keyword].Add(gwa.GwaWithoutSet);
            }

            var fromFileDict = new Dictionary <string, List <string> >();

            foreach (var r in gwaRecordsFromFile)
            {
                GSAProxy.ParseGeneralGwa(r.GwaCommand, out var keyword, out _, out _, out _, out var gwaWithoutSet, out _);
                if (!fromFileDict.ContainsKey(keyword))
                {
                    fromFileDict.Add(keyword, new List <string>());
                }
                fromFileDict[keyword].Add(gwaWithoutSet);
            }

            Initialiser.AppResources.Proxy.Close();

            var unmatching = new Dictionary <string, UnmatchedData>();

            foreach (var keyword in fromFileDict.Keys)
            {
                if (!retrievedDict.ContainsKey(keyword))
                {
                    unmatching[keyword] = new UnmatchedData
                    {
                        FromFile = fromFileDict[keyword]
                    };
                }
                else if (retrievedDict[keyword].Count != fromFileDict[keyword].Count)
                {
                    unmatching[keyword] = new UnmatchedData
                    {
                        Retrieved = (retrievedDict.ContainsKey(keyword)) ? retrievedDict[keyword] : null,
                        FromFile  = fromFileDict[keyword]
                    };
                }
            }

            Assert.AreEqual(0, unmatching.Count());

            // GSA sometimes forgets the SID - should check that this has passed through correctly here
        }
Example #16
0
        private bool ConvertSpeckleObjectsToGsaInterfacerCache(GSATargetLayer layer)
        {
            Initialiser.AppResources.Settings.TargetLayer = layer;

            // Write objects
            var currentBatch   = new List <Type>();
            var traversedTypes = new List <Type>();

            var TypePrerequisites = Initialiser.GsaKit.RxTypeDependencies;

            foreach (var tuple in receivedObjects)
            {
                tuple.Item2.Properties.Add("StreamId", tuple.Item1);
            }

            var rxObjsByType = CollateRxObjectsByType(receivedObjects.Select(tuple => tuple.Item2).ToList());

            do
            {
                currentBatch = TypePrerequisites.Where(i => i.Value.Count(x => !traversedTypes.Contains(x)) == 0).Select(i => i.Key).ToList();
                currentBatch.RemoveAll(i => traversedTypes.Contains(i));

                foreach (var t in currentBatch)
                {
                    var dummyObject     = Activator.CreateInstance(t);
                    var keyword         = dummyObject.GetAttribute <GSAObject>("GSAKeyword").ToString();
                    var valueType       = dummyObjectDict[t].SpeckleObject.GetType();
                    var speckleTypeName = valueType.GetType().Name;
                    var targetObjects   = receivedObjects.Select(o => new { o, t = o.Item2.GetType() })
                                          .Where(x => (x.t == valueType || x.t.IsSubclassOf(valueType))).Select(x => x.o).ToList();

                    for (var i = 0; i < targetObjects.Count(); i++)
                    {
                        var streamId = targetObjects[i].Item1;
                        var obj      = targetObjects[i].Item2;

                        //DESERIALISE
                        var deserialiseReturn = ((string)Converter.Deserialise(obj));
                        var gwaCommands       = deserialiseReturn.Split(new[] { '\n' }).Where(c => c.Length > 0).ToList();

                        for (var j = 0; j < gwaCommands.Count(); j++)
                        {
                            GSAProxy.ParseGeneralGwa(gwaCommands[j], out keyword, out int?foundIndex, out var foundStreamId, out var foundApplicationId,
                                                     out var gwaWithoutSet, out var gwaSetCommandType);

                            //Only cache the object against, the top-level GWA command, not the sub-commands
                            ((IGSACache)Initialiser.AppResources.Cache).Upsert(keyword, foundIndex.Value, gwaWithoutSet, applicationId: foundApplicationId,
                                                                               so: (foundApplicationId == obj.ApplicationId) ? obj : null, gwaSetCommandType: gwaSetCommandType.Value);
                        }
                    }

                    traversedTypes.Add(t);
                }
            } while (currentBatch.Count > 0);

            var toBeAddedGwa = ((IGSACache)Initialiser.AppResources.Cache).GetNewGwaSetCommands();

            for (int i = 0; i < toBeAddedGwa.Count(); i++)
            {
                Initialiser.AppResources.Proxy.SetGwa(toBeAddedGwa[i]);
                try
                {
                    Initialiser.AppResources.Proxy.Sync();
                }
                catch (Exception ex)
                {
                    TestContext.WriteLine(ex);
                    return(false);
                }
            }
            return(true);
        }