Пример #1
0
    public void OnClickLeft(int idx)
    {
        int        nextUIOrder = curUIOrder - 1;
        GameObject prefab      = prefabMap.Get(nextUIOrder, idx);

        if (prefab == null)
        {
            return;
        }

        GameObject          nextUIInst = Instantiate(prefab);
        SlideInOutComponent curUIInstSlideComponent      = curUIInst.GetComponent <SlideInOutComponent>();
        SlideInOutComponent nextUIInstSlideComponent     = nextUIInst.GetComponent <SlideInOutComponent>();
        SlideInOutComponent backgroundInstSlideComponent = backgroundInst.GetComponent <SlideInOutComponent>();

        if (curUIInstSlideComponent == null || nextUIInstSlideComponent == null)
        {
            return;
        }

        nextUIInst.transform.SetParent(gameObject.transform);
        nextUIInst.GetComponent <LobbyUIBase>().SetLobbyInst(this);

        curUIInstSlideComponent.SlideOutLeft(slideSpeed, true);
        backgroundInstSlideComponent.SlideOutLeft(slideSpeed, false);
        nextUIInstSlideComponent.SlideInLeft(slideSpeed);

        curUIOrder = nextUIOrder;
        curUIIdx   = idx;
        curUIInst  = nextUIInst;
    }
Пример #2
0
 public static void RegistEvent(EVENTTYPE eventType, EVENTID eventID, UnityAction action)
 {
     if (dic.Get(eventType, eventID) == default(UnityEvent))
     {
         dic.Set(eventType, eventID, new UnityEvent());
     }
     dic.Get(eventType, eventID).AddListener(action);
 }
Пример #3
0
        internal CallActivation CreateCallActivation()
        {
            var overload   = resolveGenericBinding(_overload);
            var activation = new CallActivation(overload);

            foreach (var param in overload.Parameters)
            {
                RValueProvider arg;

                if (isUnresolved(param))
                {
                    if (param.HasDefaultValue)
                    {
                        //there is default value for the argument
                        arg = new DefaultArgValue(param.DefaultValue, param.Type, _context);
                    }
                    else if (param.HasParam)
                    {
                        arg = new ParamArgValue(param.Type, new RValueProvider[0], _context);
                    }
                    else
                    {
                        //parameter doesnt match
                        return(null);
                    }
                }
                else
                {
                    var args = _argBindings.Get(param).ToArray();

                    if (param.HasParam)
                    {
                        arg = new ParamArgValue(param.Type, args, _context);
                    }
                    else if (args.Length != 1)
                    {
                        throw new NotSupportedException("Wrong argument count for parameter: " + param.Name);
                    }
                    else
                    {
                        //TODO type conversions
                        arg = args[0];
                    }
                }

                activation.AddArgument(arg);
            }


            return(activation);
        }
Пример #4
0
        /// <summary>
        /// Fires the events registered for given watcher.
        /// </summary>
        /// <param name="watcher">The watcher.</param>
        /// <param name="path">The path.</param>
        private static void fireEvents(FileSystemWatcher watcher, string path)
        {
            _watchers.Remove(path);
            watcher.Dispose();

            var eventsCopy = _registeredActions.Get(path).ToArray();

            foreach (var evt in eventsCopy)
            {
                _registeredActions.Remove(path, evt);

                evt();
            }
        }
Пример #5
0
        /// <summary>
        /// enqueue setter call which satisfy import from exports
        /// </summary>
        /// <param name="import"></param>
        private void setImport(JoinPoint import)
        {
            var exps = _storage.Get(import);

            if (exps == null)
            {
                return;               //allow default doesnt require setter
            }
            foreach (var exp in exps)
            {
                _joins.Add(new Join(import, exp));
            }

            callSetter(import);
        }
Пример #6
0
        /// <summary>
        /// Get available remove providers for given instance.
        /// </summary>
        /// <param name="instance">The instance which remove providers are requested.</param>
        /// <returns>IEnumerable&lt;RemoveTransformProvider&gt;.</returns>
        public IEnumerable <RemoveTransformProvider> RemoveProviders(Instance instance)
        {
            //remove from assigns
            var assignRemoveProviders = _assignRemoveProviders.Get(instance);

            foreach (var provider in assignRemoveProviders)
            {
                yield return(provider);
            }

            //remove from calls
            foreach (var call in Calls)
            {
                for (int i = 0; i < call.ArgumentValues.Length; ++i)
                {
                    var arg = call.ArgumentValues[i];
                    if (arg == instance)
                    {
                        if (call.TransformProvider.IsOptionalArgument(i))
                        {
                            //we can remove single argument
                            yield return(call.TransformProvider.RemoveArgument(i, false));
                        }
                        else
                        {
                            //remove whole call
                            yield return(call.TransformProvider.Remove());
                        }
                    }
                }
            }
        }
