Exemplo n.º 1
0
        public void AddResourceDirect( IResource resource )
        {
            if ( items.Contains( resource ) )
                return;

            items.Add( resource );
        }
        /// <summary>
        /// Generates the URI template.
        /// </summary>
        /// <param name="resource">The resource.</param>
        /// <param name="baseUri">The base URI.</param>
        /// <param name="logger">The logger.</param>
        /// <returns>A Uri template a client can expand to invoke a resource.</returns>
        /// <exception cref="System.ArgumentNullException">Throws and exception if <paramref name="resource"/> or <paramref name="logger"/> is <c>null</c>.</exception>
        public string GenerateUriTemplate(IResource resource, string baseUri, ILogger logger)
        {
            if (resource == null)
            {
                throw new ArgumentNullException("resource");
            }

            if (logger == null)
            {
                throw new ArgumentNullException("logger");
            }

            string result = null;
            try
            {
                result = GenerateUriTemplate(resource.Name, baseUri, resource.Parameters, logger);
            }
            catch (Exception exception)
            {
                logger.Error(Resources.GenerateUriExecutionError, exception, GetType());
            }

            if (result != null)
            {
                return result;
            }

            return string.Empty;
        }
Exemplo n.º 3
0
        /// <summary>
        /// Converts the resource to the specified version
        /// </summary>
        /// <param name="resource">The resource.</param>
        /// <param name="targetVersion">The target version.</param>
        /// <returns></returns>
        public IResource Convert(IResource resource, Version targetVersion)
        {
            //How does this work? If source and target versions are known, it means the classes
            //that represent them are also known and we just serialize from the source type to xml
            //and deserialize that xml to the target type, with any unsupported bits falling by the
            //wayside in the process, and any new bits flubbed with default values as part of deserialization

            var resVer = resource.GetResourceTypeDescriptor().Version;
            var dstVer = string.Format("{0}.{1}.{2}", targetVersion.Major, targetVersion.Minor, targetVersion.Build); //NOXLATE
            var dstXsd = resource.ValidatingSchema.Replace(resVer, dstVer);

            using (var sr = ResourceTypeRegistry.Serialize(resource))
            {
                using (var str = new StreamReader(sr))
                {
                    var xml = new StringBuilder(str.ReadToEnd());
                    xml.Replace(resource.ValidatingSchema, dstXsd);
                    xml.Replace("version=\"" + resVer, "version=\"" + dstVer); //NOXLATE

                    var convRes = ResourceTypeRegistry.Deserialize(xml.ToString());
                    convRes.CurrentConnection = resource.CurrentConnection;
                    convRes.ResourceID = resource.ResourceID;
                    return convRes;
                }
            }
        }
Exemplo n.º 4
0
 /// <summary>
 /// Initializes a new instance of the ProfilingDialog class
 /// </summary>
 /// <param name="item"></param>
 /// <param name="resourceId"></param>
 /// <param name="connection"></param>
 public ProfilingDialog(IResource item, string resourceId, IServerConnection connection)
     : this()
 {
     m_connection = connection;
     m_item = item;
     m_resourceId = resourceId;
 }
 /// <summary>
 /// Create an encoded resource using the specified encoding.
 /// </summary>
 /// <param name="resource">the resource to read from. Must not be <c>null</c></param>
 /// <param name="encoding">the encoding to use. If <c>null</c>, encoding will be autodetected.</param>
 /// <param name="autoDetectEncoding">whether to autoDetect encoding from byte-order marks (<see cref="StreamReader(Stream, Encoding, bool)"/>)</param>
 public EncodedResource(IResource resource, Encoding encoding, bool autoDetectEncoding)
 {
     AssertUtils.ArgumentNotNull(resource, "resource");
     this.resource = resource;
     this.encoding = encoding;
     this.autoDetectEncoding = autoDetectEncoding;
 }
Exemplo n.º 6
0
		public override void ProcessResource(IResource source, IConfigurationStore store)
		{
			XmlProcessor.XmlProcessor processor;
			if (Kernel == null)
			{
				processor = new XmlProcessor.XmlProcessor(EnvironmentName);
			}
			else
			{
				var resourceSubSystem = Kernel.GetSubSystem(SubSystemConstants.ResourceKey) as IResourceSubSystem;
				processor = new XmlProcessor.XmlProcessor(EnvironmentName, resourceSubSystem);
			}

			try
			{
				XmlNode element = processor.Process(source);

				Deserialize(element, store);
			}
			catch(XmlProcessorException)
			{
				const string message = "Unable to process xml resource ";

				throw new Exception(message);
			}
		}
Exemplo n.º 7
0
 /// <summary>
 /// Initializes a new instance of the Location class.
 /// </summary>
 /// <param name="resource"></param>
 /// <param name="source"></param>
 public Location(IResource resource, object source)
 {
     //TODO: look into re-enabling this since resource *is* NULL when parsing config classes vs. acquiring IResources
     //AssertUtils.ArgumentNotNull(resource, "resource");
     this.resource = resource;
     this.source = source;
 }
Exemplo n.º 8
0
        public void DecorateClass(IResource resource,
                                  string className,
                                  CodeTypeDeclaration resourceClass,
                                  ResourceClassGenerator generator,
                                  string serviceClassName,
                                  IEnumerable<IResourceDecorator> allDecorators)
        {
            foreach (IMethod method in resource.Methods.Values)
            {
                foreach (IParameter parameter in method.Parameters.Values)
                {
                    if (parameter.EnumValues.IsNullOrEmpty())
                    {
                        continue; // Not an enumeration type.
                    }

                    // Check whether the type already exists.
                    if (DecoratorUtil.FindFittingEnumeration(
                            resourceClass, parameter.EnumValues, parameter.EnumValueDescriptions) != null)
                    {
                        continue;
                    }

                    // Create and add the enumeration.
                    resourceClass.Members.Add(GenerateEnum(
                            resourceClass, parameter.Name, parameter.Description, parameter.EnumValues,
                            parameter.EnumValueDescriptions));
                }
            }
        }
