Пример #1
0
        public void GetHorseFromJsonFileNotExcetpion()
        {
            var    strategy = new XmlFileParser();
            string path     = "TestData/xyz.json";

            Assert.Throws <FileNotFoundException>(() => strategy.GetParticipantHorses(path));
        }
Пример #2
0
        protected override IMemberAttribute ParserMember(string typeFullName, XmlNode memberNode)
        {
            if (string.IsNullOrEmpty(typeFullName))
            {
                throw new ArgumentNullException("typeFullName");
            }

            object target = MemberCache.Get(typeFullName);

            if (null == target)
            {
                throw new Exception(string.Format("the member cache is null for {0} type.", typeFullName));
            }
            var    members = (IDictionary <string, IMemberAttribute>)target;
            object name;

            XmlFileParser.TryGetAttributeValue(memberNode, "Name", out name);
            if (null == name)
            {
                throw new Exception("there is no name in the member config item.");
            }
            IMemberAttribute member = members[name.ToString()];

            member = members[member.Name] = GenerateMember(member, memberNode);
            MemberCache.InsertOrUpdate(typeFullName, members);
            return(member);
        }
Пример #3
0
        public bool DisplayHorsesFromFile(string path)
        {
            //TODO: Use Factory pattern
            foreach (string file in Directory.GetFiles(path))
            {
                var        fileExtension = Path.GetExtension(file).ToLower();
                FileParser fileParse     = null;
                if (fileExtension == ".xml")
                {
                    fileParse = new XmlFileParser();
                }
                else if (fileExtension == ".json")
                {
                    fileParse = new JsonFileParser();
                }

                if (fileParse != null)
                {
                    var horses = fileParse.GetRacingHorses(file);
                    Console.WriteLine("Race Name is {0}", fileParse.RaceName);
                    fileParse.DisplayHorsesInOrder(horses);
                }
                else
                {
                    return(false);
                }
            }

            return(true);
        }
Пример #4
0
        public void GetHorseDetails_Fail_Case1()
        {
            var    fileParser = new XmlFileParser();
            string path       = "TestData/DoesNotExist.json";

            Assert.Throws <FileNotFoundException>(() => fileParser.GetHorseDetails(path));
        }
        public void GivenNullFilePath_WhenGetHorsesCalled_ThenReturnEmptyList()
        {
            var xmlFileParser = new XmlFileParser();
            var horses        = xmlFileParser.GetHorses(null);

            Assert.True(horses.Count() == 0);
        }
Пример #6
0
        public ModuleContainer[] getModules()
        {
            XmlFileParser parser  = new XmlFileParser(this.FullDirectoryPath);
            var           modules = parser.GetModulesFromXml();

            return(modules);
        }
Пример #7
0
        public void GetHorses_FromXmlFile_FileNotFoundException()
        {
            var    fileParser = new XmlFileParser();
            string path       = "TestData/DoesNotExist.xml";

            Assert.Throws <FileNotFoundException>(() => fileParser.GetHorseDetails(path));
        }
Пример #8
0
        public async Task ShouldParseJsonFileSuccessfully()
        {
            //Arrange
            var appConfig = new AppConfig {
                JsonFilePath = "FeedData\\Wolferhampton_Race1.json", XmlFilePath = "FeedData\\Caulfield_Race1.xml"
            };
            var IOptionsMock = Options.Create(appConfig);

            var loggerMock = new Mock <ILogger <XmlFileParser> >();

            var xmlFileParser = new XmlFileParser(IOptionsMock, loggerMock.Object);

            //Act
            var horses = await xmlFileParser.ParseAsync();

            Horse horse1 = horses.First();
            Horse horse2 = horses.Skip(1).First();

            //Assert
            Assert.True(horses.Count() == 2);
            Assert.True(horse1.Name == "Advancing" &&
                        horse1.Price == 4.2m);

            Assert.True(horse2.Name == "Coronel" &&
                        horse2.Price == 12m);
        }
