Ejemplo n.º 1
0
        public virtual void RunModel()
        {
            QueryModel model = new QueryModel(_workspace, _kind, null);
            ModelEngine engine = new ModelEngine(model);
            engine.Options.WeightScheme = WeightScheme.Custom;
            engine.Options.Timeout = 100;

            engine.RunUntil(delegate()
            {
                return model.Actions.Accessed > 5;
            });


            _query = model.QueryResult;
            _container = model.ResContainer;
            _pType = model.ResultType;

            if (_query != null || _pType != null)
            {
                switch (_queryType)
                {
                    case "server":
                        VerifyServer(_query);
                        break;
                    case "client":
                        VerifyClient(model);
                        break;
                    case "linq":
                        VerifyClientLinq(model);
                        break;
                }
            }
        }
Ejemplo n.º 2
0
 //Constructor
 public PredicateModel(Workspace w,ResourceContainer container, ResourceProperty p, KeyExpression parentKey, ResourceType resType)
 {
     _resourceContainer = container;
     _workspace = w;
     _resType = resType;
     _key = parentKey;
     _prop = p;
 }
Ejemplo n.º 3
0
        public static string ConstructETag(ResourceContainer container, IDictionary<string, object> propertyValues)
        {
            ResourceType type = container.BaseType;

            List<NodeProperty> etagProperties = type.Properties.Where(p => p.Facets.ConcurrencyModeFixed).ToList();

            string[] etagValues = etagProperties.Select(p => PrimitiveToETagString(propertyValues[p.Name])).ToArray();
            return ConstructETag(etagValues);
        }
        void SortResourceItems(ResourceContainer resourceContainer)
        {
            resourceContainer.ResourceItems.CollectionChanged -= OnResourceItemsChanged;

            var resourceItems = resourceContainer.ResourceItems.OrderBy(ResourceItemKey).ToList();
            resourceContainer.ResourceItems.Clear();
            resourceItems.ForEach(resourceContainer.ResourceItems.Add);

            resourceContainer.ResourceItems.CollectionChanged += OnResourceItemsChanged;
        }
 public void CreateIQuerableGetProperty(ResourceContainer container)
 {
     string baseType = container.BaseType.Name;
     this.WriteLines(
         "           public IQueryable<" + baseType + "> " + container.Name,
         "           {",
         "               get",
         "               {",
         "                   return EntitySetDictionary.GetEntitySet<" + baseType + ">();",
         "               }",
         "           }"
     );
 }
Ejemplo n.º 6
0
        public void Initialize(ScreenLayer initialLayer = null)
        {
            ResourceContainer = new AssemblyResourceContainer(Assembly.GetEntryAssembly(), $"{nameof(StorybrewEditor)}.Resources", "resources");

            DrawState.Initialize(ResourceContainer, Window.Width, Window.Height);
            drawContext = new DrawContext();
            drawContext.Register(this, false);
            drawContext.Register <TextureContainer>(new TextureContainerAtlas(ResourceContainer), true);
            drawContext.Register <QuadRenderer>(new QuadRendererBuffered(), true);
            drawContext.Register <LineRenderer>(new LineRendererBuffered(), true);

            try
            {
                var brewLibAssembly = Assembly.GetAssembly(typeof(Drawable));
                Skin = new Skin(drawContext.Get <TextureContainer>())
                {
                    ResolveDrawableType = (drawableTypeName) =>
                                          brewLibAssembly.GetType($"{nameof(BrewLib)}.{nameof(BrewLib.Graphics)}.{nameof(BrewLib.Graphics.Drawables)}.{drawableTypeName}", true, true),
                    ResolveWidgetType = (widgetTypeName) =>
                                        Type.GetType($"{nameof(StorybrewEditor)}.{nameof(UserInterface)}.{widgetTypeName}", false, true) ??
                                        brewLibAssembly.GetType($"{nameof(BrewLib)}.{nameof(UserInterface)}.{widgetTypeName}", true, true),
                    ResolveStyleType = (styleTypeName) =>
                                       Type.GetType($"{nameof(StorybrewEditor)}.{nameof(UserInterface)}.{nameof(UserInterface.Skinning)}.{nameof(UserInterface.Skinning.Styles)}.{styleTypeName}", false, true) ??
                                       brewLibAssembly.GetType($"{nameof(BrewLib)}.{nameof(UserInterface)}.{nameof(UserInterface.Skinning)}.{nameof(UserInterface.Skinning.Styles)}.{styleTypeName}", true, true),
                };
                Skin.Load("skin.json", ResourceContainer);
            }
            catch (Exception e)
            {
                Trace.WriteLine($"Failed to load skin: {e}");
                Skin = new Skin(drawContext.Get <TextureContainer>());
            }

            var inputDispatcher = new InputDispatcher();

            InputManager = new InputManager(Window, inputDispatcher);

            ScreenLayerManager = new ScreenLayerManager(Window, clock, this);
            inputDispatcher.Add(createOverlay(ScreenLayerManager));
            inputDispatcher.Add(ScreenLayerManager.InputHandler);

            Restart(initialLayer);

            Window.Resize  += window_Resize;
            Window.Closing += window_Closing;

            resizeToWindow();
        }
Ejemplo n.º 7
0
        public void ParseFailureApplicationNameBlank(BizTalkApplicationParser parser, ILogger logger, MigrationContext context, AzureIntegrationServicesModel model, ParsedBizTalkApplicationGroup group, Exception e)
        {
            "Given a model"
            .x(() =>
            {
                model = new AzureIntegrationServicesModel();
                group = new ParsedBizTalkApplicationGroup();
                model.MigrationSource.MigrationSourceModel = group;
                group.Applications.Add(new ParsedBizTalkApplication()
                {
                    ResourceContainerKey = "TestMsi.Key",
                });
                model.MigrationSource.MigrationSourceModel = group;

                var msiContainer = new ResourceContainer()
                {
                    Key = "TestMsi.Key", Name = "TestMsi", Type = ModelConstants.ResourceContainerMsi, ContainerLocation = @"C:\Test\Test.msi"
                };
                model.MigrationSource.ResourceContainers.Add(msiContainer);

                var adf      = "<?xml version=\"1.0\" encoding=\"utf-8\"?><ApplicationDefinition xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns=\"http://Microsoft.BizTalk.ApplicationDeployment/ApplicationDefinition.xsd\">  <Properties>    <Property Name=\"DisplayName\" Value=\"\" />    <Property Name=\"Guid\" Value=\"{319AC06C-0FAB-4B68-B2C9-2659DF322B63}\" />    <Property Name=\"Manufacturer\" Value=\"Generated by BizTalk Application Deployment\" />    <Property Name=\"Version\" Value=\"1.0.0.0\" />    <Property Name=\"ApplicationDescription\" Value=\"BizTalk Application 1\" />  </Properties>  <Resources>    <Resource Type=\"System.BizTalk:BizTalkBinding\" Luid=\"Application/SimpleMessagingApplication\">      <Properties>        <Property Name=\"IsDynamic\" Value=\"True\" />        <Property Name=\"IncludeGlobalPartyBinding\" Value=\"True\" />        <Property Name=\"ShortCabinetName\" Value=\"ITEM~0.CAB\" />        <Property Name=\"FullName\" Value=\"BindingInfo.xml\" />        <Property Name=\"Attributes\" Value=\"Archive\" />        <Property Name=\"CreationTime\" Value=\"2020-04-06 16:47:47Z\" />        <Property Name=\"LastAccessTime\" Value=\"2020-04-06 16:47:47Z\" />        <Property Name=\"LastWriteTime\" Value=\"2020-04-06 16:47:47Z\" />      </Properties>      <Files>        <File RelativePath=\"BindingInfo.xml\" Key=\"Binding\" />      </Files>    </Resource>  </Resources>  <References>    <Reference Name=\"BizTalk.System\" />    <Reference Name=\"Simple Referenced Application\" />  </References></ApplicationDefinition>";
                var resource = new ResourceDefinition()
                {
                    Key = "ApplicationDefinition.adf.Key", Name = "ApplicationDefinition.adf", Type = ModelConstants.ResourceDefinitionApplicationDefinition, ResourceContent = adf
                };
                msiContainer.ResourceDefinitions.Add(resource);

                group.Applications[0].Application.ApplicationDefinition = new ApplicationDefinitionFile(msiContainer.Key, resource.Key);
            });

            "And a logger"
            .x(() => logger = _mockLogger.Object);

            "And a context"
            .x(() => context = new MigrationContext());

            "And a parser"
            .x(() => parser = new BizTalkApplicationParser(model, context, logger));

            "When parsing"
            .x(() => e = Record.Exception(() => parser.Parse()));

            "Then the parser should not throw an exception"
            .x(() => e.Should().BeNull());

            "And the context should have an error."
            .x(() => context.Errors.Count.Should().Be(1));
        }