Exemplo n.º 9
0
        /// <summary>
        /// Initializes a new instance of the <see cref="AbstractInterpreter"/> class
        /// from an The <see cref="IResource"/>.
        /// </summary>
        /// <param name="source">The <see cref="IResource"/>.</param>
        public AbstractInterpreter(IResource source)
        {
            Contract.Require.That(source, Is.Not.Null).When("retrieving argument IResource in AbstractInterpreter constructor");

            resource = source;

        }
Exemplo n.º 10
0
        /// <summary>
        /// Initializes a new instance of the ConfigurationClass class.
        /// </summary>
        /// <param name="objectName"></param>
        /// <param name="type"></param>
        public ConfigurationClass(string objectName, Type type)
        {
            _objectName = objectName;
            _configurationClassType = type;
            _resource = new ConfigurationClassAssemblyResource(type);

        }
Exemplo n.º 11
0
        /// <summary>
        /// Validats the specified resources for common issues associated with this
        /// resource type
        /// </summary>
        /// <param name="context"></param>
        /// <param name="resource"></param>
        /// <param name="recurse"></param>
        /// <returns></returns>
        public virtual ValidationIssue[] Validate(ResourceValidationContext context, IResource resource, bool recurse)
        {
            if (!resource.GetResourceTypeDescriptor().Equals(this.SupportedResourceAndVersion))
                return null;

            return ValidateBase(context, resource, recurse);
        }
Exemplo n.º 12
0
        public string Upload(IResource resource, string storeName)
        {
            // Authenticate the application (if not authenticated) and load the OAuth token
            // if (!File.Exists(OAuthTokenFileName))
            // {
            //     AuthorizeAppOAuth(dropboxServiceProvider);
            // }

            // OAuthToken oauthAccessToken = LoadOAuthToken();

            // Login in Dropbox
            IDropbox dropbox = this.dropboxServiceProvider
                .GetApi(AuthorizationConstants.DropBoxOAuthAccessTokenValue, AuthorizationConstants.DropBoxOAuthAccessTokenSecret);

            // Display user name (from his profile)
            DropboxProfile profile = dropbox.GetUserProfileAsync().Result;

            // Upload a file
            Entry uploadFileEntry = dropbox.UploadFileAsync(resource, storeName).Result;

            // Share a file
            DropboxLink sharedUrl = dropbox.GetShareableLinkAsync(uploadFileEntry.Path).Result;

            var link = dropbox.GetMediaLinkAsync(uploadFileEntry.Path).Result;
            return link.Url;
        }
 public override void DecorateClass(IResource resource,
                           IMethod request,
                           CodeTypeDeclaration requestClass,
                           CodeTypeDeclaration resourceClass)
 {
     requestClass.Members.Add(CreateRequiredConstructor(resourceClass, request, false));
 }
		public string GetURL(IResource resource)
		{
			string url;
			_lock.AcquireReaderLock(3000);
			try
			{
				if (!_urlCache.TryGetValue(resource, out url))
				{
					var c = _lock.UpgradeToWriterLock(3000);
					try
					{
						_urlCache.Add(resource, url = GetURLInternal(resource));
					}
					finally
					{
						_lock.DowngradeFromWriterLock(ref c);
					}
				}
			}
			finally
			{
				_lock.ReleaseReaderLock();
			}
			IProxyResource pr = resource as IProxyResource;
			if (!(resource.Location is ExternalLocation) && pr != null && (pr.CultureSensitive || pr.CultureUISensitive))
			{
				url += "-";
				if (pr.CultureSensitive)
					url += CultureInfo.CurrentCulture.LCID.ToString("x");
				url += "-";
				if (pr.CultureUISensitive)
					url += CultureInfo.CurrentCulture.LCID.ToString("x");
			}
			return url;
		}
		private string GetURLInternal(IResource resource)
		{
			IResourceLocation location = resource.Location;
			string path;
			if (location is TypeLocation)
			{
				TypeLocation tl = location as TypeLocation;
				path = String.Format("{2}/{3}{0}/{1}{4}", HttpUtility.UrlPathEncode(tl.ProxyType.Assembly.GetName().Name), HttpUtility.UrlPathEncode(tl.ProxyType.FullName), AppPath, ResourceHttpHandler.AssemblyPath, ResourceHttpHandler.Extension);
			}
			else if (location is EmbeddedLocation)
			{
				EmbeddedLocation el = location as EmbeddedLocation;
				path = String.Format("{2}/{3}{0}/{1}{4}", HttpUtility.UrlPathEncode(el.Assembly.GetName().Name), HttpUtility.UrlPathEncode(el.ResourceName), AppPath, ResourceHttpHandler.AssemblyPath, ResourceHttpHandler.Extension);
			}
			else if (location is VirtualPathLocation)
			{
				VirtualPathLocation vl = location as VirtualPathLocation;
				path = HttpUtility.UrlPathEncode(vl.VirtualPath);
				if (resource is IProxyResource) path += ResourceHttpHandler.Extension;
			}
			else if (location is ExternalLocation)
			{
				ExternalLocation el = location as ExternalLocation;
				return el.Uri.ToString();
			}
			else
				throw new Exception("Unknown IResourceLocationType");
			return path + "?" + ToHex(resource.Version);
		}
        private string ParseReferenceElement(string serializedReferenceElement, IResource resource)
        {
            XElement referenceElement;
            try
            {
                referenceElement = XElement.Parse(serializedReferenceElement);
            }
            catch (Exception)
            {
                return null;
            }
            var pathAttr = referenceElement.Attribute("path");
            if (pathAttr != null)
            {
                string path = RemoveVsDocIfPresent(pathAttr.Value);
                path = path.ToAppRelativePath(resource);

                return path;
            }

            var nameAttr = referenceElement.Attribute("name");
            if(nameAttr != null)
            {
                return CreateAssemblyVirtualPath(referenceElement, nameAttr.Value);
            }

            return null;
        }
