public void It_Should_Allow_Assembly_To_Be_Passed()
 {
     var loader = new EmbeddedResourceLoader(GetType().GetTypeInfo().Assembly);
     var result = loader.Load("EmbeddedBar");
     Assert.Equal("I'm the Embedded {{bar}} template.", result);
     var loader2 = new EmbeddedResourceLoader(GetType().GetTypeInfo().Assembly, "must");
     var result2 = loader.Load("EmbeddedBar");
     Assert.Equal("I'm the Embedded {{bar}} template.", result2);
 }
Exemplo n.º 2
0
        /// <summary>
        /// Tries to load a Triple Store based on information from the Configuration Graph.
        /// </summary>
        /// <param name="g">Configuration Graph.</param>
        /// <param name="objNode">Object Node.</param>
        /// <param name="targetType">Target Type.</param>
        /// <param name="obj">Output Object.</param>
        /// <returns></returns>
        public bool TryLoadObject(IGraph g, INode objNode, Type targetType, out object obj)
        {
            obj = null;

            ITripleStore store = null;
            INode        subObj;
            Object       temp;

            // Get Property Nodes we need
            INode propStorageProvider = g.CreateUriNode(UriFactory.Create(ConfigurationLoader.PropertyStorageProvider)),
                  propAsync           = g.CreateUriNode(UriFactory.Create(ConfigurationLoader.PropertyAsync));

            // Check whether to use a specific Graph Collection
            INode collectionNode = ConfigurationLoader.GetConfigurationNode(g, objNode, g.CreateUriNode(UriFactory.Create(ConfigurationLoader.PropertyUsingGraphCollection)));

            // Instantiate the Store Class
            switch (targetType.FullName)
            {
            case TripleStore:
                if (collectionNode == null)
                {
                    store = new TripleStore();
                }
                else
                {
                    BaseGraphCollection graphCollection = ConfigurationLoader.LoadObject(g, collectionNode) as BaseGraphCollection;
                    if (graphCollection == null)
                    {
                        throw new DotNetRdfConfigurationException("Unable to load the Triple Store identified by the Node '" + objNode.ToString() + "' as the dnr:usingGraphCollection points to an object which cannot be loaded as an instance of the required type BaseGraphCollection");
                    }
                    store = new TripleStore(graphCollection);
                }
                break;

            case WebDemandTripleStore:
                store = new WebDemandTripleStore();
                break;

            case PersistentTripleStore:
                subObj = ConfigurationLoader.GetConfigurationNode(g, objNode, propStorageProvider);
                if (subObj == null)
                {
                    return(false);
                }

                temp = ConfigurationLoader.LoadObject(g, subObj);
                if (temp is IStorageProvider)
                {
                    store = new PersistentTripleStore((IStorageProvider)temp);
                }
                else
                {
                    throw new DotNetRdfConfigurationException("Unable to load a Persistent Triple Store identified by the Node '" + objNode.ToString() + "' as the value given the for dnr:genericManager property points to an Object which could not be loaded as an object which implements the IStorageProvider interface");
                }
                break;
            }

            // Read in additional data to be added to the Store
            if (store != null)
            {
                IEnumerable <INode> sources = ConfigurationLoader.GetConfigurationData(g, objNode, g.CreateUriNode(UriFactory.Create(ConfigurationLoader.PropertyUsingGraph)));

                // Read from Graphs
                foreach (INode source in sources)
                {
                    temp = ConfigurationLoader.LoadObject(g, source);
                    if (temp is IGraph)
                    {
                        store.Add((IGraph)temp);
                    }
                    else
                    {
                        throw new DotNetRdfConfigurationException("Unable to load data from a Graph for the Triple Store identified by the Node '" + objNode.ToString() + "' as one of the values for the dnr:usingGraph property points to an Object that cannot be loaded as an object which implements the IGraph interface");
                    }
                }

                // Load from Embedded Resources
                sources = ConfigurationLoader.GetConfigurationData(g, objNode, g.CreateUriNode(UriFactory.Create(ConfigurationLoader.PropertyFromEmbedded)));
                foreach (INode source in sources)
                {
                    if (source.NodeType == NodeType.Literal)
                    {
                        EmbeddedResourceLoader.Load(store, ((ILiteralNode)source).Value);
                    }
                    else
                    {
                        throw new DotNetRdfConfigurationException("Unable to load data from an Embedded Resource for the Graph identified by the Node '" + objNode.ToString() + "' as one of the values for the dnr:fromEmbedded property is not a Literal Node as required");
                    }
                }

                // Read from Files - we assume these files are Dataset Files
                sources = ConfigurationLoader.GetConfigurationData(g, objNode, g.CreateUriNode(UriFactory.Create(ConfigurationLoader.PropertyFromFile)));
                foreach (INode source in sources)
                {
                    if (source.NodeType == NodeType.Literal)
                    {
                        FileLoader.Load(store, ConfigurationLoader.ResolvePath(((ILiteralNode)source).Value));
                    }
                    else
                    {
                        throw new DotNetRdfConfigurationException("Unable to load data from a file for the Triple Store identified by the Node '" + objNode.ToString() + "' as one of the values for the dnr:fromFile property is not a Literal Node as required");
                    }
                }

                // Finally we'll apply any reasoners
                if (store is IInferencingTripleStore)
                {
                    IEnumerable <INode> reasoners = ConfigurationLoader.GetConfigurationData(g, objNode, g.CreateUriNode(UriFactory.Create(ConfigurationLoader.PropertyReasoner)));
                    foreach (INode reasoner in reasoners)
                    {
                        temp = ConfigurationLoader.LoadObject(g, reasoner);
                        if (temp is IInferenceEngine)
                        {
                            ((IInferencingTripleStore)store).AddInferenceEngine((IInferenceEngine)temp);
                        }
                        else
                        {
                            throw new DotNetRdfConfigurationException("Unable to apply a reasoner for the Graph identified by the Node '" + objNode.ToString() + "' as one of the values for the dnr:reasoner property points to an Object which cannot be loaded as an object which implements the IInferenceEngine interface");
                        }
                    }
                }

                // And as an absolute final step if the store is transactional we'll flush any changes we've made
                if (store is ITransactionalStore)
                {
                    ((ITransactionalStore)store).Flush();
                }
            }

            obj = store;
            return(store != null);
        }
