Ejemplo n.º 1
0
        public ReadOnlyCollection<IInterfaceType> GetInterfaces(bool includeInherited)
        {
            if (includeInherited && _allInterfaces == null)
            {
                List<InterfaceType> allInterfaces = new List<InterfaceType>();

                HashSet<ReferenceType> inheritedTypes = new HashSet<ReferenceType>();
                GetInheritedTypes(this, inheritedTypes);
                allInterfaces.AddRange(inheritedTypes.OfType<InterfaceType>());

                _allInterfaces = allInterfaces.ToArray();
            }
            else if (!includeInherited && _interfaces == null)
            {
                InterfaceId[] interfaceIds;
                DebugErrorHandler.ThrowOnFailure(VirtualMachine.ProtocolService.GetInterfaces(out interfaceIds, ReferenceTypeId));
                InterfaceType[] interfaces = Array.ConvertAll(interfaceIds, VirtualMachine.GetMirrorOf);
                _interfaces = interfaces;
            }

            return new ReadOnlyCollection<IInterfaceType>(includeInherited ? _allInterfaces : _interfaces);
        }
        protected override void ReadFromImpl(object obj)
        {
            ClearReferencesCache();

            Scene scene = (Scene)obj;

            GameObject[] rootGameObjects;
            if (scene.IsValid())
            {
                rootGameObjects = scene.GetRootGameObjects();
            }
            else
            {
                rootGameObjects = new GameObject[0];
            }

            List <Tuple <PersistentObject <TID>, UnityObject> > data = new List <Tuple <PersistentObject <TID>, UnityObject> >();
            List <TID> identifiers = new List <TID>();
            List <PersistentDescriptor <TID> > descriptors = new List <PersistentDescriptor <TID> >(rootGameObjects.Length);
            GetDepsFromContext getSceneDepsCtx             = new GetDepsFromContext();

            for (int i = 0; i < rootGameObjects.Length; ++i)
            {
                GameObject rootGO = rootGameObjects[i];
                PersistentDescriptor <TID> descriptor = CreateDescriptorAndData(rootGO, data, identifiers, getSceneDepsCtx);
                if (descriptor != null)
                {
                    descriptors.Add(descriptor);
                }
            }

            HashSet <object>    allDeps   = getSceneDepsCtx.Dependencies;
            Queue <UnityObject> depsQueue = new Queue <UnityObject>(allDeps.OfType <UnityObject>());
            List <Tuple <PersistentObject <TID>, UnityObject> > assets = new List <Tuple <PersistentObject <TID>, UnityObject> >();
            List <TID> assetIds = new List <TID>();

            GetDepsFromContext getDepsCtx = new GetDepsFromContext();

            while (depsQueue.Count > 0)
            {
                UnityObject uo = depsQueue.Dequeue();
                if (!uo)
                {
                    continue;
                }


                Type persistentType = m_typeMap.ToPersistentType(uo.GetType());
                if (persistentType != null)
                {
                    getDepsCtx.Clear();

                    try
                    {
                        PersistentObject <TID> persistentObject = (PersistentObject <TID>)Activator.CreateInstance(persistentType);
                        if (!(uo is GameObject) && !(uo is Component) && (uo.hideFlags & HideFlags.DontSave) == 0)
                        {
                            if (!m_assetDB.IsMapped(uo))
                            {
                                assets.Add(new Tuple <PersistentObject <TID>, UnityObject>(persistentObject, uo));
                                assetIds.Add(ToID(uo));
                                persistentObject.GetDepsFrom(uo, getDepsCtx);
                            }
                            else
                            {
                                persistentObject.GetDepsFrom(uo, getDepsCtx);
                            }
                        }
                        else
                        {
                            persistentObject.GetDepsFrom(uo, getDepsCtx);
                        }
                    }
                    catch (Exception e)
                    {
                        Debug.LogError(e.ToString());
                    }

                    foreach (UnityObject dep in getDepsCtx.Dependencies)
                    {
                        if (!allDeps.Contains(dep))
                        {
                            allDeps.Add(dep);
                            depsQueue.Enqueue(dep);
                        }
                    }
                }
            }

            List <UnityObject> externalDeps = new List <UnityObject>(allDeps.OfType <UnityObject>());

            for (int i = externalDeps.Count - 1; i >= 0; i--)
            {
                if (!m_assetDB.IsMapped(externalDeps[i]))
                {
                    externalDeps.RemoveAt(i);
                }
            }

            Descriptors = descriptors.ToArray();
            Identifiers = identifiers.ToArray();
            Data        = data.Select(t =>
            {
                PersistentObject <TID> persistentObject = t.Item1;
                persistentObject.ReadFrom(t.Item2);
                return(persistentObject);
            }).ToArray();
            Dependencies = externalDeps.Select(uo => ToID(uo)).ToArray();

            Assets = assets.Select(t =>
            {
                PersistentObject <TID> persistentObject = t.Item1;
                persistentObject.ReadFrom(t.Item2);
                return(persistentObject);
            }).ToArray();

            AssetIds = assetIds.ToArray();

            m_assetDB.UnregisterSceneObjects();
            ClearReferencesCache();
        }
Ejemplo n.º 3
0
		bool FastCheckNeedsBuild (IBuildTarget target, ConfigurationSelector configuration)
		{
			var env = Environment.GetEnvironmentVariable ("DisableFastUpToDateCheck");
			if (!string.IsNullOrEmpty (env) && env != "0" && !env.Equals ("false", StringComparison.OrdinalIgnoreCase))
				return true;

			var sei = target as SolutionEntityItem;
			if (sei != null) {
				if (sei.FastCheckNeedsBuild (configuration))
					return true;
				//TODO: respect solution level dependencies
				var deps = new HashSet<SolutionItem> ();
				CollectReferencedItems (sei, deps, configuration);
				foreach (var dep in deps.OfType<SolutionEntityItem> ()) {
					if (dep.FastCheckNeedsBuild (configuration))
						return true;
				}
				return false;
			}

			var sln = target as Solution;
			if (sln != null) {
				foreach (var item in sln.GetAllSolutionItems<SolutionEntityItem> ()) {
					if (item.FastCheckNeedsBuild (configuration))
						return true;
				}
				return false;
			}

			//TODO: handle other IBuildTargets
			return true;
		}
