Esempio n. 1
0
        //public virtual ResourceForUpload[] GetResourcesForUpload(Display display,
        //    ResourceDescriptor[] resourceDescriptors,
        //    out bool isEnoughFreeSpace)
        //{
        //    isEnoughFreeSpace = true;
        //    return new ResourceForUpload[] { };
        //}

        public virtual ResourceDescriptor[] GetResourcesForUpload(DisplayType displayType,
                                                                  ResourceDescriptor[] resourceDescriptors,
                                                                  out bool isEnoughFreeSpace)
        {
            isEnoughFreeSpace = true;
            return new ResourceDescriptor[] { };
        }
Esempio n. 2
0
        public void TestResourceCachingToFileSystem()
        {
            // the resource handler expects the filenames to be retrieved in an array
            string[] resources = new[] { "simplified_enumlibrary.xmi", "simplified_primlibrary.xmi", "simplified_cdtlibrary.xmi" };// TODO: temporarily excluded since it caused a filure for whatever reason, "simplified_cclibrary.xmi" };

            // the uri where the files to be downloaded are located
            const string downloadUri = "http://www.umm-dev.org/xmi/testresources/simplified_1/";

            // the directory on the local file system where the downloaded file is to be stored
            string storageDirectory = Directory.GetCurrentDirectory() +
                                      "\\..\\..\\..\\VIENNAAddInUnitTests\\testresources\\ResourceHandlerTest\\xmi\\download\\";

            string comparisonDirectory = Directory.GetCurrentDirectory() +
                                         "\\..\\..\\..\\VIENNAAddInUnitTests\\testresources\\ResourceHandlerTest\\xmi\\reference\\";

            // method to be tested 1: caching resources locally
            ResourceDescriptor resourceDescriptor = new ResourceDescriptor
                                                    (
                resources,
                downloadUri,
                storageDirectory

                                                    );

            (new ResourceHandler(resourceDescriptor)).CacheResourcesLocally();

            foreach (string fileName in resources)
            {
                // evaluate if the file was downloaded at all
                AssertDownloadedFileExists(storageDirectory + fileName);

                // evalate the content of the file downloaded
                AssertFileContent(comparisonDirectory + fileName, storageDirectory + fileName);
            }
        }
Esempio n. 3
0
 public void GetResourceCultureNameTest(string fileName, string expectedCulture)
 {
     var resourceDescriptor = new ResourceDescriptor();
     resourceDescriptor.FileName = fileName;
     var culture = ResourcesForCulture.GetResourceCultureName(resourceDescriptor);
     Assert.Equal(expectedCulture, culture);
 }
Esempio n. 4
0
        public void Import(Presentation presentation, ResourceDescriptor[] resourceDescriptors,
            DeviceResourceDescriptor[] deviceResourceDescriptors, 
            Func<Slide, Slide> addSlideDelegate, Func<IEnumerable<Slide>, bool> addLinkDelegate,
            Func<string, string, bool> isSlideUniqueName,
            int indent, int height)
        {
            _addSlideDelegate = addSlideDelegate;
            _addLinkDelegate = addLinkDelegate;
            _isSlideUniqueName = isSlideUniqueName;
            string selectedFile = null;
            using (OpenFileDialog openFileDialog = new OpenFileDialog())
            {
                openFileDialog.RestoreDirectory = true;
                openFileDialog.Filter = "XML Files (*.xml) | *.xml";
                openFileDialog.Multiselect = false;
                if (DialogResult.OK == openFileDialog.ShowDialog())
                {
                    selectedFile = openFileDialog.FileName;
                }
            }
            if (string.IsNullOrEmpty(selectedFile)) return;
            ImportSlide importSlide = new ImportSlide(DesignerClient.Instance.StandalonePresentationWorker,
                this);

            importSlide.Import(selectedFile, presentation, resourceDescriptors, deviceResourceDescriptors, indent, height);
        }
Esempio n. 5
0
 public void Import(string fileName,
     TechnicalServices.Persistence.SystemPersistence.Presentation.Presentation presentation,
     ResourceDescriptor[] resourceDescriptors, DeviceResourceDescriptor[] deviceResourceDescriptors,
     int indent, int height)
 {
     _indent = indent;
     _height = height;
     try
     {
         SlideBulk slideBulk = LoadFromFile(fileName, resourceDescriptors, deviceResourceDescriptors);
         if (slideBulk == null)
         {
             throw new InvalideFileException("Содержание файла некорректно. Импорт сцен невозмлжен");
         }
         CheckSlideNames(slideBulk);
         AddSlideAndLink(presentation, slideBulk);
         _importSlideController.SuccessMessage("Импорт сцен успешно завершен");
     }
     catch (InterruptOperationException)
     { }
     catch (InvalideFileException ex)
     {
         _importSlideController.ErrorMessage(ex.Message);
     }
     catch (Exception ex)
     {
         _importSlideController.ErrorMessage(string.Format("При экспорте сцен произошла неизвестная ошибка: {0}", ex));
     }
 }
Esempio n. 6
0
        public static string GetResourceCultureName(ResourceDescriptor res)
        {
            var ext = Path.GetExtension(res.FileName);

            if (string.Equals(ext, ".resx", StringComparison.OrdinalIgnoreCase) ||
                string.Equals(ext, ".restext", StringComparison.OrdinalIgnoreCase) ||
                string.Equals(ext, ".resources", StringComparison.OrdinalIgnoreCase))
            {
                var resourceBaseName = Path.GetFileNameWithoutExtension(res.FileName);
                var cultureName = Path.GetExtension(resourceBaseName);
                if (string.IsNullOrEmpty(cultureName) || cultureName.Length < 3)
                {
                    return string.Empty;
                }

                // Path.Extension adds a . to the file extension name; example - ".resources". Removing the "." with Substring 
                cultureName = cultureName.Substring(1);

                if (CultureInfoCache.KnownCultureNames.Contains(cultureName))
                {
                    return cultureName;
                }
            }

            return string.Empty;
        }