Exemplo n.º 17
0
        private static void ConvertRecursively(IResource currentResource, JObject node, JsonSerializer serializer)
        {
            if (currentResource == null)
            {
                return;
            }

            var currentResourceType = currentResource.GetType();
            var readableProperties = GetReadablePropertyInfos(currentResourceType);

            var nonResourceProperties = readableProperties.Where(IsNeitherResourceOrReservedProperty).ToList();
            var resourceProperties = readableProperties.Where(IsResourceProperty).ToList();

            node.Add(ReservedPropertyNames.Relations, JObject.FromObject(currentResource.Relations, serializer));
            var embeddedResourceObject = new JObject();
            node.Add(ReservedPropertyNames.EmbeddedResources, embeddedResourceObject);

            foreach (var resourceProperty in resourceProperties)
            {                
                var embeddedResourceNodeValue = new JObject();

                ConvertRecursively((IResource)resourceProperty.GetValue(currentResource), embeddedResourceNodeValue, serializer);
                embeddedResourceObject.Add(ToCamelCase(resourceProperty.Name), embeddedResourceNodeValue);
            }

            if (IsCollectionResourceType(currentResourceType))
            {
                var currentResourceDynamic = (dynamic) currentResource;
                var jArray = new JArray();
                string name = "";
                foreach (IResource resourceItem in currentResourceDynamic.Items)
                {
                    var embeddedResourceNodeValue = new JObject();
                    ConvertRecursively(resourceItem, embeddedResourceNodeValue, serializer);
                    jArray.Add(embeddedResourceNodeValue);
                    name =  resourceItem.GetType().Name;
                }

                // Remove the "Resource" by convention.
                if (name.EndsWith("Resource"))
                {
                    name = name.Remove(name.LastIndexOf("Resource", StringComparison.Ordinal));
                }

                embeddedResourceObject.Add(ToCamelCase(name), jArray);
            }

            foreach (var nonResourceProperty in nonResourceProperties)
            {
                var value = nonResourceProperty.GetValue(currentResource);
                if (value != null && value.GetType().GetTypeInfo().IsClass && value.GetType() != typeof(string))
                {
                    node.Add(ToCamelCase(nonResourceProperty.Name), JToken.FromObject(value, serializer));
                }
                else
                {
                    node.Add(ToCamelCase(nonResourceProperty.Name), new JValue(value));
                }                
            }
        }
Exemplo n.º 18
0
        public void DecorateClass(IResource resource,
                                  string className,
                                  CodeTypeDeclaration resourceClass,
                                  ResourceClassGenerator generator,
                                  string serviceClassName,
                                  IEnumerable<IResourceDecorator> allDecorators)
        {
            resource.ThrowIfNull("resource");
            className.ThrowIfNull("className");
            resourceClass.ThrowIfNull("resourceClass");
            generator.ThrowIfNull("generator");
            serviceClassName.ThrowIfNull("serviceClassName");
            allDecorators.ThrowIfNull("allDecorators");

            if (!resource.IsServiceResource) // Only add subresources of normal resources, not the root resource.
            {
                // Add all subresources.
                foreach (IResource subresource in resource.Resources.Values)
                {
                    // Consider all members in the current class as invalid names.
                    var forbiddenWords = from CodeTypeMember m in resourceClass.Members select m.Name;

                    // Generate and add the subresource.
                    CodeTypeDeclaration decl = GenerateSubresource(
                        subresource, serviceClassName, allDecorators, generator.RequestGenerator,
                        generator.ContainerGenerator, forbiddenWords);
                    resourceClass.Members.Add(decl);
                }
            }
        }
Exemplo n.º 19
0
        public async Task<Entry> UploadImageToCloud(IResource resource, string fileName, ITownsService towns, int townId)
        {
            string path = "/" +  CreateFolder(towns, townId) + "/" + fileName;
            Entry uploadFileEntry = await this.dropboxApi.UploadFileAsync(resource, path);

            return uploadFileEntry;
        }
Exemplo n.º 20
0
		public XmlNode Process(IResource resource)
		{
			try
			{
				using (resource)
				{
					var doc = new XmlDocument();
					using (var stream = resource.GetStreamReader())
					{
						doc.Load(stream);
					}

					engine.PushResource(resource);

					var element = Process(doc.DocumentElement);

					engine.PopResource();

					return element;
				}
			}
			catch (ConfigurationProcessingException)
			{
				throw;
			}
			catch (Exception ex)
			{
				var message = String.Format("Error processing node resource {0}", resource);

				throw new ConfigurationProcessingException(message, ex);
			}
		}
Exemplo n.º 21
0
		public virtual void Enlist(IResource resource)
		{
			logger.DebugFormat("Enlisting resource {0}", resource);

			if (resource == null) throw new ArgumentNullException("resource");

			// We can't add the resource more than once
			if (resources.Contains(resource)) return;

			if (Status == TransactionStatus.Active)
			{
				try
				{
					resource.Start();
				}
				catch(Exception ex)
				{
					state = TransactionStatus.Invalid;

					logger.Error("Enlisting resource failed", ex);

					throw;
				}
			}

			resources.Add(resource);

			logger.DebugFormat("Resource enlisted successfully {0}", resource);
		}