Пример #7
0
 /// <summary>
 /// Returns plugins that are registered for the given interface, sorted by dependencies (MefPovider.DependsOn).
 /// </summary>
 internal static IEnumerable <PluginInfo> FindPlugins(ContainerBuilder builder, Type pluginInterface)
 {
     lock (_pluginsLock)
     {
         if (_pluginsByExport == null)
         {
             var assemblies = ListAssemblies();
             try
             {
                 _pluginsByExport = LoadPlugins(assemblies);
             }
             catch (Exception ex)
             {
                 string typeLoadReport = CsUtility.ReportTypeLoadException(ex, "Cannot load plugins.", assemblies);
                 if (typeLoadReport != null)
                 {
                     throw new FrameworkException(typeLoadReport, ex);
                 }
                 else
                 {
                     ExceptionsUtility.Rethrow(ex);
                 }
             }
         }
         return(_pluginsByExport.Get(pluginInterface.FullName));
     }
 }
Пример #8
0
        /// <summary>
        /// Method that is used for searching method info of given type path - method info is NOT instantiated
        /// according to generic.
        /// </summary>
        /// <param name="typePath">Path of type which methods are searched.</param>
        /// <returns>Found methods.</returns>
        internal IEnumerable <TypeMethodInfo> AccordingType(PathInfo typePath)
        {
            var signature = typePath.ShortSignature;

            foreach (var key in _methodPaths.Keys)
            {
                if (key.Length <= signature.Length)
                {
                    continue;
                }

                var isSearchedType = key.StartsWith(signature) && !key.Substring(signature.Length + 1).Contains('.');
                if (isSearchedType)
                {
                    foreach (var method in _methodPaths.Get(key))
                    {
                        yield return(method.Info);
                    }
                }
            }
        }