Esempio n. 7
0
        /// <summary>
        /// Creates a resource
        /// </summary>
        /// <param name="resourceDescriptor"></param>
        /// <param name="resource"></param>
        /// <returns></returns>
        public async Task <Resource> Create(ResourceDescriptor resourceDescriptor, Resource resource)
        {
            var resp = await HttpClient.PostAsync(resourceDescriptor.Url, new JsonContent(ResourceSerializer.Serialize(resource)));

            resp.EnsureSuccessStatusCode();

            return(await ResourceSerializer.DeserializeResponseBodyToResource(resource.GetType(), resp));
        }
Esempio n. 8
0
 public void SelectSource(ResourceDescriptor source, bool isLocal)
 {
     ISourceNode node = null;
     if (resourceNodes.TryGetValue(source, out node))
     {
         _view.SelectSource(node, isLocal);
     }
 }
Esempio n. 9
0
        /// <summary>
        /// Gets a resource by its ID
        /// </summary>
        /// <param name="resourceDescriptor"></param>
        /// <returns></returns>
        public async Task <Resource> Get(ResourceDescriptor resourceDescriptor)
        {
            var resp = await HttpClient.GetAsync(resourceDescriptor.Url);

            resp.EnsureSuccessStatusCode();

            return(await ResourceSerializer.DeserializeResponseBodyToResource(resourceDescriptor.Type, resp));
        }
Esempio n. 10
0
        /// <summary>
        /// Gets a resource of type <see cref="T"/> by its ID
        /// </summary>
        /// <param name="resourceDescriptor"></param>
        /// <param name="resource"></param>
        /// <returns></returns>
        public virtual async Task <T> Update <T>(ResourceDescriptor resourceDescriptor, T resource) where T : Resource, new()
        {
            var resp = await HttpClient.PutAsync(resourceDescriptor.Url, new JsonContent(ResourceSerializer.Serialize(resource)));

            resp.EnsureSuccessStatusCode();

            return(await ResourceSerializer.DeserializeResponseBodyToResource <T>(resp));
        }
        public void ShouldAppendRelativePathForMajorAndMinorVersionForLocalVersions()
        {
            ResourceDescriptor defaultDescriptor = new ResourceDescriptor();
            ResourceDescriptor customDescriptor  = new ResourceDescriptor("X:\\arbitrary\\path\\", "major", "minor");

            Assert.That(customDescriptor.DownloadUri, Is.EqualTo("X:\\arbitrary\\path\\" + "major_minor\\"));
            Assert.That(customDescriptor.StorageDirectory, Is.EqualTo(defaultDescriptor.StorageDirectory + "major_minor\\"));
        }
        public void ShouldAppendRelativePathForMajorAndMinorVersionForRemoteVersions()
        {
            ResourceDescriptor defaultDescriptor = new ResourceDescriptor();
            ResourceDescriptor customDescriptor  = new ResourceDescriptor("http://xmi/", "major", "minor");

            Assert.That(customDescriptor.DownloadUri, Is.EqualTo("http://xmi/" + "major_minor/"));
            Assert.That(customDescriptor.StorageDirectory, Is.EqualTo(defaultDescriptor.StorageDirectory + "major_minor\\"));
        }
Esempio n. 13
0
        /// <summary>
        /// Gets a resource of type <see cref="T"/> by its ID
        /// </summary>
        /// <param name="resourceDescriptor"></param>
        /// <returns></returns>
        public async Task <T> Get <T>(ResourceDescriptor resourceDescriptor) where T : Resource, new()
        {
            var resp = await HttpClient.GetAsync(resourceDescriptor.Url);

            resp.EnsureSuccessStatusCode();

            return(await ResourceSerializer.DeserializeResponseBodyToResource <T>(resp));
        }
Esempio n. 14
0
        /// <summary>
        /// Queries resources of type <see cref="T"/> using the provided criteria, in the form of key/value pairs
        /// </summary>
        /// <param name="resourceDescriptor"></param>
        /// <returns></returns>
        public virtual async Task <IEnumerable <T> > Query <T>(ResourceDescriptor resourceDescriptor) where T : Resource, new()
        {
            var resp = await HttpClient.GetAsync(resourceDescriptor.Url);

            resp.EnsureSuccessStatusCode();

            return(await ResourceSerializer.DeserializeResponseBodyToResourceCollection <T>(resp));
        }
Esempio n. 15
0
 /// <summary>
 /// Initializes a new <see cref="ResourceDescriptor"/> instance.
 /// </summary>
 /// <param name="type">The type of resource to create the descriptor for.</param>
 /// <param name="offset">The offset in the resource from the start of the shader mapping.</param>
 /// <param name="descriptor">The resulting <see cref="ResourceDescriptor"/> instance.</param>
 public static void Create(int type, uint offset, out ResourceDescriptor descriptor)
 {
     descriptor.RangeType          = (D3D12_DESCRIPTOR_RANGE_TYPE)type;
     descriptor.NumDescriptors     = 1;
     descriptor.BaseShaderRegister = offset;
     descriptor.RegisterSpace      = 0;
     descriptor.Flags = D3D12_DESCRIPTOR_RANGE_FLAG_NONE;
     descriptor.OffsetInDescriptorsFromTableStart = D3D12.D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND;
 }
Esempio n. 16
0
        public void GetResourceCultureNameTest(string fileName, string expectedCulture)
        {
            var resourceDescriptor = new ResourceDescriptor();

            resourceDescriptor.FileName = fileName;
            var culture = ResourcesForCulture.GetResourceCultureName(resourceDescriptor);

            Assert.Equal(expectedCulture, culture);
        }