Exemplo n.º 3
0
            /// <summary>コンストラクタ</summary>
            /// <remarks>インナークラス</remarks>
            public SharedPropertyManager()
            {
                // 共有情報定義をロードする。
                XmlDocument xMLSP = new XmlDocument();

                if (GetConfigParameter.GetConfigValue(FxLiteral.XML_SP_DEFINITION) == null ||
                    GetConfigParameter.GetConfigValue(FxLiteral.XML_SP_DEFINITION) == "")
                {
                    // 定義が無い(offの扱い)。

                    // 共有情報定義(XmlDocument)を空で初期化
                    xMLSP.LoadXml("<?xml version=\"1.0\" encoding=\"utf-8\" ?><SPD></SPD>");
                }
                else
                {
                    //// 定義が間違っている(エラー)。

                    //// エラーをスロー
                    //throw new FrameworkException(
                    //    FrameworkExceptionMessage.ERROR_IN_WRITING_OF_FX_PATH2[0],
                    //    String.Format(FrameworkExceptionMessage.ERROR_IN_WRITING_OF_FX_PATH2[1],
                    //                    FxLiteral.XML_SP_DEFINITION));

                    #region  埋め込まれたリソース ローダでチェック(ここで落とすとハンドルされないので落とさない。)

                    if (EmbeddedResourceLoader.Exists(
                            GetConfigParameter.GetConfigValue(FxLiteral.XML_SP_DEFINITION), false))
                    {
                        // 共有情報定義(XmlDocument)を[埋め込まれたリソース]で初期化
                        xMLSP.LoadXml(EmbeddedResourceLoader.LoadXMLAsString(
                                          GetConfigParameter.GetConfigValue(FxLiteral.XML_SP_DEFINITION)));

                        //// 戻す
                        //return;
                    }
                    else
                    {
                        // 何もしない。
                    }

                    #endregion

                    #region リソース ローダでチェック(ここで落とすとハンドルされないので落とさない。)

                    if (ResourceLoader.Exists(
                            GetConfigParameter.GetConfigValue(FxLiteral.XML_SP_DEFINITION), false))
                    {
                        // 共有情報定義(XmlDocument)を[リソース]で初期化
                        xMLSP.Load(
                            PubCmnFunction.BuiltStringIntoEnvironmentVariable(
                                GetConfigParameter.GetConfigValue(FxLiteral.XML_SP_DEFINITION)));

                        //// 戻す
                        //return;
                    }
                    else
                    {
                        // 何もしない。
                    }

                    #endregion
                }

                #region すべてのSHAREDPROPタグをDictionary化

                // すべてのSHAREDPROPタグを取得、大文字・小文字は区別する。
                XmlNodeList xmlNodeList = xMLSP.GetElementsByTagName(FxLiteral.XML_SP_TAG_SHARED_PROPERTY);

                foreach (XmlNode xmlNodeSP in xmlNodeList)
                {
                    // 属性の取得
                    XmlNode xmlNodeKey = xmlNodeSP.Attributes.GetNamedItem(FxLiteral.XML_CMN_ATTR_KEY);
                    XmlNode xmlNodeVal = xmlNodeSP.Attributes.GetNamedItem(FxLiteral.XML_CMN_ATTR_VALUE);

                    if (xmlNodeKey == null)
                    {
                        // id属性なしの場合

                        throw new FrameworkException(
                                  FrameworkExceptionMessage.SHAREDPROPERTY_XML_FORMAT_ERROR[0],
                                  String.Format(FrameworkExceptionMessage.SHAREDPROPERTY_XML_FORMAT_ERROR[1],
                                                String.Format(FrameworkExceptionMessage.SHAREDPROPERTY_XML_FORMAT_ERROR_ATTR, FxLiteral.XML_CMN_ATTR_KEY, "-")));
                    }

                    if (xmlNodeVal == null)
                    {
                        // description属性なしの場合

                        throw new FrameworkException(
                                  FrameworkExceptionMessage.SHAREDPROPERTY_XML_FORMAT_ERROR[0],
                                  String.Format(FrameworkExceptionMessage.SHAREDPROPERTY_XML_FORMAT_ERROR[1],
                                                String.Format(FrameworkExceptionMessage.SHAREDPROPERTY_XML_FORMAT_ERROR_ATTR, FxLiteral.XML_CMN_ATTR_VALUE, xmlNodeKey.Value)));
                    }

                    this.DicSP.Add(xmlNodeKey.Value, xmlNodeVal.Value);
                }

                #endregion
            }
        /// <summary>コンストラクタ</summary>
        /// <remarks>CallController、ServiceInterfaceから利用するので、public</remarks>
        public InProcessNameService()
        {
            // インプロセス呼び出しの名前解決定義をロードする。

            #region  埋め込まれたリソース ローダでチェック(ここで落とすとハンドルされないので落とさない。)

            if (EmbeddedResourceLoader.Exists(
                    GetConfigParameter.GetConfigValue(FxLiteral.XML_TM_INPROCESS_DEFINITION), false))
            {
                // インプロセス呼び出しの名前解決定義(XmlDocument)を[埋め込まれたリソース]で初期化
                this.XMLTMD_InProcess.LoadXml(EmbeddedResourceLoader.LoadXMLAsString(
                                                  GetConfigParameter.GetConfigValue(FxLiteral.XML_TM_INPROCESS_DEFINITION)));

                // 戻す
                return;
            }
            else
            {
                // 何もしない。
            }

            #endregion

            #region リソース ローダでチェック(ここで落とすとハンドルされないので落とさない。)

            if (ResourceLoader.Exists(
                    GetConfigParameter.GetConfigValue(FxLiteral.XML_TM_INPROCESS_DEFINITION), false))
            {
                // インプロセス呼び出しの名前解決定義(XmlDocument)を[リソース]で初期化
                this.XMLTMD_InProcess.Load(
                    StringVariableOperator.BuiltStringIntoEnvironmentVariable(
                        GetConfigParameter.GetConfigValue(FxLiteral.XML_TM_INPROCESS_DEFINITION)));

                // 戻す
                return;
            }
            else
            {
                // 何もしない。
            }

            #endregion

            #region チェック(定義の有無や、定義の誤り)

            if (GetConfigParameter.GetConfigValue(FxLiteral.XML_TM_INPROCESS_DEFINITION) == null ||
                GetConfigParameter.GetConfigValue(FxLiteral.XML_TM_INPROCESS_DEFINITION) == "")
            {
                // 定義が無い(offの扱い)。

                // インプロセス呼び出しの名前解決定義(XmlDocument)を空で初期化
                this.XMLTMD_InProcess.LoadXml("<?xml version=\"1.0\" encoding=\"utf-8\" ?><TMD></TMD>");
            }
            else
            {
                // 定義が間違っている(エラー)。

                // 例外をスロー
                throw new FrameworkException(
                          FrameworkExceptionMessage.ERROR_IN_WRITING_OF_FX_PATH2[0],
                          String.Format(FrameworkExceptionMessage.ERROR_IN_WRITING_OF_FX_PATH2[1],
                                        FxLiteral.XML_TM_INPROCESS_DEFINITION));
            }

            #endregion
        }
Exemplo n.º 5
0
        public void FixtureSetUp()
        {
            var loader = new EmbeddedResourceLoader();

            provider = new RulesProvider(loader);
        }
Exemplo n.º 6
0
        /// <summary>
        /// Initializes a new instance of the <see cref="T:Mapsui.UI.Forms.MapView"/> class.
        /// </summary>
        public MapView()
        {
            MyLocationFollow = false;

            IsClippedToBounds = true;
            UseDoubleTap      = false;

            MyLocationLayer = new MyLocationLayer(this)
            {
                Enabled = true
            };
            _mapCalloutLayer = new Layer()
            {
                Name = CalloutLayerName, IsMapInfoLayer = true
            };
            _mapPinLayer = new Layer()
            {
                Name = PinLayerName, IsMapInfoLayer = true
            };
            _mapDrawableLayer = new Layer()
            {
                Name = DrawableLayerName, IsMapInfoLayer = true
            };

            // Get defaults from MapControl
            RotationLock = Map?.RotationLock ?? false;
            ZoomLock     = Map?.ZoomLock ?? true;
            PanLock      = Map?.PanLock ?? false;

            // Add some events to _mapControl
            Viewport.ViewportChanged += HandlerViewportChanged;
            Info        += HandlerInfo;
            SingleTap   += HandlerTap;
            DoubleTap   += HandlerTap;
            LongTap     += HandlerLongTap;
            SizeChanged += HandlerSizeChanged;

            TouchMove += (s, e) => {
                RunOnUIThread(() => MyLocationFollow = false);
            };

            // Add MapView layers to Map
            AddLayers();

            // Add some events to _mapControl.Map.Layers
            Map !.Layers.Changed += HandleLayersChanged;

#pragma warning disable IDISP004 // Don't ignore created IDisposable
            _pictMyLocationNoCenter = EmbeddedResourceLoader.Load("Images.LocationNoCenter.svg", typeof(MapView)).LoadSvgPicture() ?? throw new MissingManifestResourceException("Images.LocationNoCenter.svg");
            _pictMyLocationCenter   = EmbeddedResourceLoader.Load("Images.LocationCenter.svg", typeof(MapView)).LoadSvgPicture() ?? throw new MissingManifestResourceException("Images.LocationCenter.svg");

            _pictZoomIn   = EmbeddedResourceLoader.Load("Images.ZoomIn.svg", typeof(MapView)).LoadSvgPicture() ?? throw new MissingManifestResourceException("Images.ZoomIn.svg");
            _pictZoomOut  = EmbeddedResourceLoader.Load("Images.ZoomOut.svg", typeof(MapView)).LoadSvgPicture() ?? throw new MissingManifestResourceException("Images.ZoomOut.svg");
            _pictNorthing = EmbeddedResourceLoader.Load("Images.RotationZero.svg", typeof(MapView)).LoadSvgPicture() ?? throw new MissingManifestResourceException("Images.RotationZero.svg");
#pragma warning restore IDISP001
            CreateButtons();

            _pins.CollectionChanged     += HandlerPinsOnCollectionChanged;
            _drawable.CollectionChanged += HandlerDrawablesOnCollectionChanged;

            _mapCalloutLayer.DataSource = new ObservableCollectionProvider <Callout>(_callouts);
            _mapCalloutLayer.Style      = null; // We don't want a global style for this layer

            _mapPinLayer.DataSource = new ObservableCollectionProvider <Pin>(_pins);
            _mapPinLayer.Style      = null; // We don't want a global style for this layer

            _mapDrawableLayer.DataSource = new ObservableCollectionProvider <Drawable>(_drawable);
            _mapDrawableLayer.Style      = null; // We don't want a global style for this layer
        }
