Beispiel #1
0
        public TMeta GetMeta <TModel, TMeta>(TModel model, string metaName)
        {
            ThrowIfDisposed();

            // NOTE: GetMeta is only used by model ctor. we can safely check the resource and ignore the patch
            return(ModelRegistry.GetMetaValue <TModel, TMeta>(model, metaName));
        }
Beispiel #2
0
        public async Task Update <TModel>(TModel model)
        {
            // guard from kunckleheads
            if (model == null)
            {
                throw new ArgumentNullException(nameof(model));
            }
            ThrowIfUnmanaged(model);

            var patch = BuildPatch(model);

            // if nothing was updated, no need to continue
            if (patch == null)
            {
                return;
            }

            var allModels = ModelRegistry.IncludedModelsCreate(model);

            foreach (var newModel in allModels)
            {
                var newResource = BuildModelResource(newModel);
                // Update the model instance in the argument
                var initialize = newModel.GetType().GetInitializeMethod();
                initialize.Invoke(newModel, new object[] { newResource, this });
            }

            var includes = allModels.Select(ModelRegistry.GetResource).ToArray();

            var originalResource = ModelRegistry.GetResource(model);

            var root    = ResourceRootSingle.FromResource(patch, includes);
            var request = await HttpRequestBuilder.UpdateResource(originalResource, root);

            var response = await HttpClient.SendAsync(request).ConfigureAwait(false);

            HttpResponseListener.UpdateResource(response.StatusCode, originalResource, root);
            response.CheckStatusCode();

            if (response.StatusCode == HttpStatusCode.OK)
            {
                var responseRoot = await response.GetContentModel <ResourceRootSingle>(JsonSettings);

                // Update the model instance in the argument
                var initialize = typeof(TModel).GetInitializeMethod();
                initialize.Invoke(model, new object[] { responseRoot.Data, this });
                Cache.Update(responseRoot.Data.Id, model);
            }
            else if (response.StatusCode == HttpStatusCode.NoContent)
            {
                ModelRegistry.ApplyPatch(model, patch);
            }

            // create and cache includes
            await Task.WhenAll(allModels.Select(x => Task.Run(() =>
            {
                var resource = ModelRegistry.GetResource(x);
                Cache.Update(resource.Id, x);
            })));
        }
Beispiel #3
0
        /// <summary>
        /// creates a new <see cref="HubSpot"/>
        /// </summary>
        /// <param name="apikey">key used to access api</param>
        public HubSpot(string apikey)
        {
            ModelRegistry     registry   = new ModelRegistry();
            HubSpotRestClient restclient = new HubSpotRestClient(apikey, new Uri("https://api.hubapi.com/"));

            Companies = new CompanyApi(restclient, registry);
        }
Beispiel #4
0
        private object GetSingleRelated(object model, string rltnName)
        {
            var resource = ModelRegistry.GetResource(model);
            var request  = HttpRequestBuilder.GetRelated(resource.Id, resource.Type, rltnName);
            var response = HttpClient.SendAsync(request).GetAwaiter().GetResult();

            HttpResponseListener.GetRelated(response.StatusCode, resource.Id, resource.Type, rltnName);
            if (response.StatusCode == HttpStatusCode.NotFound)
            {
                return(null);
            }
            response.CheckStatusCode();

            // TODO: perhaps use a 3rd ResourceRoot with JToken Data to determine if array was erroneously returned
            var root = response.GetContentModel <ResourceRootSingle>(JsonSettings).GetAwaiter().GetResult();

            var rltn = root.Data;

            if (rltn == null)
            {
                return(null);
            }

            var rltnModel = CreateResourceModel(rltn);

            Cache.Update(rltn.Id, rltnModel);
            return(rltnModel);
        }