Esempio n. 17
0
        public ResourceDescriptor[] GetResourcesForUpload(ResourceDescriptor[] resourceDescriptors,
            out bool isEnoughFreeSpace)
        {
            List<ResourceDescriptor> resourcesForUpload = new List<ResourceDescriptor>(resourceDescriptors.Length);
            foreach (ResourceDescriptor resourceDescriptor in resourceDescriptors)
            {
                ResourceFileInfo resourceFileInfo = resourceDescriptor.ResourceInfo as ResourceFileInfo;
                if (resourceFileInfo == null) continue;
                //List<ResourceFileProperty> resourceIdList = new List<ResourceFileProperty>(resourceFileInfo.ResourceFileDictionary.Count);
                foreach (ResourceFileProperty property in resourceFileInfo.ResourceFileList)
                {
                    //string resourceFileName = GetRealResourceFileName(resourceDescriptor, pair.Key);
                    if (!IsResourceExists(resourceDescriptor, property.Id) || IsNewly(resourceDescriptor, property.Id))
                    {
                        //resourceIdList.Add(pair.Value);
                        property.Newly = true;
                    }
                }
                if (resourceFileInfo.ResourceFileList.Any(rfp => rfp.Newly))
                    resourcesForUpload.Add(resourceDescriptor);
                //if (resourceIdList.Count > 0)
                //    resourcesForUpload.Add(new ResourceForUpload(resourceDescriptor, resourceIdList));
            }
            long requiredSpaceForLocal = 0;
            long requiredSpaceForGlobal = 0;
            foreach (ResourceDescriptor descriptor in resourcesForUpload)
            {
                ResourceFileInfo resourceFileInfo = descriptor.ResourceInfo as ResourceFileInfo;
                if (resourceFileInfo == null) continue;
                if (descriptor.IsLocal)
                    requiredSpaceForLocal += resourceFileInfo.ResourceFileList.Sum(rfp => rfp.Newly ? rfp.Length : 0);
                else
                    requiredSpaceForGlobal += resourceFileInfo.ResourceFileList.Sum(rfp => rfp.Newly ? rfp.Length : 0);
            }

            //foreach (ResourceForUpload resourceForAgentUpload in resourcesForUpload)
            //{
            //    ResourceDescriptor descriptor = resourceForAgentUpload.ResourceDescriptor;
            //    if (descriptor.IsLocal)
            //        requiredSpaceForLocal += resourceForAgentUpload.ResourcePropertyList.Sum(rfp => rfp.Length);
            //    else
            //        requiredSpaceForGlobal += resourceForAgentUpload.ResourcePropertyList.Sum(rfp => rfp.Length);
            //}
            DriveInfo localDriveInfo = new DriveInfo(
                Path.GetFullPath(_configuration.LocalSourceFolder)[0].ToString());
            DriveInfo globalDriveInfo = new DriveInfo(
                Path.GetFullPath(_configuration.GlobalSourceFolder)[0].ToString());
            if (localDriveInfo.AvailableFreeSpace > requiredSpaceForLocal
                &&
                globalDriveInfo.AvailableFreeSpace > requiredSpaceForGlobal)
                isEnoughFreeSpace = true;
            else
                isEnoughFreeSpace = false;
            return resourcesForUpload.ToArray();
        }
Esempio n. 18
0
        /// <summary>
        /// Gets a resource of type <see cref="JobAssignment"/> by its ID
        /// </summary>
        /// <param name="resourceDescriptor"></param>
        /// <param name="resource"></param>
        /// <returns></returns>
        public override async Task <JobAssignment> Create(ResourceDescriptor resourceDescriptor, JobAssignment resource)
        {
            // create the job assinment in the data layer
            var jobAssignment = await base.Create(resourceDescriptor, resource);

            // invoke worker
            await WorkerFunctionInvoker.Invoke(Environment.WorkerFunctionName(), Environment, resource);

            // return the newly-created job assignment
            return(jobAssignment);
        }
Esempio n. 19
0
        /// <summary>
        /// Checks if a resource is local
        /// </summary>
        /// <param name="resourceDescriptor"></param>
        /// <returns></returns>
        private bool IsLocal(ResourceDescriptor resourceDescriptor)
        {
            var isLocal = !string.IsNullOrWhiteSpace(Environment.PublicUrl()) && resourceDescriptor.Url.StartsWith(Environment.PublicUrl());

            Logger.Debug("Executing operation for {0} resource at {1} (local url = {2})",
                         isLocal ? "local" : "remote",
                         resourceDescriptor.Url,
                         Environment.PublicUrl());

            return(isLocal);
        }
Esempio n. 20
0
        private TypeBase CreateConstantResourceName(ResourceDescriptor descriptor, string nameValue)
        {
            if (descriptor.IsRootType)
            {
                return(factory.Create(() => new StringLiteralType {
                    Value = nameValue
                }));
            }

            return(builtInTypes[BuiltInTypeKind.String]);
        }
Esempio n. 21
0
        protected override void onItemInserted(ResourceDescriptor descriptor)
        {
            // add onClick on resource handlers
            var button = descriptor.controller.button;

            Debug.Log("Creating onClick listener for an inventary resource: ");
            button.onClick.AddListener((() =>
            {
                CraftMenuController controller = this.CraftMenuController;
                Debug.Log("Processing click for inventary resource via controller: ", controller);
                controller.moveResourceToCraft(descriptor);
            }));
        }