Ejemplo n.º 8
0
        static void Main(string[] args)
        {
            Background = Color.Black;
            Static     = new Color(52, 73, 94);
            Foreground = new Color(253, 227, 167);

            Engine.Initialize <SfmlRenderer, IrrKlangModule.IrrKlangAudioModule>();

            Engine.EventHost.RegisterEvent <KeyDownEvent>((int)Keyboard.Key.Escape, 0, (ev) =>
            {
                while (Engine.SceneHost.CurrentScene != null)
                {
                    Engine.SceneHost.Pop();
                }
            });

            Engine.EventHost.RegisterEvent <InitializeEvent>(0, (ev) =>
            {
                Engine.DesiredResolution = new Vector2(640f, 480f);

                Container = Engine.ResourceHost.LoadDictionary("main", "Resources");
                Font12    = LoadFont("Fonts/merriweather_12.fnt");
                Font16    = LoadFont("Fonts/merriweather_16.fnt");
                Logo      = LoadTexture("logo.png");
                Player    = LoadTexture("player.png");
                Portal    = LoadTexture("portal.png");
                Hint1     = LoadTexture("hint1.png");
                Hint2     = LoadTexture("hint2.png");
                Hint3     = LoadTexture("hint3.png");
                EndScreen = LoadTexture("endscreen.png");

                Music    = LoadSound("music.wav");
                EnemyHit = LoadSound("ehit.wav");
                Cut      = LoadSound("cut.wav");
                Ground   = LoadSound("ground.wav");

                Music.Loop();

                Image image = new Image(1, 1);
                image.SetColor(0, 0, Color.White);
                Pixel = Engine.Renderer.TextureFromImage(image);

                var scene = Engine.SceneHost.CreateGlobal <MainScene>();
                Engine.SceneHost.Push(scene);
            });

            Engine.StartGame("cut", WindowStyle.Default);
        }
    private void ShowPantry(Transform visualizationRoot, ResourceContainer sumContainer)
    {
        float meals = sumContainer.CurrentAmount * sumContainer.MatterType.UnitsPerCubicMeter();

        for (int i = 0; i < visualizationRoot.childCount; i++)
        {
            visualizationRoot.GetChild(i).gameObject.SetActive(meals >= i + 1);
        }

        Collider c = visualizationRoot.GetComponent <Collider>();

        if (c != null)
        {
            c.enabled = meals > 0f;
        }
    }
Ejemplo n.º 10
0
    private void InitResourceContainer(GameObject go, Vector3Int cellPosition)
    {
        Transform interactor = go.transform.Find("interactor");

        if (interactor)
        {
            ResourceContainer container = interactor.GetComponent <ResourceContainer>();
            if (container && persistantData.resourceContainersSave.ContainsKey(cellPosition))
            {
                foreach (KeyValuePair <string, int> entry in persistantData.resourceContainersSave[cellPosition])
                {
                    container.AddItem(entry.Key, entry.Value);
                }
            }
        }
    }
Ejemplo n.º 11
0
    public static void Copy(ResourceContainer source, ResourceContainer destination)
    {
        destination.useResourceMaterial = source.useResourceMaterial;
        destination.capacity            = source.capacity;
        destination.groupSize           = source.groupSize;

        foreach (string s in source.acceptedResources)
        {
            destination.acceptedResources.Add(s);
        }
        foreach (KeyValuePair <string, int> entry in source.inventory)
        {
            destination.inventory.Add(entry.Key, entry.Value);
        }
        destination.UpdateContent();
    }
Ejemplo n.º 12
0
        public override QueryNode GetClientLinqQueryNode()
        {
            ResourceContainer resourceContainer = this.Path.ResourceContainer.ResourceContainer;
            QueryNode         query             = this.Path.GetClientLinqQueryNode();

            if (this.Options != null)
            {
                foreach (QueryOption queryOption in this.Options)
                {
                    switch (queryOption.Name)
                    {
                    case "$select":
                        query = query.Select(query.New(GetProperties(queryOption.Value, resourceContainer)));
                        break;

                    case "$filter":
                        query = query.Where(ProcessFilter(queryOption.Value, resourceContainer));
                        break;

                    case "$orderby":
                        // ascending/descending not supported
                        query = query.Sort(GetProperties(queryOption.Value, resourceContainer), true);
                        break;

                    case "$expand":
                        query = query.Expand(GetProperties(queryOption.Value, resourceContainer));
                        break;

                    case "$inlinecount":
                        query = query.Count(true);
                        break;

                    case "$top":
                        query = query.Top(int.Parse(queryOption.Value));
                        break;

                    case "$skip":
                        query = query.Skip(int.Parse(queryOption.Value));
                        break;

                    default:
                        throw new NotSupportedException(string.Format("queryOption: {0} (value: {1}) is invalid or not supported.", queryOption.Name, queryOption.Value));
                    }
                }
            }
            return(query);
        }
        public void ParseFailureEmptyXml(ApplicationDefinitionParser parser, ILogger logger, MigrationContext context, AzureIntegrationServicesModel model, ParsedBizTalkApplicationGroup group, Exception e)
        {
            "Given a model"
            .x(() =>
            {
                model = new AzureIntegrationServicesModel();
                group = CreateGroup();
                model.MigrationSource.MigrationSourceModel = group;

                var container = new ResourceContainer()
                {
                    Key = "Test.Key", Name = "Test", Type = ModelConstants.ResourceContainerCab, ContainerLocation = @"C:\Test\Test.CAB"
                };
                model.MigrationSource.ResourceContainers.Add(container);
                var adf      = string.Empty;
                var resource = new ResourceDefinition()
                {
                    Key = "Test.adf.Key", Name = "Test.adf", Type = ModelConstants.ResourceDefinitionApplicationDefinition, ResourceContent = adf
                };
                container.ResourceDefinitions.Add(resource);

                group.Applications[0].Application.ApplicationDefinition = new ApplicationDefinitionFile(container.Key, resource.Key);
            });

            "And a logger"
            .x(() => logger = _mockLogger.Object);

            "And a context"
            .x(() => context = new MigrationContext());

            "And a parser"
            .x(() => parser = new ApplicationDefinitionParser(model, context, logger));

            "When parsing"
            .x(() => e = Record.Exception(() => parser.Parse()));

            "Then the code should not throw an exception"
            .x(() => e.Should().BeNull());

            "And the parser should have recorded an error when processing the filter."
            .x(() =>
            {
                var item = group.Applications[0].Application.ApplicationDefinition.ApplicationDefinition.Should().BeNull();
                context.Errors.Count.Should().Be(1);
            });
        }