Beispiel #5
0
        protected override void CollectInput()
        {
            IEnumerable <SchemaData>       schemas       = new List <SchemaData>();
            IEnumerable <PageTemplateData> pageTemplates = new List <PageTemplateData>();

            if (!string.IsNullOrEmpty(Config.SchemaId))
            {
                schemas = SchemaCollector.FindSchema(Config.SchemaId);
            }
            else if (!string.IsNullOrEmpty(Config.TemplateId))
            {
                pageTemplates = TemplateCollector.FindTemplate(Config.TemplateId, true).Cast <PageTemplateData>();
            }
            else if (!string.IsNullOrEmpty(Config.PublicationId))
            {
                schemas       = SchemaCollector.FindSchemasForPublication(Config.PublicationId);
                pageTemplates = TemplateCollector.FindTemplatesForPublication(Config.PublicationId, true).Cast <PageTemplateData>();
            }
            else if (!string.IsNullOrEmpty(Config.FolderId))
            {
                schemas       = SchemaCollector.FindSchemasForFolder(Config.FolderId);
                pageTemplates = TemplateCollector.FindTemplatesForFolder(Config.FolderId, true).Cast <PageTemplateData>();
            }
            else
            {
                throw new Exception("You need to specify one of the following: schema (-s), publication (-p) or folder (-f)");
            }
            log.Info($"Found {schemas.Count()} schemas");
            ModelRegistry.GetInstance(Config).AddSchemas(schemas);
            log.Info($"Found {pageTemplates.Count()} page templates");
            ModelRegistry.GetInstance(Config).AddPageTemplates(pageTemplates);
        }
Beispiel #6
0
 private void ThrowIfUnmanaged(object model)
 {
     if (ModelRegistry.IsUnmanagedModel(model) || !ModelRegistry.IsManagedBy(this, model))
     {
         throw new UnmanagedModelException(model.GetType(), ModelRegistry.GetId(model));
     }
 }
Beispiel #7
0
        public void SetUp()
        {
            var pool = new ObjectPool();

            eventBus = new EventBus(pool);
            testObj  = new ModelRegistry(pool, eventBus);
        }
Beispiel #8
0
        private void AddInternal(TItem item)
        {
            if (item == null)
            {
                return;
            }

            if (ModelRegistry.IsManagedModel(item) && !ModelRegistry.IsManagedBy(Session, item))
            {
                var id = ModelRegistry.GetId(item);
                throw new UnmanagedModelException(item.GetType(), id);
            }

            var itemId = ModelRegistry.GetOrCreateId(item);

            Session.Cache.Update(itemId, item);

            if (Ids.Contains(itemId))
            {
                return;
            }

            Ids.Add(itemId);
            IsModified = true;
        }
Beispiel #9
0
        public TAttr GetAttribute <TModel, TAttr>(TModel model, string attrName)
        {
            ThrowIfDisposed();

            // NOTE: GetAttribute is only used by model ctor. we can safely check the resource and ignore the patch
            return(ModelRegistry.GetAttributeValue <TModel, TAttr>(model, attrName));
        }
Beispiel #10
0
        private void CreateModels()
        {
            _models = new ModelRegistry();
            _models.Bind <Service.ICardTemplateService, CardTemplateService>(new CardTemplateService());
            _models.Bind <IBoardModel, BoardModel>(new BoardModel(8, 8));
            _models.Bind <IArbiterModel, ArbiterModel>(new ArbiterModel());
            _models.Bind <IEndTurnButtonModel, EndTurnButtonModel>();
            _models.Bind <ICardModel, CardModel>();
            _models.Bind <IDeckModel, DeckModel>();
            _models.Bind <IHandModel, HandModel>();
            _models.Bind <IPieceModel, PieceModel>();
            _models.Bind <IPlayerModel, PlayerModel>();
            _models.Resolve();

            _boardModel       = _models.New <IBoardModel>();
            _arbiterModel     = _models.New <IArbiterModel>();
            _whitePlayerModel = _models.New <IPlayerModel>(EColor.White);
            _blackPlayerModel = _models.New <IPlayerModel>(EColor.Black);

            // make all models required. this resolves any cycles of dependancy for
            // singletons, as well as creates models used internally by other models.
            foreach (var model in _models.Instances.ToList())
            {
                model.PrepareModels();
            }
        }
Beispiel #11
0
        public Task Delete <TModel>(TModel model)
        {
            ThrowIfDisposed();

            var id = ModelRegistry.GetId(model);

            return(Delete <TModel>(id));
        }
Beispiel #12
0
 protected override void Analyze()
 {
     Console.WriteLine("TcmUri;Title;RootElementName;TypeName;Purpose;PropertyDefinitions.Count");
     foreach (var model in ModelRegistry.GetInstance(Config).ViewModels)
     {
         Console.WriteLine($"{model.TcmUri};{model.Title};{model.RootElementName};{model.TypeName};{model.Purpose};{model.PropertyDefinitions.Count()}");
     }
 }