Esempio n. 22
0
        public void TryGetResourceDescriptor_Returns_False_If_Type_Is_IIdentifiable()
        {
            // Arrange
            Type resourceType = typeof(string);

            var typeLocator = new TypeLocator();

            // Act
            ResourceDescriptor descriptor = typeLocator.TryGetResourceDescriptor(resourceType);

            // Assert
            Assert.Null(descriptor);
        }
		/// <summary>
		/// Creates an implementation of <see cref="IResource"/>
		/// based on the descriptor.
		/// <seealso cref="ResourceManager"/>
		/// <seealso cref="ResourceFacade"/>
		/// </summary>
		/// <param name="descriptor"></param>
		/// <param name="appAssembly"></param>
		/// <returns></returns>
		public IResource Create(ResourceDescriptor descriptor, Assembly appAssembly)
		{
			var assembly = ResolveAssembly(descriptor.AssemblyName, appAssembly);
			var cultureInfo = ResolveCulture(descriptor.CultureName);

			if (logger.IsDebugEnabled)
			{
				logger.DebugFormat("Creating resource name {0}, assembly {1}, resource {2}",
				                   descriptor.Name, descriptor.AssemblyName, descriptor.ResourceName);
			}

			var manager = new ResourceManager(descriptor.ResourceName, assembly, descriptor.ResourceType);
			return new ResourceFacade(manager, cultureInfo);
		}
        /// <summary>
        /// Handle update of a job
        /// </summary>
        /// <param name="resourceDescriptor"></param>
        /// <param name="resource"></param>
        public override async Task <JobProcess> Update(ResourceDescriptor resourceDescriptor, JobProcess resource)
        {
            var jobProcess = await DataHandler.Get <JobProcess>(resourceDescriptor);

            // validate the update
            if (jobProcess.JobProcessStatus == "New" && !new[] { "Running", "Completed", "Failed" }.Contains(resource.JobProcessStatus) ||
                jobProcess.JobProcessStatus == "Running" && !new[] { "Completed", "Failed" }.Contains(resource.JobProcessStatus))
            {
                throw new Exception($"Cannot change status of job process from '{jobProcess.JobProcessStatus}' to '{resource.JobProcessStatus}'");
            }

            jobProcess.JobProcessStatus = resource.JobProcessStatus;

            var job = await DataHandler.Get <Job>(jobProcess.Job.Id);

            // update job
            job.JobStatus       = jobProcess.JobProcessStatus;
            job.JobStatusReason = jobProcess.JobProcessStatusReason;

            // update output from job assignment
            if (!string.IsNullOrWhiteSpace(jobProcess.JobAssignment))
            {
                var jobAssignment = await DataHandler.Get <JobAssignment>(jobProcess.JobAssignment);

                job.JobOutput = jobAssignment.JobOutput;
            }

            await DataHandler.Update(job);

            // clear the job assignment
            jobProcess.JobAssignment = null;

            var updated = await base.Update(resourceDescriptor, jobProcess);

            // send notification to async endpoint if provided
            if (job.AsyncEndpoint != null)
            {
                if (job.JobStatus == "Completed" && !string.IsNullOrWhiteSpace(job.AsyncEndpoint.AsyncSuccess))
                {
                    await DataHandler.Get(job.AsyncEndpoint.AsyncSuccess);
                }
                else if (job.JobStatus == "Failed" && !string.IsNullOrWhiteSpace(job.AsyncEndpoint.AsyncFailure))
                {
                    await DataHandler.Get(job.AsyncEndpoint.AsyncFailure);
                }
            }

            return(updated);
        }
        protected void AddResource(string name, string resourceName, Assembly asm)
        {
            IResourceFactory resourceFactory = new DefaultResourceFactory();
            var descriptor = new ResourceDescriptor(
                null,
                name,
                resourceName,
                null,
                null);
            var resource = resourceFactory.Create(
                descriptor,
                asm);

            ControllerContext.Resources.Add(name, resource);
        }
        /// <summary>
        /// Creates an implementation of <see cref="IResource"/>
        /// based on the descriptor.
        /// <seealso cref="ResourceManager"/>
        /// <seealso cref="ResourceFacade"/>
        /// </summary>
        /// <param name="descriptor"></param>
        /// <param name="appAssembly"></param>
        /// <returns></returns>
        public IResource Create(ResourceDescriptor descriptor, Assembly appAssembly)
        {
            var assembly    = ResolveAssembly(descriptor.AssemblyName, appAssembly);
            var cultureInfo = ResolveCulture(descriptor.CultureName);

            if (logger.IsDebugEnabled)
            {
                logger.DebugFormat("Creating resource name {0}, assembly {1}, resource {2}",
                                   descriptor.Name, descriptor.AssemblyName, descriptor.ResourceName);
            }

            var manager = new ResourceManager(descriptor.ResourceName, assembly, descriptor.ResourceType);

            return(new ResourceFacade(manager, cultureInfo));
        }
        /// <summary>
        /// Attempts to get a descriptor of the resource type.
        /// </summary>
        /// <returns>
        /// True if the type is a valid json:api type (must implement <see cref="IIdentifiable"/>), false otherwise.
        /// </returns>
        internal static bool TryGetResourceDescriptor(Type type, out ResourceDescriptor descriptor)
        {
            if (!type.IsAbstract)
            {
                var possible = GetIdType(type);
                if (possible.isJsonApiResource)
                {
                    descriptor = new ResourceDescriptor(type, possible.idType);
                    return(true);
                }
            }

            descriptor = ResourceDescriptor.Empty;
            return(false);
        }
Esempio n. 28
0
        public void TryGetResourceDescriptor_Returns_Type_If_Type_Is_IIdentifiable()
        {
            // Arrange
            Type resourceType = typeof(Model);

            var typeLocator = new TypeLocator();

            // Act
            ResourceDescriptor descriptor = typeLocator.TryGetResourceDescriptor(resourceType);

            // Assert
            Assert.NotNull(descriptor);
            Assert.Equal(resourceType, descriptor.ResourceType);
            Assert.Equal(typeof(int), descriptor.IdType);
        }
