protected override IEnumerable<ICommandFilter> BuildFilters(IEnumerable<CaptionFilter> filters)
        {
            yield return new CommandFilter("[property_type]=1");

            yield return new CommandFilter(string.Format("[cube_name]='{0}'"
                                                           , filters.Single(f => f.Target == Target.Perspectives).Caption
                                                           ));

            yield return new CommandFilter(string.Format("[dimension_unique_name]='[{0}]'"
                                                            , filters.Single(f => f.Target == Target.Dimensions).Caption
                                                            ));

            yield return new CommandFilter(string.Format("[hierarchy_unique_name]='[{0}].[{1}]'"
                                                , filters.Single(f => f.Target == Target.Dimensions).Caption
                                                , filters.Single(f => f.Target == Target.Hierarchies).Caption
                                                ));

            yield return new CommandFilter(string.Format("[level_unique_name]='[{0}].[{1}].[{2}]'"
                                                , filters.Single(f => f.Target == Target.Dimensions).Caption
                                                , filters.Single(f => f.Target == Target.Hierarchies).Caption
                                                , filters.Single(f => f.Target == Target.Levels).Caption
                                                ));

            var filter = filters.SingleOrDefault(f => f.Target == Target.Properties);
            if (filter!=null)
                yield return new CommandFilter(string.Format("[property_caption]='{0}'"
                                                           , filter.Caption
                                                           ));
        }
        protected override ModelMetadata CreateMetadata(
                                     IEnumerable<Attribute> attributes,
                                     Type containerType,
                                     Func<object> modelAccessor,
                                     Type modelType,
                                     string propertyName)
        {
            var data = base.CreateMetadata(
                                 attributes,
                                 containerType,
                                 modelAccessor,
                                 modelType,
                                 propertyName);

            //Enhance the metadata with custom attributes
            var display = attributes.SingleOrDefault(a => a is DisplayAttribute);
            if (display != null)
            {
                var displayAttribute = ((DisplayAttribute)display);
                data.Watermark = displayAttribute.Prompt;
                data.Description = displayAttribute.Description;
            }

            var dropDown = attributes.SingleOrDefault(a => a is DropDownPropertyAttribute);
            if (dropDown != null)
            {
                var drop = ((DropDownPropertyAttribute) dropDown);
                data.AdditionalValues.Add("DropDownProperty.PropertyName", drop.PropertyName);
                var property = containerType.GetProperty(drop.PropertyName);
                if(property!= null)
                {
                    var attr = property.GetCustomAttributes(typeof(RequeridoAttribute), true);
                    data.IsRequired = attr.Any();
                }
            }

            var cascadingDropDown = attributes.SingleOrDefault(a => a is CascadingDropDownPropertyAttribute);
            if (cascadingDropDown != null)
            {
                var cascading = (CascadingDropDownPropertyAttribute) cascadingDropDown;
                data.AdditionalValues.Add("CascadingDropDownProperty.ParentPropertyName", cascading.ParentPropertyName);
                data.AdditionalValues.Add("CascadingDropDownProperty.ParentPrompt", cascading.ParentPrompt);
                data.AdditionalValues.Add("CascadingDropDownProperty.ActionName", cascading.ActionName);
                data.AdditionalValues.Add("CascadingDropDownProperty.ControllerName", cascading.ControllerName);
                data.AdditionalValues.Add("CascadingDropDownProperty.AreaName", cascading.AreaName);
                data.AdditionalValues.Add("CascadingDropDownProperty.ParameterName", cascading.ParameterName);
            }

            var searchDropDown = attributes.SingleOrDefault(a => a is SearcheableDropDownPropertyAttribute);
            if (searchDropDown != null)
            {
                var search = (SearcheableDropDownPropertyAttribute)searchDropDown;
                data.AdditionalValues.Add("SearcheableDropDownPropertyAttribute.ActionName", search.ActionName);
                data.AdditionalValues.Add("SearcheableDropDownPropertyAttribute.ControllerName", search.ControllerName);
                data.AdditionalValues.Add("SearcheableDropDownPropertyAttribute.Template", search.Template);
                data.AdditionalValues.Add("SearcheableDropDownPropertyAttribute.DisplayProperty", search.DisplayProperty);
            }

            return data;
        }
