Ejemplo n.º 1
0
        public MainWindow()
        {
            InitializeComponent();

            _alarmsListViewModel = new AlarmsListViewModel();
            MainAlarmListControl.MainDataGrid.ItemsSource = _alarmsListViewModel.Alarms;

            var contextParams = new CaseInsensitiveDictionary <string>();

            //contextParams.Add("SessionId", "ade2a090-d388-40ce-87fe-d5017cdf9c66");
            //contextParams.Add("UserName", "valpo");
            //contextParams.Add("UserRole", "TRAINEE");
            //contextParams.Add("WindowsUserName", "valpo");
            App.DataAccessProvider.Initialize(null, true, true, @"http://SRVEPKS01B:60080/SimcodeOpcNetServer/ServerDiscovery", "TestWpfApp", Environment.MachineName, "", contextParams);
            App.DataAccessProvider.EventMessagesCallback += XiDataAccessProviderOnEventMessagesCallback;
            App.DataAccessProvider.PropertyChanged       += DataAccessProviderOnPropertyChanged;
            XiDataAccessProviderOnConnectedOrDisconnected();

            _valueSubscription = new ValueSubscription(App.DataAccessProvider,
                                                       "/ASSETS/PI/PI_D1.PV",
                                                       (oldVst, newVst) =>
            {
                MainTextBlock.Text = newVst.Value.ValueAsString(true);
            });
        }
Ejemplo n.º 2
0
        public void AreAllElementsCorrectDataTypeShouldReturnInvalidContract()
        {
            var contractDictionary = SampleContractDictionary();

            var messageKeyDictionary = new CaseInsensitiveDictionary <object>
            {
                { "Name", "123" },
                { "Age", "NotANumber" },
                { "BigNumber", "NotANumber" },
                { "Id", "" },
                { "Birthday", "" }
            };

            var testerService = new TesterService();

            var result = testerService.DoAllMessageValuesMatchDataTypes(messageKeyDictionary, contractDictionary);

            result.IsMessageValid.ShouldBeFalse();
            result.MessageErrors.ShouldBe(new[]
            {
                "\"NotANumber\" does not match the required data type for Age (Integer).",
                "\"NotANumber\" does not match the required data type for BigNumber (Integer).",
                "\"\" does not match the required format for Id (Guid)."
            });
        }
Ejemplo n.º 3
0
        private Dictionary <string, List <string> > getFileSupercedances()
        {
            Mod.MEGame game = target.Game;
            //make dictionary from basegame files
            var fileListMapping = new CaseInsensitiveDictionary <List <string> >();
            var directories     = MELoadedFiles.GetEnabledDLC(target).OrderBy(dir => MELoadedFiles.GetMountPriority(dir, target.Game));

            foreach (string directory in directories)
            {
                var dlc = Path.GetFileName(directory);
                if (MEDirectories.OfficialDLC(target.Game).Contains(dlc))
                {
                    continue;                                                       //skip
                }
                foreach (string filePath in MELoadedFiles.GetCookedFiles(target.Game, directory, false))
                {
                    string fileName = Path.GetFileName(filePath);
                    if (fileName != null && fileName.RepresentsPackageFilePath())
                    {
                        if (fileListMapping.TryGetValue(fileName, out var supercedingList))
                        {
                            supercedingList.Insert(0, dlc);
                        }
                        else
                        {
                            fileListMapping[fileName] = new List <string>(new[] { dlc });
                        }
                    }
                }
            }

            return(fileListMapping);
        }
Ejemplo n.º 4
0
        public void ShouldValidateArrayType()
        {
            var contractDictionary = new CaseInsensitiveDictionary <SchemaObject>
            {
                { "Array", new SchemaObject
                  {
                      Type  = "Array",
                      Items = new SchemaObject()
                      {
                          Type = "Integer"
                      }
                  } }
            };

            var messageKeyDictionary = new CaseInsensitiveDictionary <object>
            {
                { "Array", "[\"134435\"]" }
            };

            var testerService = new TesterService();

            var result = testerService.DoAllMessageValuesMatchDataTypes(messageKeyDictionary, contractDictionary);

            result.IsMessageValid.ShouldBeTrue();
        }
Ejemplo n.º 5
0
    private void DiscoverBooks()
    {
        RawBooks = new CaseInsensitiveDictionary <Book>();

        // Make a list of all our content packs.
        var owned = Mod.Helper.ContentPacks.GetOwned().Select(cp => cp.Manifest.UniqueID);

        // Now scan every single mod.
        var mods = Mod.Helper.ModRegistry.GetAll();

        if (mods != null)
        {
            foreach (var mod in mods)
            {
                if (mod == null)
                {
                    continue;
                }

                DiscoverBooks(mod, owned.Contains(mod.Manifest.UniqueID));
            }
        }

        Log($"Discovered {RawBooks.Count} books in data files.", LogLevel.Debug);
    }