Exemplo n.º 22
0
		public void Setup()
		{
			setupResource = new StaticContentResource(@"<?xml version=""1.0"" encoding=""utf-8"" ?>

<configuration>

    <facilities>
      <facility id=""startable"" type=""Castle.Facilities.Startable.StartableFacility, Castle.MicroKernel"" />
    </facilities>

	<components>

		<!--if this line is uncommented (and the serviceB declared below commented), serviceA is resolved correctly -->
		<!--<component id=""ServiceB"" type=""StartableFacilityTest.B, StartableFacilityTest"" service=""StartableFacilityTest.IB, StartableFacilityTest"" />-->

		<component id=""ServiceA"" type=""Castle.Windsor.Tests.Bugs.FACILITIES_ISSUE_111.Components.A_Facilities_Issue_111, Castle.Windsor.Tests"" service=""Castle.Windsor.Tests.Bugs.FACILITIES_ISSUE_111.Components.IA_Facilities_Issue_111, Castle.Windsor.Tests"">
			<parameters>
				<ibs>
					<array>
						<item>${ServiceB}</item>
					</array>
				</ibs>
			</parameters>
		</component>

		<component id=""ServiceB"" type=""Castle.Windsor.Tests.Bugs.FACILITIES_ISSUE_111.Components.B_Facilities_Issue_111, Castle.Windsor.Tests"" service=""Castle.Windsor.Tests.Bugs.FACILITIES_ISSUE_111.Components.IB_Facilities_Issue_111, Castle.Windsor.Tests"" />

	</components>

</configuration>
");

		}
Exemplo n.º 23
0
 private void listViewModels_SelectedIndexChanged(object sender, EventArgs e)
 {
     if (listViewModels.SelectedItems.Count > 0)
     {
         selectedItem = (IResource)listViewModels.SelectedItems[0].Tag;
     }
 }
 public bool LoadMidi(IResource midiFile)
 {
     if (playing == true)
         return false;
     LoadMidiFile(new MidiFile(midiFile));
     return true;
 }
Exemplo n.º 25
0
        /// <summary>
        /// Strips for ship.
        /// </summary>
        /// <param name="resource">The resource.</param>
        /// <returns></returns>
        public SerializableResource SerializeResourceForStudio(IResource resource)
        {

            // convert the fliping errors due to json issues in c# ;(
            var errors = new List<ErrorInfo>();
            var parseErrors = resource.Errors;
            if(parseErrors != null)
            {
                errors.AddRange(parseErrors.Select(error => (error as ErrorInfo)));
            }

            var datalist = "<DataList></DataList>";

            if(resource.DataList != null)
            {
                var replace = resource.DataList.Replace("\"", GlobalConstants.SerializableResourceQuote);
                datalist = replace.Replace("'", GlobalConstants.SerializableResourceSingleQuote).ToString();
            }

            return new SerializableResource
            {
                Inputs = resource.Inputs,
                Outputs = resource.Outputs,
                ResourceCategory = resource.ResourcePath,
                ResourceID = resource.ResourceID,
                VersionInfo = resource.VersionInfo,
                ResourceName = resource.ResourceName,
                Permissions = AuthorizationService.GetResourcePermissions(resource.ResourceID),
                ResourceType = resource.ResourceType,
                IsValid = resource.IsValid,
                DataList = datalist,
                Errors = errors,
                IsNewResource = resource.IsNewResource
            };
        }
 public void LoadBank(IResource bankFile)
 {
     if (!bankFile.ReadAllowed())
         throw new Exception("The bank file provided does not have read access.");
     bank.Clear();
     assets.PatchAssetList.Clear();
     assets.SampleAssetList.Clear();
     bankName = string.Empty;
     comment = string.Empty;
     switch (IOHelper.GetExtension(bankFile.GetName()).ToLower())
     {
         case ".bank":
             bankName = IOHelper.GetFileNameWithoutExtension(bankFile.GetName());
             LoadMyBank(bankFile.OpenResourceForRead());
             break;
         case ".sf2":
             bankName = "SoundFont";
             LoadSf2(bankFile.OpenResourceForRead());
             break;
         default:
             throw new Exception("Invalid bank resource was provided. An extension must be included in the resource name.");
     }
     assets.PatchAssetList.TrimExcess();
     assets.SampleAssetList.TrimExcess();
 }
 public Spec ThrowsSecurityExceptionIfUserIsNotLoggedOn(string input, IResource output)
 {
     return
         new Spec()
         .If(UserIsNotLoggedOn)
         .Throws<SecurityException>();
 }
		/// <summary>
		/// Parses a script from the specified resource.
		/// </summary>
		/// <param name="context">The <see cref="IMansionContext"/>.</param>
		/// <param name="resource">The resource wcich to parse as script.</param>
		/// <returns>Returns the parsed script.</returns>
		/// <exception cref="ParseScriptException">Thrown when an exception occurres while parsing the script.</exception>
		public IExpressionScript Parse(IMansionContext context, IResource resource)
		{
			// validate arguments
			if (context == null)
				throw new ArgumentNullException("context");
			if (resource == null)
				throw new ArgumentNullException("resource");

			// open the script
			var cacheKey = ResourceCacheKey.Create(resource);
			return cachingService.GetOrAdd(
				context,
				cacheKey,
				() =>
				{
					// get the phrase
					string rawPhrase;
					using (var resourceStream = resource.OpenForReading())
					using (var reader = resourceStream.Reader)
						rawPhrase = reader.ReadToEnd();

					// let someone else do the heavy lifting
					var phrase = ParsePhrase(context, rawPhrase);

					// create the cache object
					return new CachedPhrase(phrase);
				});
		}
        public void DecorateClass(IResource resource,
            string className,
            CodeTypeDeclaration resourceClass,
            ResourceClassGenerator generator,
            string serviceClassName,
            IEnumerable<IResourceDecorator> allDecorators)
        {
            var gen = new ResourceGenerator(className, objectTypeProvider, commentCreator);
            foreach (var method in resource.Methods.Values)
            {
                logger.Debug("Adding RequestObject Method {0}.{1}", resource.Name, method.Name);

                // Add the default request method to the class:
                CodeTypeMember convenienceMethod = gen.CreateMethod(resourceClass, resource, method, false);
                if (convenienceMethod != null)
                {
                    resourceClass.Members.Add(convenienceMethod);
                }

                // Add the request method specifiying all parameters (also optional ones) to the class:
                if (AddOptionalParameters && method.HasOptionalParameters())
                {
                    convenienceMethod = gen.CreateMethod(resourceClass, resource, method, true);
                    if (convenienceMethod != null)
                    {
                        resourceClass.Members.Add(convenienceMethod);
                    }
                }
            }
        }
        public HtmlProxy(FileLocation location)
		{
            _includes = new IResource[0];
            _references = _builds = _includes;
			_location = location;
			_version = ChecksumHelper.GetCombinedChecksum(location.Version, _includes, _builds);
		}
Exemplo n.º 31
0
        public void ChangePropDataType()
        {
            IResource res = _storage.FindUniqueResource("PropType", "Name", "Name");

            res.SetProp("DataType", (int)PropDataType.Int);
        }
Exemplo n.º 32
0
 /* *
  * Checks if a given INode is spin:query or a sub-property of it.
  * @param predicate  the INode to test
  * @return true if predicate is a query property
  */
 public static bool isQueryProperty(IResource predicate)
 {
     return(RDFUtil.sameTerm(SPIN.PropertyQuery, predicate) || predicate.hasProperty(RDFS.PropertySubPropertyOf, SPIN.PropertyQuery));
 }
Exemplo n.º 33
0
 /* *
  * Checks whether a given module has been declared abstract using
  * <code>spin:abstract</code.
  * @param module  the module to test
  * @return true if abstract
  */
 public static bool isAbstract(IResource module)
 {
     return(module.hasProperty(SPIN.PropertyAbstract, RDFUtil.TRUE));
 }
Exemplo n.º 34
0
        /* *
         * Creates a new NamedGraph element as a blank node in a given Model.
         * @param model  the Model to generate the NamedGraph in
         * @param graphNameNode  the URI resource of the graph name
         * @param elements  the elements in the NamedGraph
         * @return a new NamedGraph
         */
        public static INamedGraph createNamedGraph(SpinProcessor model, INode graphNameNode, IResource elements)
        {
            INamedGraph result = (INamedGraph)model.CreateResource(SP.ClassNamedGraph).As(typeof(NamedGraphImpl));

            result.AddProperty(SP.PropertyGraphNameNode, graphNameNode);
            result.AddProperty(SP.PropertyElements, elements);
            return(result);
        }
Exemplo n.º 35
0
        /* *
         * Checks whether a given INode represents a SPARQL element, and returns
         * an instance of a subclass of Element if so.
         * @param resource  the INode to check
         * @return INode as an Element or null if resource is not an element
         */
        public static IElement asElement(IResource resource)
        {
            if (resource == null)
            {
                return(null);
            }
            /*sealed*/
            ITriplePattern triplePattern = asTriplePattern(resource);

            if (triplePattern != null)
            {
                return(triplePattern);
            }
            else if (resource.canAs(SP.ClassTriplePath))
            {
                return((ITriplePath)resource.As(typeof(TriplePathImpl)));
            }
            else if (resource.canAs(SP.ClassFilter))
            {
                return((IFilter)resource.As(typeof(FilterImpl)));
            }
            else if (resource.canAs(SP.ClassBind))
            {
                return((IBind)resource.As(typeof(BindImpl)));
            }
            else if (resource.canAs(SP.ClassOptional))
            {
                return((IOptional)resource.As(typeof(OptionalImpl)));
            }
            else if (resource.canAs(SP.ClassNamedGraph))
            {
                return((INamedGraph)resource.As(typeof(NamedGraphImpl)));
            }
            else if (resource.canAs(SP.ClassMinus))
            {
                return((IMinus)resource.As(typeof(MinusImpl)));
            }
            else if (resource.canAs(SP.ClassExists))
            {
                return((IExists)resource.As(typeof(ExistsImpl)));
            }
            else if (resource.canAs(SP.ClassNotExists))
            {
                return((INotExists)resource.As(typeof(NotExistsImpl)));
            }
            else if (resource.canAs(SP.ClassService))
            {
                return((IService)resource.As(typeof(ServiceImpl)));
            }
            else if (resource.canAs(SP.ClassSubQuery))
            {
                return((ISubQuery)resource.As(typeof(SubQueryImpl)));
            }
            else if (resource.canAs(SP.ClassUnion))
            {
                return((IUnion)resource.As(typeof(UnionImpl)));
            }
            else if (resource.canAs(SP.ClassValues))
            {
                return((IValues)resource.As(typeof(ValuesImpl)));
            }
            else if (isElementList(resource))
            {
                return((IElementList)resource.As(typeof(ElementListImpl)));
            }
            else
            {
                return(null);
            }
        }
 public void Enlist(IResource resource)
 {
     throw new NotImplementedException();
 }
Exemplo n.º 37
0
        public override void Execute()
        {
            if (Parameters.Count > 1)
            {
                if (Parameters[0].StartsWith("/"))
                {
                    Parameters[0] = Parameters[0].Substring(1);
                }
                LWM2MResource resource = _Client.GetResource(Parameters[0]) as LWM2MResource;
                if (resource == null)
                {
                    IResource parentResource = _Client.GetParentResource(Parameters[0]);

                    resource = parentResource as LWM2MResource;

                    if (resource == null && parentResource.Parent != null && String.IsNullOrEmpty(parentResource.Parent.Path))
                    {
                        // object instance does not exist
                        LWM2MResources resources  = parentResource as LWM2MResources;
                        string         instanceID = Parameters[0].Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries)[1];
                        parentResource = resource = resources.CreateResource(instanceID);

                        resources.ModifiedResource = resource;

                        resources.Changed();
                        //(parentResource as LWM2MResource).Changed();
                        resource = null;
                    }

                    if (resource == null)
                    {
                        LWM2MResources resources = parentResource as LWM2MResources;

                        if (resources != null)
                        {
                            string[]         paths            = Parameters[0].Split('/');
                            string           name             = paths[paths.Length - 1];
                            LWM2MResource    childResource    = null;
                            BooleanResources booleanResources = resources as BooleanResources;
                            if (booleanResources == null)
                            {
                                DateTimeResources dateTimeResources = resources as DateTimeResources;
                                if (dateTimeResources == null)
                                {
                                    FloatResources floatResources = resources as FloatResources;
                                    if (floatResources == null)
                                    {
                                        IntegerResources integerResources = resources as IntegerResources;
                                        if (integerResources == null)
                                        {
                                            OpaqueResources opaqueResources = resources as OpaqueResources;
                                            if (opaqueResources == null)
                                            {
                                                StringResources stringResources = resources as StringResources;
                                                if (stringResources == null)
                                                {
                                                }
                                                else
                                                {
                                                    childResource = new StringResource(name);
                                                }
                                            }
                                            else
                                            {
                                                childResource = new OpaqueResource(name);
                                            }
                                        }
                                        else
                                        {
                                            childResource = new IntegerResource(name);
                                        }
                                    }
                                    else
                                    {
                                        childResource = new FloatResource(name);
                                    }
                                }
                                else
                                {
                                    childResource = new DateTimeResource(name);
                                }
                            }
                            else
                            {
                                childResource = new BooleanResource(name);
                            }


                            if (childResource != null)
                            {
                                childResource.SetValue(Parameters[1]);
                                resources.Add(childResource);
                            }
                        }
                    }
                    else
                    {
                    }
                }
                else
                {
                    resource.SetValue(Parameters[1]);
                    resource.Changed();
                    LWM2MResource parent = resource.Parent as LWM2MResource;
                    if (parent != null)
                    {
                        parent.Changed();
                        LWM2MResources grandparent = parent.Parent as LWM2MResources;
                        if (grandparent != null)
                        {
                            grandparent.Changed();
                        }
                    }
                }
            }
        }