Пример #9
0
        public void GetHorseFromXmlFileNotExcetpion()
        {
            var    xmlFileParser = new XmlFileParser();
            string path          = "TestData/xyz.xml";

            Assert.Throws <FileNotFoundException>(() => xmlFileParser.GetParticipantHorses(path));
        }
        public void GivenXMLFilePath_WhenGetHorsesCalled_ThenReturnListOfHorses()
        {
            var xmlFileParser = new XmlFileParser();
            var horses        = xmlFileParser.GetHorses(@"TestData\Caulfield_Race1.xml");

            Assert.NotNull(horses);
            Assert.True(horses.Count() > 0);
        }
Пример #11
0
        public void GetHorseDetails_Success_Case1()
        {
            var    fileParser = new XmlFileParser();
            string path       = "TestData/Caulfield_Race1.xml";
            var    horses     = fileParser.GetHorseDetails(path);

            Assert.NotNull(horses);
            Assert.True(horses.Count > 0);
        }
Пример #12
0
        public void GetHorseDetails_Fail_Case1()
        {
            var    fileParser = new XmlFileParser();
            string path       = "TestData/IncompleXml.xml";
            var    horses     = fileParser.GetHorseDetails(path);

            Assert.NotNull(horses);
            Assert.True(horses.Count == 0);
        }
Пример #13
0
        public void GetHorseFromXmlFile()
        {
            var    xmlFileParser = new XmlFileParser();
            string path          = "TestData/Caulfield_Race1.xml";
            var    horses        = xmlFileParser.GetParticipantHorses(path);

            Assert.NotNull(horses);
            Assert.True(horses.Count > 0);
        }
Пример #14
0
        protected override IObjectAttribute ParserObject(XmlNode entityNode)
        {
            object imp;

            if (!XmlFileParser.TryGetAttributeValue(entityNode, "Implement", out imp))
            {
                throw new Exception("The implement config item is empty or null in Persistence.config");
            }
            object itf;

            if (!XmlFileParser.TryGetAttributeValue(entityNode, "Interface", out itf))
            {
                throw new Exception("The interface config item is empty or null in Persistence.config");
            }
            IObjectAttribute obj = new AlbianObjectAttribute
            {
                Implement = imp.ToString(),
                Interface = itf.ToString()
            };

            //反射解析实体类中属性
            string         defaultTableName;
            IReflectMember reflectMember = new ReflectMember();

            obj.MemberAttributes = reflectMember.ReflectMembers(obj.Implement, out defaultTableName);

            if (string.IsNullOrEmpty(defaultTableName))
            {
                throw new Exception("parser the defaultTableName is error.");
            }
            obj.RoutingAttributes = ParserRoutings(defaultTableName, entityNode.SelectNodes("Routings/Routing"));
            obj.MemberAttributes  = ParserMembers(obj.Implement, entityNode.SelectNodes("Members/Member"));
            obj.Cache             = ParserCache(entityNode.SelectSingleNode("Cache"));
            IDictionary <string, IMemberAttribute> pks = new Dictionary <string, IMemberAttribute>();

            foreach (var member in obj.MemberAttributes)
            {
                if (member.Value.PrimaryKey)
                {
                    pks.Add(member.Value.Name, member.Value);
                }
            }

            if (0 < pks.Count)
            {
                obj.PrimaryKeys = pks;
            }
            ObjectCache.InsertOrUpdate(obj.Implement, obj);
            return(obj);
        }
Пример #15
0
        public async Task ShouldParseXmlFileWithAnException()
        {
            //Arrange
            var appConfig = new AppConfig {
                JsonFilePath = "", XmlFilePath = ""
            };
            var IOptionsMock = Options.Create(appConfig);

            var loggerMock = new Mock <ILogger <XmlFileParser> >();

            var xmlFileParser = new XmlFileParser(IOptionsMock, loggerMock.Object);

            //Act and Assert
            await Assert.ThrowsAsync <DirectoryNotFoundException>(() => xmlFileParser.ParseAsync());
        }
