public AspNetWindowsAuthProvider(IAppHost appHost) { Provider = Name; AuthRealm = Realm; AllRoles = new List<string>(); LimitAccessToRoles = new List<string>(); if (!(appHost is AppHostBase)) { throw new NotSupportedException( "AspNetWindowsAuthProvider is only supported on ASP.NET hosts"); } //Add all pre-defined Roles used to in App to 'AllRoles' appHost.AfterInitCallbacks.Add(host => { var requiredRoles = host.Metadata.OperationsMap .SelectMany(x => x.Key.AllAttributes<RequiredRoleAttribute>() .Concat(x.Value.ServiceType.AllAttributes<RequiredRoleAttribute>())) .SelectMany(x => x.RequiredRoles); requiredRoles.Each(x => AllRoles.AddIfNotExists(x)); }); }
public static void NewMessage(int id, string href, string userId) { using (var db = new ApplicationDbContext()) { var ft = db.tForumMessages.Find(id); var t = new tNotification { tNotificationType = db.tNotificationType.Find(3), tNotification_date = System.DateTime.Now, tNotification_IsRead = false, tNotification_message = "Новое сообщение на форуме " + ft.tForumThemes.tForumList.tForumList_name + " в разделе " + "\"" + ft.tForumThemes.tForumThemes_name + "\"", tNotification_href = href }; //Отсылаем модераторам foreach (var item2 in db.Roles.Where(a => a.Name == "moderator").SelectMany(item => item.Users.Where(a => a.UserId != userId))) { t.tUsers = db.Users.Find(item2.UserId); db.tNotification.Add(t); db.SaveChanges(); } foreach (var item in ft.tForumThemes.tForumMessages.Select(a => a.tUsers).Distinct().Where(a => a.Id != userId).Where(item => !db.tNotification.Where(a => a.tUsers.Id == item.Id) .Any(a => a.tNotification_href == t.tNotification_href))) { t.tUsers = db.Users.Find(item.Id); db.tNotification.Add(t); db.SaveChanges(); } //а теперь отошлем email var emList = new List<string>(); var emailList = ft.tForumThemes.tForumMessages; var roleId = db.Roles.First(a => a.Name == "user").Id; foreach (var item in emailList.Where(a => a.tUsers.Id != userId).Where(a => a.tUsers.Roles.Any(b=> b.RoleId == roleId))) { emList.AddIfNotExists(item.tUsers.Email); } if (emList.Count() != 0) { var mm = new MailMessage { IsBodyHtml = true, Body = "<h4>Форум Талисман-SQL</h4>" + "Появилось новоое сообщение на форуме " + ft.tForumThemes.tForumList.tForumList_name + " в разделе " + ft.tForumThemes.tForumThemes_name + "<p>" + href + "</p>", Subject = "Новое сообщение на форуме Talisman-SQL" }; foreach (var item in emList) { mm.To.Add(item); } Code.Mail.SendEmail(mm); } db.Dispose(); } }
/* -> eq (equals any) -> neq (not equals any) -> eqc (equals any, case insensitive [on a case sensitive database]) -> neqc (not equals any, case insensitive [on a case sensitive database]) -> in (same as eq) -> nin (same as ne) -> lk (like) -> nlk (not like) -> nl (null) -> nnl (not null) -> gt (greater than) -> gte (greater than or equal to) -> lt (less than) -> lte (less than or equal to) -> ct (full text contains) -> ft (full text free text) -> bt (between) -> nbt (not between) */ private static IPredicate BuildPredicateFromClauseNode(Func<string, IEntityField2> fieldGetter, Func<string, List<IEntityRelation>, IEntityField2> relatedFieldGetter, FilterNode filterNode, List<IEntityRelation> inferredRelationsList) { // there are always at least 2 elements if (filterNode.ElementCount < 2) return null; var elements = filterNode.Elements; //TODO: may need to mess with relation aliases and join types in the future var relations = new List<IEntityRelation>(); var field = elements[0].IndexOf('.') == -1 ? fieldGetter(elements[0]) : relatedFieldGetter(elements[0], relations); if (field == null) throw new ArgumentNullException("Unable to locate field " + elements[0]); foreach (var relation in relations) inferredRelationsList.AddIfNotExists(relation); var comparisonOperatorStr = elements[1].ToLowerInvariant(); var valueElements = elements.Skip(2).ToArray(); var objElements = new object[valueElements.Length]; Action<string> throwINEEx = (s) => { throw new ArgumentException(string.Format("Invalid number of elements in '{0}' filter clause", s)); }; string objAlias; IPredicate predicate; switch (comparisonOperatorStr) { case ("bt"): //between case ("nbt"): //not between if (valueElements.Length < 2) throwINEEx(comparisonOperatorStr); objElements[0] = ConvertStringToFieldValue(field, valueElements[0]); objElements[1] = ConvertStringToFieldValue(field, valueElements[1]); objAlias = valueElements.Length == 3 ? valueElements[2] : null; predicate = new FieldBetweenPredicate(field, null, objElements[0], objElements[1], objAlias, comparisonOperatorStr == "nbt"); break; case ("in"): //same as eq case ("nin"): //same as ne case ("eq"): //equals any case ("neq"): //not equals any case ("eqc"): //equals any, case insensitive [on a case sensitive database] - only 1 element per clause with this option case ("neqc"): //not equals any, case insensitive [on a case sensitive database] - only 1 element per clause with this option if (valueElements.Length < 1) throwINEEx(comparisonOperatorStr); for (int i = 0; i < valueElements.Length; i++) objElements[i] = ConvertStringToFieldValue(field, valueElements[i]); if (objElements.Length == 1 || comparisonOperatorStr == "eqci" || comparisonOperatorStr == "neci") { predicate = new FieldCompareValuePredicate(field, null, comparisonOperatorStr.StartsWith("n") ? ComparisonOperator.NotEqual : ComparisonOperator.Equal, objElements[0]) { CaseSensitiveCollation = comparisonOperatorStr == "eqci" || comparisonOperatorStr == "neci" }; } else { if (comparisonOperatorStr.StartsWith("n")) predicate = (EntityField2)field != objElements; else predicate = (EntityField2)field == objElements; } break; case ("lk"): //like case ("nlk"): //not like if (valueElements.Length < 1) throwINEEx(comparisonOperatorStr); objElements[0] = ConvertStringToFieldValue(field, valueElements[0].Replace('*', '%')); objAlias = valueElements.Length == 2 ? valueElements[1] : null; predicate = new FieldLikePredicate(field, null, objAlias, (string)objElements[0], comparisonOperatorStr == "nlk"); break; case ("nl"): //null case ("nnl"): //not null predicate = new FieldCompareNullPredicate(field, null, null, comparisonOperatorStr == "nnl"); break; case ("gt"): //greater than) case ("gte"): //greater than or equal to case ("lt"): //less than case ("lte"): //less than or equal to if (valueElements.Length < 1) throwINEEx(comparisonOperatorStr); objElements[0] = ConvertStringToFieldValue(field, valueElements[0]); objAlias = valueElements.Length == 2 ? valueElements[1] : null; var comparisonOperator = ComparisonOperator.GreaterThan; if (comparisonOperatorStr == "gte") comparisonOperator = ComparisonOperator.GreaterEqual; else if (comparisonOperatorStr == "lt") comparisonOperator = ComparisonOperator.LesserThan; else if (comparisonOperatorStr == "lte") comparisonOperator = ComparisonOperator.LessEqual; predicate = new FieldCompareValuePredicate(field, null, comparisonOperator, objElements[0], objAlias); break; case ("ct"): //full text contains case ("ft"): //full text free text if (valueElements.Length < 1) throwINEEx(comparisonOperatorStr); objElements[0] = valueElements[0]; objAlias = valueElements.Length == 2 ? valueElements[1] : null; predicate = new FieldFullTextSearchPredicate(field, null, comparisonOperatorStr == "ct" ? FullTextSearchOperator.Contains : FullTextSearchOperator.Freetext, (string)objElements[0], objAlias); break; default: return null; } return predicate; }
internal static IEntityField2 GetRelatedField(EntityType entityType, string fieldInfo, List<IEntityRelation> relationsToFill) { var fieldSegments = fieldInfo.Trim('.').Split('.'); var fieldParts = fieldSegments.Take(fieldSegments.Length - 1).ToArray(); var fieldName = fieldSegments[fieldSegments.Length - 1]; for (var i = 0; i < fieldParts.Length; i++) { var isLastEntity = i == fieldParts.Length - 1; var fieldPart = fieldParts[i]; var relationMap = GetEntityTypeRelationMap(entityType); var relation = relationMap.FirstOrDefault( r => r.Value.MappedFieldName.Equals(fieldPart, StringComparison.OrdinalIgnoreCase)); if (relation.Equals(default(KeyValuePair<string, IEntityRelation>))) return null; relationsToFill.AddIfNotExists(relation.Value); var prefetchMap = GetEntityTypeIncludeMap(entityType); var prefetch = prefetchMap.FirstOrDefault(p => p.Key.Equals(fieldPart, StringComparison.OrdinalIgnoreCase)); if (prefetch.Equals(default(KeyValuePair<string, IPrefetchPathElement2>))) return null; entityType = (EntityType)prefetch.Value.ToFetchEntityType; if (isLastEntity) { var fieldKvpToReturn = GetEntityTypeFieldMap(entityType) .FirstOrDefault(f => f.Key.Equals(fieldName, StringComparison.OrdinalIgnoreCase)); var fieldToReturn = fieldKvpToReturn.Equals(default(KeyValuePair<string, IEntityField2>)) ? null : fieldKvpToReturn.Value; return fieldToReturn; } } return null; }
public string GetCode(MetadataTypes metadata, IRequest request, INativeTypesMetadata nativeTypes) { var typeNamespaces = new HashSet <string>(); var includeList = RemoveIgnoredTypes(metadata); metadata.Types.Each(x => typeNamespaces.Add(x.Namespace)); metadata.Operations.Each(x => typeNamespaces.Add(x.Request.Namespace)); var defaultImports = new List <string>(DefaultImports); if (!Config.DefaultImports.IsEmpty()) { defaultImports = Config.DefaultImports; } else { if (ReferencesGson(metadata)) { defaultImports.AddIfNotExists(GSonAnnotationsNamespace); defaultImports.AddIfNotExists(GSonReflectNamespace); } if (ReferencesStream(metadata)) { defaultImports.AddIfNotExists(JavaIoNamespace); } } var defaultNamespace = Config.GlobalNamespace ?? DefaultGlobalNamespace; string DefaultValue(string k) => request.QueryString[k].IsNullOrEmpty() ? "//" : ""; var sbInner = StringBuilderCache.Allocate(); var sb = new StringBuilderWrapper(sbInner); sb.AppendLine("/* Options:"); sb.AppendLine("Date: {0}".Fmt(DateTime.Now.ToString("s").Replace("T", " "))); sb.AppendLine("Version: {0}".Fmt(Env.VersionString)); sb.AppendLine("Tip: {0}".Fmt(HelpMessages.NativeTypesDtoOptionsTip.Fmt("//"))); sb.AppendLine("BaseUrl: {0}".Fmt(Config.BaseUrl)); if (Config.UsePath != null) { sb.AppendLine("UsePath: {0}".Fmt(Config.UsePath)); } sb.AppendLine(); sb.AppendLine("{0}Package: {1}".Fmt(DefaultValue("Package"), Config.Package)); sb.AppendLine("{0}GlobalNamespace: {1}".Fmt(DefaultValue("GlobalNamespace"), defaultNamespace)); sb.AppendLine("{0}AddPropertyAccessors: {1}".Fmt(DefaultValue("AddPropertyAccessors"), Config.AddPropertyAccessors)); sb.AppendLine("{0}SettersReturnThis: {1}".Fmt(DefaultValue("SettersReturnThis"), Config.SettersReturnThis)); sb.AppendLine("{0}AddServiceStackTypes: {1}".Fmt(DefaultValue("AddServiceStackTypes"), Config.AddServiceStackTypes)); sb.AppendLine("{0}AddResponseStatus: {1}".Fmt(DefaultValue("AddResponseStatus"), Config.AddResponseStatus)); sb.AppendLine("{0}AddDescriptionAsComments: {1}".Fmt(DefaultValue("AddDescriptionAsComments"), Config.AddDescriptionAsComments)); sb.AppendLine("{0}AddImplicitVersion: {1}".Fmt(DefaultValue("AddImplicitVersion"), Config.AddImplicitVersion)); sb.AppendLine("{0}IncludeTypes: {1}".Fmt(DefaultValue("IncludeTypes"), Config.IncludeTypes.Safe().ToArray().Join(","))); sb.AppendLine("{0}ExcludeTypes: {1}".Fmt(DefaultValue("ExcludeTypes"), Config.ExcludeTypes.Safe().ToArray().Join(","))); sb.AppendLine("{0}TreatTypesAsStrings: {1}".Fmt(DefaultValue("TreatTypesAsStrings"), Config.TreatTypesAsStrings.Safe().ToArray().Join(","))); sb.AppendLine("{0}DefaultImports: {1}".Fmt(DefaultValue("DefaultImports"), defaultImports.Join(","))); sb.AppendLine("*/"); sb.AppendLine(); foreach (var typeName in Config.TreatTypesAsStrings.Safe()) { TypeAliases[typeName] = "String"; } if (Config.Package != null) { sb.AppendLine("package {0};".Fmt(Config.Package)); sb.AppendLine(); } string lastNS = null; var existingTypes = new HashSet <string>(); var requestTypes = metadata.Operations.Select(x => x.Request).ToSet(); var requestTypesMap = metadata.Operations.ToSafeDictionary(x => x.Request); var responseTypes = metadata.Operations .Where(x => x.Response != null) .Select(x => x.Response).ToSet(); var types = metadata.Types.ToSet(); allTypes = new List <MetadataType>(); allTypes.AddRange(requestTypes); allTypes.AddRange(responseTypes); allTypes.AddRange(types); allTypes = FilterTypes(allTypes); //TypeScript doesn't support reusing same type name with different generic airity var conflictPartialNames = allTypes.Map(x => x.Name).Distinct() .GroupBy(g => g.LeftPart('`')) .Where(g => g.Count() > 1) .Select(g => g.Key) .ToList(); this.conflictTypeNames = allTypes .Where(x => conflictPartialNames.Any(name => x.Name.StartsWith(name))) .Map(x => x.Name); defaultImports.Each(x => sb.AppendLine("import {0};".Fmt(x))); sb.AppendLine(); var insertCode = InsertCodeFilter?.Invoke(allTypes, Config); if (insertCode != null) { sb.AppendLine(insertCode); } sb.AppendLine("public class {0}".Fmt(defaultNamespace.SafeToken())); sb.AppendLine("{"); //ServiceStack core interfaces foreach (var type in allTypes) { var fullTypeName = type.GetFullName(); if (requestTypes.Contains(type)) { if (!existingTypes.Contains(fullTypeName)) { MetadataType response = null; if (requestTypesMap.TryGetValue(type, out var operation)) { response = operation.Response; } lastNS = AppendType(ref sb, type, lastNS, new CreateTypeOptions { Routes = metadata.Operations.GetRoutes(type), ImplementsFn = () => { if (!Config.AddReturnMarker && operation?.ReturnsVoid != true && operation?.ReturnType == null) { return(null); } if (operation?.ReturnsVoid == true) { return(nameof(IReturnVoid)); } if (operation?.ReturnType != null) { return(Type("IReturn`1", new[] { Type(operation.ReturnType) })); } return(response != null ? Type("IReturn`1", new[] { Type(response.Name, response.GenericArgs) }) : null); }, IsRequest = true, Op = operation, }); existingTypes.Add(fullTypeName); } } else if (responseTypes.Contains(type)) { if (!existingTypes.Contains(fullTypeName) && !Config.IgnoreTypesInNamespaces.Contains(type.Namespace)) { lastNS = AppendType(ref sb, type, lastNS, new CreateTypeOptions { IsResponse = true, }); existingTypes.Add(fullTypeName); } } else if (types.Contains(type) && !existingTypes.Contains(fullTypeName)) { lastNS = AppendType(ref sb, type, lastNS, new CreateTypeOptions { IsType = true }); existingTypes.Add(fullTypeName); } } sb.AppendLine(); sb.AppendLine("}"); var addCode = AddCodeFilter?.Invoke(allTypes, Config); if (addCode != null) { sb.AppendLine(addCode); } return(StringBuilderCache.ReturnAndFree(sbInner)); }
public static void AddIfNotExists(this List <TableParsingResult> list, List <TableParsingResult> toAdd) { toAdd.ForEach(x => list.AddIfNotExists(x.TableName, x.OperationType, x.Alias)); }
public static List <IPlugin> AddIfNotExists <T>(this List <IPlugin> plugins, T plugin) where T : class, IPlugin => plugins.AddIfNotExists(plugin, null);
public static void Add(ControllerType controllerType) { _controllerTypes.AddIfNotExists(controllerType); }
public static JsonObject CreateJwtPayload( IAuthSession session, string issuer, TimeSpan expireIn, IEnumerable <string> audiences = null, IEnumerable <string> roles = null, IEnumerable <string> permissions = null) { var now = DateTime.UtcNow; var jwtPayload = new JsonObject { { "iss", issuer }, { "sub", session.UserAuthId }, { "iat", now.ToUnixTime().ToString() }, { "exp", now.Add(expireIn).ToUnixTime().ToString() }, }; jwtPayload.SetAudience(audiences?.ToList()); if (!string.IsNullOrEmpty(session.Email)) { jwtPayload["email"] = session.Email; } if (!string.IsNullOrEmpty(session.FirstName)) { jwtPayload["given_name"] = session.FirstName; } if (!string.IsNullOrEmpty(session.LastName)) { jwtPayload["family_name"] = session.LastName; } if (!string.IsNullOrEmpty(session.DisplayName)) { jwtPayload["name"] = session.DisplayName; } if (!string.IsNullOrEmpty(session.UserName)) { jwtPayload["preferred_username"] = session.UserName; } else if (!string.IsNullOrEmpty(session.UserAuthName) && !session.UserAuthName.Contains("@")) { jwtPayload["preferred_username"] = session.UserAuthName; } var profileUrl = session.GetProfileUrl(); if (profileUrl != null && profileUrl != Svg.GetDataUri(Svg.Icons.DefaultProfile)) { if (profileUrl.Length <= MaxProfileUrlSize) { jwtPayload["picture"] = profileUrl; } else { LogManager.GetLogger(typeof(JwtAuthProvider)).Warn($"User '{session.UserAuthId}' ProfileUrl exceeds max JWT Cookie size, using default profile"); jwtPayload["picture"] = HostContext.GetPlugin <AuthFeature>()?.ProfileImages?.RewriteImageUri(profileUrl); } } var combinedRoles = new List <string>(session.Roles.Safe()); var combinedPerms = new List <string>(session.Permissions.Safe()); roles.Each(x => combinedRoles.AddIfNotExists(x)); permissions.Each(x => combinedPerms.AddIfNotExists(x)); if (combinedRoles.Count > 0) { jwtPayload["roles"] = combinedRoles.ToJson(); } if (combinedPerms.Count > 0) { jwtPayload["perms"] = combinedPerms.ToJson(); } return(jwtPayload); }
private bool Case_1__1(WordMorphoAmbiguity wma_0, WordMorphoAmbiguity wma_1, WordMorphoAmbiguity wma_2) { var len_0 = wma_0.morphoAmbiguityTuples.Count; var len_1 = wma_1.morphoAmbiguityTuples.Count; if (len_0 == 1) { if (1 < len_1) { var ma_case_0 = (wma_0.morphoAmbiguityTuples[0].wordFormMorphology.MorphoAttribute & MorphoAttributeAllCases); if (!IsCaseAnycase(ma_case_0)) { for (var j = 0; j < len_1; j++) { var mat_1 = wma_1.morphoAmbiguityTuples[j]; var ma_1 = mat_1.wordFormMorphology.MorphoAttribute; if (ma_case_0 == (ma_1 & MorphoAttributeAllCases)) { _mats_1.Add(mat_1); } } if (_mats_1.Count != 0) { var wasModify = (_mats_1.Count < len_1); if (wasModify) { wasModify = Case_1__1_stepII_1(_mats_1, wma_2); if (wasModify) { wma_1.morphoAmbiguityTuples.Clear(); wma_1.morphoAmbiguityTuples.AddRange(_mats_1); } } _mats_1.Clear(); return(wasModify); } } } } else if (len_1 == 1) { var ma_case_1 = (wma_1.morphoAmbiguityTuples[0].wordFormMorphology.MorphoAttribute & MorphoAttributeAllCases); if (!IsCaseAnycase(ma_case_1)) { for (var i = 0; i < len_0; i++) { var mat_0 = wma_0.morphoAmbiguityTuples[i]; var ma_0 = mat_0.wordFormMorphology.MorphoAttribute; if (ma_case_1 == (ma_0 & MorphoAttributeAllCases)) { _mats_0.Add(mat_0); } } if (_mats_0.Count != 0) { var wasModify = (_mats_0.Count < len_0); if (wasModify) { wasModify = Case_1__1_stepII_1(_mats_0, wma_2); if (wasModify) { wma_0.morphoAmbiguityTuples.Clear(); wma_0.morphoAmbiguityTuples.AddRange(_mats_0); } } _mats_0.Clear(); return(wasModify); } } } else { for (var i = 0; i < len_0; i++) { var mat_0 = wma_0.morphoAmbiguityTuples[i]; var ma_case_0 = (mat_0.wordFormMorphology.MorphoAttribute & MorphoAttributeAllCases); if (!IsCaseAnycase(ma_case_0)) { for (var j = 0; j < len_1; j++) { var mat_1 = wma_1.morphoAmbiguityTuples[j]; var ma_1 = mat_1.wordFormMorphology.MorphoAttribute; if (ma_case_0 == (ma_1 & MorphoAttributeAllCases)) { _mats_0.AddIfNotExists(mat_0); _mats_1.AddIfNotExists(mat_1); } } } } if (_mats_0.Count != 0) { var wasModify = ((_mats_0.Count < len_0) || (_mats_1.Count < len_1)); if (wasModify) { wasModify = Case_1__1_stepII_2(wma_2); if (wasModify) { wma_0.morphoAmbiguityTuples.Clear(); wma_0.morphoAmbiguityTuples.AddRange(_mats_0); wma_1.morphoAmbiguityTuples.Clear(); wma_1.morphoAmbiguityTuples.AddRange(_mats_1); } } _mats_0.Clear(); _mats_1.Clear(); return(wasModify); } } return(false); }
public string GetCode(MetadataTypes metadata, IRequest request, INativeTypesMetadata nativeTypes) { var typeNamespaces = new HashSet <string>(); RemoveIgnoredTypes(metadata); metadata.Types.Each(x => typeNamespaces.Add(x.Namespace)); metadata.Operations.Each(x => typeNamespaces.Add(x.Request.Namespace)); var defaultImports = new List <string>(DefaultImports); if (!Config.DefaultImports.IsEmpty()) { defaultImports = Config.DefaultImports; } else { if (ReferencesGson(metadata)) { defaultImports.AddIfNotExists(GSonAnnotationsNamespace); defaultImports.AddIfNotExists(GSonReflectNamespace); } if (ReferencesStream(metadata)) { defaultImports.AddIfNotExists(JavaIoNamespace); } } Func <string, string> defaultValue = k => request.QueryString[k].IsNullOrEmpty() ? "//" : ""; var sbInner = StringBuilderCache.Allocate(); var sb = new StringBuilderWrapper(sbInner); sb.AppendLine("/* Options:"); sb.AppendLine($"Date: {DateTime.Now.ToString("s").Replace("T", " ")}"); sb.AppendLine($"Version: {Env.ServiceStackVersion}"); sb.AppendLine($"Tip: {HelpMessages.NativeTypesDtoOptionsTip.Fmt("//")}"); sb.AppendLine($"BaseUrl: {Config.BaseUrl}"); sb.AppendLine(); sb.AppendLine("{0}Package: {1}".Fmt(defaultValue("Package"), Config.Package)); sb.AppendLine("{0}AddServiceStackTypes: {1}".Fmt(defaultValue("AddServiceStackTypes"), Config.AddServiceStackTypes)); sb.AppendLine("{0}AddResponseStatus: {1}".Fmt(defaultValue("AddResponseStatus"), Config.AddResponseStatus)); sb.AppendLine("{0}AddImplicitVersion: {1}".Fmt(defaultValue("AddImplicitVersion"), Config.AddImplicitVersion)); sb.AppendLine("{0}AddDescriptionAsComments: {1}".Fmt(defaultValue("AddDescriptionAsComments"), Config.AddDescriptionAsComments)); sb.AppendLine("{0}IncludeTypes: {1}".Fmt(defaultValue("IncludeTypes"), Config.IncludeTypes.Safe().ToArray().Join(","))); sb.AppendLine("{0}ExcludeTypes: {1}".Fmt(defaultValue("ExcludeTypes"), Config.ExcludeTypes.Safe().ToArray().Join(","))); sb.AppendLine("{0}InitializeCollections: {1}".Fmt(defaultValue("InitializeCollections"), Config.InitializeCollections)); sb.AppendLine("{0}TreatTypesAsStrings: {1}".Fmt(defaultValue("TreatTypesAsStrings"), Config.TreatTypesAsStrings.Safe().ToArray().Join(","))); sb.AppendLine("{0}DefaultImports: {1}".Fmt(defaultValue("DefaultImports"), defaultImports.Join(","))); sb.AppendLine("*/"); sb.AppendLine(); foreach (var typeName in Config.TreatTypesAsStrings.Safe()) { TypeAliases[typeName] = "String"; } if (Config.Package != null) { sb.AppendLine($"package {Config.Package}"); sb.AppendLine(); } string lastNS = null; var existingTypes = new HashSet <string>(); var requestTypes = metadata.Operations.Select(x => x.Request).ToHashSet(); var requestTypesMap = metadata.Operations.ToSafeDictionary(x => x.Request); var responseTypes = metadata.Operations .Where(x => x.Response != null) .Select(x => x.Response).ToHashSet(); var types = metadata.Types.ToHashSet(); allTypes = new List <MetadataType>(); allTypes.AddRange(requestTypes); allTypes.AddRange(responseTypes); allTypes.AddRange(types); allTypes = FilterTypes(allTypes); //TypeScript doesn't support reusing same type name with different generic airity var conflictPartialNames = allTypes.Map(x => x.Name).Distinct() .GroupBy(g => g.LeftPart('`')) .Where(g => g.Count() > 1) .Select(g => g.Key) .ToList(); this.conflictTypeNames = allTypes .Where(x => conflictPartialNames.Any(name => x.Name.StartsWith(name))) .Map(x => x.Name); defaultImports.Each(x => sb.AppendLine($"import {x}")); sb.AppendLine(); //ServiceStack core interfaces foreach (var type in allTypes) { var fullTypeName = type.GetFullName(); if (requestTypes.Contains(type)) { if (!existingTypes.Contains(fullTypeName)) { MetadataType response = null; MetadataOperationType operation; if (requestTypesMap.TryGetValue(type, out operation)) { response = operation.Response; } lastNS = AppendType(ref sb, type, lastNS, new CreateTypeOptions { ImplementsFn = () => { if (!Config.AddReturnMarker && !type.ReturnVoidMarker && type.ReturnMarkerTypeName == null) { return(null); } if (type.ReturnVoidMarker) { return("IReturnVoid"); } if (type.ReturnMarkerTypeName != null) { return(Type("IReturn`1", new[] { Type(type.ReturnMarkerTypeName) })); } return(response != null ? Type("IReturn`1", new[] { Type(response.Name, response.GenericArgs) }) : null); }, IsRequest = true, }); existingTypes.Add(fullTypeName); } } else if (responseTypes.Contains(type)) { if (!existingTypes.Contains(fullTypeName) && !Config.IgnoreTypesInNamespaces.Contains(type.Namespace)) { lastNS = AppendType(ref sb, type, lastNS, new CreateTypeOptions { IsResponse = true, }); existingTypes.Add(fullTypeName); } } else if (types.Contains(type) && !existingTypes.Contains(fullTypeName)) { lastNS = AppendType(ref sb, type, lastNS, new CreateTypeOptions { IsType = true }); existingTypes.Add(fullTypeName); } } return(StringBuilderCache.ReturnAndFree(sbInner)); }
/* * -> eq (equals any) * -> neq (not equals any) * -> eqc (equals any, case insensitive [on a case sensitive database]) * -> neqc (not equals any, case insensitive [on a case sensitive database]) * -> in (same as eq) * -> nin (same as ne) * -> lk (like) * -> nlk (not like) * -> nl (null) * -> nnl (not null) * -> gt (greater than) * -> gte (greater than or equal to) * -> lt (less than) * -> lte (less than or equal to) * -> ct (full text contains) * -> ft (full text free text) * -> bt (between) * -> nbt (not between) */ private static IPredicate BuildPredicateFromClauseNode(Func <string, IEntityField2> fieldGetter, Func <string, List <IEntityRelation>, IEntityField2> relatedFieldGetter, FilterNode filterNode, List <IEntityRelation> inferredRelationsList) { // there are always at least 2 elements if (filterNode.ElementCount < 2) { return(null); } var elements = filterNode.Elements; //TODO: may need to mess with relation aliases and join types in the future var relations = new List <IEntityRelation>(); var field = elements[0].IndexOf('.') == -1 ? fieldGetter(elements[0]) : relatedFieldGetter(elements[0], relations); if (field == null) { throw new ArgumentNullException("Unable to locate field " + elements[0]); } foreach (var relation in relations) { inferredRelationsList.AddIfNotExists(relation); } var comparisonOperatorStr = elements[1].ToLowerInvariant(); var valueElements = elements.Skip(2).ToArray(); var objElements = new object[valueElements.Length]; Action <string> throwINEEx = (s) => { throw new ArgumentException(string.Format("Invalid number of elements in '{0}' filter clause", s)); }; string objAlias; IPredicate predicate; switch (comparisonOperatorStr) { case ("bt"): //between case ("nbt"): //not between if (valueElements.Length < 2) { throwINEEx(comparisonOperatorStr); } objElements[0] = ConvertStringToFieldValue(field, valueElements[0]); objElements[1] = ConvertStringToFieldValue(field, valueElements[1]); objAlias = valueElements.Length == 3 ? valueElements[2] : null; predicate = new FieldBetweenPredicate(field, null, objElements[0], objElements[1], objAlias, comparisonOperatorStr == "nbt"); break; case ("in"): //same as eq case ("nin"): //same as ne case ("eq"): //equals any case ("neq"): //not equals any case ("eqc"): //equals any, case insensitive [on a case sensitive database] - only 1 element per clause with this option case ("neqc"): //not equals any, case insensitive [on a case sensitive database] - only 1 element per clause with this option if (valueElements.Length < 1) { throwINEEx(comparisonOperatorStr); } for (int i = 0; i < valueElements.Length; i++) { objElements[i] = ConvertStringToFieldValue(field, valueElements[i]); } if (objElements.Length == 1 || comparisonOperatorStr == "eqci" || comparisonOperatorStr == "neci") { predicate = new FieldCompareValuePredicate(field, null, comparisonOperatorStr.StartsWith("n") ? ComparisonOperator.NotEqual : ComparisonOperator.Equal, objElements[0]) { CaseSensitiveCollation = comparisonOperatorStr == "eqci" || comparisonOperatorStr == "neci" }; } else { if (comparisonOperatorStr.StartsWith("n")) { predicate = (EntityField2)field != objElements; } else { predicate = (EntityField2)field == objElements; } } break; case ("lk"): //like case ("nlk"): //not like if (valueElements.Length < 1) { throwINEEx(comparisonOperatorStr); } objElements[0] = ConvertStringToFieldValue(field, valueElements[0].Replace('*', '%')); objAlias = valueElements.Length == 2 ? valueElements[1] : null; predicate = new FieldLikePredicate(field, null, objAlias, (string)objElements[0], comparisonOperatorStr == "nlk"); break; case ("nl"): //null case ("nnl"): //not null predicate = new FieldCompareNullPredicate(field, null, null, comparisonOperatorStr == "nnl"); break; case ("gt"): //greater than) case ("gte"): //greater than or equal to case ("lt"): //less than case ("lte"): //less than or equal to if (valueElements.Length < 1) { throwINEEx(comparisonOperatorStr); } objElements[0] = ConvertStringToFieldValue(field, valueElements[0]); objAlias = valueElements.Length == 2 ? valueElements[1] : null; var comparisonOperator = ComparisonOperator.GreaterThan; if (comparisonOperatorStr == "gte") { comparisonOperator = ComparisonOperator.GreaterEqual; } else if (comparisonOperatorStr == "lt") { comparisonOperator = ComparisonOperator.LesserThan; } else if (comparisonOperatorStr == "lte") { comparisonOperator = ComparisonOperator.LessEqual; } predicate = new FieldCompareValuePredicate(field, null, comparisonOperator, objElements[0], objAlias); break; case ("ct"): //full text contains case ("ft"): //full text free text if (valueElements.Length < 1) { throwINEEx(comparisonOperatorStr); } objElements[0] = valueElements[0]; objAlias = valueElements.Length == 2 ? valueElements[1] : null; predicate = new FieldFullTextSearchPredicate(field, null, comparisonOperatorStr == "ct" ? FullTextSearchOperator.Contains : FullTextSearchOperator.Freetext, (string)objElements[0], objAlias); break; default: return(null); } return(predicate); }
private static bool TryPortMissingCommentsForMember(TripleSlashMember tsMember, DocsMember dMember) { bool modified = false; if (!IsEmpty(tsMember.Summary) && IsEmpty(dMember.Summary)) { // Any member can have an empty summary PrintModifiedMember("MEMBER SUMMARY", dMember.FilePath, tsMember.Name, dMember.DocId, tsMember.Summary, dMember.Summary); dMember.Summary = tsMember.Summary; TotalModifiedIndividualElements++; modified = true; } if (!IsEmpty(tsMember.Remarks) && IsEmpty(dMember.Remarks)) { // Any member can have an empty remark PrintModifiedMember("MEMBER REMARKS", dMember.FilePath, tsMember.Name, dMember.DocId, tsMember.Remarks, dMember.Remarks); dMember.Remarks = tsMember.Remarks; TotalModifiedIndividualElements++; modified = true; } // Properties and method returns save their values in different locations if (dMember.MemberType == "Property") { if (!IsEmpty(tsMember.Returns) && IsEmpty(dMember.Value)) { PrintModifiedMember("PROPERTY", dMember.FilePath, tsMember.Name, dMember.DocId, tsMember.Returns, dMember.Value); dMember.Value = tsMember.Returns; TotalModifiedIndividualElements++; modified = true; } } else if (dMember.MemberType == "Method") { if (!IsEmpty(tsMember.Returns) && IsEmpty(dMember.Returns)) { if (tsMember.Returns != null && dMember.ReturnType == "System.Void") { ProblematicAPIs.AddIfNotExists($"Returns=[{tsMember.Returns}] in Method=[{dMember.DocId}]"); } else { PrintModifiedMember("METHOD RETURN", dMember.FilePath, tsMember.Name, dMember.DocId, tsMember.Returns, dMember.Returns); dMember.Returns = tsMember.Returns; TotalModifiedIndividualElements++; modified = true; } } } // Triple slash params may cause errors if they are missing in the code side foreach (TripleSlashParam tsParam in tsMember.Params) { DocsParam dParam = dMember.Params.FirstOrDefault(x => x.Name == tsParam.Name); bool created = false; if (dParam == null) { ProblematicAPIs.AddIfNotExists($"Param=[{tsParam.Name}] in Member DocId=[{dMember.DocId}]"); created = TryPromptParam(tsParam, dMember, out dParam); } if (created || (!IsEmpty(tsParam.Value) && IsEmpty(dParam.Value))) { PrintModifiedMember(string.Format("PARAM ({0})", created ? "CREATED" : "MODIFIED"), dParam.FilePath, tsParam.Name, dParam.Name, tsParam.Value, dParam.Value); if (!created) { dParam.Value = tsParam.Value; } TotalModifiedIndividualElements++; modified = true; } } // Exceptions are a special case: If a new one is found in code, but does not exist in docs, the whole element needs to be added foreach (TripleSlashException tsException in tsMember.Exceptions) { DocsException dException = dMember.Exceptions.FirstOrDefault(x => x.Cref.EndsWith(tsException.Cref)); bool created = false; if (dException == null) { dException = dMember.SaveException(tsException.XEException); AddedExceptions.AddIfNotExists($"{dException.Cref} in {dMember.DocId}"); created = true; } if (created || (!IsEmpty(tsException.Value) && IsEmpty(dException.Value))) { PrintModifiedMember(string.Format("EXCEPTION ({0})", created ? "CREATED" : "MODIFIED"), dException.FilePath, tsException.Cref, dException.Cref, tsException.Value, dException.Value); if (!created) { dException.Value = tsException.Value; } TotalModifiedIndividualElements++; modified = true; } } foreach (TripleSlashTypeParam tsTypeParam in tsMember.TypeParams) { DocsTypeParam dTypeParam = dMember.TypeParams.FirstOrDefault(x => x.Name == tsTypeParam.Name); bool created = false; if (dTypeParam == null) { ProblematicAPIs.AddIfNotExists($"TypeParam=[{tsTypeParam.Name}] in Member=[{dMember.DocId}]"); dTypeParam = dMember.SaveTypeParam(tsTypeParam.XETypeParam); created = true; } if (created || (!IsEmpty(tsTypeParam.Value) && IsEmpty(dTypeParam.Value))) { PrintModifiedMember(string.Format("TYPE PARAM ({0})", created ? "CREATED" : "MODIFIED"), dTypeParam.FilePath, tsTypeParam.Name, dTypeParam.Name, tsTypeParam.Value, dTypeParam.Value); if (!created) { dTypeParam.Value = tsTypeParam.Value; } TotalModifiedIndividualElements++; modified = true; } } if (modified) { ModifiedAPIs.AddIfNotExists(dMember.DocId); } return(modified); }
private List <TableParsingResult> ExtractTablesUsedInFromClause(FromClause fromClause) { List <TableParsingResult> result = new List <TableParsingResult>(); if (fromClause == null) { return(result); } foreach (TableReference tableReference in fromClause.TableReferences) { if (tableReference is JoinTableReference joinTableReference) // can be of type Qualified or UnqualifiedJoin but we care only about the abstract type { do { if (joinTableReference.SecondTableReference is NamedTableReference namedTableReference) { string tableName = ExtraceTableNameFromNamedTableRefernce(namedTableReference, out string alias); result.AddIfNotExists(tableName, SqlOperationType.SELECT, alias); } if (joinTableReference.FirstTableReference is NamedTableReference namedTableReference2) { string tableName = ExtraceTableNameFromNamedTableRefernce(namedTableReference2, out string alias); result.AddIfNotExists(tableName, SqlOperationType.SELECT, alias); } if (joinTableReference.SecondTableReference is QueryDerivedTable queryDerivedTable && queryDerivedTable.QueryExpression is QuerySpecification querySpecification) { string alias = null; if (queryDerivedTable.Alias != null) { alias = queryDerivedTable.Alias.Value; } var items = ExtractTablesFromQuerySpecification(querySpecification); //ExtractTablesUsedInFromClause(querySpecification.FromClause); // recursion path if (!string.IsNullOrWhiteSpace(alias)) { items.ForEach(x => x.Alias = alias); } result.AddIfNotExists(items); } joinTableReference = joinTableReference.FirstTableReference as JoinTableReference; }while (joinTableReference != null); } else if (tableReference is NamedTableReference namedTableReference) { string tableName = ExtraceTableNameFromNamedTableRefernce(namedTableReference, out string alias); result.AddIfNotExists(tableName, SqlOperationType.SELECT, alias); } else if (tableReference is QueryDerivedTable queryDerivedTable && queryDerivedTable.QueryExpression is QuerySpecification querySpecification) { string alias = null; if (queryDerivedTable.Alias != null) { alias = queryDerivedTable.Alias.Value; } var items = ExtractTablesFromQuerySpecification(querySpecification); //ExtractTablesUsedInFromClause(querySpecification.FromClause); // recursion path if (!string.IsNullOrWhiteSpace(alias)) { items.ForEach(x => x.Alias = alias); } result.AddIfNotExists(items); }
/// <summary> /// Initializes the AppHost. /// Calls the <see cref="Configure"/> method. /// Should be called before start. /// </summary> public virtual ServiceStackHost Init() { if (Instance != null) { throw new InvalidDataException($"ServiceStackHost.Instance has already been set ({Instance.GetType().Name})"); } Service.GlobalResolver = Instance = this; RegisterLicenseKey(AppSettings.GetNullableString("servicestack:license")); if (ServiceController == null) { ServiceController = CreateServiceController(ServiceAssemblies.ToArray()); } Config = HostConfig.ResetInstance(); OnConfigLoad(); AbstractVirtualFileBase.ScanSkipPaths = Config.ScanSkipPaths; ResourceVirtualDirectory.EmbeddedResourceTreatAsFiles = Config.EmbeddedResourceTreatAsFiles; OnBeforeInit(); ServiceController.Init(); var scanAssemblies = new List <Assembly>(ServiceAssemblies); scanAssemblies.AddIfNotExists(GetType().Assembly); RunConfigureAppHosts(scanAssemblies.SelectMany(x => x.GetTypes()) .Where(x => x.HasInterface(typeof(IConfigureAppHost)))); BeforeConfigure.Each(fn => fn(this)); Configure(Container); AfterConfigure.Each(fn => fn(this)); RunConfigureAppHosts(scanAssemblies.SelectMany(x => x.GetTypes()) .Where(x => x.HasInterface(typeof(IPostConfigureAppHost)))); if (Config.StrictMode == null && Config.DebugMode) { Config.StrictMode = true; } if (!Config.DebugMode) { Plugins.RemoveAll(x => x is RequestInfoFeature); } ConfigurePlugins(); List <IVirtualPathProvider> pathProviders = null; if (VirtualFileSources == null) { pathProviders = GetVirtualFileSources().Where(x => x != null).ToList(); VirtualFileSources = pathProviders.Count > 1 ? new MultiVirtualFiles(pathProviders.ToArray()) : pathProviders.First(); } if (VirtualFiles == null) { VirtualFiles = pathProviders?.FirstOrDefault(x => x is FileSystemVirtualFiles) as IVirtualFiles ?? GetVirtualFileSources().FirstOrDefault(x => x is FileSystemVirtualFiles) as IVirtualFiles; } OnAfterInit(); PopulateArrayFilters(); LogInitComplete(); HttpHandlerFactory.Init(); foreach (var callback in AfterInitCallbacks) { callback(this); } ReadyAt = DateTime.UtcNow; return(this); }
public static JsonObject CreateJwtPayload( IAuthSession session, string issuer, TimeSpan expireIn, IEnumerable <string> audiences = null, IEnumerable <string> roles = null, IEnumerable <string> permissions = null) { var now = DateTime.UtcNow; var jwtPayload = new JsonObject { { "iss", issuer }, { "sub", session.UserAuthId }, { "iat", now.ToUnixTime().ToString() }, { "exp", now.Add(expireIn).ToUnixTime().ToString() }, }; jwtPayload.SetAudience(audiences?.ToList()); if (!string.IsNullOrEmpty(session.Email)) { jwtPayload["email"] = session.Email; } if (!string.IsNullOrEmpty(session.FirstName)) { jwtPayload["given_name"] = session.FirstName; } if (!string.IsNullOrEmpty(session.LastName)) { jwtPayload["family_name"] = session.LastName; } if (!string.IsNullOrEmpty(session.DisplayName)) { jwtPayload["name"] = session.DisplayName; } if (!string.IsNullOrEmpty(session.UserName)) { jwtPayload["preferred_username"] = session.UserName; } else if (!string.IsNullOrEmpty(session.UserAuthName) && !session.UserAuthName.Contains("@")) { jwtPayload["preferred_username"] = session.UserAuthName; } var profileUrl = session.GetProfileUrl(); if (profileUrl != null && profileUrl != Svg.GetDataUri(Svg.Icons.DefaultProfile)) { jwtPayload["picture"] = profileUrl; } var combinedRoles = new List <string>(session.Roles.Safe()); var combinedPerms = new List <string>(session.Permissions.Safe()); roles.Each(x => combinedRoles.AddIfNotExists(x)); permissions.Each(x => combinedPerms.AddIfNotExists(x)); if (combinedRoles.Count > 0) { jwtPayload["roles"] = combinedRoles.ToJson(); } if (combinedPerms.Count > 0) { jwtPayload["perms"] = combinedPerms.ToJson(); } return(jwtPayload); }
public List<Type> GetAllTypes() { var allTypes = new List<Type>(RequestTypes); foreach (var responseType in ResponseTypes) { allTypes.AddIfNotExists(responseType); } return allTypes; }
internal static Assembly Generate(List <Model> models, string cacheAssemblyInDir) { if (!Directory.Exists(cacheAssemblyInDir)) { Directory.CreateDirectory(cacheAssemblyInDir); } // see if the models have changed var assemblyFileName = "models.dll"; var assemblyFile = Path.Combine(cacheAssemblyInDir, assemblyFileName); var modelsJsonFile = Path.Combine(cacheAssemblyInDir, "models.json"); var modelsJson = models.ToJson(); if (File.Exists(assemblyFile) && File.Exists(modelsJsonFile)) { if (File.ReadAllText(modelsJsonFile).Equals(modelsJson)) { return(AssemblyLoadContext.Default.LoadFromAssemblyPath(assemblyFile)); } } var modelCode = modelCodeFormat.Replace("{", "{{").Replace("}", "}}").Replace("{{{{", "{").Replace("}}}}", "}"); var sb = new StringBuilder(); foreach (var model in models) { sb.AppendLine(string.Format(modelCode, model.Singular, model.Plural, model.Slug.Trim('/'), string.Join("\n", model.Fields.Map(s => "public " + s.Type + " " + s.Name + " { get; set; }")))); } var nsCode = codeFormat.Replace("{", "{{").Replace("}", "}}").Replace("{{{{", "{").Replace("}}}}", "}"); var code = string.Format(nsCode, sb.ToString(), typeof(CodeGenerator).Namespace); var tree = SyntaxFactory.ParseSyntaxTree(code); var requiredAssemblies = new List <string> { Assembly.Load("netstandard, Version=2.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51").Location, typeof(object).GetTypeInfo().Assembly.Location, typeof(Attribute).GetTypeInfo().Assembly.Location, typeof(System.Runtime.AssemblyTargetedPatchBandAttribute).GetTypeInfo().Assembly.Location, typeof(System.Linq.Expressions.Expression).GetTypeInfo().Assembly.Location, typeof(ServiceStack.AppHostBase).GetTypeInfo().Assembly.Location, typeof(ServiceStack.RouteAttribute).GetTypeInfo().Assembly.Location, typeof(ServiceStack.Data.DbConnectionFactory).GetTypeInfo().Assembly.Location, typeof(ServiceStack.Configuration.IResolver).GetTypeInfo().Assembly.Location, typeof(ServiceStack.OrmLite.OrmLiteConnection).GetTypeInfo().Assembly.Location, typeof(CodeGenerator).GetTypeInfo().Assembly.Location, }; var projectReferences = typeof(CodeGenerator).GetTypeInfo().Assembly.GetReferencedAssemblies(); foreach (var ssr in projectReferences) { var asm = AssemblyLoadContext.Default.LoadFromAssemblyName(ssr); var asml = asm?.Location; if (asml != null && File.Exists(asml)) { requiredAssemblies.AddIfNotExists(asml); } } var requiredAssemblyReferences = requiredAssemblies.Map(r => MetadataReference.CreateFromFile(r)); // A single, immutable invocation to the compiler to produce a library var options = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary); var compilation = CSharpCompilation.Create(assemblyFileName) .WithOptions(options) .AddReferences(requiredAssemblyReferences) .AddSyntaxTrees(tree); if (File.Exists(assemblyFile)) { File.Delete(assemblyFile); } var compilationResult = compilation.Emit(assemblyFile); if (compilationResult.Success) { // Cache the models json File.WriteAllText(modelsJsonFile, modelsJson); // Load the assembly return(AssemblyLoadContext.Default.LoadFromAssemblyPath(assemblyFile)); } else { foreach (Diagnostic codeIssue in compilationResult.Diagnostics) { string issue = $@"ID: {codeIssue.Id}, Message: {codeIssue.GetMessage()}, Location: {codeIssue.Location.GetLineSpan()}, Severity: {codeIssue.Severity}"; Console.WriteLine(issue); } return(null); } // OR IN MEMORY // compilation = CSharpCompilation.Create(Guid.NewGuid().ToString("N")) // .WithOptions(options) // .AddReferences(requiredAssemblyReferences) // .AddSyntaxTrees(tree); // using (var ms = new MemoryStream()) // { // var compilationResult2 = compilation.Emit(ms); // if (compilationResult2.Success) // { // ms.Position = 0; // return AssemblyLoadContext.Default.LoadFromStream(ms); // } // else // { // foreach (Diagnostic codeIssue in compilationResult2.Diagnostics) // { // string issue = $@"ID: {codeIssue.Id}, Message: {codeIssue.GetMessage()}, // Location: {codeIssue.Location.GetLineSpan()}, // Severity: {codeIssue.Severity}"; // Console.WriteLine(issue); // } // return null; // } // } }