Example #3
0
        protected override void DoLast(Hero hero, IEnumerable<GameObject> objects)
        {
            var cuttableObject = objects.SingleOrDefault(o => o.Properties.Contains(Property.Cuttable));
            var cutter = objects.SingleOrDefault(o => o.Properties.Contains(Property.Cutter));

            if (cuttableObject == null || cutter == null)
            {
                return;
            }

            cuttableObject.RemoveFromContainer();

            Map.SetHObjectFromDestination(hero.Position, new Log());
            return;
        }
        public InstallerStatus PostParameters(IEnumerable<Parameter> parameters)
        {
            var connection = parameters.SingleOrDefault(k => k.Key == "connectionString").Value;
            var containerName = parameters.SingleOrDefault(k => k.Key == "containerName").Value;
            var rootUrl = parameters.SingleOrDefault(k => k.Key == "rootUrl").Value;

            var host = $"{rootUrl}{containerName}/";

            if (!TestAzureCredentials(connection, containerName))
            {
                return InstallerStatus.ConnectionError;
            }

            if (SaveParametersToXdt(this.fileSystemProvidersConfigInstallXdtPath, parameters))
            {
                if (!ExecuteFileSystemConfigTransform() || !ExecuteWebConfigTransform())
                {
                    return InstallerStatus.SaveConfigError;
                }

                if (!CheckImageProcessorWebCompatibleVersion(ImageProcessorWebMinRequiredVersion))
                {
                    return InstallerStatus.ImageProcessorWebCompatibility;
                }
                else
                {
                    // merge in storage url to ImageProcessor security.config xdt
                    SaveBlobPathToImageProcessorSecurityXdt(ImageProcessorSecurityInstallXdtPath, host);

                    // transform ImageProcessor security.config
                    if (ExecuteImageProcessorSecurityConfigTransform())
                    {
                        if (!ExecuteImageProcessorWebConfigTransform())
                        {
                            return InstallerStatus.ImageProcessorWebConfigError;
                        }
                    }
                    else
                    {
                        return InstallerStatus.ImageProcessorWebConfigError;
                    }
                }

                return InstallerStatus.Ok;
            }

            return InstallerStatus.SaveXdtError;
        }
 /// <summary>
 /// Gets the effective domain name of an OrgUnit, based on it's own CustomUrl or it's ancestry.
 /// </summary>
 /// <param name="orgUnitId">The org unit id.</param>
 /// <param name="associations">The associations.</param>
 /// <returns></returns>
 public static string GetDomainName(int orgUnitId, IEnumerable<OrgUnitAssociationDto> associations)
 {
     var association = associations.SingleOrDefault(a => a.SecondaryId == orgUnitId);
     if (association != null)
     {
         var url = association.SecondaryCustomUrl;
         if (string.IsNullOrEmpty(url))
         {
             while (association.HasAscendant)
             {
                 var ascendant = associations.Single(a => a.SecondaryId == association.PrimaryId);
                 if (!string.IsNullOrEmpty(ascendant.SecondaryCustomUrl))
                 {
                     url = ascendant.SecondaryCustomUrl;
                     break;
                 }
                 association = ascendant;
             }
         }
         if (Uri.IsWellFormedUriString(url, UriKind.Absolute))
         {
             return new Uri(url).Host;
         }
     }
     return string.Empty;
 }
        private void Init(
            string httpMethod,
            Uri url,
            string applicationPath,
            IEnumerable<KeyValuePair<string, string[]>> formData,
            IEnumerable<KeyValuePair<string, string>> cookies,
            Func<byte[], byte[]> cookieDecryptor)
        {
            HttpMethod = httpMethod;
            Url = url;
            ApplicationUrl = new Uri(url, applicationPath);
            Form = new ReadOnlyDictionary<string, string>(
                (formData ?? Enumerable.Empty<KeyValuePair<string, string[]>>())
                .ToDictionary(kv => kv.Key, kv => kv.Value.Single()));
            QueryString = QueryStringHelper.ParseQueryString(url.Query);

            var relayState = QueryString["RelayState"].SingleOrDefault();

            if (relayState != null)
            {
                var cookieName = "Kentor." + relayState;
                if (cookies.Any(c => c.Key == cookieName))
                {
                    var cookieData = cookies.SingleOrDefault(c => c.Key == cookieName).Value;

                    var unescapedBase64Data = cookieData
                        .Replace('_', '/')
                        .Replace('-', '+')
                        .Replace('.', '=');

                    CookieData = Encoding.UTF8.GetString(cookieDecryptor(
                        Convert.FromBase64String(unescapedBase64Data)));
                }
            }
        }
        ///<summary>Reads a SchemaMapping from an XML element.</summary>
        ///<param name="xml">An XML element created by <see cref="SchemaMapping.ToXml"/>.</param>
        ///<param name="schemas">The schema mapped by the mapping.</param>
        public static SchemaMapping FromXml(XElement xml, IEnumerable<TableSchema> schemas)
        {
            if (xml == null) throw new ArgumentNullException("xml");
            if (schemas == null) throw new ArgumentNullException("schemas");

            var schemaName = xml.Attribute("SchemaName").Value;
            var schema = schemas.SingleOrDefault(ts => ts.Name == schemaName);
            if (schema == null)
                throw new ArgumentException("Schema '" + schemaName + "' not found", "schemas");

            var retVal = new SchemaMapping(schema, false);

            retVal.SqlName = xml.Attribute("SqlName").Value;

            if (xml.Attribute("SqlSchemaName") != null)
                retVal.SqlSchemaName = xml.Attribute("SqlSchemaName").Value;

            foreach (var cm in xml.Elements("ColumnMapping")) {
                retVal.Columns.AddMapping(
                    schema.Columns[cm.Attribute("ColumnName").Value],
                    cm.Attribute("SqlName").Value
                );
            }
            return retVal;
        }
        public BlogPartHandler(IRepository<BlogPartRecord> repository, IWorkContextAccessor workContextAccessor, IEnumerable<IHomePageProvider> homePageProviders, IBlogPathConstraint blogPathConstraint)
        {
            _workContextAccessor = workContextAccessor;
            _blogPathConstraint = blogPathConstraint;
            _routableHomePageProvider = homePageProviders.SingleOrDefault(p => p.GetProviderName() == RoutableHomePageProvider.Name);
            Filters.Add(StorageFilter.For(repository));

            Action<PublishContentContext, RoutePart> publishedHandler = (context, route) => {
                if (route.Is<BlogPart>()) {
                    if (route.ContentItem.Id != 0 && route.PromoteToHomePage)
                        _blogPathConstraint.AddPath("");
                }
                else if (route.ContentItem.Id != 0 && route.PromoteToHomePage) {
                    _blogPathConstraint.RemovePath("");
                }
            };

            OnPublished<RoutePart>(publishedHandler);
            OnUnpublished<RoutePart>(publishedHandler);

            OnGetDisplayShape<BlogPart>((context, blog) => {
                context.Shape.Description = blog.Description;
                context.Shape.PostCount = blog.PostCount;
            });
        }
