public void Add(Type serviceType, Type requestType, Type responseType)
        {
            this.ServiceTypes.Add(serviceType);
            this.RequestTypes.Add(requestType);

            var restrictTo = requestType.FirstAttribute<RestrictAttribute>()
                          ?? serviceType.FirstAttribute<RestrictAttribute>();

            var operation = new Operation {
                ServiceType = serviceType,
                RequestType = requestType,
                ResponseType = responseType,
                RestrictTo = restrictTo,
                Actions = GetImplementedActions(serviceType, requestType),
                Routes = new List<RestPath>(),
            };

			this.OperationsMap[requestType] = operation;
			this.OperationNamesMap[operation.Name.ToLower()] = operation;
			//this.OperationNamesMap[requestType.Name.ToLower()] = operation;
			if (responseType != null)
			{
				this.ResponseTypes.Add(responseType);
				this.OperationsResponseMap[responseType] = operation;
			}

            //Only count non-core ServiceStack Services, i.e. defined outside of ServiceStack.dll or Swagger
            var nonCoreServicesCount = OperationsMap.Values
                .Count(x => x.ServiceType.Assembly != typeof(Service).Assembly
                && x.ServiceType.FullName != "ServiceStack.Api.Swagger.SwaggerApiService"
                && x.ServiceType.FullName != "ServiceStack.Api.Swagger.SwaggerResourcesService"
                && x.ServiceType.Name != "__AutoQueryServices");

            LicenseUtils.AssertValidUsage(LicenseFeature.ServiceStack, QuotaType.Operations, nonCoreServicesCount);
        }
        public void Add(Type serviceType, Type requestType, Type responseType)
        {
            this.ServiceTypes.Add(serviceType);
            this.RequestTypes.Add(requestType);

            var restrictTo = requestType.FirstAttribute<RestrictAttribute>()
                          ?? serviceType.FirstAttribute<RestrictAttribute>();

            var operation = new Operation {
                ServiceType = serviceType,
                RequestType = requestType,
                ResponseType = responseType,
                RestrictTo = restrictTo,
                Actions = GetImplementedActions(serviceType, requestType),
                Routes = new List<RestPath>(),
            };

			this.OperationsMap[requestType] = operation;
			this.OperationNamesMap[operation.Name.ToLower()] = operation;
			//this.OperationNamesMap[requestType.Name.ToLower()] = operation;
			if (responseType != null)
			{
				this.ResponseTypes.Add(responseType);
				this.OperationsResponseMap[responseType] = operation;
			}


            LicenseUtils.AssertValidUsage(LicenseFeature.ServiceStack, QuotaType.Operations, OperationsMap.Count);
        }
        public void Add(Type serviceType, Type requestType, Type responseType)
        {
            this.ServiceTypes.Add(serviceType);
            this.RequestTypes.Add(requestType);

            var restrictTo = requestType.FirstAttribute<RestrictAttribute>()
                          ?? serviceType.FirstAttribute<RestrictAttribute>();

            var operation = new Operation {
                ServiceType = serviceType,
                RequestType = requestType,
                ResponseType = responseType,
                RestrictTo = restrictTo,
                Actions = GetImplementedActions(serviceType, requestType),
                Routes = new List<RestPath>(),
            };

            this.OperationsMap[requestType] = operation;
            this.OperationNamesMap[requestType.Name.ToLower()] = operation;

            if (responseType != null)
            {
                this.ResponseTypes.Add(responseType);
                this.OperationsResponseMap[responseType] = operation;
            }
        }
        public void Add(Type serviceType, Type requestType, Type responseType)
        {
            this.ServiceTypes.Add(serviceType);
            this.RequestTypes.Add(requestType);

            var restrictTo = requestType.FirstAttribute<RestrictAttribute>()
                          ?? serviceType.FirstAttribute<RestrictAttribute>();


            var reqFilterAttrs = new[] { requestType, serviceType }
                .SelectMany(x => x.AllAttributes<IHasRequestFilter>()).ToList();
            var resFilterAttrs = (responseType != null ? new[] { responseType, serviceType } : new[] { serviceType })
                .SelectMany(x => x.AllAttributes<IHasResponseFilter>()).ToList();

            var authAttrs = reqFilterAttrs.OfType<AuthenticateAttribute>().ToList();
            var actions = GetImplementedActions(serviceType, requestType);
            authAttrs.AddRange(actions.SelectMany(x => x.AllAttributes<AuthenticateAttribute>()));

            var operation = new Operation
            {
                ServiceType = serviceType,
                RequestType = requestType,
                ResponseType = responseType,
                RestrictTo = restrictTo,
                Actions = actions.Map(x => x.Name.ToUpper()),
                Routes = new List<RestPath>(),
                RequestFilterAttributes = reqFilterAttrs,
                ResponseFilterAttributes = resFilterAttrs,
                RequiresAuthentication = authAttrs.Count > 0,
                RequiredRoles = authAttrs.OfType<RequiredRoleAttribute>().SelectMany(x => x.RequiredRoles).ToList(),
                RequiresAnyRole = authAttrs.OfType<RequiresAnyRoleAttribute>().SelectMany(x => x.RequiredRoles).ToList(),
                RequiredPermissions = authAttrs.OfType<RequiredPermissionAttribute>().SelectMany(x => x.RequiredPermissions).ToList(),
                RequiresAnyPermission = authAttrs.OfType<RequiresAnyPermissionAttribute>().SelectMany(x => x.RequiredPermissions).ToList(),
            };

            this.OperationsMap[requestType] = operation;
            this.OperationNamesMap[operation.Name.ToLower()] = operation;
            if (responseType != null)
            {
                this.ResponseTypes.Add(responseType);
                this.OperationsResponseMap[responseType] = operation;
            }

            //Only count non-core ServiceStack Services, i.e. defined outside of ServiceStack.dll or Swagger
            var nonCoreServicesCount = OperationsMap.Values
                .Count(x => x.ServiceType.Assembly != typeof(Service).Assembly
                && x.ServiceType.FullName != "ServiceStack.Api.Swagger.SwaggerApiService"
                && x.ServiceType.FullName != "ServiceStack.Api.Swagger.SwaggerResourcesService"
                && x.ServiceType.Name != "__AutoQueryServices");

            LicenseUtils.AssertValidUsage(LicenseFeature.ServiceStack, QuotaType.Operations, nonCoreServicesCount);
        }
        public static TableDefinition GetTableDefinition(Type modelType)
        {
            //Looks for PetaPoco's TableNameAtribute for the name of the table
            //If no attribute is set we use the name of the Type as the default convention
            var tableNameAttribute = modelType.FirstAttribute<TableNameAttribute>();
            string tableName = tableNameAttribute == null ? modelType.Name : tableNameAttribute.Value;

            var tableDefinition = new TableDefinition {Name = tableName};
            var objProperties = modelType.GetProperties().ToList();
            foreach (var propertyInfo in objProperties)
            {
                //If current property has an IgnoreAttribute then skip it
                var ignoreAttribute = propertyInfo.FirstAttribute<IgnoreAttribute>();
                if (ignoreAttribute != null) continue;

                //If current property has a ResultColumnAttribute then skip it
                var resultColumnAttribute = propertyInfo.FirstAttribute<ResultColumnAttribute>();
                if (resultColumnAttribute != null) continue;

                //Looks for ColumnAttribute with the name of the column, which would exist with ExplicitColumns
                //Otherwise use the name of the property itself as the default convention
                var columnAttribute = propertyInfo.FirstAttribute<ColumnAttribute>();
                string columnName = columnAttribute != null ? columnAttribute.Name : propertyInfo.Name;
                var columnDefinition = GetColumnDefinition(modelType, propertyInfo, columnName, tableName);
                tableDefinition.Columns.Add(columnDefinition);

                //Creates a foreignkey definition and adds it to the collection on the table definition
                var foreignKeyAttributes = propertyInfo.MultipleAttribute<ForeignKeyAttribute>();
                if (foreignKeyAttributes != null)
                {
                    foreach (var foreignKeyAttribute in foreignKeyAttributes)
                    {
                        var foreignKeyDefinition = GetForeignKeyDefinition(modelType, propertyInfo, foreignKeyAttribute, columnName, tableName);
                        tableDefinition.ForeignKeys.Add(foreignKeyDefinition);
                    }
                }

                //Creates an index definition and adds it to the collection on the table definition
                 var indexAttribute = propertyInfo.FirstAttribute<IndexAttribute>();
                 if (indexAttribute != null)
                 {
                     var indexDefinition = GetIndexDefinition(modelType, propertyInfo, indexAttribute, columnName, tableName);
                     tableDefinition.Indexes.Add(indexDefinition);
                 }
            }

            return tableDefinition;
        }
        public virtual RazorPage TrackPage(Type pageType)
        {
            var pageBaseType = this.Config.PageBaseType;
            var transformer = new RazorViewPageTransformer(pageBaseType);

            var pagePath = pageType.FirstAttribute<VirtualPathAttribute>().VirtualPath.TrimStart('~');
            var file = GetVirtualFile(pagePath);
            
            var page = new RazorPage
            {
                PageHost = file != null ? CreatePageHost(file, transformer) : null,
                PageType = pageType,
                IsValid = true,
                File = file,
                VirtualPath = pagePath,
            };

            AddPage(page, pagePath);
            return page;
        }
        public virtual RazorPage AddPage(Type pageType)
        {
            var virtualPathAttr = pageType.FirstAttribute<VirtualPathAttribute>();
            if (virtualPathAttr == null || !this.IsWatchedFile(virtualPathAttr.VirtualPath))
                return null;

            var pagePath = virtualPathAttr.VirtualPath.TrimStart('~');
            var page = GetPage(pagePath);
            if (page != null)
                return page;

            return TrackPage(pageType);
        }
        public static Lazy<IContentType> GetContentTypeDefinition(Type modelType)
        {
            //Check for BaseType different from ContentTypeBase
            bool hasParent = modelType.BaseType != null && modelType.BaseType != typeof(ContentTypeBase) && modelType.BaseType != typeof(object);
            var parent = new Lazy<IContentType>();
            if(hasParent)
            {
                var isResolved = _contentTypeCache.ContainsKey(modelType.BaseType.FullName);
                parent = isResolved
                             ? _contentTypeCache[modelType.BaseType.FullName].ContentType
                             : GetContentTypeDefinition(modelType.BaseType);
            }

            var contentTypeAttribute = modelType.FirstAttribute<ContentTypeAttribute>();
            var contentTypeAlias = contentTypeAttribute == null ? modelType.Name.ToUmbracoAlias() : contentTypeAttribute.Alias;
            //Check if ContentType already exists by looking it up by Alias.
            var existing = ApplicationContext.Current.Services.ContentTypeService.GetContentType(contentTypeAlias);
            
            Lazy<IContentType> contentType = contentTypeAttribute == null
                                                 ? PlainPocoConvention(modelType, existing)
                                                 : ContentTypeConvention(contentTypeAttribute, modelType, existing);

            //Check for interfaces that'll be used for ContentTypeComposition
            var mixins = GetAliasesFromTypeInterfaces(modelType);

            var definitions = new List<PropertyDefinition>();
            int order = 0;
            var objProperties = modelType.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly).ToList();
            foreach (var propertyInfo in objProperties)
            {
                var propertyTypeAttribute = propertyInfo.FirstAttribute<PropertyTypeConventionAttribute>();
                var definition = propertyTypeAttribute == null
                                     ? new PropertyDefinition()
                                     : propertyTypeAttribute.GetPropertyConvention();

                //DataTypeDefinition fallback
                if(definition.DataTypeDefinition == null)
                {
                    definition.DataTypeDefinition = Conventions.GetDataTypeDefinitionByAttributeOrType(null, propertyInfo.PropertyType);
                }

                if(string.IsNullOrEmpty(definition.PropertyGroup))
                {
                    definition.PropertyGroup = "Generic Properties";
                }

                //Alias fallback
                if (string.IsNullOrEmpty(definition.Alias))
                {
                    var aliasAttribute = propertyInfo.FirstAttribute<AliasAttribute>();
                    definition.Alias = Conventions.GetPropertyTypeAlias(aliasAttribute, propertyInfo.Name);
                    definition.Name = Conventions.GetPropertyTypeName(aliasAttribute, propertyInfo.Name);
                }

                //Description fallback
                if (string.IsNullOrEmpty(definition.Description))
                {
                    var descriptionAttribute = propertyInfo.FirstAttribute<DescriptionAttribute>();
                    definition.Description = descriptionAttribute != null
                                                 ? descriptionAttribute.Description
                                                 : string.Empty;
                }

                //SortOrder fallback
                if (definition.Order == default(int))
                {
                    var sortOrderAttribute = propertyInfo.FirstAttribute<SortOrderAttribute>();
                    definition.Order = sortOrderAttribute != null ? sortOrderAttribute.Order : order;
                }

                definitions.Add(definition);
                order++;
            }

            //Loop through definitions for PropertyGroups and create those that not already exists
            var groupDefinitions = definitions.DistinctBy(d => d.PropertyGroup);
            foreach (var groupDefinition in groupDefinitions)
            {
                var groupExists = contentType.Value.PropertyGroups.Contains(groupDefinition.PropertyGroup);
                if(groupExists == false)
                {
                    var propertyGroup = new PropertyGroup {Name = groupDefinition.PropertyGroup};
                    contentType.Value.PropertyGroups.Add(propertyGroup);
                }
            }

            //Loop through definitions for PropertyTypes and add them to the correct PropertyGroup
            foreach (var definition in definitions)
            {
                var group = contentType.Value.PropertyGroups.First(x => x.Name == definition.PropertyGroup);
                //Check if a PropertyType with the same alias already exists, as we don't want to override existing ones
                if(group.PropertyTypes.Contains(definition.Alias)) continue;

                var propertyType = new PropertyType(definition.DataTypeDefinition)
                                       {
                                           Mandatory = definition.Mandatory,
                                           ValidationRegExp = definition.ValidationRegExp,
                                           SortOrder = definition.Order,
                                           Alias = definition.Alias,
                                           Name = definition.Name
                                       };

                group.PropertyTypes.Add(propertyType);
            }

            //If current ContentType has a Parent the ParentId should be set and the ContentType added to the composition.
            if(hasParent)
            {
                contentType.Value.SetLazyParentId(new Lazy<int>(() => parent.Value.Id));
                contentType.Value.AddContentType(parent.Value);
            }
            //Add the resolved ContentType to the internal cache
            var field = new DependencyField {ContentType = contentType, Alias = contentType.Value.Alias};
            var dependencies = new List<string>();
            //If current type has a parent (inherited model) we add the alias of that type as a dependency
            if(hasParent)
            {
                dependencies.Add(parent.Value.Alias);
            }
            //Check ContentType for existing 'Allowed ContentTypes'
            if(contentType.Value.AllowedContentTypes.Any())
            {
                dependencies.AddRange(contentType.Value.AllowedContentTypes.Select(allowed => allowed.Alias));
            }
            //Check for interfaces with AliasAttribute and add those as dependencies 
            //NOTE: might also be an idea to check if ContentType has already been created/added to cache that implements the interface.
            if(mixins.Any())
            {
                foreach (var mixin in mixins)
                {
                    if(dependencies.Contains(mixin.Item1)) continue;

                    dependencies.Add(mixin.Item1);
                    var isMixinResolved = _contentTypeCache.ContainsKey(mixin.Item2);

                    Lazy<IContentType> compositionType = null;

                    if (isMixinResolved)
                    {
                        compositionType = _contentTypeCache[mixin.Item2].ContentType;
                    }
                    else
                    {
                        GetContentTypeDefinition(mixin.Item3);
                        compositionType = _contentTypeCache[mixin.Item2].ContentType;
                    }

                    contentType.Value.AddContentType(compositionType.Value);
                }
            }
            field.DependsOn = dependencies.ToArray();
            _contentTypeCache.AddOrUpdate(modelType.FullName, field, (x, y) => field);
            return contentType;
        }
        public virtual RazorPage TrackPage(Type pageType)
        {
            var pageBaseType = this.Config.PageBaseType;
            var transformer = new RazorViewPageTransformer(pageBaseType);

            var pagePath = pageType.FirstAttribute<VirtualPathAttribute>().VirtualPath.TrimStart('~');
            var file = GetVirtualFile(pagePath);
            
            var page = new RazorPage
            {
                PageHost = file != null ? new RazorPageHost(PathProvider, file, transformer, new CSharpCodeProvider(), new Dictionary<string, string>()) : null,
                PageType = pageType,
                IsValid = true,
                File = file,
                VirtualPath = pagePath,
            };

            AddPage(page, pagePath);
            return page;
        }
 private static string GetNamespace(Type type)
 {
     var attr = type.FirstAttribute<SchemaAttribute>();
     return attr != null ? attr.Name : type.Namespace;
 }
 /// <summary>
 /// Gets the namespace from an attribute marked on the type's definition
 /// </summary>
 /// <param name="type"></param>
 /// <returns>Namespace of type</returns>
 public static string GetNamespace(Type type)
 {
     var dcAttr = type.FirstAttribute<DataContractAttribute>();
     if (dcAttr != null)
     {
         return dcAttr.Namespace;
     }
     var xrAttr = type.FirstAttribute<XmlRootAttribute>();
     if (xrAttr != null)
     {
         return xrAttr.Namespace;
     }
     var xtAttr = type.FirstAttribute<XmlTypeAttribute>();
     if (xtAttr != null)
     {
         return xtAttr.Namespace;
     }
     var xeAttr = type.FirstAttribute<XmlElementAttribute>();
     if (xeAttr != null)
     {
         return xeAttr.Namespace;
     }
     return null;
 }