Exemplo n.º 7
0
        /// <summary>
        /// Get message description from message ID
        /// </summary>
        /// <param name="messageID">
        /// messageID
        /// </param>
        /// <param name="cultureName">
        /// cultureName
        /// </param>
        /// <param name="useChildUICulture">
        /// 子カルチャを使用している場合:true<br/>
        /// use ChildUICulture : true
        /// </param>
        /// <param name="notExist">
        /// 子カルチャを使用している場合で、<br/>
        /// ファイルを発見できなかった場合はtrueを返す。<br/>
        /// if useChildUICulture == true<br/>
        /// then If the file is not found, return true.
        /// </param>
        /// <returns>
        /// メッセージ記述<br/>
        /// Get message description
        /// </returns>
        private static string GetMessageDescription(
            string messageID, string cultureName,
            bool useChildUICulture, out bool notExist)
        {
            #region local

            //bool xmlfilenotExist = false;
            notExist = false;

            string tempXMLFileName = string.Empty;
            string tempXMLFilePath = string.Empty;

            string defaultXMLFileName     = string.Empty;
            string defaultXMLFilePath     = string.Empty;
            string cultureWiseXMLFileName = string.Empty;
            string cultureWiseXMLFilePath = string.Empty;

            string cultureWiseXMLParentFileName = string.Empty;
            string cultureWiseXMLParentFilePath = string.Empty;

            bool defaultXMLFilePath_ResourceLoaderExists             = false;
            bool defaultXMLFilePath_EmbeddedResourceLoaderExists     = false;
            bool cultureWiseXMLFilePath_ResourceLoaderExists         = false;
            bool cultureWiseXMLFilePath_EmbeddedResourceLoaderExists = false;

            #endregion

            defaultXMLFilePath = GetConfigParameter.GetConfigValue(FxLiteral.XML_MSG_DEFINITION);

            GetMessage.GetCultureWiseXMLFileName(
                cultureName, defaultXMLFilePath, out defaultXMLFileName, out cultureWiseXMLFilePath, out cultureWiseXMLFileName);

            // This has been added for Threadsafe
            lock (thisLock)
            {
                #region ContainsKey

                // Check that XML file is already loaded.
                if (GetMessage.DicMSG.ContainsKey(cultureWiseXMLFileName))
                {
                    // culture wise XML file is already loaded.
                    if (GetMessage.DicMSG[cultureWiseXMLFileName].ContainsKey(messageID))
                    {
                        return(GetMessage.DicMSG[cultureWiseXMLFileName][messageID]);
                    }
                    else
                    {
                        return(string.Empty);
                    }
                }
                else
                {
                    // culture wise XML file isn't loaded.
                }

                if (GetMessage.DicMSG.ContainsKey(defaultXMLFileName))
                {
                    // default XML file is already loaded.

                    if (useChildUICulture)
                    {
                        // next, try load.
                    }
                    else
                    {
                        // default XML
                        if (DicMSG[defaultXMLFileName].ContainsKey(messageID))
                        {
                            return(GetMessage.DicMSG[defaultXMLFileName][messageID]);
                        }
                        else
                        {
                            return(string.Empty);
                        }
                    }
                }
                else
                {
                    // default XML file isn't loaded.
                }

                #endregion

                #region FillDictionary

                // cultureWiseXMLFilePath
                if (EmbeddedResourceLoader.Exists(cultureWiseXMLFilePath, false))
                {
                    // Exists cultureWiseXMLFile
                    cultureWiseXMLFilePath_EmbeddedResourceLoaderExists = true;
                }
                else
                {
                    // not exists
                    if (ResourceLoader.Exists(cultureWiseXMLFilePath, false))
                    {
                        // Exists cultureWiseXMLFile
                        cultureWiseXMLFilePath_ResourceLoaderExists = true;
                    }
                    else
                    {
                        // not exists

                        // defaultXMLFilePath
                        if (EmbeddedResourceLoader.Exists(defaultXMLFilePath, false))
                        {
                            // Exists defaultXMLFilePath
                            defaultXMLFilePath_EmbeddedResourceLoaderExists = true;
                        }
                        else
                        {
                            if (ResourceLoader.Exists(defaultXMLFilePath, false))
                            {
                                // Exists defaultXMLFilePath
                                defaultXMLFilePath_ResourceLoaderExists = true;
                            }
                        }
                    }
                }

                // select file path
                if (cultureWiseXMLFilePath_ResourceLoaderExists ||
                    cultureWiseXMLFilePath_EmbeddedResourceLoaderExists)
                {
                    // cultureWiseXMLFile
                    tempXMLFileName = cultureWiseXMLFileName;
                    tempXMLFilePath = cultureWiseXMLFilePath;
                }
                else
                {
                    // If the file is not found,
                    if (useChildUICulture)
                    {
                        // Look for use the culture info of the parent.
                        notExist = true;
                        return(string.Empty);
                    }
                    else
                    {
                        if (defaultXMLFilePath_ResourceLoaderExists ||
                            defaultXMLFilePath_EmbeddedResourceLoaderExists)
                        {
                            // defaultXMLFilePath
                            tempXMLFileName = defaultXMLFileName;
                            tempXMLFilePath = defaultXMLFilePath;
                        }
                        else
                        {
                            // use empty XML.
                        }
                    }
                }

                // select load method.
                XmlDocument xMLMSG = new XmlDocument();
                Dictionary <string, string> innerDictionary = new Dictionary <string, string>();

                if (defaultXMLFilePath_EmbeddedResourceLoaderExists ||
                    cultureWiseXMLFilePath_EmbeddedResourceLoaderExists)
                {
                    // Use EmbeddedResourceLoader
                    xMLMSG.LoadXml(EmbeddedResourceLoader.LoadXMLAsString(tempXMLFilePath));

                    //added by ritu
                    GetMessage.FillDictionary(xMLMSG, innerDictionary);

                    // and initialize DicMSG[tempXMLFileName]
                    DicMSG[tempXMLFileName] = innerDictionary;
                }
                else if (defaultXMLFilePath_ResourceLoaderExists ||
                         cultureWiseXMLFilePath_ResourceLoaderExists)
                {
                    // Load normally.
                    xMLMSG.Load(PubCmnFunction.BuiltStringIntoEnvironmentVariable(tempXMLFilePath));

                    //added by ritu
                    GetMessage.FillDictionary(xMLMSG, innerDictionary);
                    // and initialize DicMSG[tempXMLFileName]
                    DicMSG[tempXMLFileName] = innerDictionary;
                }
                else
                {
                    // If the file is not found, initialized as empty XML
                    xMLMSG.LoadXml("<?xml version=\"1.0\" encoding=\"utf-8\" ?><MSGD></MSGD>");

                    //added by ritu
                    GetMessage.FillDictionary(xMLMSG, innerDictionary);

                    // and initialize DicMSG[tempXMLFileName]
                    DicMSG[tempXMLFileName] = innerDictionary;
                    //xmlfilenotExist = true;
                }

                // and return GetMessageDescription.
                if (DicMSG[tempXMLFileName].ContainsKey(messageID))
                {
                    return(GetMessage.DicMSG[tempXMLFileName][messageID]);
                }
                else
                {
                    return(string.Empty);
                }

                #endregion
            }
        }
 public void It_Should_Work_With_Templates_In_Folders()
 {
     var loader = new EmbeddedResourceLoader(GetType().GetTypeInfo().Assembly);
     var result = loader.Load("EmbeddedBar");
     Assert.Equal("I'm the Embedded {{bar}} template.", result);
 }