Example #9
0
         MapValues(
             IEnumerable<SpecificationProperty> propertyTuples,
             IEnumerable<KeyValuePair<string, IEnumerable<string>>> options,
             Func<IEnumerable<string>, System.Type, bool, Maybe<object>> converter,
             StringComparer comparer)
 {
     var sequencesAndErrors = propertyTuples
         .Select(pt =>
             options.SingleOrDefault(
                     s =>
                     s.Key.MatchName(((OptionSpecification)pt.Specification).ShortName, ((OptionSpecification)pt.Specification).LongName, comparer))
                        .ToMaybe()
                        .Return(sequence =>
                             converter(sequence.Value, pt.Property.PropertyType, pt.Specification.ConversionType.IsScalar())
                             .Return(converted =>
                                     Tuple.Create(
                                         pt.WithValue(Maybe.Just(converted)),
                                         Maybe.Nothing<Error>()),
                                     Tuple.Create<SpecificationProperty, Maybe<Error>>(
                                         pt,
                                         Maybe.Just<Error>(new BadFormatConversionError(NameInfo.FromOptionSpecification((OptionSpecification)pt.Specification))))),
                         Tuple.Create(pt, Maybe.Nothing<Error>()))
         );
     return StatePair.Create(
         sequencesAndErrors.Select(se => se.Item1),
         sequencesAndErrors.Select(se => se.Item2).OfType<Just<Error>>().Select(se => se.Value));
 }