Ejemplo n.º 4
0
 /// <summary>
 /// Creates a new PropNet from a list of Components, along with indices over
 /// those components.
 /// </summary>
 /// <param name="roles"></param>
 /// <param name="components">A list of Components.</param>
 public PropNet(List<TermObject> roles, HashSet<IComponent> components)
 {
     Roles = roles;
     Components = components;
     Propositions = RecordPropositions();
     BasePropositions = RecordBasePropositions();
     InputPropositions = RecordInputPropositions();
     LegalPropositions = RecordLegalPropositions();
     GoalPropositions = RecordGoalPropositions();
     InitProposition = RecordInitProposition();
     TerminalProposition = RecordTerminalProposition();
     LegalInputMap = MakeLegalInputMap();
     Transitions = new HashSet<ITransition>(Components.OfType<ITransition>());
 }
Ejemplo n.º 5
0
        public IEnumerable<Document> GetAllItems()
        {
            foreach (Type universalSearchItemType in GetUniversalSearchItemTypes.Keys.OrderByDescending(type => type.FullName))
            {
                using (MiniProfiler.Current.Step("Getting " + universalSearchItemType.FullName))
                {
                    var objects = new HashSet<object>();
                    using (MiniProfiler.Current.Step("Loading objects " + universalSearchItemType.Name))
                    {
                        Type type = universalSearchItemType;
                        var criteria = _session.CreateCriteria(universalSearchItemType);
                        if (typeof (SiteEntity).IsAssignableFrom(type))
                        {
                            criteria = criteria.Add(Restrictions.Eq("Site.Id", _site.Id));
                        }
                        objects.AddRange(
                            criteria
                    .Add(Restrictions.Eq("IsDeleted", false))
                                .SetCacheable(true)
                                .List()
                                .Cast<object>()
                                .Where(o => o.GetType() == type));
                    }
                    foreach (
                        var generateDocument in
                            GenerateDocuments(objects.OfType<SystemEntity>().ToHashSet(), universalSearchItemType))
                    {
                        yield return generateDocument;
                    }
                }

            }
        }
Ejemplo n.º 6
0
        // Inverts GetMoveActions. So, returns the list of move actions whose target is the current voxel.
        // Very, very slow.
        public IEnumerable <MoveAction> GetInverseMoveActions(MoveState currentstate, OctTreeNode OctTree)
        {
            if (Parent == null)
            {
                yield break;
            }

            var creature = Creature;

            if (creature == null)
            {
                yield break;
            }
            var current = currentstate.Voxel;

            if (Can(MoveType.Teleport))
            {
                var teleportObjects = Parent.Faction.OwnedObjects.Where(obj => obj.Active && obj.Tags.Contains("Teleporter"));
                foreach (var obj in teleportObjects)
                {
                    if ((obj.Position - current.WorldPosition).LengthSquared() > 2)
                    {
                        continue;
                    }

                    for (int dx = -TeleportDistance; dx <= TeleportDistance; dx++)
                    {
                        for (int dz = -TeleportDistance; dz <= TeleportDistance; dz++)
                        {
                            for (int dy = -TeleportDistance; dy <= TeleportDistance; dy++)
                            {
                                if (dx * dx + dy * dy + dz * dz > TeleportDistanceSquared)
                                {
                                    continue;
                                }
                                VoxelHandle teleportNeighbor = new VoxelHandle(Parent.World.ChunkManager.ChunkData, current.Coordinate + new GlobalVoxelOffset(dx, dy, dz));

                                if (teleportNeighbor.IsValid && teleportNeighbor.IsEmpty && !VoxelHelpers.GetNeighbor(teleportNeighbor, new GlobalVoxelOffset(0, -1, 0)).IsEmpty)
                                {
                                    yield return(new MoveAction()
                                    {
                                        InteractObject = obj,
                                        Diff = new Vector3(dx, dx, dz),
                                        SourceVoxel = teleportNeighbor,
                                        DestinationState = currentstate,
                                        MoveType = MoveType.Teleport
                                    });
                                }
                            }
                        }
                    }
                }
            }
            foreach (var v in VoxelHelpers.EnumerateCube(current.Coordinate)
                     .Select(n => new VoxelHandle(current.Chunk.Manager.ChunkData, n))
                     .Where(h => h.IsValid))
            {
                foreach (var a in GetMoveActions(new MoveState()
                {
                    Voxel = v
                }, OctTree).Where(a => a.DestinationState == currentstate))
                {
                    yield return(a);
                }

                if (!Can(MoveType.RideVehicle))
                {
                    continue;
                }
                // Now that dwarfs can ride vehicles, the inverse of the move actions becomes extremely complicated. We must now
                // iterate through all rails intersecting every neighbor and see if we can find a connection from that rail to this one.
                // Further, we must iterate through the entire rail network and enumerate all possible directions in and out of that rail.
                // Yay!
                var bodies = new HashSet <Body>();
                OctTree.EnumerateItems(v.GetBoundingBox(), bodies);
                var rails = bodies.OfType <Rail.RailEntity>().Where(r => r.Active);
                foreach (var rail in rails)
                {
                    if (rail.GetContainingVoxel() != v)
                    {
                        continue;
                    }

                    /*
                     * if (!DwarfGame.IsMainThread)
                     * {
                     *  for (int i = 0; i < 1; i++)
                     *  {
                     *      Drawer3D.DrawBox(rail.GetBoundingBox(), Color.Purple, 0.1f, false);
                     *      System.Threading.Thread.Sleep(1);
                     *  }
                     * }
                     */
                    foreach (var neighborRail in rail.NeighborRails.Select(neighbor => creature.Manager.FindComponent(neighbor.NeighborID) as Rail.RailEntity))
                    {
                        var actions = GetMoveActions(new MoveState()
                        {
                            Voxel = v, VehicleState = new VehicleState()
                            {
                                Rail = rail, PrevRail = neighborRail
                            }
                        }, OctTree);
                        foreach (var a in actions.Where(a => a.DestinationState == currentstate))
                        {
                            yield return(a);

                            /*
                             * if (!DwarfGame.IsMainThread && a.MoveType == MoveType.RideVehicle)
                             * {
                             *  for (int i = 0; i < 10; i++)
                             *  {
                             *      Drawer3D.DrawBox(rail.GetBoundingBox(), Color.Red, 0.1f, false);
                             *      System.Threading.Thread.Sleep(1);
                             *  }
                             * }
                             */
                        }
                    }

                    foreach (var a in GetMoveActions(new MoveState()
                    {
                        Voxel = v, VehicleState = new VehicleState()
                        {
                            Rail = rail, PrevRail = null
                        }
                    }, OctTree).Where(a => a.DestinationState == currentstate))
                    {
                        yield return(a);
                    }
                }
            }
        }
Ejemplo n.º 7
0
 public IEnumerable <T> GetNodes <T>()
 {
     return(m_Nodes.OfType <T>());
 }