Exemplo n.º 9
0
        public void GenderRules_json_should_be_valid_json_file()
        {
            EmbeddedResourceLoader loader = new EmbeddedResourceLoader();

            Assert.DoesNotThrow(() => loader.LoadGenderJson());
        }
Exemplo n.º 10
0
        public void Rules_yml_should_be_valid_yaml_file()
        {
            EmbeddedResourceLoader loader = new EmbeddedResourceLoader();

            Assert.DoesNotThrow(() => loader.LoadYaml());
        }
Exemplo n.º 11
0
        /// <summary>
        /// Tries to load a Graph based on information from the Configuration Graph
        /// </summary>
        /// <param name="g">Configuration Graph</param>
        /// <param name="objNode">Object Node</param>
        /// <param name="targetType">Target Type</param>
        /// <param name="obj">Output Object</param>
        /// <returns></returns>
        public bool TryLoadObject(IGraph g, INode objNode, Type targetType, out object obj)
        {
            obj = null;
            IGraph output;

            try
            {
                output = (IGraph)Activator.CreateInstance(targetType);
            }
            catch
            {
                //Any error means this loader can't load this type
                return(false);
            }

            //Now we want to find out where the data for the Graph is coming from
            //Data Source loading order is Graphs, Files, Strings, Databases, Stores, URIs
            IEnumerable <INode> sources;

            //Load from Graphs
            sources = ConfigurationLoader.GetConfigurationData(g, objNode, ConfigurationLoader.CreateConfigurationNode(g, ConfigurationLoader.PropertyFromGraph));
            foreach (INode source in sources)
            {
                ConfigurationLoader.CheckCircularReference(objNode, source, "dnr:fromGraph");

                Object graph = ConfigurationLoader.LoadObject(g, source);
                if (graph is IGraph)
                {
                    output.Merge((IGraph)graph);
                }
                else
                {
                    throw new DotNetRdfConfigurationException("Unable to load data from another Graph for the Graph identified by the Node '" + objNode.ToString() + "' as one of the values for the dnr:fromGraph property points to an Object that cannot be loaded as an object which implements the IGraph interface");
                }
            }

            //Load from Embedded Resources
            sources = ConfigurationLoader.GetConfigurationData(g, objNode, ConfigurationLoader.CreateConfigurationNode(g, ConfigurationLoader.PropertyFromEmbedded));
            foreach (INode source in sources)
            {
                if (source.NodeType == NodeType.Literal)
                {
                    EmbeddedResourceLoader.Load(output, ((ILiteralNode)source).Value);
                }
                else
                {
                    throw new DotNetRdfConfigurationException("Unable to load data from an Embedded Resource for the Graph identified by the Node '" + objNode.ToString() + "' as one of the values for the dnr:fromEmbedded property is not a Literal Node as required");
                }
            }

            //Load from Files
            sources = ConfigurationLoader.GetConfigurationData(g, objNode, ConfigurationLoader.CreateConfigurationNode(g, ConfigurationLoader.PropertyFromFile));
            foreach (INode source in sources)
            {
                if (source.NodeType == NodeType.Literal)
                {
                    FileLoader.Load(output, ConfigurationLoader.ResolvePath(((ILiteralNode)source).Value));
                }
                else
                {
                    throw new DotNetRdfConfigurationException("Unable to load data from a file for the Graph identified by the Node '" + objNode.ToString() + "' as one of the values for the dnr:fromFile property is not a Literal Node as required");
                }
            }

            //Load from Strings
            sources = ConfigurationLoader.GetConfigurationData(g, objNode, ConfigurationLoader.CreateConfigurationNode(g, ConfigurationLoader.PropertyFromString));
            foreach (INode source in sources)
            {
                if (source.NodeType == NodeType.Literal)
                {
                    StringParser.Parse(output, ((ILiteralNode)source).Value);
                }
                else
                {
                    throw new DotNetRdfConfigurationException("Unable to load data from a string for the Graph identified by the Node '" + objNode.ToString() + "' as one of the values for the dnr:fromString property is not a Literal Node as required");
                }
            }

            IEnumerable <Object> connections;

#if !NO_DATA && !NO_STORAGE
            //Load from Databases
            IEnumerable <INode> dbs = ConfigurationLoader.GetConfigurationData(g, objNode, ConfigurationLoader.CreateConfigurationNode(g, ConfigurationLoader.PropertyFromDatabase));
            dbs.All(db => !ConfigurationLoader.CheckCircularReference(objNode, db, "dnr:fromDatabase"));
            connections = dbs.Select(db => ConfigurationLoader.LoadObject(g, db));
            sources     = ConfigurationLoader.GetConfigurationData(g, objNode, ConfigurationLoader.CreateConfigurationNode(g, ConfigurationLoader.PropertyWithUri));
            foreach (Object db in connections)
            {
                if (db is ISqlIOManager)
                {
                    SqlReader reader = new SqlReader((ISqlIOManager)db);
                    foreach (INode source in sources)
                    {
                        if (source.NodeType == NodeType.Uri || source.NodeType == NodeType.Literal)
                        {
                            output.Merge(reader.Load(source.ToString()));
                        }
                        else
                        {
                            throw new DotNetRdfConfigurationException("Unable to load data from a database for the Graph identified by the Node '" + objNode.ToString() + "' as one of the values for the dnr:withUri property is not a URI/Literal Node as required");
                        }
                    }
                }
                else
                {
                    throw new DotNetRdfConfigurationException("Unable to load data from a database for the Graph identified by the Node '" + objNode.ToString() + "' as one of the values of the dnr:fromDatabase property points to an Object which cannot be loaded as an object which implements the ISqlIOManager interface");
                }
            }
#endif

#if !NO_STORAGE
            //Load from Stores
            IEnumerable <INode> stores = ConfigurationLoader.GetConfigurationData(g, objNode, ConfigurationLoader.CreateConfigurationNode(g, ConfigurationLoader.PropertyFromStore));
            stores.All(s => !ConfigurationLoader.CheckCircularReference(objNode, s, "dnr:fromStore"));
            connections = stores.Select(s => ConfigurationLoader.LoadObject(g, s));
            sources     = ConfigurationLoader.GetConfigurationData(g, objNode, ConfigurationLoader.CreateConfigurationNode(g, ConfigurationLoader.PropertyWithUri));
            foreach (Object store in connections)
            {
                if (store is IGenericIOManager)
                {
                    foreach (INode source in sources)
                    {
                        if (source.NodeType == NodeType.Uri || source.NodeType == NodeType.Literal)
                        {
                            ((IGenericIOManager)store).LoadGraph(output, source.ToString());
                        }
                        else
                        {
                            throw new DotNetRdfConfigurationException("Unable to load data from a Generic Store for the Graph identified by the Node '" + objNode.ToString() + "' as one of the values for the dnr:withUri property is not a URI/Literal Node as required");
                        }
                    }
                }
                else if (store is ITripleStore)
                {
                    foreach (INode source in sources)
                    {
                        if (source.NodeType == NodeType.Uri)
                        {
                            output.Merge(((ITripleStore)store).Graph(((IUriNode)source).Uri));
                        }
                        else if (source.NodeType == NodeType.Literal)
                        {
                            output.Merge(((ITripleStore)store).Graph(new Uri(((ILiteralNode)source).Value)));
                        }
                        else
                        {
                            throw new DotNetRdfConfigurationException("Unable to load data from a Store for the Graph identified by the Node '" + objNode.ToString() + "' as one of the values for the dnr:withUri property is not a URI/Literal Node as required");
                        }
                    }
                }
                else
                {
                    throw new DotNetRdfConfigurationException("Unable to load data from a Store for the Graph identified by the Node '" + objNode.ToString() + "' as one of the values of the dnr:fromStore property points to an Object which cannot be loaded as an object which implements either the IGenericIOManager/ITripleStore interface");
                }
            }
#endif

            //Finally load from Remote URIs
            sources = ConfigurationLoader.GetConfigurationData(g, objNode, ConfigurationLoader.CreateConfigurationNode(g, ConfigurationLoader.PropertyFromUri));
            foreach (INode source in sources)
            {
                if (source.NodeType == NodeType.Uri)
                {
#if !SILVERLIGHT
                    UriLoader.Load(output, ((IUriNode)source).Uri);
#else
                    throw new PlatformNotSupportedException("Loading Data into a Graph from a remote URI is not currently supported under Silverlight/Windows Phone 7");
#endif
                }
                else if (source.NodeType == NodeType.Literal)
                {
#if !SILVERLIGHT
                    UriLoader.Load(output, new Uri(((ILiteralNode)source).Value));
#else
                    throw new PlatformNotSupportedException("Loading Data into a Graph from a remote URI is not currently supported under Silverlight/Windows Phone 7");
#endif
                }
                else
                {
                    throw new DotNetRdfConfigurationException("Unable to load data from a URI for the Graph identified by the Node '" + objNode.ToString() + "' as one of the values for the dnr:fromUri property is not a URI/Literal Node as required");
                }
            }

            //Then are we assigning a Base URI to this Graph which overrides any existing Base URI?
            INode baseUri = ConfigurationLoader.GetConfigurationNode(g, objNode, ConfigurationLoader.CreateConfigurationNode(g, ConfigurationLoader.PropertyAssignUri));
            if (baseUri != null)
            {
                if (baseUri.NodeType == NodeType.Uri)
                {
                    output.BaseUri = ((IUriNode)baseUri).Uri;
                }
                else if (baseUri.NodeType == NodeType.Literal)
                {
                    output.BaseUri = new Uri(((ILiteralNode)baseUri).Value);
                }
                else
                {
                    throw new DotNetRdfConfigurationException("Unable to assign a new Base URI for the Graph identified by the Node '" + objNode.ToString() + "' as the value for the dnr:assignUri property is not a URI/Literal Node as required");
                }
            }

            //Finally we'll apply any reasoners
            IEnumerable <INode> reasoners = ConfigurationLoader.GetConfigurationData(g, objNode, ConfigurationLoader.CreateConfigurationNode(g, ConfigurationLoader.PropertyReasoner));
            foreach (INode reasoner in reasoners)
            {
                Object temp = ConfigurationLoader.LoadObject(g, reasoner);
                if (temp is IInferenceEngine)
                {
                    ((IInferenceEngine)temp).Apply(output);
                }
                else
                {
                    throw new DotNetRdfConfigurationException("Unable to apply a reasoner for the Graph identified by the Node '" + objNode.ToString() + "' as one of the values for the dnr:reasoner property points to an Object which cannot be loaded as an object which implements the IInferenceEngine interface");
                }
            }

            obj = output;
            return(true);
        }