Ejemplo n.º 14
0
        static void Main(string[] args)
        {
            Background = Color.Black;
            Static = new Color(52, 73, 94);
            Foreground = new Color(253, 227, 167);

            Engine.Initialize<SfmlRenderer, IrrKlangModule.IrrKlangAudioModule>();

            Engine.EventHost.RegisterEvent<KeyDownEvent>((int)Keyboard.Key.Escape, 0, (ev) =>
                {
                    while (Engine.SceneHost.CurrentScene != null)
                        Engine.SceneHost.Pop();
                });

            Engine.EventHost.RegisterEvent<InitializeEvent>(0, (ev) =>
            {
                Engine.DesiredResolution = new Vector2(640f, 480f);

                Container = Engine.ResourceHost.LoadDictionary("main", "Resources");
                Font12 = LoadFont("Fonts/merriweather_12.fnt");
                Font16 = LoadFont("Fonts/merriweather_16.fnt");
                Logo = LoadTexture("logo.png");
                Player = LoadTexture("player.png");
                Portal = LoadTexture("portal.png");
                Hint1 = LoadTexture("hint1.png");
                Hint2 = LoadTexture("hint2.png");
                Hint3 = LoadTexture("hint3.png");
                EndScreen = LoadTexture("endscreen.png");

                Music = LoadSound("music.wav");
                EnemyHit = LoadSound("ehit.wav");
                Cut = LoadSound("cut.wav");
                Ground = LoadSound("ground.wav");

                Music.Loop();

                Image image = new Image(1, 1);
                image.SetColor(0, 0, Color.White);
                Pixel = Engine.Renderer.TextureFromImage(image);

                var scene = Engine.SceneHost.CreateGlobal<MainScene>();
                Engine.SceneHost.Push(scene);
            });

            Engine.StartGame("cut", WindowStyle.Default);
        }
Ejemplo n.º 15
0
        public void Execute(object sender, ResourceEventArgs es)
        {
            if (!ChangeEnabledStateEventHandler(sender, es))
            {
                return;
            }

            SimPe.Events.ResourceContainers c = new ResourceContainers();
            foreach (SimPe.Interfaces.Files.IPackedFileDescriptor pfd in es.LoadedPackage.Package.Index)
            {
                SimPe.Interfaces.Scenegraph.IScenegraphFileIndexItem fii = new SimPe.Plugin.FileIndexItem(pfd, es.LoadedPackage.Package);
                SimPe.Events.ResourceContainer rc = new ResourceContainer(fii);
                c.Add(rc);
            }

            CreateListFromSelectionTool.Execute(c);
        }
Ejemplo n.º 16
0
 private JObject loadJson(string filename, ResourceContainer resourceContainer)
 {
     byte[] data;
     if (File.Exists(filename))
     {
         data = File.ReadAllBytes(filename);
     }
     else
     {
         data = resourceContainer?.GetBytes(filename);
     }
     if (data == null)
     {
         throw new FileNotFoundException(filename);
     }
     return(resolveIncludes(data.ToJObject(), resourceContainer));
 }
Ejemplo n.º 17
0
        private ResourceItem FindResourceItem(RegroupToResourceCommand.ConvertibleBrushReference brushReference)
        {
            ResourceContainer resourceContainer = this.designerContext.ResourceManager.FindResourceContainer(brushReference.DocumentUrl);

            if (resourceContainer != null)
            {
                foreach (ResourceItem resourceItem in (Collection <ResourceItem>)resourceContainer.ResourceItems)
                {
                    ResourceEntryItem resourceEntryItem = resourceItem as ResourceEntryItem;
                    if (resourceEntryItem != null && DocumentPrimitiveNode.GetValueAsString(resourceEntryItem.Resource.KeyNode) == brushReference.Key)
                    {
                        return((ResourceItem)resourceEntryItem);
                    }
                }
            }
            return((ResourceItem)null);
        }
Ejemplo n.º 18
0
        internal AudioStream(AudioManager manager, string path, ResourceContainer resourceContainer) : base(manager)
        {
            this.path = path;

            decodeStream = Bass.CreateStream(path, 0, 0, BassFlags.Decode | BassFlags.Prescan);
            if (decodeStream == 0)
            {
                Trace.WriteLine($"Failed to load audio stream ({path}): {Bass.LastError}");
                return;
            }

            stream = BassFx.TempoCreate(decodeStream, BassFlags.Default);
            Bass.ChannelSetAttribute(stream, ChannelAttribute.TempoUseQuickAlgorithm, 1);
            Bass.ChannelSetAttribute(stream, ChannelAttribute.TempoOverlapMilliseconds, 4);
            Bass.ChannelSetAttribute(stream, ChannelAttribute.TempoSequenceMilliseconds, 30);

            Channel = stream;
        }
Ejemplo n.º 19
0
 private JObject resolveIncludes(JObject data, ResourceContainer resourceContainer)
 {
     if (data["include"] != null)
     {
         var snapshot = new List <JToken>(data["include"]);
         foreach (var include in snapshot)
         {
             var path         = include.Value <string>();
             var includedData = loadJson(path, resourceContainer);
             data.Merge(includedData, new JsonMergeSettings()
             {
                 MergeArrayHandling     = MergeArrayHandling.Union,
                 MergeNullValueHandling = MergeNullValueHandling.Merge,
             });
         }
     }
     return(data);
 }
Ejemplo n.º 20
0
        public static KeyExpression ConstructKey(ResourceContainer container, PayloadObject entity)
        {
            Dictionary<string, object> properties = new Dictionary<string, object>();

            ResourceType type = container.BaseType;
            if (entity.Type != type.Namespace + "." + type.Name)
            {
                type = container.ResourceTypes.SingleOrDefault(rt => rt.Namespace + "." + rt.Name == entity.Type);
                if (type == null)
                    AstoriaTestLog.FailAndThrow("Could not find resource type for payload type value: " + entity.Type);
            }

            foreach (ResourceProperty property in type.Properties.OfType<ResourceProperty>())
            {
                if (property.IsNavigation || property.IsComplexType)
                    continue;

                string propertyName = property.Name;
                string valueString;
                if (entity.PayloadProperties.Any(p => p.Name == propertyName))
                {
                    PayloadSimpleProperty simpleProperty = entity[propertyName] as PayloadSimpleProperty;
                    if (simpleProperty == null)
                        continue;

                    valueString = simpleProperty.Value;
                }
                else
                {
                    continue;
                }

                object value = CommonPayload.DeserializeStringToObject(valueString, property.Type.ClrType, false, entity.Format);
                if (value is DateTime && entity.Format == SerializationFormatKind.JSON)
                {
                    // TODO: this is because the server will make any JSON datetime into UTC, and currently we always send 'unspecified' values
                    value = new DateTime(((DateTime)value).Ticks, DateTimeKind.Unspecified);
                }

                properties[propertyName] = value;
            }

            return new KeyExpression(container, type, properties);
        }
Ejemplo n.º 21
0
    public GameObject GetResourcePile(Dictionary <string, int> ressourcesList)
    {
        GameObject pile = Instantiate(resourcePilePrefab);

        pile.name = "ResourcePile";
        pile.transform.rotation   = Quaternion.Euler(0, Random.Range(0, 4) * 90f, 0);
        pile.transform.localScale = Vector3.one;

        ResourceContainer pileContainer = pile.transform.Find("interactor").gameObject.GetComponent <ResourceContainer>();

        pileContainer.capacity = 0;

        foreach (KeyValuePair <string, int> entry in ressourcesList)
        {
            pileContainer.AddItem(entry.Key, entry.Value);
        }
        pileContainer.UpdateContent();
        return(pile);
    }
Ejemplo n.º 22
0
    private void OnResourceChange(params Matter[] type)
    {
        ResourceContainer container = this.LinkedHab.Get(Matter.Biomass);

        float meals = container.CurrentAmount * container.MatterType.UnitsPerCubicMeter();

        for (int i = 0; i < BiomassStorageRoot.childCount; i++)
        {
            BiomassStorageRoot.GetChild(i).gameObject.SetActive(meals >= i + 1);
        }

        BiomassVisualization.gameObject.SetActive(meals > 0f);

        container = this.LinkedHab.Get(Matter.MealPowders);

        float powders = container.CurrentAmount * container.MatterType.UnitsPerCubicMeter();

        this.PowderVisualization.gameObject.SetActive(powders > 0f);
    }
Ejemplo n.º 23
0
 public void Save(ResourceContainer container, Vector3Int position)
 {
     if (container.inventory.Count != 0)
     {
         if (!resourceContainersSave.ContainsKey(position))
         {
             resourceContainersSave.Add(position, new Dictionary <string, int>());
         }
         resourceContainersSave[position].Clear();
         foreach (KeyValuePair <string, int> entry in container.inventory)
         {
             resourceContainersSave[position].Add(entry.Key, entry.Value);
         }
     }
     else if (resourceContainersSave.ContainsKey(position))
     {
         resourceContainersSave.Remove(position);
     }
 }