Example #10
0
        public Message(
			Guid id,
			string name,
			string description,
			Color backgroundColor,
			IEnumerable<IMessagePart> parts,
			EventHandlerCollection eventHandlerCollection = null)
        {
            name.ThrowIfNull("name");
            description.ThrowIfNull("description");
            parts.ThrowIfNull("parts");

            parts = parts.ToArray();

            IMessagePart question = parts.SingleOrDefault(arg => arg is MessageMananger);

            if (question != null && parts.Last() != question)
            {
                throw new ArgumentException("When a MessageQuestion is present, it must be the last part.", "parts");
            }

            _id = id;
            Name = name;
            Description = description;
            _backgroundColor = backgroundColor;
            _parts = parts;
            _eventHandlerCollection = eventHandlerCollection;
        }
Example #11
0
		public virtual void Compare (IEnumerable<XElement> source, IEnumerable<XElement> target)
		{
			removed.Clear ();
			modified.Clear ();

			foreach (var s in source) {
				SetContext (s);
				string sn = s.GetAttribute ("name");
				var t = target == null ? null : target.SingleOrDefault (x => x.GetAttribute ("name") == sn);
				if (t == null) {
					// not in target, it was removed
					removed.Add (s);
				} else {
					t.Remove ();
					// possibly modified
					if (Equals (s, t, modified))
						continue;

					// still in target so will be part of Added
					Modified (s, t, modified);
				}
			}
			// delayed, that way we show "Modified", "Added" and then "Removed"
			foreach (var item in removed) {
				SetContext (item);
				Removed (item);
			}
			// remaining == newly added in target
			if (target != null) {
				foreach (var item in target) {
					SetContext (item);
					Added (item, false);
				}
			}
		}
        protected override IEnumerable<ICommandFilter> BuildFilters(IEnumerable<CaptionFilter> filters)
        {
            yield return new CommandFilter(string.Format("[cube_name]='{0}'"
                                                           , filters.Single(f => f.Target == Target.Perspectives).Caption
                                                           ));

            var filter = filters.SingleOrDefault(f => f.Target == Target.Sets);
            if (filter != null)
                yield return new CommandFilter(string.Format("[set_caption]='{0}'"
                                                           , filter.Caption
                                                           ));

            var dfFilter = filters.SingleOrDefault(f => f.Target == Target.DisplayFolders);
            if (dfFilter != null)
                yield return new DisplayFolder(dfFilter.Caption);
        }
        protected override IEnumerable<ICommandFilter> BuildFilters(IEnumerable<CaptionFilter> filters)
        {
            yield return new CommandFilter("left(table_name,1)<>'$'");

            var filter = filters.SingleOrDefault(f => f.Target == Target.Perspectives);
            if (filter != null)
                yield return new CommandFilter(string.Format("[table_schema]='{0}'"
                                                            , filter.Caption
                                                            ));

            filter = filters.SingleOrDefault(f => f.Target == Target.Tables);
            if (filter != null)
                yield return new CommandFilter(string.Format("[table_name]='{0}'"
                                                           , filter.Caption
                                                           ));
        }
        public static JwtSecurityToken CreateToken(IEnumerable<Claim> claims, string secretKey, string audience, string issuer, TimeSpan? lifetime)
        {
            if (claims == null)
            {
                throw new ArgumentNullException("claims");
            }

            if (lifetime != null && lifetime < TimeSpan.Zero)
            {
                string msg = CommonResources.ArgMustBeGreaterThanOrEqualTo.FormatForUser(TimeSpan.Zero);
                throw new ArgumentOutOfRangeException("lifetime", lifetime, msg);
            }

            if (string.IsNullOrEmpty(secretKey))
            {
                throw new ArgumentNullException("secretKey");
            }

            if (claims.SingleOrDefault(c => c.Type == JwtRegisteredClaimNames.Sub) == null)
            {
                throw new ArgumentOutOfRangeException("claims", LoginResources.CreateToken_SubjectRequired);
            }

            // add the claims passed in
            Collection<Claim> finalClaims = new Collection<Claim>();
            foreach (Claim claim in claims)
            {
                finalClaims.Add(claim);
            }

            // add our standard claims
            finalClaims.Add(new Claim("ver", "3"));

            return CreateTokenFromClaims(finalClaims, secretKey, audience, issuer, lifetime);
        }
Example #15
0
        public static List GetList(IEnumerable<List> listCollection, string listName, bool breakIfNull = true)
        {
            var retVal = listCollection.SingleOrDefault(l => l.RootFolder.Name == listName);
            if (retVal == null && breakIfNull)
                throw new Exception(String.Format("List {0} not found", listName));

            return retVal;
        }