Exemplo n.º 12
0
        /// <summary>
        /// Tries to load a Triple Store based on information from the Configuration Graph
        /// </summary>
        /// <param name="g">Configuration Graph</param>
        /// <param name="objNode">Object Node</param>
        /// <param name="targetType">Target Type</param>
        /// <param name="obj">Output Object</param>
        /// <returns></returns>
        public bool TryLoadObject(IGraph g, INode objNode, Type targetType, out object obj)
        {
            obj = null;

            ITripleStore store = null;
            INode        subObj;
            bool         isAsync;
            Object       temp;

            //Get Property Nodes we need
            INode propSqlManager     = ConfigurationLoader.CreateConfigurationNode(g, ConfigurationLoader.PropertySqlManager),
                  propGenericManager = ConfigurationLoader.CreateConfigurationNode(g, ConfigurationLoader.PropertyGenericManager),
                  propAsync          = ConfigurationLoader.CreateConfigurationNode(g, ConfigurationLoader.PropertyAsync);

            //Instantiate the Store Class
            switch (targetType.FullName)
            {
            case TripleStore:
                store = new TripleStore();
                break;

#if !SILVERLIGHT
            case WebDemandTripleStore:
                store = new WebDemandTripleStore();
                break;
#endif

#if !NO_DATA && !NO_STORAGE
            case SqlTripleStore:
            case ThreadedSqlTripleStore:
            case OnDemandTripleStore:
                subObj = ConfigurationLoader.GetConfigurationNode(g, objNode, propSqlManager);
                if (subObj == null)
                {
                    return(false);
                }

                temp = ConfigurationLoader.LoadObject(g, subObj);
                if (temp is ISqlIOManager)
                {
                    if (targetType.FullName.Equals(SqlTripleStore))
                    {
                        store = new SqlTripleStore((ISqlIOManager)temp);
                    }
                    else if (targetType.FullName.Equals(OnDemandTripleStore))
                    {
                        store = new OnDemandTripleStore((ISqlIOManager)temp);
                    }
                    else if (temp is IThreadedSqlIOManager)
                    {
                        isAsync = ConfigurationLoader.GetConfigurationBoolean(g, objNode, propAsync, false);
                        store   = new ThreadedSqlTripleStore((IThreadedSqlIOManager)temp, isAsync);
                    }
                    else
                    {
                        throw new DotNetRdfConfigurationException("Unable to load a SQL Triple Store identified by the Node '" + objNode.ToString() + "' as the value given for the dnr:sqlManager property points to an Object which could not be loaded as an object which implements either the ISqlIOManager/IThreadedSqlIOManager interface");
                    }
                }
                else
                {
                    throw new DotNetRdfConfigurationException("Unable to load a SQL Triple Store identified by the Node '" + objNode.ToString() + "' as the value given for the dnr:sqlManager property points to an Object which could not be loaded as an object which implements either the ISqlIOManager interface");
                }
                break;
#endif

#if !NO_STORAGE
            case NativeTripleStore:
                subObj = ConfigurationLoader.GetConfigurationNode(g, objNode, propGenericManager);
                if (subObj == null)
                {
                    return(false);
                }

                temp = ConfigurationLoader.LoadObject(g, subObj);
                if (temp is IQueryableGenericIOManager)
                {
                    store = new NativeTripleStore((IQueryableGenericIOManager)temp);
                }
                else
                {
                    throw new DotNetRdfConfigurationException("Unable to load a Native Triple Store identified by the Node '" + objNode.ToString() + "' as the value given for the dnr:genericManager property points to an Object which could not be loaded as an object which implements the IQueryableGenericIOManager interface");
                }
                break;

            case PersistentTripleStore:
                subObj = ConfigurationLoader.GetConfigurationNode(g, objNode, propGenericManager);
                if (subObj == null)
                {
                    return(false);
                }

                temp = ConfigurationLoader.LoadObject(g, subObj);
                if (temp is IGenericIOManager)
                {
                    store = new PersistentTripleStore((IGenericIOManager)temp);
                }
                else
                {
                    throw new DotNetRdfConfigurationException("Unable to load a Persistent Triple Store identified by the Node '" + objNode.ToString() + "' as the value given the for dnr:genericManager property points to an Object which could not be loaded as an object which implements the IGenericIOManager interface");
                }
                break;
#endif
            }

            //Read in additional data to be added to the Store
            if (store != null)
            {
                IEnumerable <INode> sources = ConfigurationLoader.GetConfigurationData(g, objNode, ConfigurationLoader.CreateConfigurationNode(g, "dnr:usingGraph"));

                //Read from Graphs
                foreach (INode source in sources)
                {
                    temp = ConfigurationLoader.LoadObject(g, source);
                    if (temp is IGraph)
                    {
                        store.Add((IGraph)temp);
                    }
                    else
                    {
                        throw new DotNetRdfConfigurationException("Unable to load data from a Graph for the Triple Store identified by the Node '" + objNode.ToString() + "' as one of the values for the dnr:usingGraph property points to an Object that cannot be loaded as an object which implements the IGraph interface");
                    }
                }

                //Load from Embedded Resources
                sources = ConfigurationLoader.GetConfigurationData(g, objNode, ConfigurationLoader.CreateConfigurationNode(g, ConfigurationLoader.PropertyFromEmbedded));
                foreach (INode source in sources)
                {
                    if (source.NodeType == NodeType.Literal)
                    {
                        EmbeddedResourceLoader.Load(store, ((ILiteralNode)source).Value);
                    }
                    else
                    {
                        throw new DotNetRdfConfigurationException("Unable to load data from an Embedded Resource for the Graph identified by the Node '" + objNode.ToString() + "' as one of the values for the dnr:fromEmbedded property is not a Literal Node as required");
                    }
                }

                //Read from Files - we assume these files are Dataset Files
                sources = ConfigurationLoader.GetConfigurationData(g, objNode, ConfigurationLoader.CreateConfigurationNode(g, ConfigurationLoader.PropertyFromFile));
                foreach (INode source in sources)
                {
                    if (source.NodeType == NodeType.Literal)
                    {
                        FileLoader.Load(store, ConfigurationLoader.ResolvePath(((ILiteralNode)source).Value));
                    }
                    else
                    {
                        throw new DotNetRdfConfigurationException("Unable to load data from a file for the Triple Store identified by the Node '" + objNode.ToString() + "' as one of the values for the dnr:fromFile property is not a Literal Node as required");
                    }
                }

                //Finally we'll apply any reasoners
                if (store is IInferencingTripleStore)
                {
                    IEnumerable <INode> reasoners = ConfigurationLoader.GetConfigurationData(g, objNode, ConfigurationLoader.CreateConfigurationNode(g, ConfigurationLoader.PropertyReasoner));
                    foreach (INode reasoner in reasoners)
                    {
                        temp = ConfigurationLoader.LoadObject(g, reasoner);
                        if (temp is IInferenceEngine)
                        {
                            ((IInferencingTripleStore)store).AddInferenceEngine((IInferenceEngine)temp);
                        }
                        else
                        {
                            throw new DotNetRdfConfigurationException("Unable to apply a reasoner for the Graph identified by the Node '" + objNode.ToString() + "' as one of the values for the dnr:reasoner property points to an Object which cannot be loaded as an object which implements the IInferenceEngine interface");
                        }
                    }
                }

                //And as an absolute final step if the store is transactional we'll flush any changes we've made
                if (store is ITransactionalStore)
                {
                    ((ITransactionalStore)store).Flush();
                }
            }

            obj = store;
            return(store != null);
        }
        public void CompileLiveScriptTemplate()
        {
            const string script = @"
take = (n, [x, ...xs]:list) -->
  | n <= 0     => []
  | empty list => []
  | otherwise  => [x] ++ take n - 1, xs

take 2, [1 2 3 4 5] #=> [1, 2]

take-three = take 3
take-three [3 to 8] #=> [3, 4, 5]

# Function composition, 'reverse' from prelude.ls
last-three = reverse >> take-three >> reverse
last-three [1 to 8] #=> [6, 7, 8]
";
            var          embeddedResourceLoader = new EmbeddedResourceLoader();
            var          liveScriptCompiler     = new LiveScriptCompiler(embeddedResourceLoader);

            var expectedCompiledScript = @"(function(){
  var take, takeThree, lastThree, slice$ = [].slice;
  take = curry$(function(n, list){
    var x, xs;
    x = list[0], xs = slice$.call(list, 1);
    switch (false) {
    case !(n <= 0):
      return [];
    case !empty(list):
      return [];
    default:
      return [x].concat(take(n - 1, xs));
    }
  });
  take(2, [1, 2, 3, 4, 5]);
  takeThree = take(3);
  takeThree([3, 4, 5, 6, 7, 8]);
  lastThree = function(){
    return reverse(takeThree(reverse.apply(this, arguments)));
  };
  lastThree([1, 2, 3, 4, 5, 6, 7, 8]);
  function curry$(f, bound){
    var context,
    _curry = function(args) {
      return f.length > 1 ? function(){
        var params = args ? args.concat() : [];
        context = bound ? context || this : this;
        return params.push.apply(params, arguments) <
            f.length && arguments.length ?
          _curry.call(context, params) : f.apply(context, params);
      } : f;
    };
    return _curry();
  }
}).call(this);
".Replace("\r", "");

            var compiledTemplate = liveScriptCompiler.Compile(script);

            Assert.AreEqual(expectedCompiledScript, compiledTemplate);
        }