Beispiel #12
0
 public virtual RazorPage TrackPage(Type pageType)
 {
     var pagePath = pageType.FirstAttribute<VirtualPathAttribute>().VirtualPath.TrimStart('~');
     var page = new RazorPage { PageType = pageType, IsValid = true };
     
     AddPage(page, pagePath);
     return page;
 }
Beispiel #13
0
        public virtual RazorPage AddPage(Type pageType)
        {
            var virtualPathAttr = pageType.FirstAttribute<VirtualPathAttribute>();
            if (virtualPathAttr == null || !this.IsWatchedFile(virtualPathAttr.VirtualPath))
                return null;

            var pagePath = virtualPathAttr.VirtualPath.TrimStart('~');
            RazorPage page;
            if (this.Pages.TryGetValue(GetDictionaryPagePath(pagePath), out page)) 
                return page;

            return TrackPage(pageType);
        }
        public override string ToCreateTableStatement(Type tableType)
        {
            var sbColumns = StringBuilderCache.Allocate();
            var sbConstraints = StringBuilderCacheAlt.Allocate();
            var sbMemOptimized = StringBuilderCacheAlt.Allocate();

            var isMemoryTable = tableType.HasAttribute<SqlServerMemoryOptimizedAttribute>();

            var modelDef = OrmLiteUtils.GetModelDefinition(tableType);
            foreach (var fieldDef in modelDef.FieldDefinitions)
            {
                if (fieldDef.CustomSelect != null)
                    continue;

                var columnDefinition = GetColumnDefinition(fieldDef);
                if (columnDefinition == null)
                    continue;

                var collationAttribs = fieldDef.PropertyInfo.GetAttributes<SqlServerCollateAttribute>();
                if (collationAttribs.Count > 0)
                {
                    columnDefinition += $" COLLATE {collationAttribs[0].Collation}";
                }

                if (isMemoryTable && fieldDef.IsPrimaryKey)
                {
                    columnDefinition = columnDefinition.Replace("PRIMARY KEY", "PRIMARY KEY NONCLUSTERED");

                    var bucketCountAtribs = fieldDef.PropertyInfo.GetAttributes<SqlServerBucketCountAttribute>();
                    if (bucketCountAtribs.Count > 0)
                    {
                        columnDefinition += $" HASH WITH (BUCKET_COUNT={bucketCountAtribs[0].Count})";
                    }
                }

                if (sbColumns.Length != 0)
                    sbColumns.Append(", \n  ");

                sbColumns.Append(columnDefinition);

                if (fieldDef.ForeignKey == null || OrmLiteConfig.SkipForeignKeys)
                    continue;

                var refModelDef = OrmLiteUtils.GetModelDefinition(fieldDef.ForeignKey.ReferenceType);
                sbConstraints.Append(
                    $", \n\n  CONSTRAINT {GetQuotedName(fieldDef.ForeignKey.GetForeignKeyName(modelDef, refModelDef, NamingStrategy, fieldDef))} " +
                    $"FOREIGN KEY ({GetQuotedColumnName(fieldDef.FieldName)}) " +
                    $"REFERENCES {GetQuotedTableName(refModelDef)} ({GetQuotedColumnName(refModelDef.PrimaryKey.FieldName)})");

                sbConstraints.Append(GetForeignKeyOnDeleteClause(fieldDef.ForeignKey));
                sbConstraints.Append(GetForeignKeyOnUpdateClause(fieldDef.ForeignKey));
            }

            if (isMemoryTable)
            {
                var attrib = tableType.FirstAttribute<SqlServerMemoryOptimizedAttribute>();
                sbMemOptimized.Append(" WITH (MEMORY_OPTIMIZED=ON");
                if (attrib.Durability == SqlServerDurability.SchemaOnly)
                    sbMemOptimized.Append(", DURABILITY=SCHEMA_ONLY");
                else if (attrib.Durability == SqlServerDurability.SchemaAndData)
                    sbMemOptimized.Append(", DURABILITY=SCHEMA_AND_DATA");
                sbMemOptimized.Append(")");
            }

            var sql = $"CREATE TABLE {GetQuotedTableName(modelDef)} " +
                      $"\n(\n  {StringBuilderCache.ReturnAndFree(sbColumns)}{StringBuilderCacheAlt.ReturnAndFree(sbConstraints)} \n){StringBuilderCache.ReturnAndFree(sbMemOptimized)}; \n";

            return sql;
        }