Esempio n. 29
0
        /// <summary>
        /// Gets a resource of type <see cref="T"/> by its ID
        /// </summary>
        /// <param name="resourceDescriptor"></param>
        /// <param name="resource"></param>
        /// <returns></returns>
        public virtual async Task <T> Update(ResourceDescriptor resourceDescriptor, T resource)
        {
            // create any new child resources
            foreach (var childResource in resource.GetChildResources().Where(r => string.IsNullOrWhiteSpace(r.Id)))
            {
                await CreateResource(new ResourceDescriptor(resource.GetType()) { Parent = resourceDescriptor }, childResource);
            }

            // set the modified date to now
            resource.DateModified = DateTime.UtcNow;

            // call data layer to update the object
            resource = await DataHandler.Update(resourceDescriptor, resource);

            return(resource);
        }
Esempio n. 30
0
        protected override void onItemInserted(ResourceDescriptor descriptor)
        {
            // add onClick on resource handlers
            var button = descriptor.controller.button;

            Debug.Log("Creating onClick listener for an craft result resource: ");
            var type = descriptor.resource.GetType();

            if (type == (typeof(Galaxy)))
            {
                button.onClick.AddListener((() =>
                {
                    // FIXME asem [REFACTOR] replace this code with calling api-method from InstantiatingApi script
                    PauseMenuManager.CloseCraftMenu();
                    var result = Instantiate(prefab, new Vector3(5, 0, 0), Quaternion.identity) as GameObject;
                    result.GetComponent <SpriteRenderer>().sortingOrder = 2;
                    clear();
                }));
            }
            else if (type == (typeof(Star)))
            {
                button.onClick.AddListener((() =>
                {
                    PauseMenuManager.CloseCraftMenu();
                    InstantiatingApi.CreateStar();
                    clear();
                }));
            }
            else if (type == (typeof(Planet)))
            {
                button.onClick.AddListener((() =>
                {
                    PauseMenuManager.CloseCraftMenu();
                    InstantiatingApi.CreatePlanet();
                    clear();
                }));
            }
            else
            {
                button.onClick.AddListener((() =>
                {
                    CraftMenuController controller = this.CraftMenuController;
                    Debug.Log("Processing click for craft resource via controller: ", controller);
                    controller.moveCraftResultToResources(descriptor);
                }));
            }
        }
Esempio n. 31
0
        void FreeResource(ResourceDescriptor desc)
        {
            if (!desc.autoAlloc)
            {
                return;
            }

            if (desc.allocatedTexture != null)
            {
                CoreUtils.Destroy(desc.allocatedTexture);
            }
            else if (desc.allocatedBuffer != null)
            {
                desc.allocatedBuffer.Release();
            }
            desc.allocatedTexture = null;
            desc.allocatedBuffer  = null;
        }
        private static ResourceName CreateConstantResourceName(ResourceDescriptor descriptor, string nameValue, string description = null)
        {
            var constantNameSchema = descriptor.IsRootType ?
                                     JsonSchema.CreateSingleValuedEnum(nameValue) :
                                     new JsonSchema
            {
                JsonType = "string",
                Pattern  = $"^.*/{Regex.Escape(nameValue)}$",
            };

            constantNameSchema.Description = description;

            return(new ResourceName
            {
                HasConstantName = true,
                NameString = nameValue,
                NameSchema = constantNameSchema,
            });
        }
Esempio n. 33
0
        /// <summary>
        /// Gets the path to a resource
        /// </summary>
        /// <param name="resourceDescriptor"></param>
        /// <returns></returns>
        public string GetUrlPath(ResourceDescriptor resourceDescriptor)
        {
            // start with the type
            var path = $"/{UrlSegmentResourceMapper.GetResourceTypeName(resourceDescriptor.Type)}";

            // check if we have an ID
            if (resourceDescriptor.Id != null)
            {
                path += $"/{resourceDescriptor.Id}";
            }

            // recurse up the tree for child collections
            if (resourceDescriptor.Parent != null)
            {
                path = GetUrlPath(resourceDescriptor.Parent) + path;
            }

            return(path);
        }
        /// <summary>
        /// Overridden to send job to job processor
        /// </summary>
        /// <param name="resourceDescriptor"></param>
        /// <param name="resource"></param>
        /// <returns></returns>
        public override async Task<Job> Create(ResourceDescriptor resourceDescriptor, Job resource)
        {
            resource.JobStatus = "New";

            // create the job
            var job = await base.Create(resourceDescriptor, resource);

            // get all services
            var services = await DataHandler.Query<Service>(ResourceDescriptor.FromUrl<Service>(Environment.ServiceRegistryServicesUrl()));

            // find first service that has a job processing endpoint
            var serviceResource =
                services
                    .SelectMany(s => s.HasResource.Select(r => new {Service = s, Resource = r}))
                    .FirstOrDefault(
                        sr => sr.Resource.ResourceType == nameof(JobProcess) && !string.IsNullOrWhiteSpace(sr.Resource.HttpEndpoint));

            if (serviceResource == null)
            {
                job.JobStatusReason = "No JobProcessor endpoints registered in the service registry.";
                job.JobStatus = "Failed";

                return await Update(resourceDescriptor, job);
            }

            try
            {
                // gets the authorized url
                var url = AuthorizedUrlBuilder.GetAuthorizedUrl(serviceResource.Resource);
                
                // send the job to the job processing endpoint
                await DataHandler.Create(ResourceDescriptor.FromUrl<JobProcess>(url), new JobProcess {Job = job});

                return await Get(resourceDescriptor);
            }
            catch (Exception ex)
            {
                job.JobStatusReason = $"Failed to send job to JobProcessor endpoint {serviceResource.Resource.HttpEndpoint}: {ex}";
                job.JobStatus = "Failed";

                return await Update(resourceDescriptor, job);
            }
        }
Esempio n. 35
0
        public bool DecrementResource(ResourceDescriptor descriptor)
        {
            var resourceAmount = descriptor.resource.GetResourceAmount();

            if (resourceAmount > 1)
            {
                descriptor.resource.DecreaseAmount(1);
                descriptor.controller.resourceAmountText.text = descriptor.resource.GetResourceAmount().ToString();
                return(true);
            }
            if (resourceAmount == 1)
            {
                // deleting resource
                _resources.Remove(descriptor);
                Destroy(descriptor.resourceObject);
                return(true);
            }

            return(false);
        }