Ejemplo n.º 24
0
    public void FindSource()
    {
        Debug.Log("Looking for Mine!");
        GameObject[] resources = GameObject.FindGameObjectsWithTag("Mine");

        Debug.Log("Options:" + resources.Length);

        GameObject mine      = null;
        float      min_score = float.MaxValue;

        foreach (GameObject resource in resources)
        {
            if (resource.GetComponent <Unit>().team != GetComponent <Unit>().team)
            {
                continue;
            }

            float dist  = (transform.position - resource.transform.position).magnitude;
            int   metal = resource.GetComponent <ResourceContainer>().metal;
            if (metal == 0)
            {
                metal = 1;
            }
            float score = dist * (1 / metal);

            if (score <= min_score)
            {
                min_score = score;
                mine      = resource;
            }
        }
        if (mine == null)
        {
            return;
        }

        ResourceContainer cont = mine.GetComponent <ResourceContainer>();

        cont._po_points_idx = (cont._po_points_idx + 1) / cont._pick_off_points.Length;
        Transform source = cont._pick_off_points[cont._po_points_idx];

        _mov.SetDestination(source.position, source.rotation);
    }
Ejemplo n.º 25
0
        private bool EnsureDataSourceReachable(SceneNode targetNode, DataSourceNode dataSource)
        {
            if (!targetNode.ViewModel.Document.HasOpenTransaction || new ExpressionEvaluator(targetNode.ViewModel.DocumentRootResolver).EvaluateResource(targetNode.DocumentNodePath, ResourceReferenceType.Static, dataSource.ResourceKey) != null)
            {
                return(true);
            }
            IProjectDocument projectDocument = targetNode.ProjectContext.OpenDocument(dataSource.DocumentNode.Context.DocumentUrl);

            if (projectDocument == null || projectDocument.DocumentType != ProjectDocumentType.ResourceDictionary)
            {
                return(false);
            }
            SceneDocument   resourceDictionary1 = projectDocument.Document as SceneDocument;
            ResourceManager resourceManager     = targetNode.ViewModel.DesignerContext.ResourceManager;
            ResourceDictionaryContentProvider resourceDictionary2 = resourceManager.FindContentProviderForResourceDictionary(resourceDictionary1);
            ResourceContainer resourceContainer = resourceManager.FindResourceContainer(targetNode.DocumentContext.DocumentUrl);

            return(resourceDictionary2.EnsureLinked(targetNode.ViewModel, resourceContainer));
        }
Ejemplo n.º 26
0
    }                                                         // для структур, имеющих влияние на другие блоки; сообщает, что одна секция отвалилась

    // в финальном виде копипастить в потомков
    protected bool PrepareStructureForDestruction(bool forced)
    {
        if (forced)
        {
            UnsetBasement();
        }
        else
        {
            ResourceContainer[] resourcesLeft = ResourcesCost.GetCost(id);
            if (resourcesLeft.Length > 0 & GameMaster.demolitionLossesPercent != 1)
            {
                for (int i = 0; i < resourcesLeft.Length; i++)
                {
                    resourcesLeft[i] = new ResourceContainer(resourcesLeft[i].type, resourcesLeft[i].volume * (1 - GameMaster.demolitionLossesPercent));
                }
                GameMaster.colonyController.storage.AddResources(resourcesLeft);
            }
        }
        if (!forced & (basement != null))
        {
            basement.RemoveStructure(this);
            if (subscribedToChunkUpdate)
            {
                basement.myChunk.ChunkUpdateEvent -= ChunkUpdated;
                subscribedToChunkUpdate            = false;
            }
            SurfaceBlock lastBasement = basement;
            if (isBasement)
            {
                Block upperBlock = lastBasement.myChunk.GetBlock(lastBasement.pos.x, lastBasement.pos.y + 1, lastBasement.pos.z);
                if (upperBlock != null)
                {
                    lastBasement.myChunk.DeleteBlock(upperBlock.pos);
                }
            }
            return(true);
        }
        else
        {
            return(false);
        }
    }
Ejemplo n.º 27
0
        private void ToolStripButtonNew_Click(object sender, EventArgs e)
        {
            var message
                = "You are about to create a new resource."
                  + Environment.NewLine
                  + Environment.NewLine
                  + "All existing changes will be discarded."
                  + Environment.NewLine
                  + Environment.NewLine
                  + "Are you sure you want to continue?";

            var result = MessageBox.Show(this, message, Application.ProductName, MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);

            if (result == DialogResult.Yes)
            {
                this.ResourceContainer = new ResourceContainer();

                this.RefreshData();
            }
        }
Ejemplo n.º 28
0
        public void UpdateTakeFromSource()
        {
            #region Setup

            var mockComponentActorFactory = new Mock <ComponentActorFactory <TransportableStorage> >(Sys);
            mockComponentActorFactory.Setup(f => f.GetProps(It.IsAny <TransportableStorage>()))
            .Returns(Props.Create(() => new EntityTestActor()));
            var sourceEntity      = new Entity();
            var resourceContainer = new ResourceContainer();
            var sourceTransporter = new TransportableStorage();

            // TODO: Entity might not be needed
            var containerEntity = new Entity
            {
                resourceContainer,
                new Transportable
                {
                    Transporter = sourceTransporter
                }
            };
            var orderTargetTransportable = new TransportableStorage();
            var orderTargetEntity        = new Entity {
                orderTargetTransportable
            };
            var deliverOrder =
                new DeliverContainerToStorage(resourceContainer, orderTargetEntity,
                                              mockComponentActorFactory.Object);
            var transporterStorage = new TransportableStorage();
            var transporterEntity  = new Entity {
                transporterStorage
            };

            #endregion

            deliverOrder.Update(transporterEntity, new GameTime());
            var messageToEntityComponent = ExpectMsg <MessageToEntityComponentFirstOfType <TransportableStorage> >();
            Assert.Equal(sourceEntity.Id, messageToEntityComponent.EntityId);
            var giveTransportableTo = Assert.IsType <GiveTransportableTo>(messageToEntityComponent.Message);
            Assert.Equal(resourceContainer.Id, giveTransportableTo.Transportable.Id);
            Assert.Equal(transporterStorage.Id, giveTransportableTo.Target.Id);
        }
Ejemplo n.º 29
0
        public static Bitmap LoadBitmap(string filename, ResourceContainer resourceContainer = null)
        {
            if (File.Exists(filename))
            {
                return((Bitmap)Image.FromFile(filename, false));
            }

            if (resourceContainer == null)
            {
                return(null);
            }
            using (var stream = resourceContainer.GetStream(filename))
            {
                if (stream == null)
                {
                    Trace.WriteLine($"Texture not found: {filename}");
                    return(null);
                }
                return((Bitmap)Image.FromStream(stream, false));
            }
        }
Ejemplo n.º 30
0
    private void OnResourceChange(params Matter[] type)
    {
        print("showing table contents");
        ResourceContainer cont = this.LinkedHab.Get(Matter.RationMeals);

        if (cont != null)
        {
            RationMeal.gameObject.SetActive(cont.CurrentAmount > 0f);
        }

        cont = this.LinkedHab.Get(Matter.OrganicMeals);
        if (cont != null)
        {
            OrganicMeal.gameObject.SetActive(cont.CurrentAmount > 0f);
        }

        cont = this.LinkedHab.Get(Matter.MealShakes);
        if (cont != null)
        {
            ShakeMeal.gameObject.SetActive(cont.CurrentAmount > 0f);
        }
    }