Exemplo n.º 38
0
 public Resource(IResource copy)
     : base(copy)
 {
 }
Exemplo n.º 39
0
        /* *
         * Checks whether a given INode is a TemplateCall.  The condition for this
         * is stricter than for <code>asTemplateCall</code> as the node also must have
         * a valid template assigned to it, i.e. the type of the node must be an
         * instance of spin:Template.
         * @param node  the INode to check
         * @return true if node is a TemplateCall
         */
        public static bool isTemplateCall(IResource node)
        {
            ITemplateCall templateCall = asTemplateCall(node);

            return(templateCall != null && templateCall.getTemplate() != null);
        }
Exemplo n.º 40
0
        public static void UpdateResourceXml(IResourceCatalog resourceCatalog, Guid workspaceID, IResource effectedResource, IList <ICompileMessageTO> compileMessagesTO)
        {
            var resourceContents = resourceCatalog.GetResourceContents(workspaceID, effectedResource.ResourceID);

            UpdateXmlToDisk(effectedResource, compileMessagesTO, resourceContents);
            var serverResource = resourceCatalog.GetResource(Guid.Empty, effectedResource.ResourceName);

            if (serverResource != null)
            {
                resourceContents = resourceCatalog.GetResourceContents(Guid.Empty, serverResource.ResourceID);
                UpdateXmlToDisk(serverResource, compileMessagesTO, resourceContents);
            }
        }