Ejemplo n.º 8
0
 public TimerItem TimerItemFor(WorkflowItemEvent timerEvent)
 {
     return(_workflowItems.OfType <TimerItem>().FirstOrDefault(timerEvent.IsFor));
 }
Ejemplo n.º 9
0
        public void Compile(VFXCompilationMode compilationMode, bool forceShaderValidation)
        {
            // Prevent doing anything ( and especially showing progesses ) in an empty graph.
            if (m_Graph.children.Count() < 1)
            {
                // Cleaning
                if (m_Graph.visualEffectResource != null)
                {
                    m_Graph.visualEffectResource.ClearRuntimeData();
                }

                m_ExpressionGraph  = new VFXExpressionGraph();
                m_ExpressionValues = new VFXExpressionValueContainerDesc[] {};
                return;
            }

            Profiler.BeginSample("VFXEditor.CompileAsset");
            float  nbSteps          = 12.0f;
            string assetPath        = AssetDatabase.GetAssetPath(visualEffectResource);
            string progressBarTitle = "Compiling " + assetPath;

            try
            {
                EditorUtility.DisplayProgressBar(progressBarTitle, "Collecting dependencies", 0 / nbSteps);
                var models = new HashSet <ScriptableObject>();
                m_Graph.CollectDependencies(models, false);

                var contexts = models.OfType <VFXContext>().ToArray();

                foreach (var c in contexts) // Unflag all contexts
                {
                    c.MarkAsCompiled(false);
                }

                IEnumerable <VFXContext> compilableContexts = contexts.Where(c => c.CanBeCompiled()).ToArray();
                var compilableData = models.OfType <VFXData>().Where(d => d.CanBeCompiled());

                IEnumerable <VFXContext> implicitContexts = Enumerable.Empty <VFXContext>();
                foreach (var d in compilableData) // Flag compiled contexts
                {
                    implicitContexts = implicitContexts.Concat(d.InitImplicitContexts());
                }
                compilableContexts = compilableContexts.Concat(implicitContexts.ToArray());

                foreach (var c in compilableContexts) // Flag compiled contexts
                {
                    c.MarkAsCompiled(true);
                }

                EditorUtility.DisplayProgressBar(progressBarTitle, "Collecting attributes", 1 / nbSteps);
                foreach (var data in compilableData)
                {
                    data.CollectAttributes();
                }

                EditorUtility.DisplayProgressBar(progressBarTitle, "Process dependencies", 2 / nbSteps);
                foreach (var data in compilableData)
                {
                    data.ProcessDependencies();
                }

                EditorUtility.DisplayProgressBar(progressBarTitle, "Compiling expression Graph", 3 / nbSteps);
                m_ExpressionGraph = new VFXExpressionGraph();
                var exposedExpressionContext = ScriptableObject.CreateInstance <VFXImplicitContextOfExposedExpression>();
                exposedExpressionContext.FillExpression(m_Graph); //Force all exposed expression to be visible, only for registering in CompileExpressions

                var expressionContextOptions = compilationMode == VFXCompilationMode.Runtime ? VFXExpressionContextOption.ConstantFolding : VFXExpressionContextOption.Reduction;
                m_ExpressionGraph.CompileExpressions(compilableContexts.Concat(new VFXContext[] { exposedExpressionContext }), expressionContextOptions);

                EditorUtility.DisplayProgressBar(progressBarTitle, "Generating bytecode", 4 / nbSteps);
                var expressionDescs = new List <VFXExpressionDesc>();
                var valueDescs      = new List <VFXExpressionValueContainerDesc>();
                FillExpressionDescs(expressionDescs, valueDescs, m_ExpressionGraph);

                Dictionary <VFXContext, VFXContextCompiledData> contextToCompiledData = new Dictionary <VFXContext, VFXContextCompiledData>();
                foreach (var context in compilableContexts)
                {
                    contextToCompiledData.Add(context, new VFXContextCompiledData());
                }

                EditorUtility.DisplayProgressBar(progressBarTitle, "Generating mappings", 5 / nbSteps);
                foreach (var context in compilableContexts)
                {
                    var cpuMapper   = m_ExpressionGraph.BuildCPUMapper(context);
                    var contextData = contextToCompiledData[context];
                    contextData.cpuMapper          = cpuMapper;
                    contextData.parameters         = context.additionalMappings.ToArray();
                    contextToCompiledData[context] = contextData;
                }

                var exposedParameterDescs = new List <VFXMapping>();
                FillExposedDescs(exposedParameterDescs, m_ExpressionGraph, m_Graph.children.OfType <VFXParameter>());
                var globalEventAttributeDescs = new List <VFXLayoutElementDesc>()
                {
                    new VFXLayoutElementDesc()
                    {
                        name = "spawnCount", type = VFXValueType.Float
                    }
                };
                FillEventAttributeDescs(globalEventAttributeDescs, m_ExpressionGraph, compilableContexts);



                SubgraphInfos subgraphInfos;
                subgraphInfos.subgraphParents = new Dictionary <VFXSubgraphContext, VFXSubgraphContext>();

                subgraphInfos.subgraphs = new List <VFXSubgraphContext>();

                foreach (var subgraph in m_Graph.children.OfType <VFXSubgraphContext>().Where(t => t.subgraph != null))
                {
                    subgraphInfos.subgraphs.Add(subgraph);
                    RecursePutSubgraphParent(subgraphInfos.subgraphParents, subgraphInfos.subgraphs, subgraph);
                }

                subgraphInfos.spawnerSubgraph = new Dictionary <VFXContext, VFXSubgraphContext>();

                foreach (var subgraph in subgraphInfos.subgraphs)
                {
                    foreach (var spawner in subgraph.subChildren.OfType <VFXContext>())
                    {
                        subgraphInfos.spawnerSubgraph.Add(spawner, subgraph);
                    }
                }

                subgraphInfos.contextEffectiveInputLinks = new Dictionary <VFXContext, List <VFXContextLink>[]>();

                ComputeEffectiveInputLinks(ref subgraphInfos, compilableContexts.OfType <VFXBasicInitialize>());


                EditorUtility.DisplayProgressBar(progressBarTitle, "Generating Attribute layouts", 6 / nbSteps);
                foreach (var data in compilableData)
                {
                    data.GenerateAttributeLayout(subgraphInfos.contextEffectiveInputLinks);
                }

                var generatedCodeData = new List <GeneratedCodeData>();

                EditorUtility.DisplayProgressBar(progressBarTitle, "Generating shaders", 7 / nbSteps);
                GenerateShaders(generatedCodeData, m_ExpressionGraph, compilableContexts, contextToCompiledData, compilationMode);

                EditorUtility.DisplayProgressBar(progressBarTitle, "Saving shaders", 8 / nbSteps);
                SaveShaderFiles(m_Graph.visualEffectResource, generatedCodeData, contextToCompiledData);

                var bufferDescs    = new List <VFXGPUBufferDesc>();
                var cpuBufferDescs = new List <VFXCPUBufferDesc>();
                var systemDescs    = new List <VFXEditorSystemDesc>();

                EditorUtility.DisplayProgressBar(progressBarTitle, "Generating systems", 9 / nbSteps);
                cpuBufferDescs.Add(new VFXCPUBufferDesc()
                {
                    capacity    = 1u,
                    layout      = globalEventAttributeDescs.ToArray(),
                    stride      = globalEventAttributeDescs.First().offset.structure,
                    initialData = ComputeArrayOfStructureInitialData(globalEventAttributeDescs)
                });

                var contextSpawnToSpawnInfo = new Dictionary <VFXContext, SpawnInfo>();
                FillSpawner(contextSpawnToSpawnInfo, cpuBufferDescs, systemDescs, compilableContexts, m_ExpressionGraph, globalEventAttributeDescs, contextToCompiledData, ref subgraphInfos);

                var eventDescs = new List <VFXEventDesc>();
                FillEvent(eventDescs, contextSpawnToSpawnInfo, compilableContexts, ref subgraphInfos);

                var attributeBufferDictionnary = new Dictionary <VFXData, int>();
                var eventGpuBufferDictionnary  = new Dictionary <VFXData, int>();
                FillDependentBuffer(compilableData, bufferDescs, attributeBufferDictionnary, eventGpuBufferDictionnary);

                var contextSpawnToBufferIndex = contextSpawnToSpawnInfo.Select(o => new { o.Key, o.Value.bufferIndex }).ToDictionary(o => o.Key, o => o.bufferIndex);
                foreach (var data in compilableData)
                {
                    data.FillDescs(bufferDescs,
                                   systemDescs,
                                   m_ExpressionGraph,
                                   contextToCompiledData,
                                   contextSpawnToBufferIndex,
                                   attributeBufferDictionnary,
                                   eventGpuBufferDictionnary,
                                   subgraphInfos.contextEffectiveInputLinks);
                }

                // Update renderer settings
                VFXRendererSettings rendererSettings = GetRendererSettings(m_Graph.visualEffectResource.rendererSettings, compilableContexts.OfType <IVFXSubRenderer>());
                m_Graph.visualEffectResource.rendererSettings = rendererSettings;

                EditorUtility.DisplayProgressBar(progressBarTitle, "Setting up systems", 10 / nbSteps);
                var expressionSheet = new VFXExpressionSheet();
                expressionSheet.expressions = expressionDescs.ToArray();
                expressionSheet.values      = valueDescs.OrderBy(o => o.expressionIndex).ToArray();
                expressionSheet.exposed     = exposedParameterDescs.OrderBy(o => o.name).ToArray();

                m_Graph.visualEffectResource.SetRuntimeData(expressionSheet, systemDescs.ToArray(), eventDescs.ToArray(), bufferDescs.ToArray(), cpuBufferDescs.ToArray());
                m_ExpressionValues = expressionSheet.values;

                if (k_FnVFXResource_SetCompileInitialVariants != null)
                {
                    k_FnVFXResource_SetCompileInitialVariants(m_Graph.visualEffectResource, forceShaderValidation);
                }
            }
            catch (Exception e)
            {
                VisualEffectAsset asset = null;

                if (m_Graph.visualEffectResource != null)
                {
                    asset = m_Graph.visualEffectResource.asset;
                }

                Debug.LogError(string.Format("{2} : Exception while compiling expression graph: {0}: {1}", e, e.StackTrace, (asset != null)? asset.name:"(Null Asset)"), asset);

                // Cleaning
                if (m_Graph.visualEffectResource != null)
                {
                    m_Graph.visualEffectResource.ClearRuntimeData();
                }

                m_ExpressionGraph  = new VFXExpressionGraph();
                m_ExpressionValues = new VFXExpressionValueContainerDesc[] {};
            }
            finally
            {
                EditorUtility.DisplayProgressBar(progressBarTitle, "Importing VFX", 11 / nbSteps);
                Profiler.BeginSample("VFXEditor.CompileAsset:ImportAsset");
                AssetDatabase.ImportAsset(assetPath, ImportAssetOptions.ForceUpdate); //This should compile the shaders on the C++ size
                Profiler.EndSample();

                Profiler.EndSample();
                EditorUtility.ClearProgressBar();
            }
        }