Example #16
0
 public static Maybe<char> WithSeparator(string name, IEnumerable<OptionSpecification> specifications,
     StringComparer comparer)
 {
     return specifications.SingleOrDefault(
         a => name.MatchName(a.ShortName, a.LongName, comparer) && a.Separator != '\0')
         .ToMaybe()
         .Return(spec => Maybe.Just(spec.Separator), Maybe.Nothing<char>());
 }
        /// <summary>
        /// Resolves property ignoring casing
        /// </summary>
        /// <param name="type"></param>
        /// <param name="propertyName"></param>
        /// <returns></returns>
        internal string ResolveName(IEnumerable<PropertyInfo> properties, string propertyName)
        {
            if (properties == null) throw new ArgumentNullException("properties");

            var prop = properties.SingleOrDefault(p => p.Name.Equals(propertyName, StringComparison.OrdinalIgnoreCase));

            return prop != null ? prop.Name : propertyName;
        }
Example #18
0
 public static PropertyDescriptor GetReferenceProperty(PropertyDescriptor pd, IEnumerable<PropertyDescriptor> properties)
 {
     string refPropertyName = pd.Name + "Reference";
     return properties.SingleOrDefault<PropertyDescriptor>(delegate(PropertyDescriptor p)
     {
         return (p.Name == refPropertyName);
     });
 }
        public void Check(IEnumerable<IComponent> components, IStore<string, IArtificialIntelligence> aiStore)
        {
            var groupedByOwener = components.GroupBy(x => x.OwnerId);

            foreach (var group in groupedByOwener) {
                var enemies = components.Except(group).OfType<IFieldOfVision>();
                foreach (var component in group) {
                    foreach (var enemy in enemies) {
                        var isInFieldOfVision = enemy.IsInFieldOfVision(component.Position);
                        if (isInFieldOfVision) {
                            var artificialIntelligence = aiStore.Get(enemy.OwnerId);
                            artificialIntelligence.Fire(new ComponentSpottedEvent(enemy.OwnerId, enemy.Id, component.Id, component.OwnerId, component.Position.X, component.Position.Y, component.GetType()));
                            SpottedUnitsStore.Store(component.Id, enemy.OwnerId);
                        }
                    }
                }

            }

            //foreach (var group in groupedByOwener) {
            //    var others = components.Except(group).OfType<IFieldOfVision>();
            //    foreach (var component in group) {
            //        var spottingUnits = others.Where(x => x.IsInFieldOfVision(component.Position));

            //        foreach (var fieldOfVision in spottingUnits) {
            //            var artificialIntelligence = aiStore.Get(fieldOfVision.OwnerId);
            //            artificialIntelligence.Fire(new ComponentSpottedEvent(fieldOfVision.OwnerId,fieldOfVision.Id,component.Id,component.OwnerId,component.Position.X,component.Position.Y, component.GetType()));
            //            SpottedUnitsStore.Store(component.Id,fieldOfVision.OwnerId);
            //        }
            //    }
            //}

            var spottedUnits = SpottedUnitsStore.GetKeys();
            Parallel.ForEach(spottedUnits, (suid,loopState) =>
                                                    {
                                                        var spottedComponent = components.SingleOrDefault(x => x.Id.Equals(suid));
                                                        if(spottedComponent == null)
                                                        {
                                                            SpottedUnitsStore.Remove(suid);
                                                        }
                                                        else
                                                        {
                                                            var enemyOwnerId = SpottedUnitsStore.Get(suid);
                                                            if(enemyOwnerId == null)
                                                                return;
                                                                var enemyUnits =
                                                                components.Where(x => x.OwnerId.Equals(enemyOwnerId)).OfType<IFieldOfVision>();

                                                            if(enemyUnits.All(x => !x.IsInFieldOfVision(spottedComponent.Position)))
                                                            {
                                                                SpottedUnitsStore.Remove(spottedComponent.Id);
                                                                var artificialIntelligence = aiStore.Where(x => x.Id.Equals(enemyOwnerId)).First();
                                                                artificialIntelligence.Fire(new ComponentLeftFieldOfVisionEvent(artificialIntelligence.Id,spottedComponent.Id,spottedComponent.OwnerId,spottedComponent.Position.X,spottedComponent.Position.Y,spottedComponent.GetType()));
                                                            }

                                                        }
                                                    });
        }