Пример #9
0
 public IEnumerable <string> GetIdentityMembership(string username)
 {
     if (_membership == null)
     {
         _membership = new MultiDictionary <string, string>();
         foreach (var pair in _userGroupMembership.Split(' '))
         {
             _membership.Add(System.Environment.UserDomainName + @"\" + pair.Split('-')[0], pair.Split('-')[1]);
         }
     }
     return(_membership.Get(username).ToList());
 }
Пример #10
0
    // Start is called before the first frame update
    void Start()
    {
        prefabMap = new MultiDictionary <int, int, GameObject>();
        foreach (UIConfig cfg in uiConfig)
        {
            prefabMap.Set(cfg.order, cfg.idx, cfg.prefab);
        }
        curUIOrder = 0;
        curUIIdx   = 0;
        GameObject prefab = prefabMap.Get(curUIOrder, curUIIdx);

        curUIInst = Instantiate(prefab);
        curUIInst.transform.SetParent(gameObject.transform);
        curUIInst.GetComponent <LobbyUIBase>().SetLobbyInst(this);
    }
Пример #11
0
        /// <summary>
        /// Run exploration of path between given connectors
        /// <remarks>Exploration should be runned before path finding</remarks>.
        /// </summary>
        /// <param name="from">Connector from which path is explored.</param>
        /// <param name="to">Connector to which path is explored.</param>
        public void Explore(ConnectorDrawing from, ConnectorDrawing to)
        {
            //initialize global buffers
            _processed.Clear();
            _fromCandidates.Clear();

            //get point representation of source connector
            var fromPoint = getPoint(from);

            if (fromPoint == null)
            {
                return;
            }

            //all points on desired component are possible targets (they all are connected with self)
            var toItem       = to.OwningItem;
            var toCandidates = _itemPoints.Get(toItem);

            //run exploration
            tryEnqueue(fromPoint);
            while (_fromCandidates.Count > 0)
            {
                var fromCandidate = _fromCandidates.Dequeue();
                foreach (var toCandidate in toCandidates)
                {
                    DiagramItem obstacle;
                    tryAddEdge(fromCandidate, toCandidate, toItem, out obstacle);
                    enqueueWithObstacleEdges(fromCandidate, obstacle);
                }

                foreach (var neighbour in fromCandidate.ExploredNeighbours)
                {
                    tryEnqueue(neighbour);
                }
            }
        }
Пример #12
0
        private IEnumerable <IEnumerator <InstanceScope> > initializeFrom(MultiDictionary <Instance, InstanceScope> scopes)
        {
            var scopeEnumerators = new List <IEnumerator <InstanceScope> >();

            foreach (var instance in scopes.Keys)
            {
                var enumerator = scopes.Get(instance).GetEnumerator();
                if (!enumerator.MoveNext())
                {
                    //there is no scope for instance
                    return(null);
                }

                scopeEnumerators.Add(enumerator);
            }

            return(scopeEnumerators);
        }
        private string ReportPermissions(IUserInfo userInfo, IList <IPermissionBrowse> userPermissions, IList <Claim> requiredClaims)
        {
            // Reporting is done in a function that returns string, to avoid any performance impact when the trace log is not enabled.

            var report = new List <string>();

            var permissionsByClaim = new MultiDictionary <string, IPermissionBrowse>();

            foreach (var permission in userPermissions)
            {
                permissionsByClaim.Add(permission.ClaimResource + "." + permission.ClaimRight, permission);
            }

            foreach (var claim in requiredClaims)
            {
                string claimName        = claim.FullName;
                var    claimPermissions = permissionsByClaim.Get(claimName);
                var    allowedForRoles  = claimPermissions.Where(p => p.IsAuthorized.Value).Select(p => p.Principal).ToList();
                var    deniedForRoles   = claimPermissions.Where(p => !p.IsAuthorized.Value).Select(p => p.Principal).ToList();

                if (deniedForRoles.Count != 0)
                {
                    if (allowedForRoles.Count != 0)
                    {
                        report.Add("User " + userInfo.UserName + " claim '" + claimName + "' is denied for role " + string.Join(", ", deniedForRoles) + " and allowed for role " + string.Join(", ", allowedForRoles) + " (deny overrides allow).");
                    }
                    else
                    {
                        report.Add("User " + userInfo.UserName + " claim '" + claimName + "' is denied for role " + string.Join(", ", deniedForRoles) + ".");
                    }
                }
                else
                if (allowedForRoles.Count != 0)
                {
                    report.Add("User " + userInfo.UserName + " claim '" + claimName + "' is allowed for role " + string.Join(", ", allowedForRoles) + ".");
                }
                else
                {
                    report.Add("User " + userInfo.UserName + " claim '" + claimName + "' is denied by default (no permissions defined).");
                }
            }

            return(string.Join("\r\n", report));
        }
Пример #14
0
        private TypeMethodInfo resolveGenericBinding(TypeMethodInfo methodDefinition)
        {
            if (!_genericBindings.Keys.Any())
            {
                //there are no bindings available
                return(methodDefinition);
            }

            var translations = new Dictionary <string, string>();

            foreach (var param in _genericBindings.Keys)
            {
                var translatedName = param.Type.TypeName;
                if (translations.ContainsKey(translatedName))
                {
                    //we already have translation
                    continue;
                }

                var bindings = _genericBindings.Get(param).ToArray();
                if (bindings.Length > 1)
                {
                    throw new NotImplementedException("Determine binding for parametric parameters");
                }

                translations.Add(translatedName, bindings[0].TypeName);
            }

            //remap argument bindings from definitions parameters to current method parameters
            var genericMethod = methodDefinition.MakeGenericMethod(translations);

            for (var i = 0; i < genericMethod.Parameters.Length; ++i)
            {
                var currentParameter = genericMethod.Parameters[i];
                var oldParameter     = methodDefinition.Parameters[i];

                var args = _argBindings.Get(oldParameter);
                _argBindings.Set(currentParameter, args);
            }

            return(genericMethod);
        }
Пример #15
0
        /// <summary>
        /// Builds the meta.
        /// </summary>
        /// <returns>MetaExport.</returns>
        private MetaExport buildMeta()
        {
            var items = new List <MetaItem>();

            foreach (var key in _metaData.Keys)
            {
                var values     = _metaData.Get(key);
                var isMultiple = _metaMultiplicity[key];
                var item       = new MetaItem(key, isMultiple, values);

                items.Add(item);
            }

            _metaData.Clear();
            _metaMultiplicity.Clear();

            var meta = new MetaExport(items);

            return(meta);
        }
Пример #16
0
        /// <summary>
        /// Returns plugins that are registered for the given interface, sorted by dependencies (MefPovider.DependsOn).
        /// </summary>
        internal static IEnumerable <PluginInfo> FindPlugins(ContainerBuilder builder, Type pluginInterface)
        {
            try
            {
                lock (_pluginsLock)
                {
                    if (_pluginsByExport == null)
                    {
                        var assemblies = ListAssemblies();
                        _pluginsByExport = LoadPlugins(assemblies);
                    }

                    return(_pluginsByExport.Get(pluginInterface.FullName));
                }
            }
            catch (ReflectionTypeLoadException ex)
            {
                throw new FrameworkException(CsUtility.ReportTypeLoadException(ex, "Cannot load plugins."), ex);
            }
        }
Пример #17
0
        private void BuildProjectForTargets(BuildInformation buildInfo, ChangeObservable observable, IEnumerable <Target> targets)
        {
            targets = targets.ToArray();
            MultiDictionary <SdkInformation, Target> sdks = new MultiDictionary <SdkInformation, Target>();
            List <FormattableException> exceptions        = new List <FormattableException>();

            foreach (Target target in targets)
            {
                try
                {
                    sdks.Add(sdkRepository.GetSdk(target), target);
                }
                catch (FormattableException ex)
                {
                    exceptions.Add(ex);
                }
            }
            if (exceptions.Any())
            {
                throw new AggregateException(exceptions);
            }

            userInterface.WriteInformation($"Requested build for targets {String.Join(", ", targets.Select(x => x.GetFullName()).ToArray())}");
            foreach (SdkInformation sdk in sdks.Keys)
            {
                foreach (Target target in sdks.Get(sdk))
                {
                    userInterface.WriteInformation($"Starting build for target {target.GetFullName()}");
                    buildInfo.SdkInformation = sdk;
                    buildInfo.Target         = target;
                    buildExecuter.ExecuteBuild(buildInfo, observable);
                    userInterface.WriteInformation($"Successfully built the project {buildInfo.RootEntity.Name} for target {target.GetFullName()}.");
                }
            }
            userInterface.WriteInformation($"Finished build for all targets");
        }
        /// <summary>
        /// Reporting is done in a function that returns a string, to avoid any performance impact when the trace log is not enabled.
        /// </summary>
        private string ReportPermissions(IUserInfo userInfo, PrincipalInfo principal, Lazy<IDictionary<Guid, string>> roleNamesIndex,
            IEnumerable<Permission> userPermissions, IEnumerable<ClaimInfo> claims, IEnumerable<bool> userHasClaims)
        {
            var report = new List<string>();

            // Create an index of permissions:

            var permissionsByClaim = new MultiDictionary<Guid, Permission>();
            foreach (var permission in userPermissions)
                permissionsByClaim.Add(permission.ClaimID, permission);

            // Analyze permissions for required claims:

            foreach (var claimResult in claims.Zip(userHasClaims, (Claim, UserHasIt) => new { Claim, UserHasIt }))
            {
                var claimPermissions = claimResult.Claim.ID != null
                    ? permissionsByClaim.Get(claimResult.Claim.ID.Value)
                    : new Permission[] { };

                var permissionsDescription = claimPermissions
                    .Select(permission => new
                        {
                            permission.IsAuthorized,
                            PrincipalOrRoleName = permission.PrincipalID != null
                                ? ("principal " + (permission.PrincipalID.Value == principal.ID ? principal.Name : permission.PrincipalID.Value.ToString()))
                                : ("role " + GetRoleNameSafe(permission.RoleID.Value, roleNamesIndex))
                        })
                    .ToList();

                var allowedFor = permissionsDescription.Where(p => p.IsAuthorized).Select(p => p.PrincipalOrRoleName).ToList();
                var deniedFor = permissionsDescription.Where(p => !p.IsAuthorized).Select(p => p.PrincipalOrRoleName).ToList();

                string explanation = "User " + userInfo.UserName + " " + (claimResult.UserHasIt ? "has" : "doesn't have")
                    + " claim '" + claimResult.Claim.Resource + " " + claimResult.Claim.Right + "'. It is ";

                if (deniedFor.Count != 0)
                    if (allowedFor.Count != 0)
                        explanation += "denied for " + string.Join(", ", deniedFor) + " and allowed for " + string.Join(", ", allowedFor) + " (deny overrides allow).";
                    else
                        explanation += "denied for " + string.Join(", ", deniedFor) + ".";
                else
                    if (allowedFor.Count != 0)
                        explanation += "allowed for " + string.Join(", ", allowedFor) + ".";
                    else
                        if (claimResult.Claim.ID == null)
                            explanation += "denied by default (the claim does not exist or is no longer active).";
                        else
                            explanation += "denied by default (no permissions defined).";

                report.Add(explanation);
            }

            return string.Join("\r\n", report);
        }
Пример #19
0
 /// <summary>
 /// Get <see cref="DiagramItem"/> that are referenced by given <see cref="ConnectorDefinition"/>
 /// </summary>
 /// <param name="connectorDefinition">Definition of connector</param>
 /// <returns>Referenced <see cref="DiagramItem"/> objects</returns>
 internal IEnumerable <DiagramItem> DefiningItems(ConnectorDefinition connectorDefinition)
 {
     return(_items.Get(connectorDefinition.Reference.DefinitionID));
 }
Пример #20
0
        /// <summary>
        /// Reporting is done in a function that returns a string, to avoid any performance impact when the trace log is not enabled.
        /// </summary>
        private string ReportPermissions(IUserInfo userInfo, PrincipalInfo principal, Lazy <IDictionary <Guid, string> > roleNamesIndex,
                                         IEnumerable <Permission> userPermissions, IEnumerable <ClaimInfo> claims, IEnumerable <bool> userHasClaims)
        {
            var report = new List <string>();

            // Create an index of permissions:

            var permissionsByClaim = new MultiDictionary <Guid, Permission>();

            foreach (var permission in userPermissions)
            {
                permissionsByClaim.Add(permission.ClaimID, permission);
            }

            // Analyze permissions for required claims:

            foreach (var claimResult in claims.Zip(userHasClaims, (Claim, UserHasIt) => new { Claim, UserHasIt }))
            {
                var claimPermissions = claimResult.Claim.ID != null
                    ? permissionsByClaim.Get(claimResult.Claim.ID.Value)
                    : Array.Empty <Permission>();

                var permissionsDescription = claimPermissions
                                             .Select(permission => new
                {
                    permission.IsAuthorized,
                    PrincipalOrRoleName = permission.PrincipalID != null
                                ? ("principal " + GetPermissionsPrincipalNameSafe(permission, principal))
                                : ("role " + GetRoleNameSafe(permission.RoleID.Value, roleNamesIndex))
                })
                                             .ToList();

                var allowedFor = permissionsDescription.Where(p => p.IsAuthorized).Select(p => p.PrincipalOrRoleName).ToList();
                var deniedFor  = permissionsDescription.Where(p => !p.IsAuthorized).Select(p => p.PrincipalOrRoleName).ToList();

                string explanation;
                if (deniedFor.Count != 0)
                {
                    if (allowedFor.Count != 0)
                    {
                        explanation = $"It is denied for {string.Join(", ", deniedFor)} and allowed for {string.Join(", ", allowedFor)} (deny overrides allow).";
                    }
                    else
                    {
                        explanation = $"It is denied for {string.Join(", ", deniedFor)}.";
                    }
                }
                else if (allowedFor.Count != 0)
                {
                    explanation = $"It is allowed for {string.Join(", ", allowedFor)}.";
                }
                else if (claimResult.Claim.ID == null)
                {
                    explanation = "It is denied by default (the claim does not exist or is no longer active).";
                }
                else
                {
                    explanation = "It is denied by default (no permissions defined).";
                }

                report.Add($"User {ReportUserNameOrAnonymous(userInfo)} {(claimResult.UserHasIt ? "has" : "doesn't have")} claim '{claimResult.Claim.Resource} {claimResult.Claim.Right}'. {explanation}");
            }

            return(string.Join("\r\n", report));
        }
Пример #21
0
        public GameObject GetSpecies(int speciesIndex, bool useExisting)
        {
            Vector3    newPos      = Vector3.zero;
            GameObject newCreature = null;

            SpawnParameters sp = prefabs[speciesIndex].GetComponent <SpawnParameters>();

            if (useExisting && aliveMap.ContainsKey(prefabs[speciesIndex]))
            {
                GameObject creature = aliveMap[prefabs[speciesIndex]];
                if (!creature.GetComponent <SpawnParameters>().isSuspending)
                {
                    return(prefabs[speciesIndex]);
                }
            }
            if (suspended.ContainsKey(prefabs[speciesIndex]))
            {
                newCreature = suspended.Get(prefabs[speciesIndex]);
                if (FindPlace(newCreature, out newPos))
                {
                    suspended.Remove(prefabs[speciesIndex], newCreature);
                    Teleport(newCreature, newPos);
                    newCreature.SetActive(true);
                    if (newCreature.GetComponent <LifeColours>())
                    {
                        newCreature.GetComponent <LifeColours>().FadeIn();
                    }
                    if (newCreature.GetComponentInChildren <CreatureController>())
                    {
                        newCreature.GetComponentInChildren <CreatureController>().Restart();
                    }
                    // Change the school size every time we teleport a school
                    SchoolGenerator sg = newCreature.GetComponentInChildren <SchoolGenerator>();
                    if (sg != null)
                    {
                        sg.transform.position  = newPos;
                        sg.targetCreatureCount = Random.Range(sg.minBoidCount, sg.maxBoidCount);
                    }
                    alive.Add(newCreature);
                    aliveMap[prefabs[speciesIndex]] = newCreature;

                    /*GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
                     * cube.transform.position = newPos;
                     * cube.transform.localScale = Vector3.one * 5;
                     */
                }
            }
            else
            {
                //Debug.Log("Instiantiating a new: " + prefabs[nextCreature]);
                if (FindPlace(prefabs[speciesIndex], out newPos))
                {
                    newCreature = GameObject.Instantiate <GameObject>(prefabs[speciesIndex], newPos
                                                                      , prefabs[speciesIndex].transform.rotation * Quaternion.AngleAxis(Random.Range(0, 360), Vector3.up)
                                                                      );

                    newCreature.GetComponent <SpawnParameters>().Species = prefabs[speciesIndex];
                    if (school != null)
                    {
                        Boid b = newCreature.GetComponent <Boid>();
                        b.school = school;
                        school.boids.Add(b);
                    }

                    if (newCreature.GetComponentInChildren <CreatureController>())
                    {
                        newCreature.GetComponentInChildren <CreatureController>().mother = this;
                    }

                    newCreature.transform.parent   = this.transform;
                    newCreature.transform.position = newPos;
                    newCreature.SetActive(true);
                    alive.Add(newCreature);
                    aliveMap[prefabs[speciesIndex]] = newCreature;
                }
                else
                {
                    Debug.Log("Couldnt find a place for the new creature");
                }
            }
            return(prefabs[speciesIndex]);
        }
Пример #22
0
 public IList <Actor> GetActorsByInfo(UnitInfo info)
 {
     return(_infoToActorMapping.Get(info));
 }
Пример #23
0
 public IEnumerable <TEntity> GetEntitiesByType <TEntity>() where TEntity : Entity
 {
     return(_typeToEntityMapping.Get(typeof(TEntity)).OfType <TEntity>());
 }
Пример #24
0
 /// <summary>
 /// Gets the edits attached by given instance.
 /// </summary>
 /// <param name="attachingInstance">The attaching instance.</param>
 /// <returns>IEnumerable&lt;Edit&gt;.</returns>
 public IEnumerable <Edit> GetAttachedEdits(Instance attachingInstance)
 {
     return(_attachedEdits.Get(attachingInstance));
 }
Пример #25
0
        private (IConceptInfo ConceptInfo, List <string> Warnings) ParseNextConcept(TokenReader tokenReader, Stack <IConceptInfo> context, MultiDictionary <string, IConceptParser> conceptParsers)
        {
            var errorReports = new List <Func <(string formattedError, string simpleError)> >();
            List <Interpretation> possibleInterpretations = new List <Interpretation>();

            var keywordReader = new TokenReader(tokenReader).ReadText(); // Peek, without changing the original tokenReader's position.
            var keyword       = keywordReader.IsError ? null : keywordReader.Value;

            _onKeyword?.Invoke(tokenReader, keyword);
            if (keyword != null)
            {
                foreach (var conceptParser in conceptParsers.Get(keyword))
                {
                    TokenReader nextPosition       = new TokenReader(tokenReader);
                    var         conceptInfoOrError = conceptParser.Parse(nextPosition, context, out var warnings);

                    if (!conceptInfoOrError.IsError)
                    {
                        possibleInterpretations.Add(new Interpretation
                        {
                            ConceptInfo  = conceptInfoOrError.Value,
                            NextPosition = nextPosition,
                            Warnings     = warnings
                        });
                    }
                    else if (!string.IsNullOrEmpty(conceptInfoOrError.Error)) // Empty error means that this parser is not for this keyword.
                    {
                        errorReports.Add(() =>
                                         (string.Format("{0}: {1}\r\n{2}", conceptParser.GetType().Name, conceptInfoOrError.Error, tokenReader.ReportPosition()), conceptInfoOrError.Error));
                    }
                }
            }

            if (possibleInterpretations.Count == 0)
            {
                var(dslScript, position) = tokenReader.GetPositionInScript();
                if (errorReports.Count > 0)
                {
                    var errorReportValues  = errorReports.Select(x => x.Invoke()).ToList();
                    var errorsReport       = string.Join("\r\n", errorReportValues.Select(x => x.formattedError)).Limit(500, "...");
                    var simpleErrorsReport = string.Join("\n", errorReportValues.Select(x => x.simpleError));
                    var simpleMessage      = $"Invalid parameters after keyword '{keyword}'. Possible causes: {simpleErrorsReport}";
                    var possibleCauses     = $"Possible causes:\r\n{errorsReport}";
                    throw new DslSyntaxException(simpleMessage, "RH0003", dslScript, position, 0, possibleCauses);
                }
                else if (!string.IsNullOrEmpty(keyword))
                {
                    var simpleMessage = $"Unrecognized concept keyword '{keyword}'.";
                    throw new DslSyntaxException(simpleMessage, "RH0004", dslScript, position, 0, null);
                }
                else
                {
                    var simpleMessage = $"Invalid DSL script syntax.";
                    throw new DslSyntaxException(simpleMessage, "RH0005", dslScript, position, 0, null);
                }
            }

            Disambiguate(possibleInterpretations);
            if (possibleInterpretations.Count > 1)
            {
                var interpretations = new List <string>();
                for (int i = 0; i < possibleInterpretations.Count; i++)
                {
                    interpretations.Add($"{i + 1}. {possibleInterpretations[i].ConceptInfo.GetType().AssemblyQualifiedName}");
                }

                var simpleMessage = $"Ambiguous syntax. There are multiple possible interpretations of keyword '{keyword}': {string.Join(", ", interpretations)}.";
                var(dslScript, position) = tokenReader.GetPositionInScript();

                throw new DslSyntaxException(simpleMessage, "RH0006", dslScript, position, 0, null);
            }

            var parsedStatement = possibleInterpretations.Single();

            tokenReader.CopyFrom(parsedStatement.NextPosition);
            return(parsedStatement.ConceptInfo, parsedStatement.Warnings);
        }
Пример #26
0
        /// <summary>
        /// Reporting is done in a function that returns a string, to avoid any performance impact when the trace log is not enabled.
        /// </summary>
        private string ReportPermissions(IUserInfo userInfo, PrincipalInfo principal, Lazy <IDictionary <Guid, string> > roleNamesIndex,
                                         IEnumerable <Permission> userPermissions, IEnumerable <ClaimInfo> claims, IEnumerable <bool> userHasClaims)
        {
            var report = new List <string>();

            // Create an index of permissions:

            var permissionsByClaim = new MultiDictionary <Guid, Permission>();

            foreach (var permission in userPermissions)
            {
                permissionsByClaim.Add(permission.ClaimID, permission);
            }

            // Analyze permissions for required claims:

            foreach (var claimResult in claims.Zip(userHasClaims, (Claim, UserHasIt) => new { Claim, UserHasIt }))
            {
                var claimPermissions = claimResult.Claim.ID != null
                    ? permissionsByClaim.Get(claimResult.Claim.ID.Value)
                    : new Permission[]
                {
                };

                var permissionsDescription = claimPermissions
                                             .Select(permission => new
                {
                    permission.IsAuthorized,
                    PrincipalOrRoleName = permission.PrincipalID != null
                                ? ("principal " + (permission.PrincipalID.Value == principal.ID ? principal.Name : permission.PrincipalID.Value.ToString()))
                                : ("role " + GetRoleNameSafe(permission.RoleID.Value, roleNamesIndex))
                })
                                             .ToList();

                var allowedFor = permissionsDescription.Where(p => p.IsAuthorized).Select(p => p.PrincipalOrRoleName).ToList();
                var deniedFor  = permissionsDescription.Where(p => !p.IsAuthorized).Select(p => p.PrincipalOrRoleName).ToList();

                string explanation = "User " + userInfo.UserName + " " + (claimResult.UserHasIt ? "has" : "doesn't have")
                                     + " claim '" + claimResult.Claim.Resource + " " + claimResult.Claim.Right + "'. It is ";

                if (deniedFor.Count != 0)
                {
                    if (allowedFor.Count != 0)
                    {
                        explanation += "denied for " + string.Join(", ", deniedFor) + " and allowed for " + string.Join(", ", allowedFor) + " (deny overrides allow).";
                    }
                    else
                    {
                        explanation += "denied for " + string.Join(", ", deniedFor) + ".";
                    }
                }
                else
                if (allowedFor.Count != 0)
                {
                    explanation += "allowed for " + string.Join(", ", allowedFor) + ".";
                }
                else
                if (claimResult.Claim.ID == null)
                {
                    explanation += "denied by default (the claim does not exist or is no longer active).";
                }
                else
                {
                    explanation += "denied by default (no permissions defined).";
                }

                report.Add(explanation);
            }

            return(string.Join("\r\n", report));
        }
Пример #27
0
 /// <summary>
 /// Get components defined within given assembly.
 /// </summary>
 /// <param name="assembly">Assembly where components are searched.</param>
 /// <returns>Components defined within assembly.</returns>
 internal IEnumerable <ComponentInfo> GetComponents(AssemblyProvider assembly)
 {
     return(_assemblyComponents.Get(assembly));
 }
Пример #28
0
        protected IConceptInfo ParseNextConcept(TokenReader tokenReader, Stack <IConceptInfo> context, MultiDictionary <string, IConceptParser> conceptParsers)
        {
            var errorReports = new List <Func <string> >();
            List <Interpretation> possibleInterpretations = new List <Interpretation>();

            var keywordReader = new TokenReader(tokenReader).ReadText(); // Peek, without changing the original tokenReader's position.
            var keyword       = keywordReader.IsError ? null : keywordReader.Value;

            if (keyword != null)
            {
                foreach (var conceptParser in conceptParsers.Get(keyword))
                {
                    TokenReader nextPosition       = new TokenReader(tokenReader);
                    var         conceptInfoOrError = conceptParser.Parse(nextPosition, context);

                    if (!conceptInfoOrError.IsError)
                    {
                        possibleInterpretations.Add(new Interpretation
                        {
                            ConceptInfo  = conceptInfoOrError.Value,
                            NextPosition = nextPosition
                        });
                    }
                    else if (!string.IsNullOrEmpty(conceptInfoOrError.Error)) // Empty error means that this parser is not for this keyword.
                    {
                        errorReports.Add(() => string.Format("{0}: {1}\r\n{2}", conceptParser.GetType().Name, conceptInfoOrError.Error, tokenReader.ReportPosition()));
                    }
                }
            }

            if (possibleInterpretations.Count == 0)
            {
                if (errorReports.Count > 0)
                {
                    string errorsReport = string.Join("\r\n", errorReports.Select(x => x.Invoke())).Limit(500, "...");
                    throw new DslSyntaxException($"Invalid parameters after keyword '{keyword}'. {tokenReader.ReportPosition()}\r\n\r\nPossible causes:\r\n{errorsReport}");
                }
                else if (!string.IsNullOrEmpty(keyword))
                {
                    throw new DslSyntaxException($"Unrecognized concept keyword '{keyword}'. {tokenReader.ReportPosition()}");
                }
                else
                {
                    throw new DslSyntaxException($"Invalid DSL script syntax. {tokenReader.ReportPosition()}");
                }
            }

            int largest = possibleInterpretations.Max(i => i.NextPosition.PositionInTokenList);

            possibleInterpretations.RemoveAll(i => i.NextPosition.PositionInTokenList < largest);
            if (possibleInterpretations.Count > 1)
            {
                var report = new List <string>();
                report.Add($"Ambiguous syntax. {tokenReader.ReportPosition()}");
                report.Add($"There are multiple possible interpretations of keyword '{keyword}':");
                for (int i = 0; i < possibleInterpretations.Count; i++)
                {
                    report.Add($"{i + 1}. {possibleInterpretations[i].ConceptInfo.GetType().AssemblyQualifiedName}");
                }

                throw new DslSyntaxException(string.Join("\r\n", report));
            }

            tokenReader.CopyFrom(possibleInterpretations.Single().NextPosition);
            return(possibleInterpretations.Single().ConceptInfo);
        }
Пример #29
0
 /// <summary>
 /// Get components, which imports/exports has given contract.
 /// </summary>
 /// <param name="contract">Contract of searched imports/exports</param>
 /// <returns>Components available for contract.</returns>
 internal IEnumerable <ComponentRef> GetComponents(string contract)
 {
     return(_contrToComponents.Get(contract));
 }
Пример #30
0
 public IEnumerable <string> GetIdentityMembership(string username)
 {
     return(_membership.Get(username));
 }
        private string ReportPermissions(IUserInfo userInfo, IList<IPermissionBrowse> userPermissions, IList<Claim> requiredClaims)
        {
            // Reporting is done in a function that returns string, to avoid any performance impact when the trace log is not enabled.

            var report = new List<string>();

            var permissionsByClaim = new MultiDictionary<string, IPermissionBrowse>();
            foreach (var permission in userPermissions)
                permissionsByClaim.Add(permission.ClaimResource + "." + permission.ClaimRight, permission);

            foreach (var claim in requiredClaims)
            {
                string claimName = claim.FullName;
                var claimPermissions = permissionsByClaim.Get(claimName);
                var allowedForRoles = claimPermissions.Where(p => p.IsAuthorized.Value).Select(p => p.Principal).ToList();
                var deniedForRoles = claimPermissions.Where(p => !p.IsAuthorized.Value).Select(p => p.Principal).ToList();

                if (deniedForRoles.Count != 0)
                    if (allowedForRoles.Count != 0)
                        report.Add("User " + userInfo.UserName + " claim '" + claimName + "' is denied for role " + string.Join(", ", deniedForRoles) + " and allowed for role " + string.Join(", ", allowedForRoles) + " (deny overrides allow).");
                    else
                        report.Add("User " + userInfo.UserName + " claim '" + claimName + "' is denied for role " + string.Join(", ", deniedForRoles) + ".");
                else
                    if (allowedForRoles.Count != 0)
                        report.Add("User " + userInfo.UserName + " claim '" + claimName + "' is allowed for role " + string.Join(", ", allowedForRoles) + ".");
                    else
                        report.Add("User " + userInfo.UserName + " claim '" + claimName + "' is denied by default (no permissions defined).");
            }

            return string.Join("\r\n", report);
        }
        /// <summary>
        /// This macro implements InitializationConcept (singleton) instead of AutoInheritRowPermissionsInfo,
        /// in order to allow creating the new concepts in a single iteration.
        /// </summary>
        public IEnumerable <IConceptInfo> CreateNewConcepts(InitializationConcept conceptInfo, IDslModel existingConcepts)
        {
            var autoInheritModules = new HashSet <string>(
                existingConcepts.FindByType <AutoInheritRowPermissionsInfo>().Select(airp => airp.Module.Name));

            var autoInheritExtensionsByBase = new MultiDictionary <string, DataStructureExtendsInfo>();
            var autoInheritExtensions       = existingConcepts.FindByType <DataStructureExtendsInfo>()
                                              .Where(e => autoInheritModules.Contains(e.Extension.Module.Name));

            foreach (var autoInheritExtension in autoInheritExtensions)
            {
                autoInheritExtensionsByBase.Add(autoInheritExtension.Base.GetKey(), autoInheritExtension);
            }

            var autoInheritDetailsByMaster = new MultiDictionary <string, ReferenceDetailInfo>();
            var autoInheritDetails         = existingConcepts.FindByType <ReferenceDetailInfo>()
                                             .Where(d => autoInheritModules.Contains(d.Reference.DataStructure.Module.Name));

            foreach (var autoInheritDetail in autoInheritDetails)
            {
                autoInheritDetailsByMaster.Add(autoInheritDetail.Reference.Referenced.GetKey(), autoInheritDetail);
            }

            var rowPermissionsRead  = existingConcepts.FindByType <RowPermissionsReadInfo>();
            var rowPermissionsWrite = existingConcepts.FindByType <RowPermissionsWriteInfo>();
            var allDataStructuresWithRowPermissions = new HashSet <string>(
                rowPermissionsRead.Select(rp => rp.Source.GetKey())
                .Union(rowPermissionsWrite.Select(rp => rp.Source.GetKey())).ToList());

            var newConcepts = new List <IConceptInfo>();

            var newDataStructuresWithRowPermissions = new List <string>(allDataStructuresWithRowPermissions);

            while (newDataStructuresWithRowPermissions.Count > 0)
            {
                var newInheritences = new List <IConceptInfo>();

                newInheritences.AddRange(newDataStructuresWithRowPermissions
                                         .SelectMany(ds => autoInheritExtensionsByBase.Get(ds))
                                         .SelectMany(extension =>
                {
                    var rpFilters = new RowPermissionsPluginableFiltersInfo {
                        DataStructure = extension.Extension
                    };
                    var rpInherit = new RowPermissionsInheritFromBaseInfo {
                        RowPermissionsFilters = rpFilters
                    };
                    return(new IConceptInfo[] { rpFilters, rpInherit });
                }));

                newInheritences.AddRange(newDataStructuresWithRowPermissions
                                         .SelectMany(ds => autoInheritDetailsByMaster.Get(ds))
                                         .SelectMany(detail =>
                {
                    var rpFilters = new RowPermissionsPluginableFiltersInfo {
                        DataStructure = detail.Reference.DataStructure
                    };
                    var rpInherit = new RowPermissionsInheritFromReferenceInfo {
                        RowPermissionsFilters = rpFilters, ReferenceProperty = detail.Reference
                    };
                    return(new IConceptInfo[] { rpFilters, rpInherit });
                }));

                newConcepts.AddRange(newInheritences);

                newDataStructuresWithRowPermissions = newInheritences.OfType <RowPermissionsPluginableFiltersInfo>()
                                                      .Select(rpFilters => rpFilters.DataStructure.GetKey())
                                                      .Where(dataStructure => !allDataStructuresWithRowPermissions.Contains(dataStructure))
                                                      .ToList();

                foreach (var dataStructure in newDataStructuresWithRowPermissions)
                {
                    allDataStructuresWithRowPermissions.Add(dataStructure);
                }
            }
            ;

            return(newConcepts);
        }