Ejemplo n.º 10
0
 public T First <T>()
 {
     return(_bindings.OfType <T>().First());
 }
Ejemplo n.º 11
0
 public T Get <T>() where T : class => store.OfType <T>().FirstOrDefault();
Ejemplo n.º 12
0
        protected override void ReadFromImpl(object obj)
        {
            ClearReferencesCache();

            Scene scene = (Scene)obj;

            GameObject[] rootGameObjects;
            if (scene.IsValid())
            {
                rootGameObjects = scene.GetRootGameObjects();
            }
            else
            {
                rootGameObjects = new GameObject[0];
            }

            List <PersistentObject>     data            = new List <PersistentObject>();
            List <long>                 identifiers     = new List <long>();
            List <PersistentDescriptor> descriptors     = new List <PersistentDescriptor>(rootGameObjects.Length);
            GetDepsFromContext          getSceneDepsCtx = new GetDepsFromContext();

            for (int i = 0; i < rootGameObjects.Length; ++i)
            {
                GameObject           rootGO     = rootGameObjects[i];
                PersistentDescriptor descriptor = CreateDescriptorAndData(rootGO, data, identifiers, getSceneDepsCtx);
                if (descriptor != null)
                {
                    descriptors.Add(descriptor);
                }
            }

            HashSet <object> allDeps = getSceneDepsCtx.Dependencies;

            Queue <UnityObject> depsQueue = new Queue <UnityObject>(allDeps.OfType <UnityObject>());

            List <PersistentObject> assets = new List <PersistentObject>();
            List <int> assetIdentifiers    = new List <int>();

            GetDepsFromContext getDepsCtx = new GetDepsFromContext();

            while (depsQueue.Count > 0)
            {
                UnityObject uo = depsQueue.Dequeue();
                if (!uo)
                {
                    continue;
                }


                Type persistentType = m_typeMap.ToPersistentType(uo.GetType());
                if (persistentType != null)
                {
                    getDepsCtx.Clear();

                    try
                    {
                        PersistentObject persistentObject = (PersistentObject)Activator.CreateInstance(persistentType);
                        if (!(uo is GameObject) && !(uo is Component))
                        {
                            if (!m_assetDB.IsMapped(uo))
                            {
                                if (uo is Texture2D)
                                {
                                    Texture2D texture = (Texture2D)uo;
                                    if (texture.isReadable)  //
                                    {
                                        persistentObject.ReadFrom(uo);
                                        assets.Add(persistentObject);
                                        assetIdentifiers.Add(uo.GetInstanceID());
                                        persistentObject.GetDepsFrom(uo, getDepsCtx);
                                    }
                                }
                                else
                                {
                                    persistentObject.ReadFrom(uo);
                                    assets.Add(persistentObject);
                                    assetIdentifiers.Add(uo.GetInstanceID());
                                    persistentObject.GetDepsFrom(uo, getDepsCtx);
                                }
                            }
                            else
                            {
                                persistentObject.GetDepsFrom(uo, getDepsCtx);
                            }
                        }
                        else
                        {
                            persistentObject.GetDepsFrom(uo, getDepsCtx);
                        }
                    }
                    catch (Exception e)
                    {
                        Debug.LogError(e.ToString());
                    }

                    foreach (UnityObject dep in getDepsCtx.Dependencies)
                    {
                        if (!allDeps.Contains(dep))
                        {
                            allDeps.Add(dep);
                            depsQueue.Enqueue(dep);
                        }
                    }
                }
            }

            List <UnityObject> externalDeps = new List <UnityObject>(allDeps.OfType <UnityObject>());

            for (int i = externalDeps.Count - 1; i >= 0; i--)
            {
                if (!m_assetDB.IsMapped(externalDeps[i]))
                {
                    externalDeps.RemoveAt(i);
                }
            }

            Descriptors  = descriptors.ToArray();
            Identifiers  = identifiers.ToArray();
            Data         = data.ToArray();
            Dependencies = externalDeps.Select(uo => m_assetDB.ToID(uo)).ToArray();

            Assets           = assets.ToArray();
            AssetIdentifiers = assetIdentifiers.ToArray();

            ClearReferencesCache();
        }