Example #20
0
        public bool Do(Hero hero, IEnumerable<GameObject> objects)
        {
            var branch = objects.SingleOrDefault(o => o is Branch);
            var stone = objects.SingleOrDefault(ao => ao.Properties.Contains(Property.Cutter));

            if (branch == null || stone == null)
                return true;

            branch.RemoveFromContainer();
            var diggingStick = new DiggingStick();

            if (!hero.AddToBag(diggingStick))
            {
                Game.Map.SetHObjectFromDestination(hero.Position, diggingStick);
            }

            return true;
        }
        public IVirtualMachine Attach(IEnumerable<KeyValuePair<string, IConnectorArgument>> arguments)
        {
            var pid = (IConnectorIntegerArgument)arguments.Single(i => i.Key == "pid").Value;
            var sourcePaths = (IConnectorStringArgument)arguments.SingleOrDefault(i => i.Key == "sourcePaths").Value;

            VirtualMachine virtualMachine = VirtualMachine.BeginAttachToProcess(pid.Value, sourcePaths.StringValue.Split(';'));
            virtualMachine.AttachComplete += OnAttachComplete;
            return virtualMachine;
        }
        private static void AssertMemberType(DataType expectedType, IEnumerable<Binding> memberBindings, string key)
        {
            var binding = memberBindings.SingleOrDefault(x => x.Identifier == key);

            if (binding != null)
                binding.Type.ShouldEqual(expectedType);
            else
                throw new Exception("Failed to look up the type of '" + key + "' in the Scope");
        }
        protected virtual PropertyInfo GetInterfaceNamedStructureIdProperty(Type structureType, IEnumerable<PropertyInfo> properties)
        {
            if (!structureType.IsInterface)
                return null;

            var propertyName = StructureIdPropertyNames.GetInterfaceTypeNamePropertyNameFor(structureType);

            return properties.SingleOrDefault(p => p.Name.Equals(propertyName));
        }
        internal TableColumns( DBConnection cn, string table, bool forRevisionHistoryLogic )
        {
            try {
                // NOTE: Cache this result.
                AllColumns = Column.GetColumnsInQueryResults( cn, "SELECT * FROM " + table, true );

                foreach( var col in AllColumns ) {
                    // This hack allows code to be generated against a database that is configured for ASP.NET Application Services.
                    var isAspNetApplicationServicesTable = table.StartsWith( "aspnet_" );

                    if( !( cn.DatabaseInfo is OracleInfo ) && col.DataTypeName == typeof( string ).ToString() && col.AllowsNull && !isAspNetApplicationServicesTable )
                        throw new UserCorrectableException( "String column " + col.Name + " allows null, which is not allowed." );
                }

                // Identify key, identity, and non identity columns.
                var nonIdentityColumns = new List<Column>();
                foreach( var col in AllColumns ) {
                    if( col.IsKey )
                        keyColumns.Add( col );
                    if( col.IsIdentity ) {
                        if( identityColumn != null )
                            throw new UserCorrectableException( "Only one identity column per table is supported." );
                        identityColumn = col;
                    }
                    else
                        nonIdentityColumns.Add( col );
                }
                if( !keyColumns.Any() )
                    throw new UserCorrectableException( "The table must contain a primary key or other means of uniquely identifying a row." );

                // If the table has a composite key, try to use the identity as the key instead since this will enable InsertRow to return a value.
                if( identityColumn != null && keyColumns.Count > 1 ) {
                    keyColumns.Clear();
                    keyColumns.Add( identityColumn );
                }

                RowVersionColumn = AllColumns.SingleOrDefault( i => i.IsRowVersion );
                AllColumnsExceptRowVersion = AllColumns.Where( i => !i.IsRowVersion ).ToArray();
                AllNonIdentityColumnsExceptRowVersion = nonIdentityColumns.Where( i => !i.IsRowVersion ).ToArray();

                if( forRevisionHistoryLogic ) {
                    if( keyColumns.Count != 1 ) {
                        throw new UserCorrectableException(
                            "A revision history modification class can only be created for tables with exactly one primary key column, which is assumed to also be a foreign key to the revisions table." );
                    }
                    primaryKeyAndRevisionIdColumn = keyColumns.Single();
                    if( primaryKeyAndRevisionIdColumn.IsIdentity )
                        throw new UserCorrectableException( "The revision ID column of a revision history table must not be an identity." );
                }

                dataColumns = AllColumns.Where( col => !col.IsIdentity && !col.IsRowVersion && col != primaryKeyAndRevisionIdColumn ).ToArray();
            }
            catch( Exception e ) {
                throw UserCorrectableException.CreateSecondaryException( "An exception occurred while getting columns for table " + table + ".", e );
            }
        }
		public static void Equal(IEnumerable<IdentityClaim> expected, IEnumerable<IdentityClaim> actual)
		{
			Assert.True((expected == null && actual == null) || (expected != null && actual != null));
			Assert.Equal(expected.Count(), actual.Count());

			foreach(var e in expected)
			{
				Assert.True(actual.SingleOrDefault(a => a.ClaimType == e.ClaimType && a.ClaimValue == e.ClaimValue) != null);
			}
		}