Exemplo n.º 41
0
 /// <summary>
 /// Reads the specified configuration section into the supplied
 /// <see cref="System.Collections.Specialized.NameValueCollection"/>.
 /// </summary>
 /// <param name="resource">The resource to read.</param>
 /// <param name="configSection">The section name.</param>
 /// <param name="properties">
 /// The collection that is to be populated. May be
 /// <see langword="null"/>.
 /// </param>
 /// <returns>
 /// A newly populated
 /// <see cref="System.Collections.Specialized.NameValueCollection"/>.
 /// </returns>
 /// <exception cref="System.IO.IOException">
 /// If any errors are encountered while attempting to open a stream
 /// from the supplied <paramref name="resource"/>.
 /// </exception>
 /// <exception cref="System.Xml.XmlException">
 /// If any errors are encountered while loading or reading (this only applies to
 /// v1.1 and greater of the .NET Framework) the actual XML.
 /// </exception>
 /// <exception cref="System.Exception">
 /// If any errors are encountered while loading or reading (this only applies to
 /// v1.0 of the .NET Framework).
 /// </exception>
 /// <exception cref="Spring.Objects.FatalObjectException">
 /// If the configuration section was otherwise invalid.
 /// </exception>
 public static NameValueCollection Read(
     IResource resource, string configSection, NameValueCollection properties)
 {
     return(ConfigurationReader.Read(resource, configSection, properties, true));
 }
Exemplo n.º 42
0
 /* *
  * Checks whether a given INode is a variable.
  * @param node  the node to check
  * @return true if node is a variable
  */
 public static bool isVariable(IResource node)
 {
     return(asVariable(node) != null);
 }
 /// <summary>
 /// Creates a new instance of the ObjectDefinitionParsingException class.
 /// </summary>
 /// <param name="resourceLocation">
 /// The resource location (e.g. an XML object definition file) associated
 /// with the offending object definition.
 /// </param>
 /// <param name="message">
 /// A message about the exception.
 /// </param>
 /// <param name="name">
 /// The name of the object that triggered the exception.
 /// </param>
 /// <param name="rootCause">
 /// The root exception that is being wrapped.
 /// </param>
 public ObjectDefinitionParsingException(IResource resourceLocation, string name, string message, Exception rootCause)
     : base(resourceLocation, name, message, rootCause)
 {
 }