Пример #16
0
        protected override IRoutingAttribute ParserRouting(string defaultTableName, XmlNode routingNode)
        {
            if (null == routingNode)
            {
                throw new ArgumentNullException("routingNode");
            }
            object name;

            XmlFileParser.TryGetAttributeValue(routingNode, "Name", out name);
            if (null == name)
            {
                throw new Exception("the Name for the routing node is null.");
            }
            object storageName;

            XmlFileParser.TryGetAttributeValue(routingNode, "StorageName", out storageName);
            if (null == storageName)
            {
                throw new Exception("the StorageName for the routing node is null.");
            }
            object tableName;

            XmlFileParser.TryGetAttributeValue(routingNode, "TableName", out tableName);
            object owner;

            XmlFileParser.TryGetAttributeValue(routingNode, "Owner", out owner);
            object oPermission;

            XmlFileParser.TryGetAttributeValue(routingNode, "Permission", out oPermission);

            IRoutingAttribute rounting = new RoutingAttribute
            {
                Name        = name.ToString(),
                StorageName = storageName.ToString(),
                TableName   = null == tableName ? defaultTableName : tableName.ToString(),
                Permission  =
                    null == oPermission
                                                         ? PermissionMode.WR
                                                         : ConvertToPermissionMode.Convert(oPermission.ToString()),
            };

            if (null != owner)
            {
                rounting.Owner = owner.ToString();
            }
            return(rounting);
        }
Пример #17
0
        /// <summary>
        /// Adds the xml file to the configuration. Multiple different files can be added.
        /// </summary>
        /// <param name="configuration"></param>
        /// <param name="file">the file to use</param>
        /// <param name="namespaces">The xml namespaces to load</param>
        /// <param name="eagerLoad">if the file should be eagerly loaded rather than lazily loaded</param>
        /// <returns></returns>
        public static IEnvironmentConfiguration WithXmlFile(this IEnvironmentConfiguration configuration, string file,
                                                            IDictionary <string, string> namespaces = null, bool eagerLoad = false)
        {
            XmlFileParser parser = null;

            if (configuration.HasValue(typeof(XmlFileParser).FullName))
            {
                parser = configuration.GetValue <XmlFileParser>(typeof(XmlFileParser).FullName);
            }
            else
            {
                configuration.SetValue(typeof(XmlFileParser).FullName, parser = new XmlFileParser());
            }
            if (parser.Files.Keys.Any(x => String.Equals(x, file, StringComparison.OrdinalIgnoreCase)))
            {
                return(configuration);
            }
            else
            {
                var data = new XmlFileParser.FileDataHolder();
                if (eagerLoad)
                {
                    try
                    {
                        data.ParsedFile = XDocument.Parse(File.ReadAllText(file));
                    }
                    catch
                    {
                        data.ParsingFailed = true;
                    }
                }

                data.Path = file;
                if (namespaces != null && namespaces.Any())
                {
                    foreach (var keyValuePair in namespaces)
                    {
                        data.NamespaceManager.AddNamespace(keyValuePair.Key, keyValuePair.Value);
                    }
                }

                parser.Files.Add(file, data);
            }

            return(configuration);
        }
Пример #18
0
        private static IMemberAttribute GenerateMember(IMemberAttribute member, XmlNode memberNode)
        {
            if (null == memberNode)
            {
                return(member);
            }
            object oFieldName;
            object oAllowNull;
            object oLength;
            object oPrimaryKey;
            object oDbType;
            object oIsSave;

            if (XmlFileParser.TryGetAttributeValue(memberNode, "FieldName", out oFieldName) && null != oFieldName)
            {
                member.FieldName = oFieldName.ToString().Trim();
            }
            if (XmlFileParser.TryGetAttributeValue(memberNode, "AllowNull", out oAllowNull) && null != oAllowNull)
            {
                member.AllowNull = bool.Parse(oAllowNull.ToString().Trim());
            }
            if (XmlFileParser.TryGetAttributeValue(memberNode, "Length", out oLength) && null != oLength)
            {
                member.Length = int.Parse(oLength.ToString().Trim());
            }
            if (XmlFileParser.TryGetAttributeValue(memberNode, "PrimaryKey", out oPrimaryKey) && null != oPrimaryKey)
            {
                member.PrimaryKey = bool.Parse(oPrimaryKey.ToString().Trim());
                if (member.PrimaryKey)
                {
                    member.AllowNull = false;
                }
            }
            if (XmlFileParser.TryGetAttributeValue(memberNode, "DbType", out oDbType) && null != oDbType)
            {
                member.DBType = ConvertToDbType.Convert(oDbType.ToString());
            }
            if (XmlFileParser.TryGetAttributeValue(memberNode, "IsSave", out oIsSave) && null != oIsSave)
            {
                member.IsSave = bool.Parse(oIsSave.ToString().Trim());
            }
            return(member);
        }
