示例#1
0
 public bool Equals(LfgUser other)
 {
     return(other != null &&
            Username.Equals(other.Username) &&
            Discriminator.Equals(other.Discriminator) &&
            DiscordId.Equals(other.DiscordId));
 }
示例#2
0
 public LocationSource(String name, Discriminator discrimintor)
 {
     this.Id        = System.Guid.NewGuid();
     this.Name      = name;
     this.Discri    = discrimintor;
     this.mapMarker = new LocationSourceMapMarker(this);
 }
示例#3
0
        public LocationSource createLocationSource(string name, Discriminator discriminator)
        {
            LocationSource user = new LocationSource(name, discriminator);

            this.LocationSources.Add(user);
            return(user);
        }
        private Link CreateLink()
        {
            var link = new Link
            {
                Rel  = "StudentTransportation",
                Href = $"/sample-student-transportation/studentTransportations/{ResourceId:n}"
            };

            if (string.IsNullOrEmpty(Discriminator))
            {
                return(link);
            }

            string[] linkParts = Discriminator.Split('.');

            if (linkParts.Length < 2)
            {
                return(link);
            }

            var resource = GeneratedArtifactStaticDependencies.ResourceModelProvider.GetResourceModel()
                           .GetResourceByFullName(new FullName(linkParts[0], linkParts[1]));

            // return the default link if the relationship is already correct, and/or if the resource is not found.
            if (resource == null || link.Rel == resource.Name)
            {
                return(link);
            }

            return(new Link
            {
                Rel = resource.Name,
                Href = $"/{resource.SchemaUriSegment()}/{resource.PluralName.ToCamelCase()}/{ResourceId:n}"
            });
        }
        private List <Flowchart> GetFlowcharts()
        {
            string name, path;

            string[]         filePaths  = Directory.GetFiles(@"./Flowcharts");
            List <Flowchart> flowcharts = new List <Flowchart>();

            for (int i = 0; i < filePaths.Length; ++i)
            {
                path = filePaths[i];
                name = Path.GetFileName(path);
                name = name.Replace("_", " ");
                name = name.Replace(".json", "");

                string text;
                var    fileStream = new FileStream(path, FileMode.Open, FileAccess.Read);
                using (var streamReader = new StreamReader(fileStream, Encoding.UTF8))
                {
                    text = streamReader.ReadToEnd();
                }
                var flowchart = JsonConvert.DeserializeObject <Flowchart>(text);
                flowchart.Name = name;
                var d = new Discriminator { /*Priority = Priority.Green*/
                };
                flowcharts.Add(flowchart);
            }
            return(flowcharts);
        }
        /// <summary>
        /// Builds the discriminator and his subMaps
        /// </summary>
        /// <param name="resultMapConfig">The result map config.</param>
        /// <param name="resultClass">The result class.</param>
        /// <param name="dataExchangeFactory">The data exchange factory.</param>
        /// <param name="waitDiscriminatorResolution">The wait discriminator resolution.</param>
        /// <returns></returns>
        private static Discriminator BuildDiscriminator(
            IConfiguration resultMapConfig,
            Type resultClass,
            DataExchangeFactory dataExchangeFactory,
            WaitDiscriminatorResolution waitDiscriminatorResolution)
        {
            Discriminator discriminator = null;
            // Build the Discriminator/Case Property

            ConfigurationCollection discriminatorsConfig = resultMapConfig.Children.Find(ConfigConstants.ELEMENT_DISCRIMINATOR);

            if (discriminatorsConfig.Count > 0)
            {
                //configScope.ErrorContext.MoreInfo = "initialize discriminator";

                // Find the cases
                IList <Case>            cases       = new List <Case>();
                ConfigurationCollection caseConfigs = discriminatorsConfig[0].Children.Find(ConfigConstants.ELEMENT_CASE);
                for (int i = 0; i < caseConfigs.Count; i++)
                {
                    Case caseElement = CaseDeSerializer.Deserialize(caseConfigs[i]);
                    cases.Add(caseElement);
                }

                discriminator = DiscriminatorDeSerializer.Deserialize(
                    discriminatorsConfig[0],
                    resultClass,
                    dataExchangeFactory,
                    cases
                    );
                waitDiscriminatorResolution(discriminator);
            }
            return(discriminator);
        }
 public void ProcessDiscriminator(Discriminator dis)
 {
     if(ProcessOperatorObject != null)
         ProcessDiscriminatorObject(dis);
     foreach(var obj in dis.Children)
         obj.AcceptVisitor(this);
 }
示例#8
0
        /// <summary>
        /// Build a Discriminator object
        /// </summary>
        /// <param name="configuration">The configuration.</param>
        /// <param name="resultClass">The result class.</param>
        /// <param name="dataExchangeFactory">The data exchange factory.</param>
        /// <param name="cases">The case element.</param>
        /// <returns></returns>
        public static Discriminator Deserialize(
            IConfiguration configuration,
            Type resultClass,
            DataExchangeFactory dataExchangeFactory,
            IList <Case> cases)
        {
            string callBackName = ConfigurationUtils.GetStringAttribute(configuration.Attributes, ConfigConstants.ATTRIBUTE_TYPEHANDLER);
            string clrType      = ConfigurationUtils.GetStringAttribute(configuration.Attributes, ConfigConstants.ATTRIBUTE_TYPE);
            int    columnIndex  = ConfigurationUtils.GetIntAttribute(configuration.Attributes, ConfigConstants.ATTRIBUTE_COLUMNINDEX, ResultProperty.UNKNOWN_COLUMN_INDEX);
            string columnName   = ConfigurationUtils.GetStringAttribute(configuration.Attributes, ConfigConstants.ATTRIBUTE_COLUMN);
            string dbType       = ConfigurationUtils.GetStringAttribute(configuration.Attributes, ConfigConstants.ATTRIBUTE_DBTYPE);
            string nullValue    = configuration.GetAttributeValue(ConfigConstants.ATTRIBUTE_NULLVALUE);

            Discriminator discriminator = new Discriminator(
                callBackName,
                clrType,
                columnIndex,
                columnName,
                dbType,
                nullValue,
                cases,
                resultClass,
                dataExchangeFactory
                );

            return(discriminator);
        }
示例#9
0
 /// <summary>
 /// Serves as the default hash function.
 /// </summary>
 /// <returns>
 /// A hash code for the current object.
 /// </returns>
 public override int GetHashCode()
 {
     unchecked
     {
         var hashCode = Properties.Aggregate(Endpoint.GetHashCode(), (i, pair) => (i * 397) ^ propertyComparer.GetHashCode(pair));
         hashCode = (hashCode * 397) ^ (Discriminator?.GetHashCode() ?? 0);
         return(hashCode);
     }
 }