Example #26
0
        public bool Do(Hero hero, IEnumerable<GameObject> objects)
        {
            var branch = objects.SingleOrDefault(o => o is Branch);
            var stone = objects.SingleOrDefault(o => o is Rock);

            if (branch == null || stone == null)
                return true;

            branch.RemoveFromContainer();
            stone.RemoveFromContainer();
            var axe = new StoneAxe();

            if (!hero.AddToBag(axe))
            {
                Game.Map.SetHObjectFromDestination(hero.Position, axe);
            }

            return true;
        }
		public static void Equal(IEnumerable<IdentityUserLogin> expected, IEnumerable<IdentityUserLogin> actual)
		{
			Assert.True((expected == null && actual == null) || (expected != null && actual != null));
			Assert.Equal(expected.Count(), actual.Count());

			foreach (var e in expected)
			{
				Assert.True(actual.SingleOrDefault(a => a.LoginProvider == e.LoginProvider && a.ProviderKey == e.ProviderKey && a.ProviderDisplayName == e.ProviderDisplayName) != null);
			}
		}
        private static void Generate(
            IEnumerable<TableDefinition> tableDefinitions,
            ProjectItem mappingsProjectItem,
            string templatePath)
        {            
            // Create mapping files
            foreach (var tableDefinition in tableDefinitions)
            {
                var mappingFileName = TableDefinitionHelper.GetMappingFileName(tableDefinition) + ".cs";
                mappingsProjectItem.ProjectItems.AddFromTemplate(templatePath, mappingFileName);
            }

            // Add mapping instructions
            foreach (ProjectItem projectItem in mappingsProjectItem.ProjectItems)
            {
                var name = projectItem.Name;
                var tableDefinition = tableDefinitions.SingleOrDefault(t => TableDefinitionHelper.GetMappingFileName(t) + ".cs" == name);
                var codeNamespace = CodeModelHelper.GetNameSpaceFromFileCode(projectItem.FileCodeModel);
                var fullNamespace = codeNamespace.FullName.Replace(NamespaceValues.Mappings, NamespaceValues.Models);

                // Add the import instructions.
                var fileCodeModel = (FileCodeModel2)projectItem.FileCodeModel;
                fileCodeModel.AddImport(fullNamespace);
                fileCodeModel.AddImport(NamespaceValues.OrmMappings);

                // Add inheritance to BaseMapping.
                var cls = CodeModelHelper.GetCodeClassFromFileCode(projectItem.FileCodeModel);
                cls.Access = vsCMAccess.vsCMAccessPublic;
                var fullyQualifiedName = string.Format("BaseMapping<{0}>", tableDefinition.TableName);
                cls.AddBase(fullyQualifiedName);

                // Modify the constructor
                cls.AddFunction(TableDefinitionHelper.GetMappingFileName(tableDefinition),
                    vsCMFunction.vsCMFunctionConstructor,
                    null,
                    -1,
                    vsCMAccess.vsCMAccessPublic, null);
                var constructor = (CodeFunction)cls.Children.Item(1);
                var startPoint = constructor.GetStartPoint(vsCMPart.vsCMPartBody).CreateEditPoint();
                startPoint.StartOfLine();
                startPoint.Indent();
                startPoint.Insert("ToTable(\"" + tableDefinition.TableSchema + "." + tableDefinition.TableName + "\"); \n");

                foreach (var columnDefinition in tableDefinition.ColumnDefinitions)
                {
                    var statement = "Property(t => t." + columnDefinition.ColumnName + ").HasColumnName(\"" +
                                    columnDefinition.ColumnName + "\"); \n";
                    startPoint.Indent(Count: 3);
                    startPoint.Insert(statement);
                }

                startPoint.EndOfLine();
                startPoint.Indent(Count: 2);
            }
        }
        private IElement CreateElement(RenderContext renderContext, XmlNode currentNode, IEnumerable<Type> availableTypes)
        {
            var nodeName = currentNode.LocalName;
            Type controlType = availableTypes.SingleOrDefault(a => a.GetCustomAttributes(typeof(ElementNameAttribute), false).Cast<ElementNameAttribute>().Any(c => c.ElementName.Equals(nodeName)));

            if (controlType == null)
            {
                throw new ControlNotSupportedException($"Control {nodeName} is not supported.");
            }

            IElement element = (IElement)Activator.CreateInstance(controlType, renderContext);

            foreach(XmlAttribute attribute in currentNode.Attributes)
            {
                // skip namespaced attributes, they belong to other implementations.
                if (attribute.Name.Contains(":"))
                    continue;

               PropertyInfo property = controlType.GetProperties().SingleOrDefault(p => p.GetCustomAttributes(typeof(AttributeNameAttribute), false).Cast<AttributeNameAttribute>().Any(c => c.Name.Equals(attribute.Name)));

                if (property != null)
                {
                    if (property.PropertyType == typeof(Boolean))
                    {
                        property.SetValue(element, Boolean.Parse(attribute.Value));
                    }
                    else
                    {
                        property.SetValue(element, attribute.Value);
                    }
                    
                }
                else
                {
                    throw new AttributeNotSupportedException($"Control {nodeName} is does not support attribute {attribute.Name}.");
                }
            }

            IElementContainer container = element as IElementContainer;

            if (container != null)
            {
                var childNodes = currentNode.ChildNodes;

                foreach (XmlNode node in childNodes)
                {
                    container.Elements.Add(CreateElement(renderContext, node, availableTypes));
                }

                return container;
            }

            return element;
            
        }          