Пример #19
0
        public void Init(string filePath)
        {
            if (string.IsNullOrEmpty(filePath))
            {
                throw new ArgumentNullException("filePath");
            }
            try
            {
                XmlDocument doc   = XmlFileParser.LoadXml(filePath);
                XmlNodeList nodes = XmlFileParser.Analyze(doc, "AlbianObjects");
                if (1 != nodes.Count) //root node
                {
                    throw new Exception("Analyze the Objects node is error in the Persistence.config");
                }

                ParserObjects(nodes[0]);
            }
            catch (Exception exc)
            {
                throw exc;
            }
        }
Пример #20
0
        public void Init(string filePath)
        {
            if (string.IsNullOrEmpty(filePath))
            {
                throw new ArgumentNullException("filePath");
            }
            try
            {
                XmlDocument doc   = XmlFileParser.LoadXml(filePath);
                XmlNodeList nodes = XmlFileParser.Analyze(doc, "Storages");
                if (1 != nodes.Count) //root node
                {
                    throw new Exception("Analyze the Storages node is error in the Storage.config");
                }

                IDictionary <string, IStorageAttribute> dic = ParserStorages(nodes[0]);
                if (null == dic)
                {
                    if (null != Logger)
                    {
                        Logger.Error("no storage attribute in the config file.");
                    }
                    throw new Exception("no storage attribute in the config file.");
                }
                foreach (KeyValuePair <string, IStorageAttribute> kv in dic)
                {
                    if (kv.Value.Pooling)
                    {
                        DbConnectionPoolManager.CreatePool(kv.Value.Name, kv.Value.DatabaseStyle, kv.Value.MinPoolSize,
                                                           kv.Value.MaxPoolSize);
                    }
                }
            }
            catch (Exception exc)
            {
                throw exc;
            }
        }
Пример #21
0
        protected override ICacheAttribute ParserCache(XmlNode node)
        {
            if (null == node)
            {
                new CacheAttribute
                {
                    Enable   = true,
                    LifeTime = 300,
                };
            }
            ICacheAttribute cache = new CacheAttribute();
            object          oEnable;
            object          oLifeTime;

            if (XmlFileParser.TryGetAttributeValue(node, "Enable", out oEnable))
            {
                cache.Enable = string.IsNullOrEmpty(oEnable.ToString()) ? false : bool.Parse(oEnable.ToString());
            }
            if (XmlFileParser.TryGetAttributeValue(node, "LifeTime", out oLifeTime))
            {
                cache.LifeTime = string.IsNullOrEmpty(oLifeTime.ToString()) ? 0 : int.Parse(oLifeTime.ToString());
            }
            return(cache);
        }
 public XmlParserTests()
 {
     _parser = new XmlFileParser();
 }