Esempio n. 36
0
 private bool IsNewly(ResourceDescriptor resourceDescriptor, string resourceId)
 {
     ResourceFileInfo resourceFileInfo = resourceDescriptor.ResourceInfo as ResourceFileInfo;
     if (resourceFileInfo == null) return false;
     string resourceFileName = GetResourceInfoFullFileName(resourceDescriptor);
     if (!File.Exists(resourceFileName)) return true;
     ResourceInfo stored = resourceDescriptor.ResourceInfo.GetResourceInfo(resourceFileName, ExtraTypes);
     ResourceFileInfo storedResourceFileInfo = stored as ResourceFileInfo;
     if (storedResourceFileInfo == null) return false;
     ResourceFileProperty resourceFileProperty =
         storedResourceFileInfo.ResourceFileList.Find(rfp => rfp.Id.Equals(resourceId));
     return resourceFileProperty == null
                ? true
                :
                    resourceFileProperty.ModifiedUtc.CompareTo(
                    resourceFileInfo.ResourceFileList.Find(rfp => rfp.Id.Equals(resourceId)).ModifiedUtc) < 0;
     //if (resourceFileProperty == null)
     //    return true;
     //return resourceFileProperty.ModifiedUtc.CompareTo(resourceFileInfo.ResourceFileDictionary[resourceId].ModifiedUtc) < 0;
 }
Esempio n. 37
0
        /// <summary>
        /// должно вызываться после десериализации для инициализации ссылочных полей
        /// </summary>
        /// <returns>возвращается список оборудования которое отсутсвует в конфигурации и таким образом было исключено из сценария</returns>
        public string[] InitReference(ModuleConfiguration config, ResourceDescriptor[] descriptors,
            DeviceResourceDescriptor[] deviceResourceDescriptors)
        {
            foreach (KeyValuePair<int, SlideLinkList> pair in _linkDictionary)
            {
                foreach (Link link in pair.Value.LinkList)
                {
                    link.NextSlide = SlideList.Find(sl => sl.Id == link.NextSlideId);
                    if (link.NextSlide == null)
                        throw new KeyNotFoundException("SlideBulk.InitReference: Нет такого слайда в коллекции");
                }
            }

            // Initreference для каждого слайда
            List<string> deletedEquipment = new List<string>();
            foreach (Slide sl in SlideList)
            {
                deletedEquipment.AddRange(sl.InitReference(config, descriptors, deviceResourceDescriptors, true));
            }
            return deletedEquipment.Distinct().ToArray();
        }
Esempio n. 38
0
        public void UpdateManagedResource(ResourceDescriptor desc)
        {
            if (desc.autoAlloc && desc.allocatedTexture == null && desc.allocatedBuffer == null)
            {
                AllocateResource(desc);
            }
            if (!desc.autoAlloc && (desc.allocatedTexture != null || desc.allocatedBuffer != null))
            {
                FreeResource(desc);
            }

            // TODO: check allocated size vs settings and do patch stuff
            if (desc.allocatedTexture != null)
            {
                var t              = desc.allocatedTexture;
                int expectedWidth  = desc.textureAllocMode == TextureAllocMode.SameAsOutput ? rtSettings.GetWidth(graph) : (int)desc.textureAllocMode;
                int expectedHeight = desc.textureAllocMode == TextureAllocMode.SameAsOutput ? rtSettings.GetHeight(graph) : (int)desc.textureAllocMode;
                int expectedDepth  = desc.textureAllocMode == TextureAllocMode.SameAsOutput ? rtSettings.GetDepth(graph) : (int)desc.textureAllocMode;
                if (t.width != expectedWidth || t.height != expectedHeight || t.volumeDepth != expectedDepth)
                {
                    t.Release();
                    t.width       = expectedWidth;
                    t.height      = expectedHeight;
                    t.volumeDepth = expectedDepth;
                    t.Create();
                }
            }
            if (desc.allocatedBuffer != null)
            {
                var b = desc.allocatedBuffer;

                if (b.stride != desc.bufferStride || b.count != desc.bufferSize)
                {
                    b.Release();
                    desc.allocatedBuffer = AllocComputeBuffer(desc.bufferSize, desc.bufferStride);
                }
            }
        }