示例#10
0
        public bool TryPeek(out Discriminator discriminator)
        {
            if (discriminatorStack.Count == 0)
            {
                discriminator = Discriminator.Invalid;
                return(false);
            }

            discriminator = discriminatorStack.Peek();
            return(true);
        }
示例#11
0
 public void ProcessDiscriminator(Discriminator dis)
 {
     if (ProcessOperatorObject != null)
     {
         ProcessDiscriminatorObject(dis);
     }
     foreach (var obj in dis.Children)
     {
         obj.AcceptVisitor(this);
     }
 }
示例#12
0
        public static Discriminator Deserialize(XmlNode node, ConfigurationScope configScope)
        {
            Discriminator       discriminator = new Discriminator();
            NameValueCollection attributes    = NodeUtils.ParseAttributes(node, configScope.Properties);

            discriminator.CallBackName = NodeUtils.GetStringAttribute(attributes, "typeHandler");
            discriminator.CLRType      = NodeUtils.GetStringAttribute(attributes, "type");
            discriminator.ColumnIndex  = NodeUtils.GetIntAttribute(attributes, "columnIndex", -999999);
            discriminator.ColumnName   = NodeUtils.GetStringAttribute(attributes, "column");
            discriminator.DbType       = NodeUtils.GetStringAttribute(attributes, "dbType");
            discriminator.NullValue    = attributes["nullValue"];
            return(discriminator);
        }
示例#13
0
        public static IParsingResultExtended Parse(ParsingContext context)
        {
            RewindState rewind = context.RewindState;

            if (!context.Parser.VerifyString("Z"))
            {
                return(null);
            }

            IParsingResult         encoding = Encoding.Parse(context);
            IParsingResultExtended name;
            Discriminator          discriminator;

            if (encoding == null || !context.Parser.VerifyString("E"))
            {
                context.Rewind(rewind);
                return(null);
            }

            if (context.Parser.VerifyString("s"))
            {
                discriminator = Discriminator.Parse(context);
                return(new Relative(encoding, null, discriminator));
            }

            if (context.Parser.VerifyString("d"))
            {
                int?param = context.Parser.ParseNumber();

                if (context.Parser.VerifyString("_"))
                {
                    name = Name.Parse(context);
                    if (name != null)
                    {
                        return(new Default(encoding, param, name));
                    }
                }
                context.Rewind(rewind);
                return(null);
            }
            name = Name.Parse(context);
            if (name != null)
            {
                discriminator = Discriminator.Parse(context);
                return(new Relative(encoding, name, discriminator));
            }
            context.Rewind(rewind);
            return(null);
        }
示例#14
0
        /// <summary>
        /// Deserialize a ResultMap object
        /// </summary>
        /// <param name="node"></param>
        /// <param name="configScope"></param>
        /// <returns></returns>
        public static Discriminator Deserialize(XmlNode node, ConfigurationScope configScope)
        {
            Discriminator discriminator = new Discriminator();

            NameValueCollection prop = NodeUtils.ParseAttributes(node, configScope.Properties);

            discriminator.CallBackName = NodeUtils.GetStringAttribute(prop, "typeHandler");
            discriminator.CLRType      = NodeUtils.GetStringAttribute(prop, "type");
            discriminator.ColumnIndex  = NodeUtils.GetIntAttribute(prop, "columnIndex", ResultProperty.UNKNOWN_COLUMN_INDEX);
            discriminator.ColumnName   = NodeUtils.GetStringAttribute(prop, "column");
            discriminator.DbType       = NodeUtils.GetStringAttribute(prop, "dbType");
            discriminator.NullValue    = prop["nullValue"];

            return(discriminator);
        }