Ejemplo n.º 31
0
        public ScriptManager(ResourceContainer resourceContainer, string scriptsNamespace, string scriptsSourcePath, string commonScriptsPath, string scriptsLibraryPath, string compiledScriptsPath, IEnumerable <string> referencedAssemblies)
        {
            this.resourceContainer   = resourceContainer;
            this.scriptsNamespace    = scriptsNamespace;
            this.scriptsSourcePath   = scriptsSourcePath;
            this.commonScriptsPath   = commonScriptsPath;
            this.scriptsLibraryPath  = scriptsLibraryPath;
            this.compiledScriptsPath = compiledScriptsPath;

            ReferencedAssemblies = referencedAssemblies;

            scriptWatcher = new FileSystemWatcher()
            {
                Filter = "*.cs",
                Path   = scriptsSourcePath,
                IncludeSubdirectories = false,
            };
            scriptWatcher.Created            += scriptWatcher_Changed;
            scriptWatcher.Changed            += scriptWatcher_Changed;
            scriptWatcher.Renamed            += scriptWatcher_Changed;
            scriptWatcher.Deleted            += scriptWatcher_Changed;
            scriptWatcher.Error              += (sender, e) => Trace.WriteLine($"Watcher error (script): {e.GetException()}");
            scriptWatcher.EnableRaisingEvents = true;
            Trace.WriteLine($"Watching (script): {scriptsSourcePath}");

            libraryWatcher = new FileSystemWatcher()
            {
                Filter = "*.cs",
                Path   = scriptsLibraryPath,
                IncludeSubdirectories = true,
            };
            libraryWatcher.Created            += libraryWatcher_Changed;
            libraryWatcher.Changed            += libraryWatcher_Changed;
            libraryWatcher.Renamed            += libraryWatcher_Changed;
            libraryWatcher.Deleted            += libraryWatcher_Changed;
            libraryWatcher.Error              += (sender, e) => Trace.WriteLine($"Watcher error (library): {e.GetException()}");
            libraryWatcher.EnableRaisingEvents = true;
            Trace.WriteLine($"Watching (library): {scriptsLibraryPath}");
        }
Ejemplo n.º 32
0
    private void UpdateContainerViewer(ResourceContainer container)
    {
        containerViewer.SetActive(true);
        containerLoad.text = container.load.ToString() + "/" + container.capacity.ToString();
        containerName.text = container.transform.parent.gameObject.name + ":";

        if (container.inventory.Count > containersIcons.Count)
        {
            Debug.LogWarning("Not enough prefab in InteractionUI.containerViewer to assign all resources icon");
        }

        int index = 0;

        foreach (KeyValuePair <string, int> entry in container.inventory)
        {
            if (ResourceDictionary.instance.resources.ContainsKey(entry.Key))
            {
                containersIcons[index].gameObject.SetActive(true);
                containersIcons[index].data        = ResourceDictionary.instance.resources[entry.Key];
                containersIcons[index].icon.sprite = ResourceDictionary.instance.resources[entry.Key].icon;
                containersIcons[index].text.text   = entry.Value < 1000 ? entry.Value.ToString() : (entry.Value / 1000).ToString("##.#") + "k";
                index++;
            }
            else
            {
                Debug.LogWarning("Container refer to an unknown resource : " + entry.Key);
            }

            if (index >= containersIcons.Count)
            {
                break;
            }
        }

        for (; index < containersIcons.Count; index++)
        {
            containersIcons[index].gameObject.SetActive(false);
        }
    }
Ejemplo n.º 33
0
        public static IModelElement CreateMediaStoreDeployment(Uri uri)
        {
            var appServer = new ResourceContainer()
            {
                Name = "Application Server"
            };
            var computeEnvironment = new ResourceEnvironment();

            computeEnvironment.Container.Add(appServer);
            var deployment = new MediaStore()
            {
                Environment     = computeEnvironment,
                WebForm         = appServer,
                AudioStore      = appServer,
                UserManagement  = appServer,
                OggEncoder      = appServer,
                EncodingAdapter = appServer,
                DBAdapter       = appServer,
                MySqlClient     = appServer
            };

            return(deployment);
        }
Ejemplo n.º 34
0
 override public ResourceContainer[] GetUpgradeCost()
 {
     if (level < 4)
     {
         ResourceContainer[] cost = ResourcesCost.GetCost(upgradedIndex);
         float discount           = GameMaster.upgradeDiscount;
         for (int i = 0; i < cost.Length; i++)
         {
             cost[i] = new ResourceContainer(cost[i].type, cost[i].volume * discount);
         }
         return(cost);
     }
     else
     {
         ResourceContainer[] cost = ResourcesCost.GetCost(HQ_4_ID);
         float discount           = GameMaster.upgradeCostIncrease + level - 4;
         for (int i = 0; i < cost.Length; i++)
         {
             cost[i] = new ResourceContainer(cost[i].type, cost[i].volume * discount);
         }
         return(cost);
     }
 }
Ejemplo n.º 35
0
        public static Project Load(string projectPath, bool withCommonScripts, ResourceContainer resourceContainer)
        {
            // Binary format isn't saved anymore and may be obsolete:
            // Load from the text format if possible even if the binary format has been selected.
            var textFormatPath = projectPath.Replace(DefaultBinaryFilename, DefaultTextFilename);

            if (projectPath.EndsWith(BinaryExtension) && File.Exists(textFormatPath))
            {
                projectPath = textFormatPath;
            }

            var project = new Project(projectPath, withCommonScripts, resourceContainer);

            if (projectPath.EndsWith(BinaryExtension))
            {
                project.loadBinary(projectPath);
            }
            else
            {
                project.loadText(textFormatPath);
            }
            return(project);
        }
Ejemplo n.º 36
0
        private void Initialize()
        {
            var backUp = new ResourceContainer("..", new FileBrowseLink(Path.Combine(_currentPath, ".."), this));

            Items.Add(backUp);

            // Enumerate folders and files
            var dirs = Directory.GetDirectories(_currentPath);

            // Add them to the file explorer
            foreach (var dir in dirs)
            {
                var dirInfo = new DirectoryInfo(dir);

                var resource = new ResourceContainer(dirInfo.Name, new FileBrowseLink(dir, this), IconsDescription.Folder);
                Items.Add(resource);

                dirInfo = null;
            }

            var files = Directory.GetFiles(_currentPath);

            // Add them to the file explorer
            foreach (var file in files)
            {
                var fileInfo = new FileInfo(file);
                if (!ValidFileTypes.Contains(fileInfo.Extension))
                {
                    continue;
                }

                var resource = new ResourceContainer(fileInfo.Name, new FileBrowseLink(file, this), IconsDescription.Runbook);
                Items.Add(resource);

                fileInfo = null;
            }
        }
Ejemplo n.º 37
0
        public async Task ProcessAsync(IEvent @event)
        {
            var providerUpdateEvent = (IntegrationProviderUpdateEvent)@event;

            _logger.Information(nameof(FitbitProviderUpdateEventHandler), providerUpdateEvent.Properties);

            FitbitUpdateNotification fitbitUpdate =
                ((JObject)providerUpdateEvent.Data.ProviderData)
                .ToObject <FitbitUpdateNotification>();

            string accessToken = await _fitbitTokenService.GetAccessTokenAsync(providerUpdateEvent.Data.UserId);

            ResourceContainer resource = await _fitbitClient.GetResourceAsync(
                ownerType : fitbitUpdate.OwnerType,
                ownerId : fitbitUpdate.OwnerId,
                collectionType : fitbitUpdate.CollectionType,
                date : fitbitUpdate.Date,
                accessToken : accessToken);

            if (resource.Body is null)
            {
                _logger.LogWarning($"Data mapping not supported: {JsonConvert.SerializeObject(resource)}");
                return;
            }

            await _fhirClient.EnsurePatientDeviceAsync(providerUpdateEvent.Data.UserId);

            IoMTModel iomtModel = new BodyWeight
            {
                Weight = resource.Body.Weight,
                MeasurementDateTime = fitbitUpdate.Date,
                DeviceId            = providerUpdateEvent.Data.UserId,
                PatientId           = providerUpdateEvent.Data.UserId
            };

            await _iomtDataPublisher.PublishAsync(iomtModel);
        }
Ejemplo n.º 38
0
            private ResourceBodyTree CanonicalResourcePayload(Workspace workspace, ResourceContainer resourceContainer)
            {
                ResourceType type = resourceContainer.BaseType;
                
                // TODO: support PUT by adding key support.

                ResourceInstanceProperty[] keyProperties = new ResourceInstanceProperty[0];
                ResourceInstanceKey keyExpression = new ResourceInstanceKey(resourceContainer,type, keyProperties);

                List<ResourceInstanceProperty> properties = new List<ResourceInstanceProperty>();
                foreach (NodeProperty p in type.Properties)
                {
                    // TODO: support to implement binding.
                    if (p.Type is ResourceCollection)
                    {
                        continue;
                    }
                    if (p.Type is ComplexType)
                    {
                        continue;
                    }

                    properties.Add(new ResourceInstanceSimpleProperty(p.Name, p.GetSampleValue()));
                }

                KeyedResourceInstance instance = new KeyedResourceInstance(keyExpression, properties.ToArray());
                return instance;
            }