Esempio n. 39
0
        void AllocateResource(ResourceDescriptor desc)
        {
            var t = desc.sType.type;

            if (t == typeof(ComputeBuffer))
            {
                desc.allocatedBuffer = AllocComputeBuffer(desc.bufferSize, desc.bufferStride);
            }
            else if (typeof(Texture).IsAssignableFrom(t))
            {
                int expectedWidth  = desc.textureAllocMode == TextureAllocMode.SameAsOutput ? rtSettings.GetWidth(graph) : (int)desc.textureAllocMode;
                int expectedHeight = desc.textureAllocMode == TextureAllocMode.SameAsOutput ? rtSettings.GetHeight(graph) : (int)desc.textureAllocMode;
                int expectedDepth  = desc.textureAllocMode == TextureAllocMode.SameAsOutput ? rtSettings.GetDepth(graph) : (int)desc.textureAllocMode;

                RenderTextureDescriptor descriptor = new RenderTextureDescriptor
                {
                    // TODO: custom size
                    width             = expectedWidth,
                    height            = expectedHeight,
                    volumeDepth       = expectedDepth,
                    autoGenerateMips  = false,
                    useMipMap         = false,
                    graphicsFormat    = GraphicsFormat.R16G16B16A16_SFloat,
                    enableRandomWrite = true,
                    depthBufferBits   = 0,
                    dimension         = TextureUtils.GetDimensionFromType(t),
                    msaaSamples       = 1,
                };
                desc.allocatedTexture = new RenderTexture(descriptor)
                {
                    name      = "AutoAllocated - " + name,
                    hideFlags = HideFlags.HideAndDontSave,
                };
                desc.allocatedTexture.Create();
            }
        }
 public ResourceDescriptor CopySourceFromGlobalToLocal(ResourceDescriptor descriptor, string uniqueName)
 {
     return _presentationClient.Channel.CopySourceFromGlobalToLocal(UserIdentity, descriptor, uniqueName);
 }
		protected void AddResource(string name, string resourceName, Assembly asm)
		{
			IResourceFactory resourceFactory = new DefaultResourceFactory();
			ResourceDescriptor descriptor = new ResourceDescriptor(
				null,
				name,
				resourceName,
				null,
				null);
			IResource resource = resourceFactory.Create(
				descriptor,
				asm);
			ControllerContext.Resources.Add(name, resource);
		}
 public SlideBulk LoadSlideBulk(string fileName, ResourceDescriptor[] resourceDescriptors, DeviceResourceDescriptor[] deviceResourceDescriptors)
 {
     throw new System.NotImplementedException();
 }
 public SavePresentationResult SavePresentationChanges(PresentationInfo presentationInfo, Slide[] slides, out ResourceDescriptor[] notExistedResources, out DeviceResourceDescriptor[] notExistedDeviceResources, out int[] labelNotExists,
     out UserIdentity[] whoLock, out int[] slidesAlreadyExistsId)
 {
     return _presentationClient.Channel.SavePresentationChanges(UserIdentity, presentationInfo, slides, out notExistedResources, out notExistedDeviceResources, out labelNotExists,
         out whoLock, out slidesAlreadyExistsId);
 }
Esempio n. 44
0
 public virtual ResourceDescriptor InitSourceDownload(UserIdentity identity, ResourceDescriptor resourceDescriptor)
 {
     throw new System.NotImplementedException();
 }
Esempio n. 45
0
 public virtual FileSaveStatus SaveSource(UserIdentity userIdentity, ResourceDescriptor resourceDescriptor, SourceStatus status, out string newResourceId)
 {
     throw new System.NotImplementedException();
 }
 public bool IsResourceAvailable(ResourceDescriptor descriptor)
 {
     return _presentationClient.Channel.IsResourceAvailable(descriptor);
 }
Esempio n. 47
0
 public ResourceDescriptor CopySourceFromLocalToGlobal(UserIdentity sender, ResourceDescriptor resourceDescriptor)
 {
     return _sourceDAL.CopySourceFromLocalToGlobal(sender, resourceDescriptor);
 }
Esempio n. 48
0
 public ResourceDescriptor CopySourceFromGlobalToLocal(UserIdentity sender, ResourceDescriptor resourceDescriptor,
                                                       string presentationUniqueName)
 {
     return _sourceDAL.CopySourceFromGlobalToLocal(sender, resourceDescriptor, presentationUniqueName);
 }
Esempio n. 49
0
 public bool IsResourceAvailable(ResourceDescriptor descriptor)
 {
     return _sourceDAL.IsResourceAvailable(descriptor);
 }
Esempio n. 50
0
 public FileSaveStatus GetSourceStatus(ResourceDescriptor descriptor)
 {
     return _sourceDAL.GetSourceStatus(descriptor);
 }
 public ResourceDescriptor CopySourceFromLocalToGlobal(ResourceDescriptor descriptor)
 {
     return _presentationClient.Channel.CopySourceFromLocalToGlobal(UserIdentity, descriptor);
 }
Esempio n. 52
0
 private SlideBulk LoadFromFile(string fileName, ResourceDescriptor[] resourceDescriptors,
     DeviceResourceDescriptor[] deviceResourceDescriptors)
 {
     return _standalonePresentationWorker.LoadSlideBulk(fileName, resourceDescriptors, deviceResourceDescriptors);
 }
Esempio n. 53
0
 public void RemoveManagedResource(ResourceDescriptor desc)
 {
     FreeResource(desc);
     managedResources.Remove(desc);
 }
Esempio n. 54
0
 public PresentationInfo[] GetPresentationWhichContainsSource(ResourceDescriptor resourceDescriptor)
 {
     return _presentationDAL.GetPresentationWhichContainsSource(resourceDescriptor);
 }