Ejemplo n.º 6
0
        public void ShouldPopulateReferencesDefinedSeparately()
        {
            var contractDictionary = new CaseInsensitiveDictionary <SchemaObject>
            {
                { "Contract", new SchemaObject {
                      Type = "Object"
                  } },
                { "Custom", new SchemaObject {
                      Type = "String", Example = "Custom example"
                  } }
            };

            contractDictionary["Contract"].Properties = new CaseInsensitiveDictionary <SchemaObject>
            {
                { "Test", new SchemaObject {
                      Reference = "#/Custom"
                  } },
            };

            var result = SchemaObject.PopulateReferences(contractDictionary);

            result.HasReferenceError.ShouldBeFalse();
            result.SchemaDictionary["Contract"].Properties["Test"].Type.ShouldBe("String");
            result.SchemaDictionary["Contract"].Properties["Test"].Example.ShouldBe("Custom example");
        }
Ejemplo n.º 7
0
        public void ShouldFailValidationForArrayTypeWithIncorrectItemType(string dataType, string format, string itemString)
        {
            var contractDictionary = new CaseInsensitiveDictionary <SchemaObject>
            {
                { "Array", new SchemaObject
                  {
                      Type  = "Array",
                      Items = new SchemaObject
                      {
                          Type   = dataType,
                          Format = format
                      }
                  } }
            };

            var messageKeyDictionary = new CaseInsensitiveDictionary <object>
            {
                { "Array", $"[\"{itemString}\"]" }
            };

            var testerService = new TesterService();

            var result = testerService.DoAllMessageValuesMatchDataTypes(messageKeyDictionary, contractDictionary);

            result.IsMessageValid.ShouldBeFalse();
            result.MessageErrors[0].ShouldBe($"An item in the Items array for Array does not match the required data type ({format ?? dataType}).");
        }
Ejemplo n.º 8
0
        public void ShouldFailValidationForArrayTypeWithLessThanMinItems()
        {
            var contractDictionary = new CaseInsensitiveDictionary <SchemaObject>
            {
                { "Array", new SchemaObject
                  {
                      Type  = "Array",
                      Items = new SchemaObject()
                      {
                          Type = "Integer"
                      },
                      MinItems = 2
                  } }
            };

            var messageKeyDictionary = new CaseInsensitiveDictionary <object>
            {
                { "Array", "[\"1\"]" }
            };

            var testerService = new TesterService();

            var result = testerService.DoAllMessageValuesMatchDataTypes(messageKeyDictionary, contractDictionary);

            result.IsMessageValid.ShouldBeFalse();
            result.MessageErrors[0].ShouldBe("The Items array for Array does not have the minimum number (2) of items required.");
        }
Ejemplo n.º 9
0
        public void AreAllElementsInContractContainedInMessageShouldReturnValidContract()
        {
            var contractDictionary = new CaseInsensitiveDictionary <SchemaObject>
            {
                { "Name", new SchemaObject
                  {
                      Type = "String"
                  } },
                { "Age", new SchemaObject
                  {
                      Type = "Integer"
                  } }
            };

            var messageKeyDictionary = new CaseInsensitiveDictionary <object>
            {
                { "Name", "Robert" },
                { "Age", "31" }
            };

            var testService = new TesterService();

            var result = testService.AreAllElementsInContractContainedInMessage(messageKeyDictionary, contractDictionary);

            result.IsMessageValid.ShouldBeTrue();
        }
Ejemplo n.º 10
0
        public void GeneratesProperObjectSampleData()
        {
            var propertyDictionary = new CaseInsensitiveDictionary <SchemaObject>();

            propertyDictionary.Add("IntegerProp", new SchemaObject()
            {
                Type = DataType.Integer.Value
            });
            propertyDictionary.Add("StringProp", new SchemaObject()
            {
                Type = DataType.String.Value
            });
            propertyDictionary.Add("ObjectProp", new SchemaObject()
            {
                Type       = DataType.Object.Value,
                Properties = new CaseInsensitiveDictionary <SchemaObject>()
                {
                    {
                        "InnerProp", new SchemaObject()
                        {
                            Type = DataType.Integer.Value
                        }
                    }
                }
            });

            var objectString = SampleData.GenerateSampleData(DataType.Object, null, properties: propertyDictionary);

            objectString = objectString.Replace("\"\"", "\"");
            objectString.ShouldBe("{\"IntegerProp\":\"30\",\"StringProp\":\"String text\",\"ObjectProp\":{\"InnerProp\":\"30\"}}");
        }