Exemplo n.º 44
0
 /// <summary>
 /// Reads the specified configuration section into a
 /// <see cref="System.Collections.Specialized.NameValueCollection"/>.
 /// </summary>
 /// <param name="resource">The resource to read.</param>
 /// <param name="configSection">The section name.</param>
 /// <returns>
 /// A newly populated
 /// <see cref="System.Collections.Specialized.NameValueCollection"/>.
 /// </returns>
 /// <exception cref="System.IO.IOException">
 /// If any errors are encountered while attempting to open a stream
 /// from the supplied <paramref name="resource"/>.
 /// </exception>
 /// <exception cref="System.Xml.XmlException">
 /// If any errors are encountered while loading or reading (this only applies to
 /// v1.1 and greater of the .NET Framework) the actual XML.
 /// </exception>
 /// <exception cref="System.Exception">
 /// If any errors are encountered while loading or reading (this only applies to
 /// v1.0 of the .NET Framework).
 /// </exception>
 /// <exception cref="Spring.Objects.FatalObjectException">
 /// If the configuration section was otherwise invalid.
 /// </exception>
 public static NameValueCollection Read(IResource resource, string configSection)
 {
     return(ConfigurationReader.Read(resource, configSection, new NameValueCollection()));
 }
Exemplo n.º 45
0
 /// <summary>
 /// Loads the resource.
 /// </summary>
 /// <param name="resource">Resource to load</param>
 /// <param name="type">Type of resource</param>
 /// <param name="parameters">Loader parameters</param>
 /// <returns>Loaded object</returns>
 public abstract Object Load(IResource resource, Type type, LoaderParameters parameters);
Exemplo n.º 46
0
 public static Resource FindMatchingResource(AssemblyDefinition adef, IResource item)
 {
     return(adef.MainModule.Resources.FirstOrDefault(p => p.Name == item.Name));
 }
Exemplo n.º 47
0
 public FEnumItem(Type type, object item)
 {
     _item     = item;
     _type     = type;
     _resource = RResource.Find(_type);
 }
 public ResourceTypeProperty(IResource resource) : base(resource)
 {
 }
Exemplo n.º 49
0
 /// <summary>
 /// Applies a HTTP method on a specific resource.
 /// </summary>
 /// <param name="method">
 /// The HTTP method.
 /// </param>
 /// <param name="resource">
 /// The resource.
 /// </param>
 /// <param name="options">
 /// The options.
 /// </param>
 public void Apply(HttpMethod method, IResource resource, Dictionary <string, object> options)
 {
     Handle(method, resource, options, new List <Uri>());
 }
 public SqlServer(IResource resource) : base(resource)
 {
 }
Exemplo n.º 51
0
 /// <summary>
 /// Indicates wheter a given resource is part of the model.
 /// </summary>
 /// <param name="resource">A resource object.</param>
 /// <param name="transaction">ransaction associated with this action.</param>
 /// <returns>True if the resource is part of the model, False if not.</returns>
 public bool ContainsResource(IResource resource, ITransaction transaction = null)
 {
     return(ContainsResource(resource.Uri, transaction));
 }
Exemplo n.º 52
0
 public FEnumItem(object item)
 {
     _item     = item;
     _type     = item.GetType();
     _resource = RResource.Find(_type);
 }
Exemplo n.º 53
0
 public void Remove(IResource resource)
 {
     myResources.Remove(resource);
     OnResourceRemoved(resource);
 }
Exemplo n.º 54
0
        public async Task <HalResourceInspectedContext> OnResourceInspectionAsync(
            HalResourceInspectingContext context,
            HalResourceInspectionDelegate next)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            if (next == null)
            {
                throw new ArgumentNullException(nameof(next));
            }

            if (!context.IsRootResource)
            {
                throw new NotSupportedException("This inspector does not support embedded resources.");
            }

            if (context.Resource == null)
            {
                return(await next());
            }

            if (context.ActionContext == null)
            {
                throw new ArgumentException("ActionContext cannot be null.", nameof(context));
            }

            if (!(context.ActionContext.ActionDescriptor is ControllerActionDescriptor descriptor))
            {
                throw new HalException("Could not establish ControllerActionDescriptor reference.");
            }

            if (context.ActionContext.HttpContext == null || context.ActionContext.HttpContext.Features == null)
            {
                throw new ArgumentException("HttpContext features cannot be null.", nameof(context));
            }

            if (context.MvcPipeline == null)
            {
                throw new ArgumentException("Context does not contain the mvc pipeline.", nameof(context));
            }

            var requestFeature = context.ActionContext.HttpContext.Features.Get <IHttpRequestFeature>();
            var links          = linkService.GetLinks <HalEmbedAttribute>(descriptor, context.ActionContext, context.OriginalObject);

            foreach (var link in links)
            {
                var halRequestFeature = new HalHttpRequestFeature(requestFeature)
                {
                    Method = "GET",
                    Path   = link.Uri
                };

                var halContext = new HalHttpContext(context.ActionContext.HttpContext, halRequestFeature);

                logger.LogDebug("About to invoke MVC pipeline with a GET request on path '{0}'.", link.Uri);
                await context.MvcPipeline.Pipeline(halContext);

                var response = halContext.Response as HalHttpResponse;
                if (response.StatusCode >= 200 && response.StatusCode <= 299)
                {
                    logger.LogDebug("MVC pipeline returned success status code {0}. Invoking HAL resource factory.", response.StatusCode);
                    IResource embedded = await context.EmbeddedResourcePipeline(response.ActionContext, response.Resource);

                    embedded.Rel = link.Rel;

                    if (embedded is IResourceCollection collection)
                    {
                        if (collection.Collection != null)
                        {
                            logger.LogDebug("Embedding collection of {0} resources to rel '{0}'", collection.Collection.Count, link.Rel);
                            foreach (var item in collection.Collection)
                            {
                                item.Rel = link.Rel;
                                context.Resource.Embedded.Add(item);
                            }
                        }
                    }
                    else
                    {
                        logger.LogDebug("Embedding resource to rel '{0}'", link.Rel);
                        context.Resource.Embedded.Add(embedded);
                    }
                }
                else
                {
                    logger.LogWarning("MVC pipeline returned non-success status code {0}. Ignoring result.", response.StatusCode);
                }
            }

            var result = await next();

            logger.LogTrace("After invoke next.");

            return(result);
        }