Пример #23
0
        private static IStorageAttribute GenerateStorageAttribute(XmlNode node)
        {
            IStorageAttribute storageAttribute = new StorageAttribute();
            object            oName;
            object            oServer;
            object            oDateBase;
            object            oUid;
            object            oPassword;
            object            oMinPoolSize;
            object            oMaxPoolSize;
            object            oTimeout;
            object            oPooling;
            object            oIntegratedSecurity;
            object            oDbClass;
            object            oCharset;
            object            oTransactional;

            foreach (XmlNode n in node.ChildNodes)
            {
                switch (n.Name)
                {
                case "Name":
                {
                    if (XmlFileParser.TryGetNodeValue(n, out oName))
                    {
                        storageAttribute.Name = oName.ToString().Trim();
                    }
                    break;
                }

                case "DatabaseStyle":
                {
                    if (XmlFileParser.TryGetNodeValue(n, out oDbClass))
                    {
                        storageAttribute.DatabaseStyle = ConvertToDatabaseStyle.Convert(oDbClass.ToString());
                    }
                    break;
                }

                case "Server":
                {
                    if (XmlFileParser.TryGetNodeValue(n, out oServer))
                    {
                        storageAttribute.Server = oServer.ToString().Trim();
                    }
                    break;
                }

                case "Database":
                {
                    if (XmlFileParser.TryGetNodeValue(n, out oDateBase))
                    {
                        storageAttribute.Database = oDateBase.ToString().Trim();
                    }
                    break;
                }

                case "Uid":
                {
                    if (XmlFileParser.TryGetNodeValue(n, out oUid))
                    {
                        storageAttribute.Uid = oUid.ToString().Trim();
                    }
                    break;
                }

                case "Password":
                {
                    if (XmlFileParser.TryGetNodeValue(n, out oPassword))
                    {
                        storageAttribute.Password = oPassword.ToString().Trim();
                    }
                    break;
                }

                case "MinPoolSize":
                {
                    if (XmlFileParser.TryGetNodeValue(n, out oMinPoolSize))
                    {
                        storageAttribute.MinPoolSize = Math.Abs(int.Parse(oMinPoolSize.ToString().Trim()));
                    }
                    break;
                }

                case "MaxPoolSize":
                {
                    if (XmlFileParser.TryGetNodeValue(n, out oMaxPoolSize))
                    {
                        storageAttribute.MaxPoolSize = Math.Abs(int.Parse(oMaxPoolSize.ToString().Trim()));
                    }
                    break;
                }

                case "Timeout":
                {
                    if (XmlFileParser.TryGetNodeValue(n, out oTimeout))
                    {
                        storageAttribute.Timeout = Math.Abs(int.Parse(oTimeout.ToString().Trim()));
                    }
                    break;
                }

                case "Pooling":
                {
                    if (XmlFileParser.TryGetNodeValue(n, out oPooling))
                    {
                        storageAttribute.Pooling = bool.Parse(oPooling.ToString().Trim());
                    }
                    break;
                }

                case "IntegratedSecurity":
                {
                    if (XmlFileParser.TryGetNodeValue(n, out oIntegratedSecurity))
                    {
                        string sIntegratedSecurity = oIntegratedSecurity.ToString().Trim();
                        if ("false" == sIntegratedSecurity.ToLower() || "no" == sIntegratedSecurity.ToLower())
                        {
                            storageAttribute.IntegratedSecurity = false;
                        }
                        if ("true" == sIntegratedSecurity.ToLower() ||
                            "yes" == sIntegratedSecurity.ToLower() || "sspi" == sIntegratedSecurity.ToLower())
                        {
                            storageAttribute.IntegratedSecurity = true;
                        }
                    }
                    break;
                }

                case "Charset":
                {
                    if (XmlFileParser.TryGetNodeValue(n, out oCharset))
                    {
                        storageAttribute.Charset = oCharset.ToString().Trim();
                    }
                    break;
                }

                case "Transactional":
                {
                    if (XmlFileParser.TryGetNodeValue(n, out oTransactional))
                    {
                        storageAttribute.Transactional = bool.Parse(oTransactional.ToString().Trim());
                    }
                    break;
                }
                }
            }
            if (string.IsNullOrEmpty(storageAttribute.Name))
            {
                throw new Exception("the name is empty in the storage.config");
            }
            if (string.IsNullOrEmpty(storageAttribute.Server))
            {
                throw new Exception("the Server is empty in the storage.config");
            }
            if (string.IsNullOrEmpty(storageAttribute.Database))
            {
                throw new Exception("the Database is empty in the storage.config");
            }
            return(storageAttribute);
        }
        public void GivenInvalidFilePath_WhenGetHorsesCalled_ThenExceptionThrown()
        {
            var xmlFileParser = new XmlFileParser();

            Assert.Throws <FileNotFoundException>(() => xmlFileParser.GetHorses(@"TestData\test.xml"));
        }
        public void GivenPathToTextFile_WhenGetHorsesCalled_ThenExceptionThrown()
        {
            var xmlFileParser = new XmlFileParser();

            Assert.Throws <InvalidOperationException>(() => xmlFileParser.GetHorses(@"TestData\TextFile1.txt"));
        }