Exemplo n.º 14
0
        /// <summary>
        /// Tries to load a Graph based on information from the Configuration Graph.
        /// </summary>
        /// <param name="g">Configuration Graph.</param>
        /// <param name="objNode">Object Node.</param>
        /// <param name="targetType">Target Type.</param>
        /// <param name="obj">Output Object.</param>
        /// <returns></returns>
        public bool TryLoadObject(IGraph g, INode objNode, Type targetType, out object obj)
        {
            obj = null;
            IGraph output;

            // Check whether to use a specific Triple Collection
            INode collectionNode = ConfigurationLoader.GetConfigurationNode(g, objNode, g.CreateUriNode(UriFactory.Create(ConfigurationLoader.PropertyUsingTripleCollection)));

            try
            {
                if (collectionNode == null)
                {
                    // Simple Graph creation
                    output = (IGraph)Activator.CreateInstance(targetType);
                }
                else
                {
                    // Graph with custom triple collection
                    BaseTripleCollection tripleCollection = ConfigurationLoader.LoadObject(g, collectionNode) as BaseTripleCollection;
                    if (tripleCollection == null)
                    {
                        throw new DotNetRdfConfigurationException("Unable to load the Graph identified by the Node '" + objNode.ToString() + "' as the dnr:usingTripleCollection points to an object which cannot be loaded as an instance of the required type BaseTripleCollection");
                    }
                    output = (IGraph)Activator.CreateInstance(targetType, new Object[] { tripleCollection });
                }
            }
            catch
            {
                // Any error means this loader can't load this type
                return(false);
            }

            // Now we want to find out where the data for the Graph is coming from
            // Data Source loading order is Graphs, Files, Strings, Databases, Stores, URIs
            IEnumerable <INode> sources;

            // Load from Graphs
            sources = ConfigurationLoader.GetConfigurationData(g, objNode, g.CreateUriNode(UriFactory.Create(ConfigurationLoader.PropertyFromGraph)));
            foreach (INode source in sources)
            {
                ConfigurationLoader.CheckCircularReference(objNode, source, "dnr:fromGraph");

                Object graph = ConfigurationLoader.LoadObject(g, source);
                if (graph is IGraph)
                {
                    output.Merge((IGraph)graph);
                }
                else
                {
                    throw new DotNetRdfConfigurationException("Unable to load data from another Graph for the Graph identified by the Node '" + objNode.ToString() + "' as one of the values for the dnr:fromGraph property points to an Object that cannot be loaded as an object which implements the IGraph interface");
                }
            }

            // Load from Embedded Resources
            sources = ConfigurationLoader.GetConfigurationData(g, objNode, g.CreateUriNode(UriFactory.Create(ConfigurationLoader.PropertyFromEmbedded)));
            foreach (INode source in sources)
            {
                if (source.NodeType == NodeType.Literal)
                {
                    EmbeddedResourceLoader.Load(output, ((ILiteralNode)source).Value);
                }
                else
                {
                    throw new DotNetRdfConfigurationException("Unable to load data from an Embedded Resource for the Graph identified by the Node '" + objNode.ToString() + "' as one of the values for the dnr:fromEmbedded property is not a Literal Node as required");
                }
            }

            // Load from Files
            sources = ConfigurationLoader.GetConfigurationData(g, objNode, g.CreateUriNode(UriFactory.Create(ConfigurationLoader.PropertyFromFile)));
            foreach (INode source in sources)
            {
                if (source.NodeType == NodeType.Literal)
                {
                    FileLoader.Load(output, ConfigurationLoader.ResolvePath(((ILiteralNode)source).Value));
                }
                else
                {
                    throw new DotNetRdfConfigurationException("Unable to load data from a file for the Graph identified by the Node '" + objNode.ToString() + "' as one of the values for the dnr:fromFile property is not a Literal Node as required");
                }
            }

            // Load from Strings
            sources = ConfigurationLoader.GetConfigurationData(g, objNode, g.CreateUriNode(UriFactory.Create(ConfigurationLoader.PropertyFromString)));
            foreach (INode source in sources)
            {
                if (source.NodeType == NodeType.Literal)
                {
                    StringParser.Parse(output, ((ILiteralNode)source).Value);
                }
                else
                {
                    throw new DotNetRdfConfigurationException("Unable to load data from a string for the Graph identified by the Node '" + objNode.ToString() + "' as one of the values for the dnr:fromString property is not a Literal Node as required");
                }
            }

            IEnumerable <Object> connections;

            // Load from Stores
            IEnumerable <INode> stores = ConfigurationLoader.GetConfigurationData(g, objNode, g.CreateUriNode(UriFactory.Create(ConfigurationLoader.PropertyFromStore)));

            stores.All(s => !ConfigurationLoader.CheckCircularReference(objNode, s, "dnr:fromStore"));
            connections = stores.Select(s => ConfigurationLoader.LoadObject(g, s));
            sources     = ConfigurationLoader.GetConfigurationData(g, objNode, g.CreateUriNode(UriFactory.Create(ConfigurationLoader.PropertyWithUri)));
            foreach (Object store in connections)
            {
                if (store is IStorageProvider)
                {
                    foreach (INode source in sources)
                    {
                        if (source.NodeType == NodeType.Uri || source.NodeType == NodeType.Literal)
                        {
                            ((IStorageProvider)store).LoadGraph(output, source.ToString());
                        }
                        else
                        {
                            throw new DotNetRdfConfigurationException("Unable to load data from a Generic Store for the Graph identified by the Node '" + objNode.ToString() + "' as one of the values for the dnr:withUri property is not a URI/Literal Node as required");
                        }
                    }
                }
                else if (store is ITripleStore)
                {
                    foreach (INode source in sources)
                    {
                        if (source.NodeType == NodeType.Uri)
                        {
                            output.Merge(((ITripleStore)store)[((IUriNode)source).Uri]);
                        }
                        else if (source.NodeType == NodeType.Literal)
                        {
                            output.Merge(((ITripleStore)store)[UriFactory.Create(((ILiteralNode)source).Value)]);
                        }
                        else
                        {
                            throw new DotNetRdfConfigurationException("Unable to load data from a Store for the Graph identified by the Node '" + objNode.ToString() + "' as one of the values for the dnr:withUri property is not a URI/Literal Node as required");
                        }
                    }
                }
                else
                {
                    throw new DotNetRdfConfigurationException("Unable to load data from a Store for the Graph identified by the Node '" + objNode.ToString() + "' as one of the values of the dnr:fromStore property points to an Object which cannot be loaded as an object which implements either the IStorageProvider/ITripleStore interface");
                }
            }

            // Load from Datasets
            IEnumerable <INode> ds = ConfigurationLoader.GetConfigurationData(g, objNode, g.CreateUriNode(UriFactory.Create(ConfigurationLoader.PropertyFromDataset)));

            ds.All(d => !ConfigurationLoader.CheckCircularReference(objNode, d, ConfigurationLoader.PropertyFromDataset));
            IEnumerable <Object> datasets = ds.Select(d => ConfigurationLoader.LoadObject(g, d));

            sources = ConfigurationLoader.GetConfigurationData(g, objNode, g.CreateUriNode(UriFactory.Create(ConfigurationLoader.PropertyWithUri)));
            foreach (Object dataset in datasets)
            {
                if (dataset is ISparqlDataset)
                {
                    foreach (INode source in sources)
                    {
                        if (source.NodeType == NodeType.Uri)
                        {
                            output.Merge(((ISparqlDataset)dataset)[((IUriNode)sources).Uri]);
                        }
                        else if (source.NodeType == NodeType.Literal)
                        {
                            output.Merge(((ISparqlDataset)dataset)[UriFactory.Create(((ILiteralNode)source).Value)]);
                        }
                        else
                        {
                            throw new DotNetRdfConfigurationException("Unable to load data from a Dataset for the Graph identified by the Node '" + objNode.ToString() + "' as one of the values for the dnr:withUri property is not a URI/Literal Node as required");
                        }
                    }
                }
                else
                {
                    throw new DotNetRdfConfigurationException("Unable to load data from a Dataset for the Graph identified by the Node '" + objNode.ToString() + "' as one of the values of the dnr:fromDataset property points to an Object which cannot be loaded as an object which implements the required ISparqlDataset interface");
                }
            }


            // Finally load from Remote URIs
            sources = ConfigurationLoader.GetConfigurationData(g, objNode, g.CreateUriNode(UriFactory.Create(ConfigurationLoader.PropertyFromUri)));
            foreach (INode source in sources)
            {
                if (source.NodeType == NodeType.Uri)
                {
                    UriLoader.Load(output, ((IUriNode)source).Uri);
                }
                else if (source.NodeType == NodeType.Literal)
                {
                    UriLoader.Load(output, UriFactory.Create(((ILiteralNode)source).Value));
                }
                else
                {
                    throw new DotNetRdfConfigurationException("Unable to load data from a URI for the Graph identified by the Node '" + objNode.ToString() + "' as one of the values for the dnr:fromUri property is not a URI/Literal Node as required");
                }
            }

            // Then are we assigning a Base URI to this Graph which overrides any existing Base URI?
            INode baseUri = ConfigurationLoader.GetConfigurationNode(g, objNode, g.CreateUriNode(UriFactory.Create(ConfigurationLoader.PropertyAssignUri)));

            if (baseUri != null)
            {
                if (baseUri.NodeType == NodeType.Uri)
                {
                    output.BaseUri = ((IUriNode)baseUri).Uri;
                }
                else if (baseUri.NodeType == NodeType.Literal)
                {
                    output.BaseUri = UriFactory.Create(((ILiteralNode)baseUri).Value);
                }
                else
                {
                    throw new DotNetRdfConfigurationException("Unable to assign a new Base URI for the Graph identified by the Node '" + objNode.ToString() + "' as the value for the dnr:assignUri property is not a URI/Literal Node as required");
                }
            }

            // Finally we'll apply any reasoners
            IEnumerable <INode> reasoners = ConfigurationLoader.GetConfigurationData(g, objNode, g.CreateUriNode(UriFactory.Create(ConfigurationLoader.PropertyReasoner)));

            foreach (INode reasoner in reasoners)
            {
                Object temp = ConfigurationLoader.LoadObject(g, reasoner);
                if (temp is IInferenceEngine)
                {
                    ((IInferenceEngine)temp).Apply(output);
                }
                else
                {
                    throw new DotNetRdfConfigurationException("Unable to apply a reasoner for the Graph identified by the Node '" + objNode.ToString() + "' as one of the values for the dnr:reasoner property points to an Object which cannot be loaded as an object which implements the IInferenceEngine interface");
                }
            }

            obj = output;
            return(true);
        }