Ejemplo n.º 39
0
 public static KeyedResourceInstance CreateKeyedResourceInstanceByClone(ResourceContainer container, ResourceType resourceType)
 {
     return CreateKeyedResourceInstanceByClone(container, resourceType, false);
 }
Ejemplo n.º 40
0
        public static KeyedResourceInstance CreateKeyedResourceInstanceByClone(ResourceContainer container, ResourceType resourceType, bool excludeRelationships)
        {
            Workspace workspace = container.Workspace;
            //Clone for an existing resource, and update its key
            KeyExpression keyExpression = workspace.GetRandomExistingKey(container, resourceType);

            if (keyExpression == null)
                return null;

            KeyedResourceInstance dataObject = workspace.GetSingleResourceByKey(keyExpression);
            if (dataObject == null)
                return null;

            ResourceInstanceKey key = null;
            
            // if there are any non-server-generated key properties, then we need to build the key
            if (keyExpression.ResourceType.Properties.Any(p => p.PrimaryKey != null && !p.Facets.ServerGenerated))
            {
                ResourceType newResourceType = container.ResourceTypes.Where(rt => rt.Name == dataObject.TypeName).FirstOrDefault();
                key = CreateUniqueKey(container, newResourceType);
            }

            //Foreach property in dataObject create a ResourceProperty
            List<ResourceInstanceProperty> properties = new List<ResourceInstanceProperty>();
            properties.AddRange(dataObject.Properties.OfType<ResourceInstanceSimpleProperty>().ToArray());
            properties.AddRange(dataObject.Properties.OfType<ResourceInstanceComplexProperty>().ToArray());
            if (!excludeRelationships)
                properties.AddRange(CloneRequiredRelationships(container, keyExpression.ResourceType, keyExpression));

            KeyedResourceInstance keyResourceInstance = null;
            if (key != null)
                keyResourceInstance = new KeyedResourceInstance(key, properties.ToArray());
            else
                keyResourceInstance = new KeyedResourceInstance(dataObject.ResourceSetName, dataObject.TypeName, properties.ToArray());
            return keyResourceInstance;

        }
Ejemplo n.º 41
0
 public static void ExecuteLinq(Workspace workspace, ExpNode q, ResourceContainer container)
 {
     try
     {
         ExecuteLinq(workspace, q, container, false, null);
     }
     catch (Exception e)
     {
         AstoriaTestLog.FailAndContinue(e);
     }
 }
Ejemplo n.º 42
0
        internal static ResourceInstanceKey CreateUniqueKey(ResourceContainer container, ResourceType resType, KeyExpressions relatedForeignKeys, KeyExpressions existingKeys)
        {
            KeyExpressions possibleRelatedForeignKeys = new KeyExpressions();
            Workspace workspace = container.Workspace;
            int keysGenerated = 0;
            bool keyTrying = true;
            ResourceInstanceKey resourceInstanceKey = null;
            do
            {
                possibleRelatedForeignKeys = new KeyExpressions();
                resourceInstanceKey = TryCreateUniqueResourceInstanceKey(container, resType, possibleRelatedForeignKeys);

                KeyExpression keyExpression = resourceInstanceKey.CreateKeyExpression(container, resType);

                // need to make sure its not a duplicate
                //
                if (existingKeys == null)
                {
                    KeyedResourceInstance o = workspace.GetSingleResourceByKey(keyExpression);

                    if (o == null)
                        keyTrying = false;
                }
                else
                {
                    keyTrying = existingKeys.Contains(keyExpression);
                }

                keysGenerated++;
                if (keysGenerated > 25)
                    throw new Microsoft.Test.ModuleCore.TestFailedException("Unable to create a unique key");
            }
            while (keyTrying);
            relatedForeignKeys.Add(possibleRelatedForeignKeys);
            return resourceInstanceKey;
        }
Ejemplo n.º 43
0
 public static string ConstructETag(ResourceContainer container, PayloadObject entity)
 {
     KeyExpression key = ConstructKey(container, entity);
     return key.ETag;
 }
Ejemplo n.º 44
0
 public KeyedResourceInstance CreateRandomResource(ResourceContainer container, bool populateNavProps)
 {
     return CreateRandomResource(container, null, populateNavProps);
 }
Ejemplo n.º 45
0
 public KeyedResourceInstance CreateRandomResource(ResourceContainer container, KeyExpressions existingKeys)
 {
     return CreateRandomResource(container, existingKeys, true);
 }
Ejemplo n.º 46
0
        private static List<ResourceInstanceProperty> CloneRequiredRelationships(ResourceContainer container, ResourceType resourceType, KeyExpression keyExpression)
        {
            List<ResourceInstanceProperty> properties = new List<ResourceInstanceProperty>();
            //Foreach Navigation Property in dataObject create a bind 
            Dictionary<ResourceProperty, KeyExpressions> navigationProperties = GetAllAssociatedKeys(container, resourceType, keyExpression);
            foreach (ResourceProperty navProperty in navigationProperties.Keys)
            {
                //ResourceAssociationEnd otherEnd = navProperty.ResourceAssociation.GetOtherEnd(navProperty);
                ResourceType navPropertyResourceType = (navProperty.Type is CollectionType ? (navProperty.Type as CollectionType).SubType : navProperty.Type) as ResourceType;
                ResourceContainer otherContainer = container.FindDefaultRelatedContainer(navProperty);

                bool foreignKeyViolation = false;
                foreach (ResourceProperty otherProperty in otherContainer.BaseType.Key.Properties)
                {
                    if (otherProperty.ForeignKeys.Count() > 0)
                    {
                        ResourceType otherType = otherProperty.ForeignKeys.First().PrimaryKey.Properties.OfType<ResourceProperty>().First().ResourceType;
                        if (otherType == container.BaseType)
                        {
                            foreignKeyViolation = true;
                            break;
                        }
                    }
                }
                if (foreignKeyViolation)
                    continue;

                KeyExpressions keyExpressions = navigationProperties[navProperty];
                if (navProperty.Type is ResourceType)
                {
                    if (keyExpressions.Count > 0)
                    {
                        properties.Add(CreateRefInstanceProperty(keyExpressions[0], otherContainer, navProperty));
                    }
                }
                else
                {
                    ResourceInstanceProperty property = CreateCollectionInstanceProperty(keyExpressions, otherContainer, navProperty);
                    if (property != null)
                    {
                        properties.Add(property);
                    }
                }

            }
            return properties;
        }
Ejemplo n.º 47
0
 public KeyedResourceInstance CreateRandomResource(ResourceContainer container)
 {
     return CreateRandomResource(container, true);
 }
Ejemplo n.º 48
0
        public static Dictionary<ResourceProperty, KeyExpressions> GetAllAssociatedKeys(ResourceContainer container, ResourceType resourceType, KeyExpression keyExpression)
        {
            Workspace workspace = container.Workspace;
            Dictionary<ResourceProperty, KeyExpressions> listOfKeyExpressions = new Dictionary<ResourceProperty, KeyExpressions>();

            foreach (ResourceProperty resourceProperty in resourceType.Properties)
            {
                if (resourceProperty.IsNavigation)
                {
                    KeyExpressions keys = workspace.GetExistingAssociatedKeys(container, resourceProperty, keyExpression);
                    listOfKeyExpressions.Add(resourceProperty, keys);
                }
            }
            return listOfKeyExpressions;
        }