Beispiel #13
0
        private void InitializeRegistry()
        {
            _modelRegistry = new ModelRegistry();
            _viewRegistry  = new ViewRegistry();

            RegisterMaterial(1, new MaterialInfo("stone", Textures.Stone, new RenderProperties(), new MaterialBehavior()));
            RegisterMaterial(2, new MaterialInfo("dirt", Textures.Dirt, new RenderProperties(), new MaterialBehavior()));
            RegisterMaterial(3, new MaterialInfo("grass", Textures.Grass, new RenderProperties(), new MaterialBehavior()));
            RegisterMaterial(4, new MaterialInfo("sand", Textures.Sand, new RenderProperties(), new MaterialBehavior()));
        }
Beispiel #14
0
        public bool Contains(TItem item)
        {
            if (item == null)
            {
                return(false);
            }

            Initialize();

            return(Ids.Contains(ModelRegistry.GetId(item)));
        }
Beispiel #15
0
        public void GetResourceType__Given_WovenModel__Then_GetType()
        {
            var config = new ModelConfiguration(typeof(TestWovenModel));

            var subject = new ModelRegistry(new[] { config }, new JsonSerializerSettings());

            var result1 = subject.GetResourceType(typeof(TestWovenModel));
            var result2 = subject.GetResourceType <TestWovenModel>();

            Assert.Equal("testWovenModel", result1);
            Assert.Equal("testWovenModel", result2);
        }
Beispiel #16
0
        public Guid GetReferenceId <TModel>(TModel model, string attrName)
        {
            var relationships = ModelRegistry.GetResource(model)?.Relationships;

            if (relationships == null)
            {
                return(Guid.Empty);
            }

            return(relationships.TryGetValue(attrName, out var rltn)
                ? rltn.Data?.SelectToken("id").ToObject <Guid>() ?? Guid.Empty
                : Guid.Empty);
        }
Beispiel #17
0
        public void SetModelId__Given__WovenModel__When_NoIdProperty__Then_SetId
            (Guid id)
        {
            var config = new ModelConfiguration(typeof(ModelWithNoIdSetter));

            var subject = new ModelRegistry(new[] { config }, new JsonSerializerSettings());

            var model = new ModelWithNoIdSetter();

            subject.SetId(model, id);

            Assert.Equal(id, model.Id);
        }
Beispiel #18
0
        /// <summary>
        /// creates a new <see cref="HubSpot"/>
        /// </summary>
        /// <param name="restclient">rest client used to access hubspot</param>
        /// <param name="options">options for hubspot api</param>
        public HubSpot(HubSpotRestClient restclient, HubSpotOptions options = null)
        {
            options = options ?? new HubSpotOptions();
            ModelRegistry registry = new ModelRegistry();

            Contacts     = new ContactApi(options, restclient, registry);
            Companies    = new CompanyApi(restclient, registry);
            Associations = new AssociationApi(restclient);
            Deals        = new DealsApi(restclient, registry);
            Tickets      = new TicketsApi(restclient, registry);
            BlogPosts    = new BlogPostApi(restclient, registry);
            Engagements  = new EngagementsApi(options, restclient, registry);
        }
Beispiel #19
0
        public TRltn GetReference <TModel, TRltn>(TModel model, string rltnName)
        {
            ThrowIfDisposed();

            // Assumption here is that GetReference is only used by HasOne to initialize itself
            var resource = ModelRegistry.GetResource(model);

            if (resource == null)
            {
                throw new UnmanagedModelException(model.GetType(), ModelRegistry.GetId(model));
            }
            var relationships = resource.Relationships;

            if (relationships == null || !relationships.TryGetValue(rltnName, out var rltn))
            {
                var related = GetSingleRelated(model, rltnName);
                rltn = new Relationship
                {
                    Data = related != null
                        ? JToken.FromObject(ModelRegistry.GetResource(related).ToResourceIdentifier())
                        : JValue.CreateNull()
                };
            }

            // if we make it to here, 'rltn' has been set
            if (rltn == null)
            {
                throw new ModelMapException("Cannot find HasOne relationship", model.GetType(), ModelRegistry.GetId(model));
            }
            var rltnData = rltn.Data;
            ResourceIdentifier rltnIdentifier;

            if (rltnData == null || rltnData.Type == JTokenType.Null)
            {
                return(default(TRltn));
            }
            if (rltnData.Type == JTokenType.Object)
            {
                // TODO: I don't like that we're performing this conversion for every get
                rltnIdentifier = rltnData.ToObject <ResourceIdentifier>();
            }
            else
            {
                throw new ModelMapException(
                          $"Relationship {rltnName} mapped as [HasOne] but json relationship data was not an object",
                          typeof(TModel),
                          ModelRegistry.GetId(model));
            }
            // calling Get<TRltn>(...) here will check the cache first, then go remote if necessary
            return(Get <TRltn>(rltnIdentifier.Id).GetAwaiter().GetResult());
        }