Exemplo n.º 15
0
        /// <summary>
        /// log4net.ILogインスタンスの取得
        /// </summary>
        /// <param name="loggerName">ロガー名</param>
        /// <returns>log4netのインターフェイス</returns>
        public static log4net.ILog GetLog4netIf(string loggerName)
        {
            lock (LogManager._lock)
            {
                // null対策
                if (LogManager._logIfHt == null)
                {
                    LogManager._logIfHt = new Dictionary <string, log4net.ILog>();
                }

                // すでにlog4net.ILogインスタンスが存在する。
                if (LogManager._logIfHt.ContainsKey(loggerName)) // Dic化でnullチェック変更
                {
                    // 生成済みのlog4net.ILogインスタンスを返す。
                    return((log4net.ILog)LogManager._logIfHt[loggerName]);
                }
                else
                {
                    // #12-start

                    // 定義ファイル
                    string log4netConfFile = GetConfigParameter.GetConfigValue(PubLiteral.LOG4NET_CONF_FILE);

                    // log4netの設定ファイルのパス
                    if (log4netConfFile == null || log4netConfFile == "")
                    {
                        // 定義ファイルのパスが無い場合

                        // 空のロガーを返す(エラーにはならない)
                        return(log4net.LogManager.GetLogger(""));
                    }
                    else
                    {
                        // 埋め込まれたリソース ローダで存在チェック
                        if (EmbeddedResourceLoader.Exists(log4netConfFile, false))
                        {
                            // ログ定義 [埋め込まれたリソース]
                            XmlDocument xmlDef = new XmlDocument();

                            // Exceptionが上がり得る。
                            xmlDef.LoadXml(EmbeddedResourceLoader.LoadXMLAsString(log4netConfFile));

                            if (xmlDef["log4net"] == null)
                            {
                                // XmlElement(log4net)が無い場合
                                throw new ArgumentException(String.Format(
                                                                PublicExceptionMessage.XML_ELEMENT_ERROR,
                                                                PublicExceptionMessage.XML_ELEMENT_ERROR_LOG4NET));
                            }

                            // log4net
                            XmlConfigurator.Configure(xmlDef["log4net"]);
                        }
                        else
                        {
                            // リソース ローダで存在チェック(存在しなければエラー)
                            ResourceLoader.Exists(log4netConfFile, true);

                            // ログ定義 [リソース ファイル] → ストリームを開く
                            FileStream s = new FileStream(
                                PubCmnFunction.BuiltStringIntoEnvironmentVariable(log4netConfFile),
                                FileMode.Open, FileAccess.Read, FileShare.Read);

                            // log4netのXML形式の設定ファイルを読み込む。
                            XmlConfigurator.Configure(s);
                            s.Close();
                        }

                        // log4net.ILogインスタンスを初期化する。
                        LogManager._logIfHt.Add(loggerName, log4net.LogManager.GetLogger(loggerName));

                        // 生成したlog4net.ILogインスタンスを返す。
                        return((log4net.ILog)LogManager._logIfHt[loggerName]);
                    }

                    // #12-end
                }
            }
        }
 public void It_Should_Not_Throw_When_Resource_Doesnt_Exist()
 {
     var loader = new EmbeddedResourceLoader(GetType().GetTypeInfo().Assembly);
     var result = loader.Load("Foo");
     Assert.Null(result);
 }