Ejemplo n.º 11
0
        private void CheckObjectType(SchemaObject propertySchemaObject, KeyValuePair <string, object> kv,
                                     TestMessageResult testMessageResult, bool allowSubset)
        {
            CaseInsensitiveDictionary <object> innerObject = null;

            try
            {
                var json = JsonConvert.SerializeObject(kv.Value);
                innerObject = JsonConvert.DeserializeObject <CaseInsensitiveDictionary <object> >(json);
            }
            catch (Exception)
            {
                AddTypeError(testMessageResult, kv.Value.ToString(), kv.Key, "Object");
            }
            if (propertySchemaObject.Properties != null)
            {
                foreach (var innerProperty in propertySchemaObject.Properties)
                {
                    if (innerObject != null && innerObject.ContainsKey(innerProperty.Key))
                    {
                        ChecksForMessage(innerProperty.Value,
                                         new KeyValuePair <string, object>($"{kv.Key}{ParentOfSymbol}{innerProperty.Key}",
                                                                           innerObject[innerProperty.Key]), testMessageResult, allowSubset);
                    }
                    else
                    {
                        if (!allowSubset)
                        {
                            AddNotFoundError(testMessageResult, $"{kv.Key}{ParentOfSymbol}{innerProperty.Key}");
                        }
                    }
                }
            }
        }
Ejemplo n.º 12
0
            public bool Validate(string dlcName, GameTarget target, CaseInsensitiveDictionary <string> loadedFiles)
            {
                foreach (var outfit in Outfits)
                {
                    // Check packages
                    if (!loadedFiles.ContainsKey($@"{outfit.HenchPackage}.pcc"))
                    {
                        Log.Error($@"SquadmateMergeInfo failed validation: {outfit.HenchPackage}.pcc not found in game");
                        return(false);
                    }

                    if (Game.IsGame3())
                    {
                        if (!loadedFiles.ContainsKey($@"{outfit.HenchPackage}_Explore.pcc"))
                        {
                            Log.Error($@"SquadmateMergeInfo failed validation: {outfit.HenchPackage}_Explore.pcc not found in game");
                            return(false);
                        }
                    }

                    if (!loadedFiles.ContainsKey($@"SFXHenchImages_{dlcName}.pcc"))
                    {
                        Log.Error($@"SquadmateMergeInfo failed validation: SFXHenchImages_{dlcName}.pcc not found in game");
                        return(false);
                    }
                }

                return(true);
            }