Beispiel #20
0
        public void GetModelAttributes__Given_WovenModel__GetConfig()
        {
            var config = new ModelConfiguration(typeof(TestWovenModel));

            var subject = new ModelRegistry(new[] { config }, new JsonSerializerSettings());

            var result = subject.GetAttributeConfigs(typeof(TestWovenModel));

            var camelizedConfig  = result.Single(x => x.Property.Name == "CamelizedProperty");
            var customizedConfig = result.Single(x => x.Property.Name == "CustomizedProperty");

            Assert.Equal("camelizedProperty", camelizedConfig.AttributeName);
            Assert.Equal("customized-property", customizedConfig.AttributeName);
        }
Beispiel #21
0
        public IEnumerable <Guid> GetRelationshipIds <TModel>(TModel model, string rltnName)
        {
            var relationships = ModelRegistry.GetResource(model)?.Relationships;

            if (relationships == null)
            {
                return(Array.Empty <Guid>());
            }

            return(relationships.TryGetValue(rltnName, out var rltn)
                ? rltn.Data?.SelectTokens("[*].id")
                   .Select(id => id.ToObject <Guid>())
                   .ToArray() ?? Array.Empty <Guid>()
                : Array.Empty <Guid>());
        }
Beispiel #22
0
        public async Task Delete <TModel>(Guid id)
        {
            var resourceType = ModelRegistry.GetResourceType <TModel>();
            var request      = HttpRequestBuilder.DeleteResource(resourceType, id);
            var response     = await HttpClient.SendAsync(request);

            HttpResponseListener.DeleteResource(response.StatusCode, id, resourceType);
            response.CheckStatusCode();
            var model = Cache.Retrieve <TModel>(id);

            if (model != null)
            {
                ModelRegistry.DetachModel(model);
            }
            Cache.Remove(id);
        }
Beispiel #23
0
        public ISession CreateSession(Action <HttpClient> configureClient = null)
        {
            var modelRegistry = new ModelRegistry(ModelConfigurations, JsonSettings);

            return(new Session(() =>
            {
                var client = HttpClientFactory();
                configureClient?.Invoke(client);
                return client;
            },
                               new HttpRequestBuilder(HttpRequestModifier),
                               new BasicCacheProvider(modelRegistry),
                               modelRegistry,
                               JsonSettings,
                               HttpResponseListener));
        }
Beispiel #24
0
        public object CreateResourceModel(IResourceIdentifier resource)
        {
            if (resource == null)
            {
                return(null);
            }

            var type = ModelRegistry.GetModelType(resource.Type);

            Log.Debug(() => $"activating session-managed instance of {type.FullName}:{{{resource.Id}}}");
            var model      = Activator.CreateInstance(type);
            var initialize = type.GetInitializeMethod();

            initialize.Invoke(model, new object[] { resource, this });
            return(model);
        }
Beispiel #25
0
        public void GetModelId__Given__WovenModel__When_IdSet__Then_GetId
            (Guid id)
        {
            var config = new ModelConfiguration(typeof(ModelWithPublicIdSetter));

            var subject = new ModelRegistry(new[] { config }, new JsonSerializerSettings());

            var model = new ModelWithPublicIdSetter
            {
                Id = id
            };

            var result = subject.GetId(model);

            Assert.Equal(id, result);
        }