Exemplo n.º 17
0
        public override void ResetDB()
        {
            var resetStmt = EmbeddedResourceLoader.ReadFullContent("Scripts", "resetDB.sql");

            SQLConnectionExecutor.ExecuteSQLNonQuery(ConnectionString, resetStmt);
        }
 public void It_Should_Work_With_Different_Extensions()
 {
     var loader = new EmbeddedResourceLoader(GetType().GetTypeInfo().Assembly, "must");
     var result = loader.Load("EmbeddedBar");
     Assert.Equal("I'm the Embedded {{bar}} template.", result);
 }
Exemplo n.º 19
0
        /// <summary>
        /// https://github.com/dotnetrdf/dotnetrdf/wiki/UserGuide-Reading-RDF
        /// </summary>
        public void PlayWithReadingRdf()
        {
            #region Reading RDF from Files
            IGraph       g         = new Graph();
            IGraph       h         = new Graph();
            TurtleParser ttlparser = new TurtleParser();

            // Load using a Filename
            ttlparser.Load(g, "HelloWorld.ttl");

            // Load using a StreamReader
            ttlparser.Load(h, new StreamReader("HelloWorld.ttl"));

            try
            {
                IGraph         g2       = new Graph();
                NTriplesParser ntparser = new NTriplesParser();

                //Load using Filename
                ntparser.Load(g2, "HelloWorld.nt");
            }
            catch (RdfParseException parseEx)
            {
                //This indicates a parser error e.g unexpected character, premature end of input, invalid syntax etc.
                Console.WriteLine("Parser Error");
                Console.WriteLine(parseEx.Message);
            }
            catch (RdfException rdfEx)
            {
                //This represents a RDF error e.g. illegal triple for the given syntax, undefined namespace
                Console.WriteLine("RDF Error");
                Console.WriteLine(rdfEx.Message);
            }
            #endregion

            #region Reading RDF from URIs

            try
            {
                IGraph g3 = new Graph();
                //UriLoader.Load(g3, new Uri("http://dbpedia.org/resource/Barack_Obama"));
            }
            catch (RdfParseException parseEx)
            {
                //This indicates a parser error e.g unexpected character, premature end of input, invalid syntax etc.
                Console.WriteLine("Parser Error");
                Console.WriteLine(parseEx.Message);
            }
            catch (RdfException rdfEx)
            {
                //This represents a RDF error e.g. illegal triple for the given syntax, undefined namespace
                Console.WriteLine("RDF Error");
                Console.WriteLine(rdfEx.Message);
            }
            #endregion

            #region Reading RDF from Embedded Resources

            try
            {
                IGraph g4 = new Graph();
                EmbeddedResourceLoader.Load(g4, "embedded.ttl, PlayWithDotNetRDF");
                Console.WriteLine(g4.IsEmpty);
            }
            catch (RdfParseException parseEx)
            {
                //This indicates a parser error e.g unexpected character, premature end of input, invalid syntax etc.
                Console.WriteLine("Parser Error");
                Console.WriteLine(parseEx.Message);
            }
            catch (RdfException rdfEx)
            {
                //This represents a RDF error e.g. illegal triple for the given syntax, undefined namespace
                Console.WriteLine("RDF Error");
                Console.WriteLine(rdfEx.Message);
            }
            #endregion

            #region Reading RDF from Strings

            Graph g5 = new Graph();
            StringParser.Parse(g5, "<http://example.org/a> <http://example.org/b> <http://example.org/c>.");

            Graph          g6     = new Graph();
            NTriplesParser parser = new NTriplesParser();
            parser.Load(g6, new StringReader("<http://example.org/a> <http://example.org/b> <http://example.org/c>."));

            #endregion

            #region Store Parsers

            /*
             * TripleStore store = new TripleStore();
             * TriGParser trigparser = new TriGParser();
             *
             * //Load the Store
             * trigparser.Load(store, "Example.trig");
             */

            #endregion

            #region Advanced Parsing

            // Create a Handler and use it for parsing
            CountHandler handler      = new CountHandler();
            TurtleParser turtleParser = new TurtleParser();
            turtleParser.Load(handler, "HelloWorld.ttl");

            //Print the resulting count
            Console.WriteLine(handler.Count + " Triple(s)");

            // https://github.com/dotnetrdf/dotnetrdf/wiki/UserGuide-Handlers-API
            #endregion

            /*
             * Parser Class         Supported Input
             * NTriplesParser       NTriples
             * Notation3Parser  Notation 3, Turtle, NTriples, some forms of TriG
             * NQuadsParser         NQuads, NTriples
             * RdfAParser           RDFa 1.0 embedded in (X)HTML, some RDFa 1.1 support
             * RdfJsonParser        RDF/JSON (Talis specification)
             * RdfXmlParser         RDF/XML
             * TriGParser           TriG
             * TriXParser           TriX
             * TurtleParser         Turtle, NTriples
             * JsonLdParser         JSON-LD
             */
        }
 public void It_Should_Be_Able_To_Find_EmbeddedResources()
 {
     var loader = new EmbeddedResourceLoader(GetType().GetTypeInfo().Assembly);
     var result = loader.Load("EmbeddedFoo");
     Assert.Equal("I'm the Embedded {{foo}} template.", result);
 }
        public void CompileIcedCoffeeTemplate()
        {
            const string script = @"# Assignment:
number   = 42
opposite = true

# Conditions:
number = -42 if opposite

# Functions:
square = (x) -> x * x

# Arrays:
list = [1, 2, 3, 4, 5]

# Objects:
math =
  root:   Math.sqrt
  square: square
  cube:   (x) -> x * square x

# Splats:
race = (winner, runners...) ->
  print winner, runners

# Existence:
alert ""I knew it!"" if elvis?

# Array comprehensions:
cubes = (math.cube num for num in list)";
            var          embeddedResourceLoader = new EmbeddedResourceLoader();
            var          icedCoffeeCompiler     = new IcedCoffeeCompiler(embeddedResourceLoader);

            var expectedCompiledScript = @"(function() {
  var cubes, list, math, num, number, opposite, race, square,
    __slice = [].slice;



  number = 42;

  opposite = true;

  if (opposite) {
    number = -42;
  }

  square = function(x) {
    return x * x;
  };

  list = [1, 2, 3, 4, 5];

  math = {
    root: Math.sqrt,
    square: square,
    cube: function(x) {
      return x * square(x);
    }
  };

  race = function() {
    var runners, winner;
    winner = arguments[0], runners = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
    return print(winner, runners);
  };

  if (typeof elvis !== ""undefined"" && elvis !== null) {
    alert(""I knew it!"");
  }

  cubes = (function() {
    var _i, _len, _results;
    _results = [];
    for (_i = 0, _len = list.length; _i < _len; _i++) {
      num = list[_i];
      _results.push(math.cube(num));
    }
    return _results;
  })();

}).call(this);
".Replace("\r", "");

            var compiledTemplate = icedCoffeeCompiler.Compile(script);

            Assert.AreEqual(expectedCompiledScript, compiledTemplate);
        }