Exemplo n.º 55
0
 private void OnResourceRemoved(IResource resource) =>
 ResourceRemoved?.Invoke(this, new ResourceEventArgs(resource));
Exemplo n.º 56
0
 /// <summary>
 /// Removes the given resource from the model and its backing RDF store. Note that there is no verification
 /// that the given resource and its stored represenation have identical properties.
 /// </summary>
 /// <param name="resource">A resource object.</param>
 /// <param name="transaction">ransaction associated with this action.</param>
 public void DeleteResource(IResource resource, ITransaction transaction = null)
 {
     DeleteResource(resource.Uri);
 }
Exemplo n.º 57
0
 public bool MatchQuery(string query, IResource res)
 {
     return(false);
 }
Exemplo n.º 58
0
 public void Add(IResource resource)
 {
     myResources.Add(resource);
     OnResourceAdded(resource);
 }
Exemplo n.º 59
0
        public void  ProcessQuery(string query)
        {
            //-----------------------------------------------------------------
            //  Avoid perform any UI (and other, generally) work if we are
            //  shutting down - some components (like DefaultViewPane) may
            //  already be disposed.
            //-----------------------------------------------------------------
            if (Core.State != CoreState.Running)
            {
                return;
            }

            //-----------------------------------------------------------------
            //  Extract Search Extension subphrases, extract them out of the
            //  query and convert them into the list of conditions.
            //-----------------------------------------------------------------
            int anchorPos;

            string[]  resTypes        = null;
            bool      parseSuccessful = false;
            ArrayList conditions      = new ArrayList();

            do
            {
                string anchor;
                FindSearchExtension(query, out anchor, out anchorPos);
                if (anchorPos != -1)
                {
                    parseSuccessful = ParseSearchExtension(anchor, anchorPos, ref query, out resTypes, conditions);
                }
            }while((anchorPos != -1) && parseSuccessful);

            //-----------------------------------------------------------------
            //  Create condition from the query
            //-----------------------------------------------------------------
            IFilterRegistry fMgr           = Core.FilterRegistry;
            IResource       queryCondition = ((FilterRegistry)fMgr).CreateStandardConditionAux(null, query, ConditionOp.QueryMatch);

            FilterRegistry.ReferCondition2Template(queryCondition, fMgr.Std.BodyMatchesSearchQueryXName);

            conditions.Add(queryCondition);

            //-----------------------------------------------------------------
            bool showContexts = Core.SettingStore.ReadBool("Resources", "ShowSearchContext", true);
            bool showDelItems = Core.SettingStore.ReadBool("Search", "ShowDeletedItems", true);

            IResource[] condsList = (IResource[])conditions.ToArray(typeof(IResource));
            IResource   view      = Core.ResourceStore.FindUniqueResource(FilterManagerProps.ViewResName, "DeepName", Core.FilterRegistry.ViewNameForSearchResults);

            if (view != null)
            {
                fMgr.ReregisterView(view, fMgr.ViewNameForSearchResults, resTypes, condsList, null);
            }
            else
            {
                view = fMgr.RegisterView(fMgr.ViewNameForSearchResults, resTypes, condsList, null);
            }
            Core.FilterRegistry.SetVisibleInAllTabs(view);

            //-----------------------------------------------------------------
            //  Set additional properties characteristic only for "Search Results"
            //  view.
            //-----------------------------------------------------------------
            ResourceProxy proxy = new ResourceProxy(view);

            proxy.BeginUpdate();
            proxy.SetProp(Core.Props.Name, AdvancedSearchForm.SearchViewPrefix + query);
            proxy.SetProp("_DisplayName", AdvancedSearchForm.SearchViewPrefix + query);
            proxy.SetProp(Core.Props.ShowDeletedItems, showDelItems);
            proxy.SetProp("ShowContexts", showContexts);
            proxy.SetProp("ForceExec", true);
            if (Core.SettingStore.ReadBool("Search", "AutoSwitchToResults", true))
            {
                proxy.SetProp("RunToTabIfSingleTyped", true);
            }
            else
            {
                proxy.DeleteProp("RunToTabIfSingleTyped");
            }
            proxy.EndUpdate();

            //-----------------------------------------------------------------
            //  Add new view to the panel
            //  Some steps to specify the correct user-ordering for the new view.
            //-----------------------------------------------------------------
            Core.ResourceTreeManager.LinkToResourceRoot(view, int.MinValue);

            new UserResourceOrder(Core.ResourceTreeManager.ResourceTreeRoot).Insert(0, new int[] { view.Id }, false, null);

            //-----------------------------------------------------------------
            //  If we still in the Running mode we can do some UI work...
            //-----------------------------------------------------------------
            if (Core.State == CoreState.Running)
            {
                Core.UIManager.BeginUpdateSidebar();
                Core.LeftSidebar.ActivateViewPane(StandardViewPanes.ViewsCategories);
                Core.UIManager.EndUpdateSidebar();
                Core.LeftSidebar.DefaultViewPane.SelectResource(view);
            }
        }
Exemplo n.º 60
0
        public bool MatchQuery(string query, IResource res)
        {
            bool matched = _queryManager.MatchResource(res, query);

            return(matched);
        }