Example #30
0
        public Story ParseBlocks(IEnumerable<Block> blocks)
        {
            // get the story
            var storyBlock = blocks.SingleOrDefault(b => b.Type == BlockType.Story);
            if(storyBlock == null) throw new FicdownException("No story block found");

            Anchor storyAnchor;
            try
            {
                storyAnchor = Utilities.GetInstance(storyBlock.Name, storyBlock.LineNumber).ParseAnchor(storyBlock.Name);
            }
            catch(FicdownException ex)
            {
                throw new FicdownException(ex.BlockName, ex.LineNumber, "Story block must be an anchor pointing to the first scene");
            }

            if (storyAnchor.Href.Target == null || storyAnchor.Href.Conditions != null ||
                storyAnchor.Href.Toggles != null)
                throw new FicdownException(storyBlock.Name, storyBlock.LineNumber, "Story href should only have target");

            var story = new Story
            {
                Name = storyAnchor.Text,
                Description = string.Join("\n", storyBlock.Lines.Select(l => l.Text)).Trim(),
                Scenes = new Dictionary<string, IList<Scene>>(),
                Actions = new Dictionary<string, Action>()
            };

            var sid = 1;
            var scenes = blocks.Where(b => b.Type == BlockType.Scene).Select(b => BlockToScene(b, sid++));
            foreach (var scene in scenes)
            {
                if (!story.Scenes.ContainsKey(scene.Key)) story.Scenes.Add(scene.Key, new List<Scene>());
                story.Scenes[scene.Key].Add(scene);
            }
            var aid = 1;
            try
            {
                story.Actions =
                    blocks.Where(b => b.Type == BlockType.Action).Select(b => BlockToAction(b, aid++)).ToDictionary(a => a.Toggle, a => a);
            }
            catch(ArgumentException)
            {
                var a = blocks.First(b => b.Type == BlockType.Action && blocks.Any(d => b != d && BlockToAction(b, 0).Toggle == BlockToAction(d, 0).Toggle));
                var actionA = BlockToAction(a, a.LineNumber);
                var dupe = blocks.First(b => b.Type == BlockType.Action && b != a && BlockToAction(b, 0).Toggle == actionA.Toggle);
                throw new FicdownException(actionA.Toggle, actionA.LineNumber, string.Format("Action is defined again on line {0}", dupe.LineNumber));
            }

            if (!story.Scenes.ContainsKey(storyAnchor.Href.Target))
                throw new FicdownException(storyBlock.Name, storyBlock.LineNumber, string.Format("Story targets non-existent scene: {0}", storyAnchor.Href.Target));
            story.FirstScene = storyAnchor.Href.Target;

            return story;
        }