Ejemplo n.º 49
0
        internal static KeyedResourceInstance CreateKeyedResourceInstanceByExactClone(ResourceContainer container, ResourceType resourceType, object dataObject)
        {
            List<ResourceInstanceProperty> properties = new List<ResourceInstanceProperty>();
            List<ResourceInstanceProperty> keyProperties = new List<ResourceInstanceProperty>();
            properties.AddRange(CloneObjectToResourceInstanceProperties(resourceType.Properties.OfType<ResourceProperty>().Where(rp => rp.PrimaryKey == null && rp.IsNavigation == false), dataObject));
            keyProperties.AddRange(CloneObjectToResourceInstanceProperties(resourceType.Properties.OfType<ResourceProperty>().Where(rp => rp.PrimaryKey != null && rp.IsNavigation == false), dataObject));

            ResourceInstanceKey key = new ResourceInstanceKey(container, resourceType, keyProperties.ToArray());
            KeyedResourceInstance keyResourceInstance = new KeyedResourceInstance(key, properties.ToArray());
            return keyResourceInstance;

        }
Ejemplo n.º 50
0
        public virtual void DirectedTests()
        {
            QueryModel model = new QueryModel(_workspace, SerializationFormatKind.Atom, null);
            ModelEngine engine = new ModelEngine(model);

            engine.Options.WeightScheme = WeightScheme.Custom;
            engine.Options.Timeout = 100;

            engine.RunUntil(delegate()
            {
                return engine.Models.Actions.AllCovered;
            });

            //engine.RunScenario(model.Actions.Find("From", "Where", " Navigation","Select","Expand"));
            //engine.RunUntil(delegate()
            //{
            //    return model.Actions.Accessed > 4;
            //});

             _query = model.QueryResult;
            _container = model.ResContainer;
            _pType = model.ResultType;

            if (_query != null || _pType != null)
            {
                VerifyClient(model);
            }
        }
Ejemplo n.º 51
0
        public override IQueryable ResourceContainerToQueryable(ResourceContainer container)
        {
            //Get Lts Type
            Type type = this._resourceTypeToWorkspaceTypeList[container.BaseType];

            DataContext context = new DataContext(this.Database.DatabaseConnectionString);

            MethodInfo method = context.GetType().GetMethod("GetTable", new Type[] { });
            MethodInfo genMethod = method.MakeGenericMethod(new Type[] { type });

            object o = genMethod.Invoke(context, new object[] { });

            if (container.HasInterceptorExpression)
            {
                o = ApplyQueryInterceptorExpression(container, o as IQueryable);
            }
            return (IQueryable)o;
        }
Ejemplo n.º 52
0
        internal KeyedResourceInstance CreateRandomResource(ResourceContainer container, KeyExpressions existingKeys, bool populateNavProps)
        {
            KeyExpressions relatedForeignKeys = new KeyExpressions();
            ResourceInstanceKey key = ResourceInstanceUtil.CreateUniqueKey(container, this, relatedForeignKeys, existingKeys);
            List<ResourceInstanceProperty> properties = new List<ResourceInstanceProperty>();

            // populate the non-key, non-navigation properties
            //
            foreach (ResourceProperty p in this.Properties.OfType<ResourceProperty>().Where(rp => rp.IsNavigation == false && rp.PrimaryKey == null))
            {
                if (p.Facets.IsIdentity)
                    continue;

                ResourceInstanceProperty property = p.CreateRandomResourceInstanceProperty();
                properties.Add(property);
            }

            if (populateNavProps)
            {
                // populate the navigation properties, but don't go by key, as some foreign keys MAY NOT HAVE ASSOCIATED NAVIGATION PROPERTIES
                //
                foreach (ResourceProperty p in this.Properties.OfType<ResourceProperty>().Where(rp => rp.IsNavigation))
                {
                    // find a key for this navigation property
                    KeyExpression navPropKey = null;
                    foreach (KeyExpression keyExp in relatedForeignKeys)
                    {
                        //if (p.Type.Equals(keyExp.ResourceType)
                        //    || p.Type is ResourceType && (p.Type as ResourceType).BaseTypes.Contains(keyExp.ResourceType))
                        if (p.OtherAssociationEnd.ResourceType.Equals(keyExp.ResourceType))
                        {
                            navPropKey = keyExp;
                            break;
                        }
                    }

                    ResourceContainer associatedContainer = container.FindDefaultRelatedContainer(p);
                    if (navPropKey == null)
                    {

                        if (p.OtherAssociationEnd.ResourceType.Key.Properties.OfType<ResourceProperty>()
                            .Where(rp => rp.ForeignKeys.Any())
                            .Any(rp => rp.ForeignKeys.First().PrimaryKey.Properties.OfType<ResourceProperty>().First().ResourceType.Equals(this)))
                        {
                            // this association has a fk back to the current type, so it cannot be based on any existing entity
                            AstoriaTestLog.WriteLineIgnore("Skipping nav prop '{0}.{1}' due to foreign key constraint on entity being created", this.Name, p.Name);
                            continue;
                        }
                        else
                            navPropKey = associatedContainer.Workspace.GetRandomExistingKey(associatedContainer, p.OtherAssociationEnd.ResourceType);
                    }

                    if (navPropKey != null)
                    {
                        if (p.OtherAssociationEnd.Multiplicity == Multiplicity.Many)
                            properties.Add(ResourceInstanceUtil.CreateCollectionInstanceProperty(new KeyExpressions(navPropKey), navPropKey.ResourceContainer, p));
                        else
                            properties.Add(ResourceInstanceUtil.CreateRefInstanceProperty(navPropKey, navPropKey.ResourceContainer, p));
                    }
                }
            }
            return ResourceInstanceUtil.CreateKeyedResourceInstance(key.CreateKeyExpression(container, this), container, properties.ToArray());
        }
Ejemplo n.º 53
0
 public static KeyedResourceInstance CreateKeyedResourceInstance(KeyExpression exp, ResourceContainer container, params ResourceInstanceProperty[] properties)
 {
     ResourceType resType = exp.Properties.OfType<ResourceProperty>().First().ResourceType;
     ResourceInstanceKey instanceKey = ResourceInstanceKey.ConstructResourceInstanceKey(exp);
     return new KeyedResourceInstance(instanceKey, properties);
 }
Ejemplo n.º 54
0
        public KeyedResourceInstance CreateRandomResource(ResourceContainer container, KeyExpression specifiedKey)
        {
            List<ResourceInstanceProperty> properties = new List<ResourceInstanceProperty>();

            foreach (ResourceProperty p in this.Properties.OfType<ResourceProperty>().Where(rp => rp.IsNavigation == false && rp.PrimaryKey == null))
            {
                ResourceInstanceProperty property = p.CreateRandomResourceInstanceProperty();
                properties.Add(property);
            }

            return ResourceInstanceUtil.CreateKeyedResourceInstance(specifiedKey, container, properties.ToArray());
        }
Ejemplo n.º 55
0
        public static string ConstructRandomETag(ResourceContainer container)
        {
            ResourceType type = container.BaseType;
            
            Dictionary<string, object> randomProperties = new Dictionary<string, object>();

            foreach (NodeProperty p in type.Properties.Where(p => p.Facets.ConcurrencyModeFixed))
                randomProperties[p.Name] = (p as ResourceProperty).CreateRandomResourceSimpleInstanceProperty().PropertyValue;

            return ConstructETag(container, randomProperties);
        }
Ejemplo n.º 56
0
 public static ResourceInstanceProperty CreateCollectionInstanceProperty(KeyExpressions keyExps, ResourceContainer container, ResourceProperty navProperty)
 {
     ResourceType navResourceType = (navProperty.Type as CollectionType).SubType as ResourceType;
     List<AssociationResourceInstance> associationNodes = new List<AssociationResourceInstance>();
     foreach (KeyExpression associatedKey in keyExps)
     {
         ResourceInstanceKey resourceInstanceKey = ResourceInstanceKey.ConstructResourceInstanceKey(associatedKey);
         associationNodes.Add(new AssociationResourceInstance(resourceInstanceKey, AssociationOperation.Add));
     }
     if (associationNodes.Count > 0)
     {
         ResourceInstanceNavColProperty navigationProperty = new ResourceInstanceNavColProperty(navProperty.Name, associationNodes.ToArray());
         return navigationProperty;
     }
     return null;
 }