Ejemplo n.º 13
0
        public void ExtractToFolder(string outputfolder)
        {
            // scripts and assets
            foreach (var mc in FilesToMergeInto.SelectMany(x => x.MergeChanges))
            {
                if (mc.ScriptUpdate != null)
                {
                    File.WriteAllText(Path.Combine(outputfolder, Path.GetFileName(mc.ScriptUpdate.ScriptFileName)), mc.ScriptUpdate.ScriptText);
                    mc.ScriptUpdate.ScriptText = null;
                }

                if (mc.AssetUpdate != null)
                {
                    File.WriteAllBytes(Path.Combine(outputfolder, Path.GetFileName(mc.AssetUpdate.AssetName)), Assets[mc.AssetUpdate.AssetName].AssetBinary);
                }
            }

            // assets
            Assets = null;

            // json
            File.WriteAllText(Path.Combine(outputfolder, $@"{Path.GetFileNameWithoutExtension(MergeModFilename)}.json"),
                              JsonConvert.SerializeObject(this, Formatting.Indented, new JsonSerializerSettings
            {
                NullValueHandling    = NullValueHandling.Ignore,
                DefaultValueHandling = DefaultValueHandling.Ignore
            }));
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Gets a list of superceding package files from the DLC of the game. Only files in DLC mods are returned
        /// </summary>
        /// <param name="target">Target to get supercedances for</param>
        /// <returns>Dictionary mapping filename to list of DLCs that contain that file, in order of highest priority to lowest</returns>
        public static Dictionary <string, List <string> > GetFileSupercedances(GameTarget target, string[] additionalExtensionsToInclude = null)
        {
            //make dictionary from basegame files
            var fileListMapping = new CaseInsensitiveDictionary <List <string> >();
            var directories     = MELoadedFiles.GetEnabledDLCFolders(target.Game, target.TargetPath).OrderBy(dir => MELoadedFiles.GetMountPriority(dir, target.Game)).ToList();

            foreach (string directory in directories)
            {
                var dlc = Path.GetFileName(directory);
                if (MEDirectories.OfficialDLC(target.Game).Contains(dlc))
                {
                    continue;                                                       //skip
                }
                foreach (string filePath in MELoadedFiles.GetCookedFiles(target.Game, directory, false, additionalExtensions: additionalExtensionsToInclude))
                {
                    string fileName = Path.GetFileName(filePath);
                    if (fileName != null && fileName.RepresentsPackageFilePath() || (additionalExtensionsToInclude != null && additionalExtensionsToInclude.Contains(Path.GetExtension(fileName))))
                    {
                        if (fileListMapping.TryGetValue(fileName, out var supercedingList))
                        {
                            supercedingList.Insert(0, dlc);
                        }
                        else
                        {
                            fileListMapping[fileName] = new List <string>(new[] { dlc });
                        }
                    }
                }
            }

            return(fileListMapping);
        }
        private static NameWrapper AddNameToUniqueStrings(string name, Dictionary <string, string> dontShortenStrings,
                                                          CaseInsensitiveDictionary <StringWrapper> uniqueStrings)
        {
            NameWrapper nameWrapper = new NameWrapper();

            List <string> nameStrings = StringUtils.SplitAndReallyRemoveEmptyEntries(name, Utils.NAME_SEPARATOR, StringComparison.OrdinalIgnoreCase);

            foreach (string nameString in nameStrings)
            {
                bool          canShorten = !dontShortenStrings.ContainsKey(nameString);
                StringWrapper stringWrapper;
                if (uniqueStrings.TryGetValue(nameString, out stringWrapper))
                {
                    DebugUtils.AssertDebuggerBreak(stringWrapper.CanShorten == canShorten);
                }
                else
                {
                    stringWrapper = new StringWrapper(nameString, canShorten);
                    uniqueStrings.Add(nameString, stringWrapper);
                }
                nameWrapper.AddString(stringWrapper);
            }

            return(nameWrapper);
        }
Ejemplo n.º 16
0
        public PythonFormatter()
        {
            Interpreter = Python.CreateEngine();
            Locals      = new CaseInsensitiveDictionary <object>();

            //_engine.Sys.setdefaultencodingImpl((object)Encoding.Default.HeaderName);
            //Locals["a"] = (object)new PythonFormatter._Void<object>(this._A);
            //Locals["apf"] = (object)new PythonFormatter._Void<object, MarcField, string>(this._APF);
            //Locals["aps"] = (object)new PythonFormatter._Void<object, object, object>(this._APS);
            //Locals["apsf"] = (object)new PythonFormatter._Void<object, MarcField, string, object>(this._APSF);
            //Locals["asf"] = (object)new PythonFormatter._Void<MarcField, string>(this._ASF);
            //Locals["ca"] = (object)new PythonFormatter._Void<bool, object, object>(this._CA);
            //Locals["fm"] = (object)new Func<string, string>(this._FM);
            //Locals["fma"] = (object)new Func<string, string[]>(this._FMA);
            //Locals["iif"] = (object)new Func<object, object, object>(this._IIF);
            //Locals["gf"] = (object)new Func<string, MarcField>(this._GF);
            //Locals["gfa"] = (object)new Func<string, MarcField[]>(this._GFA);
            //Locals["nl"] = (object)new PythonFormatter._Void(this._NL);
            //Locals["p"] = (object)new Func<string, bool>(this._P);
            //Locals["pf"] = (object)new Func<string, MarcField, string, string>(this._PF);
            //Locals["ps"] = (object)new Func<MarcField, string, bool>(this._PS);
            //Locals["sf"] = (object)new Func<MarcField, string, string>(this._SF);
            //Locals["v"] = (object)new PythonFormatter._Void<string>(this._V);
            //Locals["va"] = (object)new PythonFormatter._Void<string, string>(this._VA);
            //Locals["vl"] = (object)new PythonFormatter._Void<string>(this._VL);
            //Locals["vla"] = (object)new PythonFormatter._Void<string, string>(this._VLA);
        }
Ejemplo n.º 17
0
        public static CaseInsensitiveDictionary <SchemaObject> BuildSchemaDictionary <T>(string contractString, Func <T> handleRefError, Func <T> handleFailure)
        {
            var schemaDictionary = new CaseInsensitiveDictionary <SchemaObject>();

            try
            {
                var schemaObject = (JsonObject)JsonValue.Parse(contractString);
                foreach (var key in schemaObject.Keys)
                {
                    var contractObjectString = schemaObject[key].ToString();
                    var contractObject       = ConvertJsonToSchema(contractObjectString);
                    schemaDictionary.Add(key, contractObject);
                }

                if (schemaDictionary["Contract"].Properties.Any(p => p.Value.Reference != null))
                { // References are used in the schema, so populate them
                    var populatedDictionary = PopulateReferences(schemaDictionary);
                    if (populatedDictionary.HasReferenceError)
                    {
                        handleRefError();
                    }
                    schemaDictionary = populatedDictionary.SchemaDictionary;
                }
            }
            catch
            {
                handleFailure();
            }

            return(schemaDictionary);
        }
Ejemplo n.º 18
0
        public void ShouldFailValidationForNonArrayType()
        {
            var contractDictionary = new CaseInsensitiveDictionary <SchemaObject>
            {
                { "TestArray", new SchemaObject
                  {
                      Type  = "Array",
                      Items = new SchemaObject()
                      {
                          Type = "Integer"
                      },
                  } }
            };

            var messageKeyDictionary = new CaseInsensitiveDictionary <object>
            {
                { "TestArray", "123" }
            };

            var testerService = new TesterService();

            var result = testerService.DoAllMessageValuesMatchDataTypes(messageKeyDictionary, contractDictionary);

            result.IsMessageValid.ShouldBeFalse();
            result.MessageErrors[0].ShouldBe("\"123\" does not match the required data type for TestArray (array).");
        }
Ejemplo n.º 19
0
        public static Dictionary <string, CaseInsensitiveDictionary <ThirdPartyServices.ThirdPartyModInfo> > FetchThirdPartyIdentificationManifest(bool overrideThrottling = false)
        {
            if (!File.Exists(Utilities.GetThirdPartyIdentificationCachedFile()) || (!overrideThrottling && Utilities.CanFetchContentThrottleCheck()))
            {
                try
                {
                    using var wc = new System.Net.WebClient();

                    string json = wc.DownloadStringAwareOfEncoding(ThirdPartyIdentificationServiceURL);
                    File.WriteAllText(Utilities.GetThirdPartyIdentificationCachedFile(), json);
                    return(JsonConvert.DeserializeObject <Dictionary <string, CaseInsensitiveDictionary <ThirdPartyServices.ThirdPartyModInfo> > >(json));
                }
                catch (Exception e)
                {
                    //Unable to fetch latest help.
                    Log.Error("Error fetching online third party identification service: " + e.Message);

                    if (File.Exists(Utilities.GetThirdPartyIdentificationCachedFile()))
                    {
                        Log.Warning("Using cached third party identification service instead");
                        return(JsonConvert.DeserializeObject <Dictionary <string, CaseInsensitiveDictionary <ThirdPartyServices.ThirdPartyModInfo> > >(File.ReadAllText(Utilities.GetThirdPartyIdentificationCachedFile())));
                    }
                    else
                    {
                        Log.Error("Unable to load third party identification service and local file doesn't exist. Returning a blank copy.");
                        Dictionary <string, CaseInsensitiveDictionary <ThirdPartyServices.ThirdPartyModInfo> > d = new Dictionary <string, CaseInsensitiveDictionary <ThirdPartyServices.ThirdPartyModInfo> >();
                        d["ME1"] = new CaseInsensitiveDictionary <ThirdPartyServices.ThirdPartyModInfo>();
                        d["ME2"] = new CaseInsensitiveDictionary <ThirdPartyServices.ThirdPartyModInfo>();
                        d["ME3"] = new CaseInsensitiveDictionary <ThirdPartyServices.ThirdPartyModInfo>();
                        return(d);
                    }
                }
            }
            return(JsonConvert.DeserializeObject <Dictionary <string, CaseInsensitiveDictionary <ThirdPartyServices.ThirdPartyModInfo> > >(File.ReadAllText(Utilities.GetThirdPartyIdentificationCachedFile())));
        }
Ejemplo n.º 20
0
 /// <summary>
 /// Initializes a new instance of the
 /// <see cref="IrbisStopWords"/> class.
 /// </summary>
 /// <param name="fileName">The name.</param>
 public IrbisStopWords
 (
     [CanBeNull] string fileName
 )
 {
     FileName    = fileName;
     _dictionary = new CaseInsensitiveDictionary <object>();
 }
Ejemplo n.º 21
0
        private static void BuildDisplayText(CaseInsensitiveDictionary <SchemaObject> properties, bool fullDetails, int depth = 0)
        {
            foreach (var property in properties)
            {
                var dataType  = property.Value.GetDataType();
                var format    = property.Value.Format;
                var reference = property.Value.Reference;
                var pattern   = property.Value.Pattern;

                if (pattern != null && fullDetails)
                {
                    if (format != null || reference != null)
                    {
                        pattern = $"; Pattern: {pattern}";
                    }
                    else
                    {
                        pattern = $"Pattern: {pattern}";
                    }
                }
                else
                {
                    pattern = "";
                }

                string displayText;
                if (dataType == DataType.Array)
                {
                    var itemsSchema = property.Value.Items;
                    var itemsType   = new[]
                    {
                        itemsSchema.Reference?.ToLower(), itemsSchema.Format, itemsSchema.Type
                    }.First(x => !string.IsNullOrWhiteSpace(x));

                    displayText = $"<span class='contract-display-row' style='--depth:{depth};'><em>{property.Key}</em> - {dataType.Value} ({itemsType})<br></span>";
                    _displayContractRows.Add(displayText);

                    if (itemsSchema.GetDataType() == DataType.Object)
                    {
                        BuildDisplayText(itemsSchema.Properties, fullDetails, depth + 1);
                    }
                }
                else if (dataType == DataType.Object)
                {
                    displayText = $"<span class='contract-display-row' style='--depth:{depth};'><em>{property.Key}</em> - {dataType.Value}<br></span>";
                    _displayContractRows.Add(displayText);
                    BuildDisplayText(property.Value.Properties, fullDetails, depth + 1);
                }
                else
                {
                    var displayModifier = format != null || reference != null || pattern != "";
                    var modifier        = displayModifier ? $" ({format}{reference}{pattern})" : "";
                    displayText = $"<span class='contract-display-row' style='--depth:{depth};'><em>{property.Key}</em> - {dataType.Value}{modifier}<br></span>";
                    _displayContractRows.Add(displayText);
                }
            }
        }
Ejemplo n.º 22
0
        /// <summary>
        ///A test for Remove
        ///</summary>
        public void RemoveTestHelper <TValue>()
        {
            var    target = new CaseInsensitiveDictionary <TValue>();
            var    key    = "a";
            TValue value  = default(TValue);

            target.Add(key, value);
            target.Remove(key);
            Assert.IsFalse(((Dictionary <string, TValue>)target).ContainsKey(key));
        }
Ejemplo n.º 23
0
            private static string GetExample(CaseInsensitiveDictionary <SchemaObject> schemaDictionary, SchemaObject schemaObject)
            {
                string sampleString;
                string referenceKey = null;
                var    dataType     = schemaObject.GetDataType();

                if (!string.IsNullOrEmpty(schemaObject.Reference))
                {
                    referenceKey = schemaObject.Reference.Replace(@"#/", "");
                }

                // use the Example as the sample data if given
                if (dataType == DataType.Object)
                {
                    sampleString = GenerateSampleString(schemaDictionary, schemaObject.Properties);
                }
                else if (schemaObject.Example != null)
                {
                    if (dataType == DataType.String && schemaObject.GetFormat() == Format.DateTime)
                    {
                        var date = (DateTime)schemaObject.Example;
                        sampleString = $"\"{date:yyyy-MM-ddTHH:mm:ssZ}\"";
                    }
                    else if (dataType == DataType.Array)
                    {
                        var arrayExample = schemaObject.Example.ToString().Replace(Environment.NewLine, "");
                        if (schemaObject.Example.ToString()[0] != '[') // example of a single item instead of a list
                        {
                            arrayExample = $"[{arrayExample}]";
                        }

                        sampleString = arrayExample;
                    }
                    else if (dataType == DataType.String)
                    {
                        sampleString = $"\"{schemaObject.Example}\"";
                    }
                    else
                    {
                        sampleString = schemaObject.Example.ToString();
                    }
                }
                else if (!string.IsNullOrEmpty(referenceKey) && schemaDictionary[referenceKey].Example != null)
                {
                    sampleString = $"\"{schemaDictionary[referenceKey].Example}\"";
                }
                else
                {
                    var sampleValue = GenerateSampleData(schemaObject.GetDataType(), schemaObject.GetFormat(), schemaObject.Pattern, schemaObject.Properties,
                                                         schemaObject.Items, schemaObject.MinItems, schemaObject.MaxItems);
                    sampleString = sampleValue;
                }

                return(sampleString);
            }
Ejemplo n.º 24
0
        /// <summary>
        /// Loads the metadata (mappings, types, etc) for this DataModel.
        /// </summary>
        /// <param name="type"></param>
        private void PreInitialize(Type type)
        {
            InnerData         = new CaseInsensitiveDictionary <object>();
            EntityMappings    = GetMapping(type);
            ColumnMappedValue = new ColumnMappedValueProperty(this, EntityMappings);
            Convert           = new DataModelConverter(this);

            DataChanging      += DataModel_DataChanging;
            DataChanged       += DataModel_DataChanged;
            ModifiedProperties = new CaseInsensitiveStringList();
        }
Ejemplo n.º 25
0
        /// <summary>
        ///A test for ContainsKey
        ///</summary>
        public void ContainsKeyTestHelper <TValue>()
        {
            var    target = new CaseInsensitiveDictionary <TValue>();
            string key    = "a";

            target.Add(key, default(TValue));
            bool actual;

            actual = target.ContainsKey(key);
            Assert.IsTrue(actual);
        }
        public void AccessingCaseInsensitiveDictionaryItem_ConstructedFromExistingDictionary_ReturnsAppropriateValue()
        {
            var dictionary = new Dictionary <string, string>()
            {
                { "KEY1", "Value1" },
            };

            var caseInsensitiveDictionary = new CaseInsensitiveDictionary <string>(dictionary);

            Assert.AreEqual("Value1", caseInsensitiveDictionary["key1"]);
        }
        private static CaseInsensitiveDictionary <StringWrapper> GetUniqueStrings(IDictionary <string, Table> tables, List <KeyValuePair <string, string> > nameReplacements,
                                                                                  out Dictionary <Table, NameWrapper> tableNames,
                                                                                  out Dictionary <Column, NameWrapper> columnNames)
        {
            Dictionary <string, string> dontShortenStrings;

            if (nameReplacements == null)
            {
                dontShortenStrings = new Dictionary <string, string>();
            }
            else
            {
                dontShortenStrings = new Dictionary <string, string>(nameReplacements.Count);
                foreach (KeyValuePair <string, string> pair in nameReplacements)
                {
                    dontShortenStrings[pair.Value] = pair.Value;
                }
            }

            CaseInsensitiveDictionary <StringWrapper> uniqueStrings = new CaseInsensitiveDictionary <StringWrapper>();

            tableNames  = new Dictionary <Table, NameWrapper>();
            columnNames = new Dictionary <Column, NameWrapper>();

            foreach (Table table in tables.Values)
            {
                if (!string.IsNullOrEmpty(table.TableNamePrefix))
                {
                    List <string> nameStrings = StringUtils.SplitAndReallyRemoveEmptyEntries(table.TableNamePrefix, Utils.NAME_SEPARATOR,
                                                                                             StringComparison.OrdinalIgnoreCase);

                    foreach (string nameString in nameStrings)
                    {
                        dontShortenStrings[nameString] = nameString;
                    }
                }
            }
            foreach (Table table in tables.Values)
            {
                NameWrapper nameWrapper = AddNameToUniqueStrings(table.TableName, dontShortenStrings, uniqueStrings);
                tableNames.Add(table, nameWrapper);

                foreach (Column column in table.AllColumns)
                {
                    if (!column.IsPrimaryKey && !column.IsForeignKey)
                    {
                        nameWrapper = AddNameToUniqueStrings(column.ColumnName, dontShortenStrings, uniqueStrings);
                        columnNames.Add(column, nameWrapper);
                    }
                }
            }

            return(uniqueStrings);
        }
Ejemplo n.º 28
0
        /// <summary>
        ///     You can set updateValueItems = false and invoke PollElementValuesChangesAsync(...) manually.
        /// </summary>
        /// <param name="elementIdsMap"></param>
        /// <param name="elementValueListCallbackIsEnabled"></param>
        /// <param name="eventListCallbackIsEnabled"></param>
        /// <param name="serverAddress"></param>
        /// <param name="clientApplicationName"></param>
        /// <param name="clientWorkstationName"></param>
        /// <param name="systemNameToConnect"></param>
        /// <param name="contextParams"></param>
        public void Initialize(ElementIdsMap?elementIdsMap,
                               bool elementValueListCallbackIsEnabled,
                               bool eventListCallbackIsEnabled,
                               string serverAddress,
                               string clientApplicationName, string clientWorkstationName, string systemNameToConnect, CaseInsensitiveDictionary <string> contextParams)
        {
            Close();

            //Logger?.LogDebug("Starting ModelDataProvider. сallbackDoer is not null " + (сallbackDispatcher is not null).ToString());

            _elementValueListCallbackIsEnabled = elementValueListCallbackIsEnabled;
            _eventListCallbackIsEnabled        = eventListCallbackIsEnabled;
            _serverAddress                          = serverAddress;
            _systemNameToConnect                    = systemNameToConnect;
            _xiDataListItemsManager.XiSystem        = _systemNameToConnect;
            _xiEventListItemsManager.XiSystem       = _systemNameToConnect;
            _xiDataJournalListItemsManager.XiSystem = _systemNameToConnect;
            _clientApplicationName                  = clientApplicationName;
            _clientWorkstationName                  = clientWorkstationName;
            _contextParams                          = contextParams;

            _lastSuccessfulConnectionDateTimeUtc = DateTime.UtcNow;

            //string pollIntervalMsString =
            //    ConfigurationManager.AppSettings["PollIntervalMs"];
            //if (!String.IsNullOrWhiteSpace(pollIntervalMsString) &&
            //    Int32.TryParse(pollIntervalMsString, out int pollIntervalMs))
            //{
            //    _pollIntervalMs = pollIntervalMs;
            //}
            _pollIntervalMs = 1000;

            _cancellationTokenSource = new CancellationTokenSource();
            var cancellationToken = _cancellationTokenSource.Token;

            var previousWorkingTask = _workingTask;

            _workingTask = Task.Factory.StartNew(() =>
            {
                if (previousWorkingTask is not null)
                {
                    previousWorkingTask.Wait();
                }
                WorkingTaskMainAsync(cancellationToken).Wait();
            }, TaskCreationOptions.LongRunning);

            IsInitialized = true;

            foreach (ValueSubscriptionObj valueSubscriptionObj in _valueSubscriptionsCollection.Values)
            {
                valueSubscriptionObj.ValueSubscription.MappedElementIdOrConst = AddItem(valueSubscriptionObj);
            }
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="serverAddress"></param>
        /// <param name="clientApplicationName"></param>
        /// <param name="clientWorkstationName"></param>
        /// <param name="systemNameToConnect"></param>
        /// <param name="contextParams"></param>
        public void InitiateConnection(string serverAddress,
                                       string clientApplicationName,
                                       string clientWorkstationName,
                                       string systemNameToConnect,
                                       CaseInsensitiveDictionary <string> contextParams)
        {
            if (_disposed)
            {
                throw new ObjectDisposedException(@"Cannot access a disposed DataGrpcServerProxy.");
            }

            if (_connectionInfo is not null)
            {
                throw new Exception(@"DataGrpc context already exists.");
            }

#if DEBUG
            TimeSpan requestedServerContextTimeoutMs = new TimeSpan(0, 30, 0);
#else
            TimeSpan requestedServerContextTimeoutMs = new TimeSpan(0, 0, 30);
#endif
            GrpcChannel?grpcChannel = null;
            try
            {
                grpcChannel = GrpcChannel.ForAddress(serverAddress);

                var resourceManagementClient = new DataAccess.DataAccessClient(grpcChannel);

                var clientContext = new ClientContext(_logger,
                                                      _callbackDispatcher,
                                                      resourceManagementClient,
                                                      clientApplicationName,
                                                      clientWorkstationName,
                                                      (uint)requestedServerContextTimeoutMs.TotalMilliseconds,
                                                      CultureInfo.CurrentUICulture.Name,
                                                      systemNameToConnect,
                                                      contextParams
                                                      );

                _connectionInfo = new ConnectionInfo(grpcChannel, resourceManagementClient, clientContext);
            }
            catch
            {
                if (grpcChannel is not null)
                {
                    grpcChannel.Dispose();
                }
                throw;
            }

            _connectionInfo.ClientContext.ContextNotifyEvent += ClientContextOnContextNotifyEvent;
        }
Ejemplo n.º 30
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="logger"></param>
        /// <param name="resourceManagementClient"></param>
        /// <param name="clientApplicationName"></param>
        /// <param name="clientWorkstationName"></param>
        /// <param name="requestedServerContextTimeoutMs"></param>
        /// <param name="requestedServerCultureName"></param>
        /// <param name="systemNameToConnect"></param>
        /// <param name="contextParams"></param>
        public ClientContext(ILogger <GrpcDataAccessProvider> logger,
                             IDispatcher callbackDispatcher,
                             DataAccess.DataAccessClient resourceManagementClient,
                             string clientApplicationName,
                             string clientWorkstationName,
                             uint requestedServerContextTimeoutMs,
                             string requestedServerCultureName,
                             string systemNameToConnect,
                             CaseInsensitiveDictionary <string> contextParams)
        {
            _logger                   = logger;
            _callbackDispatcher       = callbackDispatcher;
            _resourceManagementClient = resourceManagementClient;
            _applicationName          = clientApplicationName;
            _workstationName          = clientWorkstationName;

            var initiateRequest = new InitiateRequest
            {
                ClientApplicationName           = clientApplicationName,
                ClientWorkstationName           = clientWorkstationName,
                RequestedServerContextTimeoutMs = requestedServerContextTimeoutMs,
                RequestedServerCultureName      = requestedServerCultureName,
            };

            initiateRequest.SystemNameToConnect = systemNameToConnect;
            initiateRequest.ContextParams.Add(contextParams);

            InitiateReply initiateReply = _resourceManagementClient.Initiate(initiateRequest);

            _serverContextId        = initiateReply.ContextId;
            _serverContextTimeoutMs = initiateReply.ServerContextTimeoutMs;
            _serverCultureName      = initiateReply.ServerCultureName;

            if (_serverContextId == @"")
            {
                throw new Exception("Server returns empty contextId.");
            }

            SetResourceManagementLastCallUtc();

            _callbackMessageStream = resourceManagementClient.SubscribeForCallback(new SubscribeForCallbackRequest
            {
                ContextId = _serverContextId
            });

            _serverContextIsOperational = true;

            Task.Factory.StartNew(() =>
            {
                ReadCallbackMessagesAsync(_callbackMessageStream.ResponseStream, _cancellationTokenSource.Token).Wait();
            }, TaskCreationOptions.LongRunning);
        }