Esempio n. 55
0
 public SavePresentationResult SavePresentationChanges(UserIdentity userIdentity, PresentationInfo presentationInfo,
     Slide[] newSlideArr, out ResourceDescriptor[] resourcesNotExists,
     out DeviceResourceDescriptor[] deviceResourcesNotExists, out int[] labelNotExists,
     out UserIdentity[] whoLock,
     out int[] slidesAlreadyExistsId)
 {
     resourcesNotExists = new ResourceDescriptor[] { };
     deviceResourcesNotExists = new DeviceResourceDescriptor[] {};
     whoLock = new UserIdentity[] { };
     slidesAlreadyExistsId = new int[] { };
     labelNotExists = presentationInfo.GetUsedLabels().Except(
         _configuration.LabelStorageAdapter.GetLabelStorage().Select(lb => lb.Id)).ToArray();
     if (labelNotExists.Length != 0) return SavePresentationResult.LabelNotExists;
     if (!IsStandAlone)
     {
         // необходим лок уровня презентации
         LockingInfo info = _lockService.GetLockInfo(ObjectKeyCreator.CreatePresentationKey(presentationInfo));
         if (info == null || !info.UserIdentity.Equals(userIdentity)) return SavePresentationResult.PresentationNotLocked;
     }
     string[] deletedEquipment;
     Presentation presentationStored = _presentationDAL.GetPresentation(
         presentationInfo.UniqueName, _sourceDAL, _deviceSourceDAL, out deletedEquipment);
     if (presentationStored == null) return SavePresentationResult.PresentationNotExists;
     resourcesNotExists = GetNotExistedResource(newSlideArr);
     deviceResourcesNotExists = GetNotExistedDeviceResource(newSlideArr, presentationInfo);
     if (resourcesNotExists.Length != 0 || deviceResourcesNotExists.Length != 0) return SavePresentationResult.ResourceNotExists;
     LockingInfo[] lockedSlides;
     Slide[] slideAlreadyExists;
     presentationStored = Merge(userIdentity, presentationInfo, newSlideArr, presentationStored,
         out lockedSlides, out slideAlreadyExists);
     if (presentationStored == null)
     {
         SavePresentationResult result = SavePresentationResult.Unknown;
         if (lockedSlides.Length != 0)
         {
             whoLock = lockedSlides.Select(li => li.UserIdentity).ToArray();
             result = SavePresentationResult.SlideLocked;
         }
         if (slideAlreadyExists.Length != 0)
         {
             slidesAlreadyExistsId = slideAlreadyExists.Select(sl => sl.Id).ToArray();
             result = SavePresentationResult.SlideAlreadyExists;
         }
         return result;
     }
     bool isSuccess = _presentationDAL.SavePresentation(userIdentity, presentationStored);
     if (isSuccess)
     {
         PresentationKey presentationKey = ObjectKeyCreator.CreatePresentationKey(presentationStored);
         ObjectChanged(userIdentity, new List<ObjectInfo> { new ObjectInfo(userIdentity, presentationKey) },
                       new PresentationInfo(presentationStored), true);
     }
     else
     {
         return SavePresentationResult.Unknown;
     }
     return SavePresentationResult.Ok;
 }
 public bool SaveSlideChanges(string uniqueName, Slide[] slides, out int[] notLockedSlide, out ResourceDescriptor[] notExistedResources, out DeviceResourceDescriptor[] notExistedDeviceResources, out int[] labelNotExists)
 {
     return _presentationClient.Channel.SaveSlideChanges(UserIdentity, uniqueName, slides, out  notLockedSlide, out notExistedResources, out notExistedDeviceResources, out labelNotExists);
 }
Esempio n. 57
0
 public bool SaveSlideChanges(UserIdentity userIdentity, string presentationUniqueName,
     Slide[] slideToSave, out int[] slideIdNotLocked,
     out ResourceDescriptor[] resourcesNotExists,
     out DeviceResourceDescriptor[] deviceResourcesNotExists,
     out int[] labelNotExists)
 {
     resourcesNotExists = new ResourceDescriptor[] { };
     deviceResourcesNotExists = new DeviceResourceDescriptor[] {};
     labelNotExists =
         slideToSave.Select(sl => sl.LabelId).Where(id=>id>0).Distinct().Except(
             _configuration.LabelStorageAdapter.GetLabelStorage().Select(lb => lb.Id)).ToArray();
     List<int> slideNotLocked = new List<int>(slideToSave.Length);
     slideIdNotLocked = slideNotLocked.ToArray();
     if (labelNotExists.Length != 0) return false;
     if (slideToSave.Length == 0) return true;
     if (!IsStandAlone)
     {
         //Presentation pres = BinarySerializer.Deserialize<Presentation>(presentation);
         // проверка что слайды залочены данным пользователем
         foreach (Slide slide in slideToSave)
         {
             LockingInfo info =
                 _lockService.GetLockInfo(ObjectKeyCreator.CreateSlideKey(presentationUniqueName, slide.Id));
             if (info == null || !info.UserIdentity.Equals(userIdentity))
                 slideNotLocked.Add(slide.Id);
         }
     }
     slideIdNotLocked = slideNotLocked.ToArray();
     string[] deletedEquipment;
     Presentation presentation = _presentationDAL.GetPresentation(presentationUniqueName,
         _sourceDAL, _deviceSourceDAL, out deletedEquipment);
     if (presentation == null) return false;
     PresentationInfo presentationInfo = new PresentationInfo(presentation);
     resourcesNotExists = GetNotExistedResource(slideToSave);
     deviceResourcesNotExists = GetNotExistedDeviceResource(slideToSave, presentationInfo);
     if (slideIdNotLocked.Length != 0 || resourcesNotExists.Length != 0 || deviceResourcesNotExists.Length != 0)
         return false;
     presentation = Merge(presentation, slideToSave);
     if (presentation == null) return false;
     bool isSuccess = _presentationDAL.SavePresentation(userIdentity, presentation);
     if (isSuccess)
     {
         List<ObjectInfo> objectInfoList = new List<ObjectInfo>();
         foreach (Slide slide in slideToSave)
         {
             objectInfoList.Add(new ObjectInfo(userIdentity,
                                               ObjectKeyCreator.CreateSlideKey(presentationUniqueName, slide.Id)));
         }
         PresentationKey presentationKey = ObjectKeyCreator.CreatePresentationKey(presentationUniqueName);
         ObjectChanged(userIdentity, objectInfoList, new PresentationInfo(presentation), false);
     }
     return isSuccess;
 }
Esempio n. 58
0
 public RemoveResult DeleteSource(UserIdentity sender, ResourceDescriptor descriptor)
 {
     PresentationInfo[] presentationInfos = _presentationDAL.GetPresentationWhichContainsSource(descriptor);
     if (presentationInfos != null && presentationInfos.Length != 0) return RemoveResult.LinkedToPresentation;
     return _sourceDAL.DeleteSource(sender, descriptor) ? RemoveResult.Ok : RemoveResult.NotExists;
 }
Esempio n. 59
0
 public SourceWindow(ResourceDescriptor info)
     : this(info.ResourceInfo.Name)
 {
     Mapping = info;
 }
 public RemoveResult DeleteSource(ResourceDescriptor descriptor)
 {
     return _presentationClient.Channel.DeleteSource(UserIdentity, descriptor);
 }