Ejemplo n.º 13
0
 public T[] GetObjectsOfType <T>() where T : ITextLineObject
 {
     return(objects.OfType <T>().ToArray());
 }
Ejemplo n.º 14
0
 public T FirstOfTypeOrDefault <T>() => _tags.OfType <T>().SingleOrDefault();
        public async Task <Graph.Group> CreateUnifiedGroupForPropertyAsync(GraphServiceClient graphService, string graphAccessToken, ListItem propertyItem, IEnumerable <Graph.User> members)
        {
            var propertyTitle       = propertyItem["Title"] as string;
            var propertyOwnerName   = propertyItem["sl_owner"] as string;
            var querypropertyOwners = (await graphService.Users.Request().Filter(string.Format("displayName eq '{0}'", propertyOwnerName)).GetAsync()).CurrentPage;
            var propertyOwner       = querypropertyOwners.Count > 0 ? querypropertyOwners[0] : null;

            if (propertyOwner == null)
            {
                return(null);
            }
            // Create Office 365 Group
            string  groupId   = string.Empty;
            dynamic groupJSON = new JObject();

            groupJSON.displayName     = propertyTitle;
            groupJSON.mailNickname    = propertyTitle.Replace(" ", "");
            groupJSON.securityEnabled = false;
            groupJSON.mailEnabled     = true;
            groupJSON.description     = "Property Group";
            groupJSON.groupTypes      = new JArray("Unified");
            HttpRequestMessage message = new HttpRequestMessage(HttpMethod.Post, string.Format("{0}groups", AADAppSettings.GraphResourceUrl));

            message.Content = new StringContent(groupJSON.ToString(), System.Text.Encoding.UTF8, "application/json");
            message.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            message.Headers.Authorization = new AuthenticationHeaderValue("Bearer", graphAccessToken);
            using (HttpClient client = new HttpClient())
            {
                var responseMessage = await client.SendAsync(message);

                if (responseMessage.StatusCode != System.Net.HttpStatusCode.Created)
                {
                    throw new System.Web.Http.HttpResponseException(responseMessage.StatusCode);
                }

                var payload = await responseMessage.Content.ReadAsStringAsync();

                groupId = JObject.Parse(payload)["id"].ToString();
            }
            var group = await graphService.Groups[groupId].Request().GetAsync() as Graph.Group;

            // Add users to Office 365 Group
            var groupMembers  = new HashSet <Graph.User>(members);
            var groupOwners   = new HashSet <Graph.User>();
            var adminUserName = _currentUserName;
            var queryAdmins   = (await graphService.Users.Request().Filter(string.Format("mail eq '{0}'", adminUserName)).GetAsync()).CurrentPage;
            var admin         = queryAdmins.Count > 0 ? queryAdmins[0] : null;

            if (admin != null)
            {
                groupMembers.Add(admin);
                groupOwners.Add(admin);
            }
            if (propertyOwner != null)
            {
                groupMembers.Add(propertyOwner);
                groupOwners.Add(propertyOwner);
            }

            foreach (var user in groupMembers.OfType <Graph.User>())
            {
                try
                {
                    await GraphServiceExtension.AddUserToGroupMembersAsync(graphService, group, user, graphAccessToken);
                }
                catch { }
            }

            foreach (var user in groupOwners.OfType <Graph.User>())
            {
                try
                {
                    await GraphServiceExtension.AddUserToGroupOwnersAsync(graphService, group, user, graphAccessToken);
                }
                catch { }
            }

            return(group);
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Callback for the MouseDown event.
        /// </summary>
        /// <param name="e">The event.</param>
        protected void OnMouseDown(MouseDownEvent e)
        {
            if (m_Active)
            {
                e.StopImmediatePropagation();
                return;
            }

            if (CanStartManipulation(e))
            {
                if (m_GraphView == null)
                {
                    return;
                }

                m_SelectedElement = null;

                // avoid starting a manipulation on a non movable object
                m_ClickedElement = e.target as GraphElement;
                if (m_ClickedElement == null)
                {
                    var ve = e.target as VisualElement;
                    m_ClickedElement = ve?.GetFirstAncestorOfType <GraphElement>();
                    if (m_ClickedElement == null)
                    {
                        return;
                    }
                }

                // Only start manipulating if the clicked element is movable, selected and that the mouse is in its clickable region (it must be deselected otherwise).
                if (!m_ClickedElement.IsMovable() || !m_ClickedElement.ContainsPoint(m_ClickedElement.WorldToLocal(e.mousePosition)))
                {
                    return;
                }

                // If we hit this, this likely because the element has just been unselected
                // It is important for this manipulator to receive the event so the previous one did not stop it
                // but we shouldn't let it propagate to other manipulators to avoid a re-selection
                if (!m_ClickedElement.IsSelected())
                {
                    e.StopImmediatePropagation();
                    return;
                }

                m_SelectedElement = m_ClickedElement;

                m_OriginalPos = new Dictionary <GraphElement, OriginalPos>();

                var selection = m_GraphView.GetSelection();

                var elementsToMove = new HashSet <GraphElement>(selection.Select(model => model.GetUI(m_GraphView)).OfType <GraphElement>());

                var selectedPlacemats = new HashSet <Placemat>(elementsToMove.OfType <Placemat>());
                foreach (var placemat in selectedPlacemats)
                {
                    placemat.GetElementsToMove(e.shiftKey, elementsToMove);
                }

                m_EdgesToUpdate.Clear();
                HashSet <INodeModel> nodeModelsToMove = new HashSet <INodeModel>(elementsToMove.Select(element => element.Model).OfType <INodeModel>());
                foreach (var edge in m_GraphView.Edges.ToList())
                {
                    if (nodeModelsToMove.Contains(edge.Input?.NodeModel) && nodeModelsToMove.Contains(edge.Output?.NodeModel))
                    {
                        m_EdgesToUpdate.Add(edge);
                    }
                }

                foreach (GraphElement ce in elementsToMove)
                {
                    if (ce == null || !ce.IsMovable())
                    {
                        continue;
                    }

                    Rect geometry = ce.GetPosition();
                    Rect geometryInContentViewSpace = ce.hierarchy.parent.ChangeCoordinatesTo(m_GraphView.ContentViewContainer, geometry);
                    m_OriginalPos[ce] = new OriginalPos
                    {
                        pos = geometryInContentViewSpace,
                    };
                }

                m_OriginalMouse = e.mousePosition;
                m_ItemPanDiff   = Vector3.zero;

                if (m_PanSchedule == null)
                {
                    m_PanSchedule = m_GraphView.schedule.Execute(Pan).Every(panInterval).StartingIn(panInterval);
                    m_PanSchedule.Pause();
                }

                m_Snapper.BeginSnap(m_SelectedElement);

                m_Active = true;
                target.CaptureMouse(); // We want to receive events even when mouse is not over ourself.
                e.StopImmediatePropagation();
            }
        }
Ejemplo n.º 17
0
 ///<summary>See interface documentation</summary>
 public IQueryable <TEntity> Query <TEntity>() => _db.OfType <TEntity>().AsQueryable();
Ejemplo n.º 18
0
 /// <summary>
 /// Derived classes can augment the available external event producers (observables)
 /// by overriding this method and concatenating other observables to the ones provided
 /// in the constructor (if any).
 /// </summary>
 /// <typeparam name="TEvent">Type of event being looked up.</typeparam>
 protected virtual IEnumerable <IObservable <TEvent> > GetObservables <TEvent>()
 {
     return(observables.OfType <IObservable <TEvent> >());
 }
        /// <summary>
        /// Handles the PreviewKeyDown event on AdaptedControl, and changes the selection
        /// if the user navigates using the keyboard</summary>
        /// <param name="sender">Sender</param>
        /// <param name="e">Event args</param>
        protected virtual void PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
        {
            Keys keyData   = e.KeyData;
            Keys modifiers = keyData & Keys.Modifiers;

            keyData &= ~Keys.Modifiers;

            if (IsNavigationKey(keyData))
            {
                List <TNode> oldSelection;

                // If the user is reversing direction of a past shift+selection, and they didn't
                //  overshoot the beginning (i.e., the stack isn't empty), then don't search for
                //  nodes and instead restore a past selection.
                if (modifiers == Keys.Shift &&
                    OppositeNavigationKeys(m_lastKeyWithShift, keyData) &&
                    m_shiftKeySelectionStack.Count > 0)
                {
                    oldSelection = m_shiftKeySelectionStack.Pop();
                    ChangeSelection(oldSelection);
                    return;
                }

                // We need to know the current selection now.
                oldSelection = new List <TNode>(m_selectionContext.SelectionCount);
                oldSelection.AddRange(m_selectionContext.GetSelection <TNode>());

                // If the user is doing a shift+selection, then push the current selection on to the
                //  stack. But if the user chose a new direction, clear the stack first.
                bool pushOldSelectionIfSelectionChanges = false;
                if (modifiers == Keys.Shift)
                {
                    if (m_lastKeyWithShift != Keys.None && m_lastKeyWithShift != keyData)
                    {
                        m_lastKeyWithShift = Keys.None;
                        m_shiftKeySelectionStack.Clear();
                    }
                    pushOldSelectionIfSelectionChanges = true;
                }
                else
                {
                    m_lastKeyWithShift = Keys.None;
                    m_shiftKeySelectionStack.Clear();
                }

                // Do a search from the existing selected nodes, looking only along wires.
                var connectedNodes = new HashSet <TNode>();
                foreach (TNode startElement in m_selectionContext.GetSelection <TNode>())
                {
                    foreach (TNode connectedNode in FindConnectedNodes(startElement, keyData, modifiers))
                    {
                        connectedNodes.Add(connectedNode);
                    }
                }

                // If no connected nodes were found, then look for the nearest nodes.
                if (connectedNodes.Count == 0)
                {
                    foreach (TNode startElement in m_selectionContext.GetSelection <TNode>())
                    {
                        TNode nearestNode = FindNearestNode(startElement, keyData, modifiers);
                        if (nearestNode != null)
                        {
                            connectedNodes.Add(nearestNode);
                        }
                    }
                }

                // If we have new connected nodes then change the selection.
                if (connectedNodes.Count > 0)
                {
                    // With this keyboard navigation, the Control key doesn't seem to make sense
                    //  for toggling nodes in the selection.
                    modifiers &= ~Keys.Control;

                    var newSelection = new HashSet <TNode>(oldSelection);
                    KeysUtil.Select(newSelection, connectedNodes, modifiers);

                    if (!newSelection.SetEquals(oldSelection))
                    {
                        ChangeSelection(newSelection);

                        if (pushOldSelectionIfSelectionChanges)
                        {
                            m_lastKeyWithShift = keyData;
                            m_shiftKeySelectionStack.Push(new List <TNode>(oldSelection));
                        }

                        // Attempt to pan, to make sure the newly selected nodes are visible
                        if (m_transformAdapter != null)
                        {
                            Rectangle boundingRect = m_pickingAdapter.GetBounds(newSelection.OfType <object>());
                            m_transformAdapter.PanToRect(boundingRect);
                        }
                    }
                }
            }
        }
Ejemplo n.º 20
0
        public void SanitizeGraph()
        {
            if (m_GraphSanitized)
            {
                return;
            }

            var objs = new HashSet <ScriptableObject>();

            CollectDependencies(objs);

            foreach (var model in objs.OfType <VFXModel>())
            {
                try
                {
                    model.Sanitize(m_GraphVersion); // This can modify dependencies but newly created model are supposed safe so we dont care about retrieving new dependencies
                }
                catch (Exception e)
                {
                    Debug.LogError(string.Format("Exception while sanitizing model: {0} of type {1}: {2} {3}", model.name, model.GetType(), e, e.StackTrace));
                }
            }

            if (m_UIInfos != null)
            {
                try
                {
                    m_UIInfos.Sanitize(this);
                }
                catch (Exception e)
                {
                    Debug.LogError(string.Format("Exception while sanitizing VFXUI: : {0} {1}", e, e.StackTrace));
                }
            }

            systemNames.Sync(this);


            int resourceCurrentVersion = 0;
            // Stop using reflection after 2020.2;
            FieldInfo info = typeof(VisualEffectResource).GetField("CurrentVersion", BindingFlags.Static | System.Reflection.BindingFlags.Public);

            if (info != null)
            {
                resourceCurrentVersion = (int)info.GetValue(null);
            }

            if (m_ResourceVersion < resourceCurrentVersion) // Graph not up to date
            {
                if (m_ResourceVersion < 1)                  // Version before gradient interpreted as linear
                {
                    foreach (var model in objs.OfType <VFXSlotGradient>())
                    {
                        Gradient           value = (Gradient)model.value;
                        GradientColorKey[] keys  = value.colorKeys;

                        for (int i = 0; i < keys.Length; ++i)
                        {
                            var colorKey = keys[i];
                            colorKey.color = colorKey.color.linear;
                            keys[i]        = colorKey;
                        }
                        value.colorKeys = keys;
                        model.value     = new Gradient();
                        model.value     = value;
                    }
                }
            }
            m_ResourceVersion = resourceCurrentVersion;
            m_GraphSanitized  = true;
            m_GraphVersion    = CurrentVersion;

#if !CASE_1289829_HAS_BEEN_FIXED
            if (visualEffectResource != null && (visualEffectResource.updateMode & VFXUpdateMode.ExactFixedTimeStep) == VFXUpdateMode.ExactFixedTimeStep)
            {
                visualEffectResource.updateMode = visualEffectResource.updateMode & ~VFXUpdateMode.ExactFixedTimeStep;
                Debug.Log("Sanitize : Exact Fixed Time has been automatically reset to false to avoid an unexpected behavior.");
            }
#endif

            UpdateSubAssets(); //Should not be necessary : force remove no more referenced object from asset
        }
Ejemplo n.º 21
0
 public List <Entity> TestSet()
 {
     return(set.OfType <Entity>().ToList());
 }
Ejemplo n.º 22
0
 public T[] GetChildrenOfClass <T>() where T : Instance
 {
     T[] result = children.OfType <T>().ToArray();
     return(result);
 }
        public async Task<Graph.Group> CreateUnifiedGroupForPropertyAsync(GraphServiceClient graphService, string graphAccessToken, ListItem propertyItem, IEnumerable<Graph.User> members)
        {
            var propertyTitle = propertyItem["Title"] as string;
            var propertyOwnerName = propertyItem["sl_owner"] as string;
            var querypropertyOwners = (await graphService.Users.Request().Filter(string.Format("displayName eq '{0}'", propertyOwnerName)).GetAsync()).CurrentPage;
            var propertyOwner = querypropertyOwners.Count > 0 ? querypropertyOwners[0] : null;
            if (propertyOwner == null) return null;
            // Create Office 365 Group
            string groupId = string.Empty;
            dynamic groupJSON = new JObject();
            groupJSON.displayName = propertyTitle;
            groupJSON.mailNickname = propertyTitle.Replace(" ", "");
            groupJSON.securityEnabled = false;
            groupJSON.mailEnabled = true;
            groupJSON.description = "Property Group";
            groupJSON.groupTypes = new JArray("Unified");
            HttpRequestMessage message = new HttpRequestMessage(HttpMethod.Post, string.Format("{0}groups", AADAppSettings.GraphResourceUrl));
            message.Content = new StringContent(groupJSON.ToString(), System.Text.Encoding.UTF8, "application/json");
            message.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            message.Headers.Authorization = new AuthenticationHeaderValue("Bearer", graphAccessToken);
            using (HttpClient client = new HttpClient())
            {
                var responseMessage = await client.SendAsync(message);

                if (responseMessage.StatusCode != System.Net.HttpStatusCode.Created)
                    throw new System.Web.Http.HttpResponseException(responseMessage.StatusCode);

                var payload = await responseMessage.Content.ReadAsStringAsync();

                groupId = JObject.Parse(payload)["id"].ToString();
            }
            var group = await graphService.Groups[groupId].Request().GetAsync() as Graph.Group;

            // Add users to Office 365 Group
            var groupMembers = new HashSet<Graph.User>(members);
            var groupOwners = new HashSet<Graph.User>();
            var adminUserName = _currentUserName;
            var queryAdmins = (await graphService.Users.Request().Filter(string.Format("mail eq '{0}'", adminUserName)).GetAsync()).CurrentPage;
            var admin = queryAdmins.Count > 0 ? queryAdmins[0] : null;
            if (admin != null)
            {
                groupMembers.Add(admin);
                groupOwners.Add(admin);
            }
            if (propertyOwner != null)
            {
                groupMembers.Add(propertyOwner);
                groupOwners.Add(propertyOwner);
            }

            foreach (var user in groupMembers.OfType<Graph.User>())
            {
                try
                {
                    await GraphServiceExtension.AddUserToGroupMembersAsync(graphService, group, user, graphAccessToken);
                }
                catch{ }
            }

            foreach (var user in groupOwners.OfType<Graph.User>())
            {
                try
                {
                    await GraphServiceExtension.AddUserToGroupOwnersAsync(graphService, group, user, graphAccessToken);
                }
                catch{ }
            }

            return group;
        }
Ejemplo n.º 24
0
 // todo does this actually give a performance benefit?
 /// <summary>
 ///     Gets all GameObjects of type <typeparamref name="T" />
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <returns>IEnumerable{T}</returns>
 public static IEnumerable <T> Get <T>() where T : GameObject
 {
     return(allGameObjects.OfType <T>());
 }
        private static void CollectUsedSymbols(RemovableDeclarationCollector declarationCollector,
            HashSet<ISymbol> usedSymbols, HashSet<ISymbol> declaredPrivateSymbols)
        {
            var symbolNames = declaredPrivateSymbols.Select(s => s.Name).ToImmutableHashSet();
            var anyRemovableIndexers = declaredPrivateSymbols
                .OfType<IPropertySymbol>()
                .Any(p => p.IsIndexer);
            var anyRemovableCtors = declaredPrivateSymbols
                .OfType<IMethodSymbol>()
                .Any(m => m.MethodKind == MethodKind.Constructor);

            var identifiers = declarationCollector.ClassDeclarations
                .SelectMany(container => container.SyntaxNode.DescendantNodes()
                    .Where(node =>
                        node.IsKind(SyntaxKind.IdentifierName))
                    .Cast<IdentifierNameSyntax>()
                    .Where(node => symbolNames.Contains(node.Identifier.ValueText))
                    .Select(node =>
                        new SyntaxNodeSemanticModelTuple<SyntaxNode>
                        {
                            SyntaxNode = node,
                            SemanticModel = container.SemanticModel
                        }));

            var generic = declarationCollector.ClassDeclarations
                .SelectMany(container => container.SyntaxNode.DescendantNodes()
                    .Where(node =>
                        node.IsKind(SyntaxKind.GenericName))
                    .Cast<GenericNameSyntax>()
                    .Where(node => symbolNames.Contains(node.Identifier.ValueText))
                    .Select(node =>
                        new SyntaxNodeSemanticModelTuple<SyntaxNode>
                        {
                            SyntaxNode = node,
                            SemanticModel = container.SemanticModel
                        }));

            var allNodes = identifiers.Concat(generic);

            if (anyRemovableIndexers)
            {
                var nodes = declarationCollector.ClassDeclarations
                    .SelectMany(container => container.SyntaxNode.DescendantNodes()
                        .Where(node => node.IsKind(SyntaxKind.ElementAccessExpression))
                        .Select(node =>
                            new SyntaxNodeSemanticModelTuple<SyntaxNode>
                            {
                                SyntaxNode = node,
                                SemanticModel = container.SemanticModel
                            }));

                allNodes = allNodes.Concat(nodes);
            }

            if (anyRemovableCtors)
            {
                var nodes = declarationCollector.ClassDeclarations
                    .SelectMany(container => container.SyntaxNode.DescendantNodes()
                        .Where(node => node.IsKind(SyntaxKind.ObjectCreationExpression))
                        .Select(node =>
                            new SyntaxNodeSemanticModelTuple<SyntaxNode>
                            {
                                SyntaxNode = node,
                                SemanticModel = container.SemanticModel
                            }));

                allNodes = allNodes.Concat(nodes);
            }

            foreach (var node in allNodes)
            {
                var symbol = node.SemanticModel.GetSymbolInfo(node.SyntaxNode).Symbol;
                var methodSymbol = symbol as IMethodSymbol;

                if (methodSymbol != null &&
                    methodSymbol.MethodKind == MethodKind.ReducedExtension)
                {
                    symbol = methodSymbol.ReducedFrom;
                }

                if (symbol != null)
                {
                    usedSymbols.Add(symbol.OriginalDefinition);
                }
            }
        }
 private static Title GetTitle(int variable, HashSet <Claim> claims)
 {
     return(claims.OfType <Title>().Single(t => t.Variable == variable));
 }
Ejemplo n.º 27
0
        internal INamespaceSet GetReturnValue(int unionStrength = 0)
        {
            var result = (unionStrength >= 0 && unionStrength <= UnionComparer.MAX_STRENGTH)
                ? NamespaceSet.CreateUnion(UnionComparer.Instances[unionStrength])
                : NamespaceSet.Empty;

            var units = new HashSet<AnalysisUnit>();
            units.Add(AnalysisUnit);
            if (_allCalls != null) {
                units.UnionWith(_allCalls.Values);
            }

            result = result.UnionAll(units.OfType<FunctionAnalysisUnit>().Select(unit => unit.ReturnValue.TypesNoCopy));

            return result;
        }
Ejemplo n.º 28
0
 public static T GetTool <T>() where T : ToolBase => register_tools.OfType <T>().FirstOrDefault();
        public async Task<IGroup> CreateUnifiedGroupForPropertyAsync(GraphService graphService, ListItem propertyItem, IEnumerable<Graph.IUser> members)
        {
            var propertyTitle = propertyItem["Title"] as string;
            var propertyOwnerName = propertyItem["sl_owner"] as string;
            var propertyOwner = await graphService.GetFirstUserAsync(i => i.displayName == propertyOwnerName);

            // Create group
            var group = new Graph.Group
            {
                displayName = propertyTitle,
                mailNickname = propertyTitle.Replace(" ", ""),
                securityEnabled = false,
                mailEnabled = true,
                groupType = "Unified",
                description = "Property Group",
            };
            try
            {
                await graphService.groups.AddGroupAsync(group);
            }
            catch { }

            // Add users to group
            var groupMembers = new HashSet<Graph.IUser>(members);
            var groupOwners = new HashSet<Graph.IUser>();
            var adminUserName = HttpContext.Current.User.Identity.Name;
            var admin = await graphService.GetFirstUserAsync(i => i.mail == adminUserName);
            if (admin != null)
            {
                groupMembers.Add(admin);
                groupOwners.Add(admin);
            }
            if (propertyOwner != null)
            {
                groupMembers.Add(propertyOwner);
                groupOwners.Add(propertyOwner);
            }
            
            foreach (var user in groupMembers.OfType<Graph.User>())
            {
                group.members.Add(user);
                try
                {
                    await group.SaveChangesAsync();
                }
                catch { }
            }

            foreach (var user in groupOwners.OfType<Graph.User>())
            {
                group.owners.Add(user);
                try
                {
                    await group.SaveChangesAsync();
                }
                catch { }
            }

            return group;
        }
Ejemplo n.º 30
0
 /// <summary>
 /// Возвращает все кодеки указанного типа.
 /// </summary>
 /// <typeparam name="T">Тип кодека.</typeparam>
 /// <returns>Кодеки заданного типа присутствующие в стеке.</returns>
 public IEnumerable <T> GetCodecs <T>()
 {
     return(_codecs.OfType <T>());
 }