Beispiel #26
0
        public async Task <IEnumerable <TModel> > Query <TModel>(IQueryContext query)
        {
            query = query ?? new QueryContext <TModel>();

            if (query.PageLimit != null && query.PageLimit <= 0)
            {
                return(Enumerable.Empty <TModel>());
            }
            if (query.PageSize != null && query.PageSize <= 0)
            {
                return(Enumerable.Empty <TModel>());
            }

            var include = ModelRegistry.GetInclude <TModel>();

            var request = HttpRequestBuilder.QueryResources(query, include);

            var response = await HttpClient.SendAsync(request).ConfigureAwait(false);

            HttpResponseListener.QueryResources(response.StatusCode, query);
            if (response.StatusCode == HttpStatusCode.NotFound)
            {
                return(Enumerable.Empty <TModel>());
            }
            response.CheckStatusCode();

            var root = await response.GetContentModel <ResourceRootCollection>(JsonSettings);

            var createData = Task.WhenAll(root.Data.Select(x => Task.Run(() =>
            {
                var dataModel = CreateResourceModel <TModel>(x);
                Cache.Update(x.Id, dataModel);
                return(dataModel);
            })));
            var createIncludes = root.Included != null
                ? Task.WhenAll(root.Included.Select(x => Task.Run(() =>
            {
                var includedModel = CreateResourceModel(x);
                Cache.Update(x.Id, includedModel);
            })))
                : Task.CompletedTask;

            await Task.WhenAll(createIncludes, createData);

            return(createData.Result);
        }
Beispiel #27
0
        /// <summary>
        /// Executes the compilation process.
        /// </summary>
        /// <param name="compilation">The compilation object.</param>
        /// <param name="outputStream">The output stream to write to.</param>
        /// <returns>The compilation result.</returns>
        public CompilationResult Execute(CompilationRequest input, Stream outputStream)
        {
            var context = new CompilationContext
            {
                Input        = input,
                OutputStream = outputStream,
                Result       = new CompilationResult()
            };

            // TODO: move model registry into
            // compilation context instance

            // this locks the current scope
            ModelRegistry.BeginRegistration();
            CompilationContext.Current = context;
            var profiler = new ProcessProfiler();

            try
            {
                foreach (var proc in _processes)
                {
                    profiler.Execute(proc, context);
                    if (context.Result.HasErrors)
                    {
                        break;
                    }
                }
            }
            catch (CompilationException compEx)
            {
                context.Result.AddError(compEx.ToErrorMessage());
            }
            catch (Exception ex)
            {
                context.Result.AddError("Unexpected Error: " + ex.Message);
            }
            finally
            {
                // release lock
                ModelRegistry.EndRegistration();
                CompilationContext.Current = null;
                profiler.End();
            }

            return(context.Result);
        }
Beispiel #28
0
        public Resource BuildModelResource(object model)
        {
            var resourceType = ModelRegistry.GetResourceType(model.GetType());

            // attributes
            var modelAttributes = ModelRegistry.GetAttributeValues(model);

            foreach (var attr in modelAttributes.Properties().ToArray())
            {
                if (attr.Value.Type == JTokenType.Null)
                {
                    attr.Remove();
                }
            }

            // relationships
            // Note: this process sets unset model Ids in order to create relationships
            var relationships = ModelRegistry.GetRelationshipValues(model);

            foreach (var rtln in relationships.ToList())
            {
                if (rtln.Value.Data.Type == JTokenType.Null)
                {
                    relationships.Remove(rtln);
                }
            }

            var modelMeta = ModelRegistry.GetMetaValues(model);

            foreach (var meta in modelMeta.Properties().ToArray())
            {
                if (meta.Value.Type == JTokenType.Null)
                {
                    meta.Remove();
                }
            }

            return(new Resource
            {
                Id = ModelRegistry.GetId(model),
                Type = resourceType,
                Attributes = modelAttributes.HasValues ? modelAttributes : null,
                Relationships = relationships.Any() ? relationships : null,
                Meta = modelMeta.HasValues ? modelMeta : null
            });
        }
        public void TestNamedAndIgnoredProerties(Type type)
        {
            var modelRegistry = new ModelRegistry();
            var properties    = modelRegistry.Get(type);

            var name2 = properties.GetMapping("Name1");

            Assert.True(name2 == "name2");

            var nameA = properties.GetMapping("NameA");

            Assert.True(nameA == "namea");

            var ignore = properties.GetMapping("Ignore");

            Assert.Null(ignore);
        }
Beispiel #30
0
 internal RemoteGenericBag(Session.Session session, object owner, string name, IEnumerable <TItem> items = null) :
     base(session, owner, name)
 {
     if (items == null)
     {
         // pull from owner resource
         var relationships = ModelRegistry.GetResource(owner).Relationships;
         if (relationships != null && relationships.TryGetValue(name, out var rltn))
         {
             var ids = rltn.Data?.SelectTokens("[*].id");
             ids.Each(id => Ids.Add(id.ToObject <Guid>()));
         }
     }
     else
     {
         items.Each(Add);
     }
 }