示例#15
0
 public override int GetHashCode()
 {
     unchecked
     {
         var hashCode = Id.GetHashCode();
         hashCode = (hashCode * 397) ^ (AvatarId != null ? AvatarId.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ (Mention != null ? Mention.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ (Username != null ? Username.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ (Discriminator != null ? Discriminator.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ CreatedAt.GetHashCode();
         hashCode = (hashCode * 397) ^ IsBot.GetHashCode();
         hashCode = (hashCode * 397) ^ (Presence != null ? Presence.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ (DirectMessageChannel != null ? DirectMessageChannel.GetHashCode() : 0);
         return(hashCode);
     }
 }
示例#16
0
        public void EmptyDiscriminator()
        {
            var ide = new IdentityDao
            {
                Id          = "test",
                Name        = "Test",
                Permissions = new[] {
                    new PermissionDao {
                        Value    = true,
                        Function = Admin.Id.ToString(),
                        Scopes   = new[] {
                            new ScopeDao
                            {
                                Discriminator = Discriminators.Category.Purchases,
                                Propagation   = ScopePropagation.ToMe | ScopePropagation.ToInclusions
                            }
                        }
                    }
                }.ToList()
            };

            string permissionExplanation = "Tengo:\r\n" +
                                           $" - Permiso ADMIN en la categoria 'Purchases' y sus subcategorias\r\n";

            var query =
                $"¿Debería poder '{nameof(Create)}' una instancia de documento Word sin categoria?\r\n" +
                " No";

            PrintTestTriedStarted(permissionExplanation + query);
            Assert.False(ide.Can(Create).Instance(File.Document.Word.Word1), permissionExplanation + query);
            PrintTestTriedStarted(permissionExplanation + query);
            Assert.False(ide.Can(Create).ByAll(
                             Factory.Get <TypeDiscriminatorFactory>().FromType <WordDocumentDao>(),
                             Discriminator.Empty <CategoryDao>()), permissionExplanation + query);

            query =
                $"¿Debería poder '{nameof(Create)}' una instancia de documento Word de la categoria 'Purchases'?\r\n" +
                " Si";
            PrintTestTriedStarted(permissionExplanation + query);
            Assert.True(ide.Can(Create).Instance(File.Document.Word.Word1.Transform(w => w.Category = Discriminators.Category.Purchases)), permissionExplanation + query);

            query =
                $"¿Debería poder '{nameof(Create)}' una instancia de documento Word de la categoria 'Sales'?\r\n" +
                " No";
            PrintTestTriedStarted(permissionExplanation + query);
            Assert.False(ide.Can(Create).Instance(File.Document.Word.Word1.Transform(w => w.Category = Discriminators.Category.Sales)), permissionExplanation + query);
        }
示例#17
0
        /// <summary>
        ///     Writes a discriminator to a string
        /// </summary>
        /// <param name="disc">the constraint discriminator</param>
        /// <returns>a string representation of the discriminator</returns>
        public static string WriteDiscrimator(Discriminator disc)
        {
            switch (disc)
            {
            case Discriminator.EQUAL: return("=");

            case Discriminator.GREATER_THAN: return(">");

            case Discriminator.GREATHER_THAN_OR_EQUAL: return(">=");

            case Discriminator.LESS_THAN: return("<");

            case Discriminator.LESS_THAN_OR_EQUAL: return("<=");

            default: throw new ArgumentException("Not a valid discriminator!");
            }
        }
示例#18
0
 public void updateLocationSource(Discriminator discriminator, IntPoint screenPos)
 {
     if (locationSources.Count == 0)
     {
         return;
     }
     lock (this.locationSources)
     {
         for (int i = 0; i < locationSources.Count; i++)
         {
             if (locationSources[i].Discri.IsSimilar(discriminator))
             {
                 locationSources[i].ScreenPos = screenPos;
                 locationSources[i].LatLng    = MapOverlayForm.Instance.FromLocalToLatLng(screenPos.X, screenPos.Y);
             }
         }
     }
 }
        public void It_Is_Built_Correctly()
        {
            var             build  = new DiscriminatorBuilder();
            ExpressionValue val    = MockRepository.GenerateMock <ExpressionValue>();
            Operator        op     = Operator.Equal;
            IColumn         column = MockRepository.GenerateMock <IColumn>();;
            Discriminator   dis    = build.SingleConditionDiscriminator(column, op, val);

            Assert.That(dis.RootGrouping, Is.Not.Null);
            Assert.That(dis.RootGrouping.Groupings, Is.Empty);
            Assert.That(dis.RootGrouping.Conditions, Has.Count(1));

            Condition condition = dis.RootGrouping.Conditions[0];

            Assert.That(condition.Column, Is.SameAs(column));
            Assert.That(condition.Operator, Is.SameAs(op));
            Assert.That(condition.ExpressionValue, Is.SameAs(val));
        }
示例#20
0
        static Formatter()
        {
            CommentContent = new Discriminator("CommentContent");
            CommentStartSymbol = new Discriminator("CommentStartSymbol");
            CommentEndSymbol = new Discriminator("CommentEndSymbol");

            StringLiteralContent = new Discriminator("StringLiteralContent");
            StringLiteralStartSymbol = new Discriminator("StringLiteralStartSymbol");
            StringLiteralEndSymbol = new Discriminator("StringLiteralEndSymbol");

            DataLiteralContent = new Discriminator("DataLiteralContent");
            DsvLiteralTerminator = new Discriminator("DsvLiteralTerminator");
            QuotedValueLiteralStartSymbol = new Discriminator("QuotedValueLiteralStartSymbol");
            QuotedValueLiteralEndSymbol = new Discriminator("QuotedValueLiteralEndSymbol");

            NumberLiteralContent = new Discriminator("NumberLiteralContent");
            NumberLiteralBasePrefix = new Discriminator("NumberLiteralBasePrefix");
            NumberLiteralTypeModifierSuffix = new Discriminator("NumberLiteralTypeModifierSuffix");
        }
示例#21
0
        private static string extractContent(string combinedContent, Discriminator discriminator)
        {
            var sign               = discriminator == Discriminator.Added ? "+" : "-";
            var antiSign           = discriminator == Discriminator.Added ? "-" : "+";
            var extractLinePattern = @"(\r\n|^)(?'ExtractLine'\" + sign + ".*?(\r\n|$))";
            var extractLineMatches = Regex.Matches(combinedContent, extractLinePattern, RegexOptions.Multiline);
            var trimLinePattern    = @"(\r\n|^)(?'TrimLine'\" + antiSign + "(?'RestOfLine'.*?(\r\n|$)))";
            var newContent         = combinedContent;

            foreach (Match lineMatch in extractLineMatches)
            {
                var extractLine = lineMatch.Groups["ExtractLine"].Value;
                newContent = newContent.Replace(extractLine, "");
            }
            var trimLineMatches = Regex.Matches(newContent, trimLinePattern, RegexOptions.Multiline);

            foreach (Match trimMatch in trimLineMatches)
            {
                var trimLine   = trimMatch.Groups["TrimLine"].Value;
                var restOfLine = trimMatch.Groups["RestOfLine"].Value;
                newContent = newContent.Replace(trimLine, restOfLine);
            }
            return(newContent);
        }
 /// <summary>
 /// Stores Discriminator from which the subMaps property must be resolved
 /// Delay resolution until all the ResultMap are processed.
 /// ///
 /// </summary>
 /// <param name="discriminator">The discriminator.</param>
 private void WaitDiscriminatorResolution(Discriminator discriminator)
 {
     discriminators.Add(discriminator);
 }
        /// <summary>
        /// Deserializes the specified config.
        /// </summary>
        /// <param name="config">The config.</param>
        /// <param name="dataExchangeFactory">The data exchange factory.</param>
        /// <param name="waitResultPropertyResolution">The wait result property resolution delegate.</param>
        /// <param name="waitDiscriminatorResolution">The wait discriminator resolution.</param>
        /// <returns></returns>
        public static ResultMap Deserialize(
            IConfiguration config,
            DataExchangeFactory dataExchangeFactory,
            WaitResultPropertyResolution waitResultPropertyResolution,
            WaitDiscriminatorResolution waitDiscriminatorResolution
            )
        {
            string id         = config.Id;
            string className  = ConfigurationUtils.GetMandatoryStringAttribute(config, ConfigConstants.ATTRIBUTE_CLASS);
            string extends    = config.GetAttributeValue(ConfigConstants.ATTRIBUTE_EXTENDS);
            string groupBy    = config.GetAttributeValue(ConfigConstants.ATTRIBUTE_GROUPBY);
            string keyColumns = config.GetAttributeValue(ConfigConstants.ATTRIBUTE_KEYS_PROPERTIES);
            string suffix     = ConfigurationUtils.GetStringAttribute(config.Attributes, ConfigConstants.ATTRIBUTE_SUFFIX, string.Empty);
            string prefix     = ConfigurationUtils.GetStringAttribute(config.Attributes, ConfigConstants.ATTRIBUTE_PREFIX, string.Empty);

            Type          type                   = dataExchangeFactory.TypeHandlerFactory.GetType(className);
            IDataExchange dataExchange           = dataExchangeFactory.GetDataExchangeForClass(type);
            IFactory      factory                = null;
            ArgumentPropertyCollection arguments = new ArgumentPropertyCollection();

            #region Get the constructor & associated parameters

            ConfigurationCollection constructors = config.Children.Find(ConfigConstants.ELEMENT_CONSTRUCTOR);

            if (constructors.Count > 0)
            {
                IConfiguration constructor = constructors[0];

                Type[]   argumentsType = new Type[constructor.Children.Count];
                string[] argumentsName = new string[constructor.Children.Count];

                // Builds param name list
                for (int i = 0; i < constructor.Children.Count; i++)
                {
                    argumentsName[i] = ConfigurationUtils.GetStringAttribute(constructor.Children[i].Attributes, ConfigConstants.ATTRIBUTE_ARGUMENTNAME);
                }

                // Find the constructor
                ConstructorInfo constructorInfo = GetConstructor(id, type, argumentsName);

                // Build ArgumentProperty and parameter type list
                for (int i = 0; i < constructor.Children.Count; i++)
                {
                    ArgumentProperty argumentMapping = ArgumentPropertyDeSerializer.Deserialize(
                        constructor.Children[i],
                        type,
                        constructorInfo,
                        dataExchangeFactory);

                    arguments.Add(argumentMapping);

                    if (argumentMapping.NestedResultMapName.Length > 0)
                    {
                        waitResultPropertyResolution(argumentMapping);
                    }

                    argumentsType[i] = argumentMapping.MemberType;
                }
                // Init the object factory
                factory = dataExchangeFactory.ObjectFactory.CreateFactory(type, argumentsType);
            }
            else
            {
                if (!dataExchangeFactory.TypeHandlerFactory.IsSimpleType(type) && type != typeof(DataRow))
                {
                    factory = dataExchangeFactory.ObjectFactory.CreateFactory(type, Type.EmptyTypes);
                }
            }

            #endregion

            ResultPropertyCollection properties = BuildResultProperties(
                id,
                config,
                type,
                prefix,
                suffix,
                dataExchangeFactory,
                waitResultPropertyResolution);
            Discriminator discriminator = BuildDiscriminator(config, type, dataExchangeFactory, waitDiscriminatorResolution);

            ResultMap resultMap = new ResultMap(
                id,
                className,
                extends,
                groupBy,
                keyColumns,
                type,
                dataExchange,
                factory,
                dataExchangeFactory.TypeHandlerFactory,
                properties,
                arguments,
                discriminator
                );

            return(resultMap);
        }
示例#24
0
        public void GrantParentDeniedChildren()
        {
            var ide = new IdentityDao
            {
                Id          = "test",
                Name        = "Test",
                Permissions = new[] {
                    new PermissionDao {
                        Value    = true,
                        Function = Admin.Id.ToString(),
                        Scopes   = new[] {
                            new ScopeDao
                            {
                                Discriminator = Discriminators.Location.Country.Spain,
                                Propagation   = ScopePropagation.ToMe | ScopePropagation.ToInclusions
                            }
                        }
                    },
                    new PermissionDao {
                        Value    = false,
                        Function = Read.Id.ToString(),
                        Scopes   = new[] {
                            new ScopeDao
                            {
                                Discriminator = Discriminators.Location.City.Madrid,
                                Propagation   = ScopePropagation.ToMe | ScopePropagation.ToInclusions
                            },
                            new ScopeDao
                            {
                                Discriminator = Factory.Get <TypeDiscriminatorFactory>().FromType <PersonDao>(),
                                Propagation   = ScopePropagation.ToMe | ScopePropagation.ToInclusions
                            },
                        }
                    },
                }
            };

            string permissionExplanation = "Tengo:\r\n" +
                                           $" - Permiso ADMIN en el estado 'Spain' y sus sublocalizaciones\r\n" +
                                           $" - Denegado READ personas en la ciudad 'Madrid' y sus sublocalizaciones\r\n";

            var query =
                $"¿Debería poder '{nameof(Create)}' una instancia de persona sin ciudad?\r\n" +
                " No";

            PrintTestTriedStarted(permissionExplanation + query);
            Assert.False(ide.Can(Create).Instance(Person.Admin), permissionExplanation + query);

            query =
                $"¿Debería poder '{nameof(Create)}' una instancia de persona sin ciudad?\r\n" +
                " No";
            PrintTestTriedStarted(permissionExplanation + query);
            Assert.False(ide.Can(Create).ByAll(
                             Factory.Get <TypeDiscriminatorFactory>().FromType <PersonDao>(),
                             Discriminator.Empty <CityDao>()), permissionExplanation + query);

            {
                query =
                    $"¿Debería poder '{nameof(Create)}' una instancia de persona con la ciudad Madrid?\r\n" +
                    " No";

                PrintTestTriedStarted(permissionExplanation + query);
                Assert.False(ide.Can(Create).Instance(Person.MadridAdmin), permissionExplanation + query);

                PrintTestTriedStarted(permissionExplanation + query);
                Assert.False(ide.Can(Create).ByAll(
                                 Factory.Get <TypeDiscriminatorFactory>().FromType <PersonDao>(),
                                 Discriminators.Location.City.Madrid),
                             permissionExplanation + query);
            }

            {
                query =
                    $"¿Debería poder '{nameof(Create)}' una instancia de persona con la ciudad Alcorcon?\r\n" +
                    " Si";

                PrintTestTriedStarted(permissionExplanation + query);
                Assert.True(ide.Can(Create).Instance(Person.AlcorconAdmin), permissionExplanation + query);

                PrintTestTriedStarted(permissionExplanation + query);
                Assert.True(ide.Can(Create).ByAll(
                                Factory.Get <TypeDiscriminatorFactory>().FromType <PersonDao>(),
                                Discriminators.Location.City.Alcorcon), permissionExplanation + query);
            }

            var source = new[] { Person.AlcorconAdmin, Person.MadridAdmin };

            query =
                $"¿Debería filtrar para '{nameof(Create)}' una instancia de pesona con la ciudad Alcorcon?\r\n" +
                " No";
            PrintTestTriedStarted(permissionExplanation + query);
            var source1 = source.AuthorizedTo(ide, Create);

            using (Printer.Indent2("Source filtered results:"))
            {
                foreach (var per in source1)
                {
                    Printer.WriteLine("Person: " + per);
                }
            }
            Assert.True(source1.Contains(Person.AlcorconAdmin), permissionExplanation + query);

            query =
                $"¿Debería filtrar para '{nameof(Create)}' una instancia de pesona con la ciudad Madrid?\r\n" +
                " Si";
            PrintTestTriedStarted(permissionExplanation + query);
            Assert.False(source.AuthorizedTo(ide, Create).Contains(Person.MadridAdmin), permissionExplanation + query);

            query =
                $"¿Debería poder '{nameof(Read)}' objetos del tipo Word?\r\n" +
                " Si";
            PrintTestTriedStarted(permissionExplanation + query);
            Assert.True(ide.Can(Read).Type <WordDocumentDao>(), permissionExplanation + query);
        }
示例#25
0
 public override string ToString()
 {
     return($"{Username}#{"0000".Remove(4 - Discriminator.ToString().Length) + Discriminator.ToString()}");
 }
示例#26
0
        public static void EntitiesContextInitialization <T>() where T : EntitiesContext
        {
            if (_contexts.Value.FirstOrDefault(c => c.Name == (typeof(T).Name)).IsNull())
            {
                string sessionid = MVCEngine.Tools.Session.Session.CreateUserSession(typeof(T).Name);
                Task   task      = new Task(() =>
                {
                    Dictionary <MVCEngine.Model.Internal.Descriptions.DynamicProperties, string[]> dynamicList =
                        new Dictionary <MVCEngine.Model.Internal.Descriptions.DynamicProperties, string[]>();
                    Context ctx = new Context()
                    {
                        Name    = typeof(T).Name,
                        Entites = new List <EntityClass>()
                    };
                    _contexts.Value.Add(ctx);
                    _entitiesCollection.Value.Add(ctx.Name, new Dictionary <string, Func <object, object> >());

                    typeof(T).GetFields().Where(f => f.FieldType.Name == "EntitiesCollection`1" && f.IsPublic).
                    ToList().ForEach((f) =>
                    {
                        List <string> realTimeValidator = new List <string>();
                        PropertyInfo ctxInfo            = f.FieldType.GetProperty("Context");
                        Type entityType = f.FieldType.GetGenericArguments().First <Type>();
                        Debug.Assert(typeof(Entity).IsAssignableFrom(entityType), "Entity[" + entityType.FullName + "] it cann't be recognise as valid entity.");
                        if (typeof(Entity).IsAssignableFrom(entityType))
                        {
                            if (!_entites.Value.ContainsKey(entityType.FullName))
                            {
                                EntityClass entityClass = new EntityClass();
                                Debug.Assert(!ctx.Entites.Exists((t) => { return(t.Name == entityType.Name); }), "Entity[" + entityType.Name + "] is defined twice.");
                                if (!ctx.Entites.Exists((t) => { return(t.Name == entityType.Name); }))
                                {
                                    entityClass.Name       = entityType.Name;
                                    entityClass.EntityType = entityType;
                                    entityClass.Attributes.AddRange(Attribute.GetCustomAttributes(entityType));

                                    _entitiesCollection.Value[ctx.Name].Add(entityType.Name, LambdaTools.FieldGetter(typeof(T), f));

                                    var propertyquery = entityType.GetProperties().Where(p => p.CanRead && p.GetGetMethod().IsVirtual);
                                    propertyquery.ToList().ForEach((p) =>
                                    {
                                        EntityProperty property = new EntityProperty()
                                        {
                                            Name         = p.Name,
                                            PropertyType = p.PropertyType,
                                            PropertyInfo = p,
                                            Setter       = p.CanWrite ? LambdaTools.PropertySetter(entityType, p) : null,
                                            Getter       = LambdaTools.PropertyGetter(entityType, p)
                                        };
                                        property.Attibutes.AddRange(Attribute.GetCustomAttributes(p));
                                        entityClass.Properties.Add(property);

                                        if (typeof(Entity).IsAssignableFrom(p.PropertyType))
                                        {
                                            property.ReletedEntity = new ReletedEntity()
                                            {
                                                Related           = Releted.Entity,
                                                RelatedEntityName = p.PropertyType.Name
                                            };
                                        }
                                        else if (p.PropertyType.Name == "EntitiesCollection`1")
                                        {
                                            property.ReletedEntity = new ReletedEntity()
                                            {
                                                Related           = Releted.List,
                                                RelatedEntityName = p.PropertyType.GetGenericArguments().First <Type>().Name
                                            };
                                        }
                                        Attribute.GetCustomAttributes(p).ToList().ForEach((a) =>
                                        {
                                            Relation relation           = null;
                                            Discriminator discriminator = null;
                                            PropertyValidator validator = null;
                                            DefaultValue defaultValue   = null;
                                            Synchronized synchronized   = null;
                                            Formatter formatter         = null;
                                            NotIntercept notIntercept   = null;
                                            Intercept intercept         = null;
                                            attribute.DynamicProperties dynamicProperties = null;
                                            if (a.IsTypeOf <PrimaryKey>())
                                            {
                                                Debug.Assert(entityClass.Properties.FirstOrDefault(primary => primary.PrimaryKey).IsNull(), "Entity[" + entityType.Name + "] at least two primary key property defined");
                                                property.PrimaryKey            = true;
                                                entityClass.PrimaryKeyProperty = property;
                                                entityClass.PrimaryKey         = property.Getter;
                                            }
                                            else if ((relation = a.CastToType <Relation>()).IsNotNull())
                                            {
                                                EntitiesRelation r = ctx.Relations.FirstOrDefault(re => re.Name == relation.RelationName);
                                                Debug.Assert(r.IsNull(), "Relation[" + relation.RelationName + "] is declared at least twice");
                                                if (property.ReletedEntity.IsNotNull())
                                                {
                                                    EntitiesRelation entityrelation = new EntitiesRelation()
                                                    {
                                                        Name   = relation.RelationName,
                                                        Parent = new EntityRelated()
                                                        {
                                                            EntityName = relation.ParentEntity,
                                                            Key        = relation.ParentProperty
                                                        },
                                                        Child = new EntityRelated()
                                                        {
                                                            EntityName = relation.ChildEntity,
                                                            Key        = relation.ChildProperty
                                                        },
                                                        OnDelete = relation.OnDelete,
                                                        OnAccept = relation.OnAccept,
                                                        OnFreeze = relation.OnFreeze
                                                    };
                                                    ctx.Relations.Add(entityrelation);
                                                    property.ReletedEntity.Relation = entityrelation;
                                                }
                                            }
                                            else if ((synchronized = a.CastToType <Synchronized>()).IsNotNull())
                                            {
                                                if (property.ReletedEntity.IsNotNull())
                                                {
                                                    property.ReletedEntity.Synchronized = true;
                                                }
                                            }
                                            else if ((discriminator = a.CastToType <Discriminator>()).IsNotNull())
                                            {
                                                if (property.ReletedEntity.IsNotNull())
                                                {
                                                    property.ReletedEntity.Discriminators.Add(discriminator);
                                                }
                                            }
                                            else if ((validator = a.CastToType <PropertyValidator>()).IsNotNull())
                                            {
                                                property.Validators.Add(validator);
                                            }
                                            else if ((defaultValue = a.CastToType <DefaultValue>()).IsNotNull())
                                            {
                                                property.DefaultValue = defaultValue;
                                            }
                                            else if ((dynamicProperties = a.CastToType <attribute.DynamicProperties>()).IsNotNull())
                                            {
                                                if (property.ReletedEntity.IsNotNull() && property.ReletedEntity.Related == Releted.List)
                                                {
                                                    entityClass.DynamicProperties = new Internal.Descriptions.DynamicProperties()
                                                    {
                                                        CodeProperty = dynamicProperties.CodeProperty,
                                                        Property     = property,
                                                    };
                                                    dynamicList.Add(entityClass.DynamicProperties, dynamicProperties.ValueProperties);
                                                }
                                            }
                                            else if ((formatter = a.CastToType <Formatter>()).IsNotNull())
                                            {
                                                property.AddFormatter(formatter);
                                            }
                                            else if ((notIntercept = a.CastToType <NotIntercept>()).IsNotNull())
                                            {
                                                if (notIntercept.InterceptorId.IsNullOrEmpty())
                                                {
                                                    property.RemoveGetInterceptor(string.Empty);
                                                    property.RemoveSetInterceptor(string.Empty);
                                                }
                                                else
                                                {
                                                    if (notIntercept.Method == Method.Get)
                                                    {
                                                        property.RemoveGetInterceptor(notIntercept.InterceptorId);
                                                    }
                                                    else
                                                    {
                                                        property.RemoveSetInterceptor(notIntercept.InterceptorId);
                                                    }
                                                }
                                            }
                                            else if ((intercept = a.CastToType <Intercept>()).IsNotNull() && intercept.Method.IsNotNull())
                                            {
                                                if (intercept.Method.Contains(Method.Get))
                                                {
                                                    property.AddGetInterceptor(intercept.InterceptorId);
                                                }

                                                if (intercept.Method.Contains(Method.Set))
                                                {
                                                    property.AddSetInterceptor(intercept.InterceptorId);
                                                }
                                            }
                                        });
                                    });
                                    Attribute.GetCustomAttributes(entityType).ToList().ForEach((a) =>
                                    {
                                        EntityValidator validator = null;
                                        if ((validator = a.CastToType <EntityValidator>()).IsNotNull())
                                        {
                                            entityClass.Validators.Add(validator);
                                        }
                                    });
                                    ctx.Entites.Add(entityClass);
                                }
                                _entites.Value.Add(entityType.FullName, entityClass);
                            }
                            else
                            {
                                ctx.Entites.Add(_entites.Value[entityType.FullName]);
                            }
                        }
                    });
                    ctx.Relations.ForEach((r) =>
                    {
                        EntityClass entity = ctx.Entites.FirstOrDefault(e => e.Name == r.Parent.EntityName);
                        Debug.Assert(entity.IsNotNull(), "Relation[" + r.Name + "] parent entity not found");
                        r.Parent.Entity         = entity;
                        EntityProperty property = entity.Properties.FirstOrDefault(p => p.Name == r.Parent.Key);
                        Debug.Assert(property.IsNotNull(), "Entity[" + entity.Name + "] property[" + r.Parent.Key + "] not defined");
                        r.Parent.Type  = property.PropertyType;
                        r.Parent.Value = property.Getter;

                        EntityClass childEntity = ctx.Entites.FirstOrDefault(e => e.Name == r.Child.EntityName);
                        Debug.Assert(childEntity.IsNotNull(), "Relation[" + r.Name + "] child entity not found");
                        r.Child.Entity = childEntity;
                        EntityProperty childProperty = childEntity.Properties.FirstOrDefault(p => p.Name == r.Child.Key);
                        Debug.Assert(childProperty.IsNotNull(), "Entity[" + childEntity.Name + "] property[" + r.Child.Key + "] not defined");
                        r.Child.Type  = childProperty.PropertyType;
                        r.Child.Value = childProperty.Getter;
                    });

                    var reletedquery = ctx.Entites.Where(e => e.Properties.Count(p => p.ReletedEntity.IsNotNull()) > 0).
                                       SelectMany(e => e.Properties.Where(p => p.ReletedEntity.IsNotNull()), (e, p) => new { Entity = e, Property = p });

                    reletedquery.ToList().ForEach((ep) =>
                    {
                        EntityClass entityClass = ctx.Entites.FirstOrDefault(e => e.Name == ep.Property.ReletedEntity.RelatedEntityName);
                        Debug.Assert(entityClass.IsNotNull(), "Entity[" + ep.Property.ReletedEntity.RelatedEntityName + "] dosen't have collection");
                        ep.Property.ReletedEntity.RelatedEntity = entityClass;
                        if (ep.Property.ReletedEntity.Relation.IsNull())
                        {
                            if (!ep.Property.ReletedEntity.RelationName.IsNullOrEmpty())
                            {
                                EntitiesRelation relation = ctx.Relations.FirstOrDefault(r => r.Name == ep.Property.ReletedEntity.RelationName);
                                Debug.Assert(relation.IsNotNull(), "Relation[" + ep.Property.ReletedEntity.RelationName + "] not defined");
                                ep.Property.ReletedEntity.Relation = relation;
                            }
                            else
                            {
                                List <EntitiesRelation> relations = null;
                                if (ep.Property.ReletedEntity.Related == Releted.Entity)
                                {
                                    relations = ctx.Relations.Where(r => r.Parent.EntityName == ep.Property.ReletedEntity.RelatedEntityName && r.Child.EntityName == ep.Entity.Name).ToList();
                                }
                                else
                                {
                                    relations = ctx.Relations.Where(r => r.Parent.EntityName == ep.Entity.Name && r.Child.EntityName == ep.Property.ReletedEntity.RelatedEntityName).ToList();
                                }

                                Debug.Assert(relations.Count() < 2, "Relation[" + ep.Property.ReletedEntity.RelatedEntityName + "-" + ep.Entity.Name + "] more then one");
                                if (relations.Count() == 1)
                                {
                                    ep.Property.ReletedEntity.Relation = relations[0];
                                }
                            }
                        }
                        if (ep.Property.ReletedEntity.Synchronized)
                        {
                            ep.Property.ReletedEntity.RelatedEntity.Synchronized(ep.Entity.Name, ep.Property.Name);
                        }
                        if (ep.Property.ReletedEntity.Related == Releted.List)
                        {
                            ep.Property.AddGetInterceptor(CollectionInterceptorDispatcher.GetId(ep.Property.ReletedEntity.Relation.Child.Entity.EntityType));
                        }
                        else
                        {
                            ep.Property.AddGetInterceptor(EntityInterceptorDispatcher.GetId(ep.Property.ReletedEntity.RelatedEntityName));
                        }
                    });

                    foreach (MVCEngine.Model.Internal.Descriptions.DynamicProperties dynamicProperty in dynamicList.Keys)
                    {
                        foreach (string p in dynamicList[dynamicProperty])
                        {
                            EntityProperty property = dynamicProperty.Property.ReletedEntity.RelatedEntity.Properties.FirstOrDefault(pr => pr.Name == p);
                            if (property.IsNotNull())
                            {
                                dynamicProperty.ValuesProperties.Add(property.PropertyType, property.Name);
                            }
                        }
                    }
                });

                task.ContinueWith((antecedent) =>
                {
                    MVCEngine.Tools.Session.Session.ReleaseSession(sessionid);
                });

                task.ContinueWith((antecedent) =>
                {
                    if (_contexts.IsValueCreated)
                    {
                        _contexts.Value.Clear();
                    }
                    //ToDo log exception into log file
                }, TaskContinuationOptions.ExecuteSynchronously | TaskContinuationOptions.OnlyOnFaulted);

                MVCEngine.Tools.Session.Session.SetSessionData(sessionid, "InitializeTask", task);

                task.Start();
            }
        }
        /// <summary>
        /// 音声ファイルを開き、生成された特徴ベクトルのリストを返す
        /// </summary>
        /// <param name="waveFilePath">WAVEファイルのフルパス</param>
        /// <param name="discriminator">識別器<para>識別させない場合は省略して下さい。</para></param>
        /// <param name="threshold">棄却レベル<para>識別のさせる場合、この値を下回ると識別結果をUnknownと判定します。</para></param>
        /// <returns>
        /// 生成された特徴ベクトルのリスト
        /// <para>識別器を指定している場合は、識別結果を添付します。</para>
        /// </returns>
        public List <Result> GenerateFeatureList(string waveFilePath, Discriminator discriminator = null, double threshold = 0.0)
        {
            var ans = new List <Result>(0);                                                          // 結果を格納する

            if (System.IO.File.Exists(waveFilePath))
            {
                WaveReader wave_file = new WaveReader();
                wave_file.Open(waveFilePath);                                                       // waveファイルを開く
                if (wave_file.IsOpen)
                {
                    try
                    {
                        this.Lock = true;
                        this.SetGenerator(wave_file);
                        this._generator.Log = this.Log;
                        DFT fft = new DFT(this.ReadAmount, Window.WindowKind.Hanning);              // FFTを実施する準備
                        while (wave_file.IsOpen && wave_file.ReadLimit == false)                    // 読めるなら、全て読むまでループ
                        {
                            MusicData data = wave_file.Read(this.ReadAmount);                       // ファイルからread_size_sec秒間読み込み。
                            double[]  sound;
                            if (data.UsableCH == MusicData.UsableChannel.Left)                      // データの入っている方を格納する
                            {
                                sound = data.GetData(MusicData.Channel.Left);                       //
                            }
                            else
                            {
                                sound = data.GetData(MusicData.Channel.Right);
                            }
                            FFTresult result = fft.FFT(sound, (double)wave_file.SamplingRate);      // FFTを実行. FFTサイズが音声データよりも小さい場合、始めの方しか処理されないので注意.
                            this._generator.Add(result);
                            if (this._generator.Ready)
                            {
                                //Console.WriteLine("検出したようです。");                          // デバッグモードで動かしながら確認するためのコンソール出力
                                Result feature = this._generator.GetFeature();                      // 特徴ベクトル生成
                                if (discriminator == null)
                                {
                                    ans.Add(feature);                                               // 答えを格納
                                }
                                else
                                {
                                    Discriminator.IDandLikelihood id = discriminator.Discriminate(feature.FeatureVector);
                                    string name = id.ID;
                                    if (id.Likelihood < threshold)
                                    {
                                        name = "Unknown";
                                    }
                                    feature.DiscriminationResult = name;
                                    if (!(this.MatchOnlyAtDiscrimination == true && name != feature.FilterName))
                                    {
                                        ans.Add(feature);
                                    }
                                }
                            }
                        }
                    }
                    catch (SystemException e)
                    {
                        throw new Exception(e.Message);
                    }
                }
                else
                {
                    throw new Exception("Waveファイルを開くことができませんでした。\nWaveReaderクラスエラーメッセージ:" + wave_file.ErrorMessage);
                }
                wave_file.Close();                                                              // waveファイルを閉じる
            }
            this.Lock = false;
            return(ans);
        }
示例#28
0
 public bool Equals(User other)
 {
     return(Discriminator.Equals(other.Discriminator) && Tag.Equals(other.Tag) && Name.Equals(other.Name));
 }
示例#29
0
 /// <summary>
 /// Executes discriminator code (sort of Where statement) to check if ExecuteAction is allowed to be executed
 /// </summary>
 /// <param name="messageBusEvent">The type of message bus event</param>
 /// <returns>True if ExecuteAction is allowed, otherwise false</returns>
 public virtual bool ExecuteDiscriminator(object messageBusEvent)
 {
     return(!this.IsDisposed && (Discriminator?.Invoke(messageBusEvent as T) ?? true));
 }
示例#30
0
        public Mappings GetMappings(DbContext ctx, Type t)
        {
            Discriminator discriminator = null;
            var           objectContext = ((IObjectContextAdapter)ctx).ObjectContext;
            var           workspace     = objectContext.MetadataWorkspace;
            var           containerName = objectContext.DefaultContainerName;

            t = ObjectContext.GetObjectType(t);
            var entityName = t.Name;

            // If we are dealing with table inheritance we need the base type name as well.
            var baseEntityName = t.BaseType?.Name;

            var storageMapping =
                (EntityContainerMapping)workspace.GetItem <GlobalItem>(containerName, DataSpace.CSSpace);
            var entitySetMaps      = storageMapping.EntitySetMappings.ToList();
            var associationSetMaps = storageMapping.AssociationSetMappings.ToList();

            //
            // Add mappings for all scalar properties. That is, for all properties
            // that do not represent other entities (navigation properties).
            //
            var entitySetMap = entitySetMaps
                               .Single(m =>
                                       m.EntitySet.ElementType.Name == entityName ||
                                       m.EntitySet.ElementType.Name == baseEntityName);
            var typeMappings = entitySetMap.EntityTypeMappings;

            var propertyMappings = new List <PropertyMapping>();

            NavigationProperty[] navigationProperties = new NavigationProperty[0];

            // As long as we do not deal with table inheritance
            // we assume there is only one type mapping available.
            if (typeMappings.Count() == 1)
            {
                var typeMapping = typeMappings[0];
                var fragments   = typeMapping.Fragments;
                var fragment    = fragments[0];

                propertyMappings.AddRange(fragment.PropertyMappings);

                navigationProperties =
                    typeMapping.EntityType.DeclaredMembers
                    .Where(m => m.BuiltInTypeKind == BuiltInTypeKind.NavigationProperty)
                    .Cast <NavigationProperty>()
                    .Where(p => p.RelationshipType is AssociationType)
                    .ToArray();
            }
            // If we have more than one type mapping we assume that we are
            // dealing with table inheritance.
            else
            {
                foreach (var tm in typeMappings)
                {
                    var name = tm.EntityType != null ? tm.EntityType.Name : tm.IsOfEntityTypes[0].Name;

                    if (name == baseEntityName ||
                        name == entityName)
                    {
                        var fragments = tm.Fragments;
                        var fragment  = fragments[0];
                        if (fragment.Conditions.Any())
                        {
                            var valueConditionMapping =
                                (ValueConditionMapping)fragment.Conditions[0];
                            discriminator = new Discriminator
                            {
                                Column = valueConditionMapping.Column,
                                Value  = valueConditionMapping.Value
                            };
                        }
                        var uknownMappings = fragment.PropertyMappings
                                             .Where(m => propertyMappings.All(pm => pm.Property.Name != m.Property.Name));

                        propertyMappings.AddRange(uknownMappings);
                    }
                }

                //var typeMapping = typeMappings.Single(tm => tm.IsOfEntityTypes[0].Name == entityName);
            }


            var columnMappings = new List <TableColumnMapping>();

            columnMappings.AddRange(
                propertyMappings
                .Where(p => p is ScalarPropertyMapping)
                .Cast <ScalarPropertyMapping>()
                .Where(m => !m.Column.IsStoreGeneratedComputed)
                .Select(p => new TableColumnMapping
            {
                EntityProperty = p.Property,
                TableColumn    = p.Column
            }));
            var complexPropertyMappings = propertyMappings
                                          .Where(p => p is ComplexPropertyMapping)
                                          .Cast <ComplexPropertyMapping>()
                                          .ToArray();

            if (complexPropertyMappings.Any())
            {
                columnMappings.AddRange(GetTableColumnMappings(complexPropertyMappings, true));
            }

            var columnMappingByPropertyName = columnMappings.ToDictionary(m => m.EntityProperty.Name, m => m);
            var columnMappingByColumnName   = columnMappings.ToDictionary(m => m.TableColumn.Name, m => m);

            //
            // Add mappings for all navigation properties.
            //
            //
            var foreignKeyMappings = new List <ForeignKeyMapping>();

            foreach (var navigationProperty in navigationProperties)
            {
                var relType = (AssociationType)navigationProperty.RelationshipType;

                // Only bother with unknown relationships
                if (foreignKeyMappings.All(m => m.NavigationPropertyName != navigationProperty.Name))
                {
                    var fkMapping = new ForeignKeyMapping
                    {
                        NavigationPropertyName = navigationProperty.Name,
                        BuiltInTypeKind        = navigationProperty.TypeUsage.EdmType.BuiltInTypeKind,
                    };

                    //
                    // Many-To-Many
                    //
                    if (associationSetMaps.Any() &&
                        associationSetMaps.Any(m => m.AssociationSet.Name == relType.Name))
                    {
                        var map           = associationSetMaps.Single(m => m.AssociationSet.Name == relType.Name);
                        var sourceMapping =
                            new TableColumnMapping
                        {
                            TableColumn    = map.SourceEndMapping.PropertyMappings[0].Column,
                            EntityProperty = map.SourceEndMapping.PropertyMappings[0].Property,
                        };
                        var targetMapping =
                            new TableColumnMapping
                        {
                            TableColumn    = map.TargetEndMapping.PropertyMappings[0].Column,
                            EntityProperty = map.TargetEndMapping.PropertyMappings[0].Property,
                        };

                        fkMapping.FromType = (map.SourceEndMapping.AssociationEnd.TypeUsage.EdmType as RefType)
                                             ?.ElementType.Name;
                        fkMapping.ToType = (map.TargetEndMapping.AssociationEnd.TypeUsage.EdmType as RefType)
                                           ?.ElementType.Name;
                        var schema = map.StoreEntitySet.Schema;
                        var name   = map.StoreEntitySet.Table ?? map.StoreEntitySet.Name;

                        fkMapping.AssociationMapping = new AssociationMapping
                        {
                            TableName = new TableName
                            {
                                Name   = name,
                                Schema = schema,
                            },
                            Source = sourceMapping,
                            Target = targetMapping
                        };
                    }
                    //
                    // One-To-One or One-to-Many
                    //
                    else
                    {
                        fkMapping.FromType = relType.Constraint.FromProperties.First().DeclaringType.Name;
                        fkMapping.ToType   = relType.Constraint.ToProperties.First().DeclaringType.Name;

                        var foreignKeyRelations = new List <ForeignKeyRelation>();
                        for (int i = 0; i < relType.Constraint.FromProperties.Count; i++)
                        {
                            foreignKeyRelations.Add(new ForeignKeyRelation
                            {
                                FromProperty = relType.Constraint.FromProperties[i].Name,
                                ToProperty   = relType.Constraint.ToProperties[i].Name,
                            });
                        }

                        fkMapping.ForeignKeyRelations = foreignKeyRelations.ToArray();
                    }

                    foreignKeyMappings.Add(fkMapping);
                }
            }

            var tableName = GetTableName(ctx, t);

            var mappings = new Mappings
            {
                TableName                   = tableName,
                Discriminator               = discriminator,
                ComplexPropertyNames        = complexPropertyMappings.Select(m => m.Property.Name).ToArray(),
                ColumnMappingByPropertyName = columnMappingByPropertyName,
                ColumnMappingByColumnName   = columnMappingByColumnName,
                ToForeignKeyMappings        = foreignKeyMappings.Where(m => m.ToType == entityName).ToArray(),
                FromForeignKeyMappings      = foreignKeyMappings.Where(m => m.FromType == entityName).ToArray()
            };

            foreach (var toPropertyName in mappings.ToForeignKeyMappings.SelectMany(m =>
                                                                                    m.ForeignKeyRelations.Select(r => r.ToProperty)))
            {
                if (mappings.ColumnMappingByPropertyName.ContainsKey(toPropertyName))
                {
                    var tableColumnMapping = mappings.ColumnMappingByPropertyName[toPropertyName];
                    tableColumnMapping.IsForeignKey = true;
                }
            }

            foreach (var toPropertyName in mappings.FromForeignKeyMappings.SelectMany(m =>
                                                                                      m.ForeignKeyRelations.Select(r => r.ToProperty)))
            {
                if (mappings.ColumnMappingByPropertyName.ContainsKey(toPropertyName))
                {
                    var tableColumnMapping = mappings.ColumnMappingByPropertyName[toPropertyName];
                    tableColumnMapping.IsForeignKey = true;
                }
            }

            var associationMappings = mappings.ToForeignKeyMappings
                                      .Where(m => m.AssociationMapping != null)
                                      .Select(m => m.AssociationMapping);

            foreach (var associationMapping in associationMappings)
            {
                associationMapping.Source.IsForeignKey = true;
                associationMapping.Target.IsForeignKey = true;
            }

            associationMappings = mappings.FromForeignKeyMappings
                                  .Where(m => m.AssociationMapping != null)
                                  .Select(m => m.AssociationMapping);
            foreach (var associationMapping in associationMappings)
            {
                associationMapping.Source.IsForeignKey = true;
                associationMapping.Target.IsForeignKey = true;
            }

            return(mappings);
        }
示例#31
0
 /// <summary>
 /// Formats the user into username#discriminator
 /// </summary>
 /// <returns></returns>
 public override string ToString()
 {
     return(Username + "#" + Discriminator.ToString("D4"));
 }
示例#32
0
        }                  //Used for cloning

        public override string ToString() => Name != null ? $"{Name}#{Discriminator.ToString("D4")}" : Id.ToIdString();