Ejemplo n.º 57
0
        private static ResourceInstanceKey TryCreateUniqueResourceInstanceKey(ResourceContainer container, ResourceType resType, KeyExpressions relatedForeignKeys)
        {
            Workspace workspace = container.Workspace;
            List<ResourceInstanceSimpleProperty> keyProperties = new List<ResourceInstanceSimpleProperty>();

            Dictionary<ResourceProperty, ResourceProperty> foreignKeyMap
                = resType.Key.Properties.OfType<ResourceProperty>()
                .Where(p => p.ForeignKeys.Any())
                .ToDictionary(p => p, p => p.ForeignKeys.First().PrimaryKey.Properties.OfType<ResourceProperty>().First());
            Dictionary<string, ResourceProperty> reverseForeignKeyMap = new Dictionary<string, ResourceProperty>();
            foreach (KeyValuePair<ResourceProperty, ResourceProperty> pair in foreignKeyMap)
                reverseForeignKeyMap[pair.Value.Name] = pair.Key;

            Dictionary<ResourceProperty, object> propertyValues = new Dictionary<ResourceProperty, object>();

            List<ResourceProperty> constrainedProperties = new List<ResourceProperty>();
            foreach(ResourceProperty property in resType.Key.Properties.OfType<ResourceProperty>())
            {
                if(foreignKeyMap.ContainsKey(property))
                    constrainedProperties.Add(property);
                else
                {
                    NodeValue obj = (property.Type as PrimitiveType).CreateRandomValueForFacets(property.Facets);
                    propertyValues[property] = obj.ClrValue;
                }
            }

            foreach (ResourceProperty currentProperty in constrainedProperties)
            {
                if (propertyValues.ContainsKey(currentProperty))
                    continue;

                ResourceProperty foreignProperty = foreignKeyMap[currentProperty];

                ResourceContainer foreignContainer = container.FindDefaultRelatedContainer(foreignProperty.ResourceType);
                KeyExpression foreignKey = relatedForeignKeys.Where(k => k.ResourceContainer == foreignContainer).FirstOrDefault();
                if (foreignKey == null)
                {
                    KeyExpressions foreignKeys = workspace.GetAllExistingKeysOfType(foreignContainer, foreignProperty.ResourceType);
                    while (foreignKey == null && foreignKeys.Any())
                    {
                        foreignKey = foreignKeys.Choose();

                        // ensure that for every property in the key, it matches any local values
                        for (int i = 0; i < foreignKey.Properties.Length; i++)
                        {
                            string keyPropertyName = foreignKey.Properties[i].Name;
                            ResourceProperty localProperty;
                            if (reverseForeignKeyMap.TryGetValue(keyPropertyName, out localProperty))
                            {
                                object keyValue = foreignKey.Values[i].ClrValue;
                                object localValue;
                                if (propertyValues.TryGetValue(localProperty, out localValue))
                                {
                                    if (localValue != keyValue)
                                    {
                                        foreignKeys.Remove(foreignKey);
                                        foreignKey = null;
                                        break;
                                    }
                                }
                            }
                        }
                    }

                    if (foreignKey == null)
                        AstoriaTestLog.FailAndThrow("Could not find an appropriate foreign key");
                    relatedForeignKeys.Add(foreignKey);
                }

                for (int i = 0; i < foreignKey.Properties.Length; i++)
                {
                    NodeProperty p = foreignKey.Properties[i];

                    if (p.Name == foreignProperty.Name)
                        propertyValues[currentProperty] = foreignKey.Values[i].ClrValue;
                    else if (p.ForeignKeys.Count() > 0)
                    {
                        string foreign = p.ForeignKeys.First().PrimaryKey.Properties.OfType<ResourceProperty>().First().Name;

                        ResourceProperty localProperty;
                        if (reverseForeignKeyMap.TryGetValue(foreign, out localProperty))
                            propertyValues[localProperty] = foreignKey.Values[i].ClrValue;
                    }
                }
            }

            foreach(ResourceProperty property in resType.Key.Properties.OfType<ResourceProperty>())
                if(!propertyValues.ContainsKey(property))
                    propertyValues[property] = (object)null;

            foreach (KeyValuePair<ResourceProperty, object> pair in propertyValues)
            {
                keyProperties.Add(new ResourceInstanceSimpleProperty(pair.Key.Facets, pair.Key.Name, pair.Value));
            }

            ResourceInstanceKey resourceInstanceKey = new ResourceInstanceKey(container, resType, keyProperties.ToArray());
            return resourceInstanceKey;
        }
Ejemplo n.º 58
0
 public static ResourceInstanceProperty CreateRefInstanceProperty(KeyExpression keyExp, ResourceContainer container, ResourceProperty navProperty)
 {
     ResourceType navResourceType = navProperty.Type as ResourceType;
     ResourceInstanceKey resourceInstanceKey = ResourceInstanceKey.ConstructResourceInstanceKey(keyExp);
     return new ResourceInstanceNavRefProperty(navProperty.Name, new AssociationResourceInstance(resourceInstanceKey, AssociationOperation.Add));
 }
Ejemplo n.º 59
0
        internal static KeyedResourceInstance CreateKeyedResourceInstanceFromPayloadObject(ResourceContainer container, ResourceType resourceType, PayloadObject payloadObject)
        {
            List<ResourceInstanceProperty> properties = new List<ResourceInstanceProperty>();
            List<ResourceInstanceProperty> keyProperties = new List<ResourceInstanceProperty>();

            foreach (ResourceProperty property in resourceType.Properties.OfType<ResourceProperty>())
            {
                if (property.IsNavigation)
                    continue;

                if (property.IsComplexType)
                {
                    PayloadComplexProperty fromPayload = payloadObject[property.Name] as PayloadComplexProperty;
                    properties.Add(ConvertComplexPayloadObjectToComplexProperty(property, fromPayload));
                }
                else
                {
                    string stringValue;
                    if (payloadObject.PayloadProperties.Any(p => p.Name == property.Name))
                    {
                        PayloadSimpleProperty fromPayload = payloadObject[property.Name] as PayloadSimpleProperty;
                        stringValue = fromPayload.Value;
                    }
                    else
                    {
                        if (!payloadObject.CustomEpmMappedProperties.TryGetValue(property.Name, out stringValue))
                            stringValue = null;
                    }

                    ResourceInstanceProperty newProperty = null;
                    object val = CommonPayload.DeserializeStringToObject(stringValue, property.Type.ClrType, false, payloadObject.Format);
                    newProperty = new ResourceInstanceSimpleProperty(property.Name, new NodeValue(val, property.Type));

                    if (property.PrimaryKey != null)
                        keyProperties.Add(newProperty);
                    else
                        properties.Add(newProperty);
                }
            }

            ResourceInstanceKey key = new ResourceInstanceKey(container, resourceType, keyProperties.ToArray());
            return new KeyedResourceInstance(key, properties.ToArray());

        }
Ejemplo n.º 60
0
        public static void ExecuteLinq(Workspace workspace, ExpNode q, ResourceContainer container, bool bSingle, ExpNode altq)
        {

            System.Uri uri = new Uri(workspace.ServiceUri);

            WebDataCtxWrapper ctx = new WebDataCtxWrapper(uri);
            ctx.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
            ctx.MergeOption = MergeOption.NoTracking;

            Type resType = container.BaseType.ClientClrType;
            ResolveClientType(workspace, ctx, resType);

            Type cType = typeof(WebDataCtxWrapper);
            MethodInfo mi = cType.GetMethod("CreateQuery", new Type[] { typeof(string) });

            Type pType = container.BaseType.ClientClrType;
            MethodInfo miConstructed = mi.MakeGenericMethod(pType);

            string uri2 = container.Name;
            AstoriaTestLog.WriteLineIgnore(workspace.ServiceUri + "/" + uri2);

            object[] args = { uri2 };
            object query = miConstructed.Invoke(ctx, args);

            LinqQueryBuilder lb = new LinqQueryBuilder(workspace, (IQueryable)query);
            string uri3 = lb.Build(q);
            AstoriaTestLog.WriteLineIgnore("Linq expression: " + lb.QueryExpression);

            //if (bSingle)
            //{
            //    var single = lb.QueryResultSingle;
            //    VerifyLinqSingle(workspace, altq, single, container);
            //}
            //else
            //{
            var queryable = lb.QueryResult;
            VerifyLinq(workspace, q, (IQueryable)queryable);
            //}

        }