public Parser(byte[] source) { if (source == null || source.Length <= 0) { return; } this.source = source; items = new ItemCollection(); // преобразуем данные в текст string sourceString = GetSourceAsString(); // при запросе // первая строка содержит метод запроса, путь и версию HTTP протокола string httpInfo = sourceString.Substring(0, sourceString.IndexOf("\r\n")); var myReg = new Regex(@"(?<method>.+)\s+(?<path>.+)\s+HTTP/(?<version>[\d\.]+)", RegexOptions.Multiline); if (myReg.IsMatch(httpInfo)) { Match m = myReg.Match(httpInfo); if (m.Groups["method"].Value.ToUpper() == "POST") { method = MethodsList.POST; } else if (m.Groups["method"].Value.ToUpper() == "CONNECT") { method = MethodsList.CONNECT; } else { method = MethodsList.GET; } // или можно определить метод вот так // _Method = (MethodsList)Enum.Parse(typeof(MethodsList), m.Groups["method"].Value.ToUpper()); // но надежней всеже использовать условие path = m.Groups["path"].Value; httpVersion = m.Groups["version"].Value; } else { // при ответе // первая строка содержит код состояния myReg = new Regex(@"HTTP/(?<version>[\d\.]+)\s+(?<status>\d+)\s*(?<msg>.*)", RegexOptions.Multiline); Match m = myReg.Match(httpInfo); int.TryParse(m.Groups["status"].Value, out statusCode); statusMessage = m.Groups["msg"].Value; httpVersion = m.Groups["version"].Value; } // выделяем заголовки (до первых двух переводов строк) headersTail = sourceString.IndexOf("\r\n\r\n"); if (headersTail != -1) { // хвост найден, отделяем заголовки sourceString = sourceString.Substring(sourceString.IndexOf("\r\n") + 2, headersTail - sourceString.IndexOf("\r\n") - 2); } // парсим заголовки и заносим их в коллекцию myReg = new Regex(@"^(?<key>[^\x3A]+)\:\s{1}(?<value>.+)$", RegexOptions.Multiline); MatchCollection mc = myReg.Matches(sourceString); foreach (Match mm in mc) { string key = mm.Groups["key"].Value; if (!items.ContainsKey(key)) { // если указанного заголовка нет в коллекции, добавляем его items.AddItem(key, mm.Groups["value"].Value.Trim("\r\n ".ToCharArray())); } } }
private static MethodsList GetSvcMethods(IEnumerable <MethodInfoData> allList, IServiceContainer services) { var queryAndInvokes = allList.GetQueryAndInvokeOnly().ToArray(); var methodList = new MethodsList(); Array.ForEach(queryAndInvokes, info => { var m = MethodDescription.FromMethodInfo(info, services); methodList.Add(m); }); return(methodList); }
private void AssertNoRestrictedMetaIdentifierUsed() { const string meta = "__meta__"; if (FieldsMap.Keys.Select(x => x.Split('.').First()).Contains(meta) || EnumsMap.Keys.Select(x => x.Split('.').First()).Contains(meta) || ConstsMap.Keys.Select(x => x.Split('.').First()).Contains(meta) || MethodsList.Contains(meta)) { throw new InvalidOperationException( $"{meta} identifier is restricted for internal client-side purposes, please use different name."); } }
public static MethodsList GetSvcMethods(this IEnumerable <MethodInfoData> allList, IValueConverter valueConverter) { MethodInfoData[] queryAndInvokes = allList.GetQueryAndInvokeOnly().ToArray(); MethodsList methodList = new MethodsList(); Array.ForEach(queryAndInvokes, info => { MethodDescription methodDescription = MethodDescription.FromMethodInfo(info, valueConverter); methodList.Add(methodDescription); }); return(methodList); }
/// <summary> /// Generates client validation rule with the basic set of parameters. /// </summary> /// <param name="type">The validation type.</param> /// <returns> /// Client validation rule with the basic set of parameters. /// </returns> /// <exception cref="System.ComponentModel.DataAnnotations.ValidationException"></exception> protected ModelClientValidationRule GetBasicRule(string type) { try { var rule = new ModelClientValidationRule { ErrorMessage = FormattedErrorMessage, ValidationType = ProvideUniqueValidationType(type) }; rule.ValidationParameters.Add("expression", Expression.ToJson()); Debug.Assert(FieldsMap != null); if (FieldsMap.Any()) { rule.ValidationParameters.Add("fieldsmap", FieldsMap.ToJson()); } Debug.Assert(ConstsMap != null); if (ConstsMap.Any()) { rule.ValidationParameters.Add("constsmap", ConstsMap.ToJson()); } Debug.Assert(EnumsMap != null); if (EnumsMap.Any()) { rule.ValidationParameters.Add("enumsmap", EnumsMap.ToJson()); } Debug.Assert(MethodsList != null); if (MethodsList.Any()) { rule.ValidationParameters.Add("methodslist", MethodsList.ToJson()); } Debug.Assert(ParsersMap != null); if (ParsersMap.Any()) { rule.ValidationParameters.Add("parsersmap", ParsersMap.ToJson()); } Debug.Assert(ErrFieldsMap != null); if (ErrFieldsMap.Any()) { rule.ValidationParameters.Add("errfieldsmap", ErrFieldsMap.ToJson()); } return(rule); } catch (Exception e) { throw new ValidationException( $"{GetType().Name}: collecting of client validation rules for {FieldName} field failed.", e); } }
/// <summary> /// Attaches client validation rule to the context. /// </summary> /// <param name="context">The Client Model Validation Context.</param> /// <param name="type">The validation type.</param> /// <param name="defaultErrorMessage">The default Error Message.</param> /// <returns> /// void /// </returns> /// <exception cref="System.ComponentModel.DataAnnotations.ValidationException"></exception> protected void AttachValidationRules(ClientModelValidationContext context, string type, string defaultErrorMessage) { var errorMessage = !string.IsNullOrEmpty(FormattedErrorMessage) ? FormattedErrorMessage : defaultErrorMessage; var uniqueValidationType = ProvideUniqueValidationType(type); try { MergeAttribute(context.Attributes, "data-val", "true"); MergeAttribute(context.Attributes, $"data-val-{uniqueValidationType}", errorMessage); MergeAttribute(context.Attributes, $"data-val-{uniqueValidationType}-expression", Expression.ToJson()); Debug.Assert(FieldsMap != null); if (FieldsMap.Any()) { MergeAttribute(context.Attributes, $"data-val-{uniqueValidationType}-fieldsmap", FieldsMap.ToJson()); } Debug.Assert(ConstsMap != null); if (ConstsMap.Any()) { MergeAttribute(context.Attributes, $"data-val-{uniqueValidationType}-constsmap", ConstsMap.ToJson()); } Debug.Assert(EnumsMap != null); if (EnumsMap.Any()) { MergeAttribute(context.Attributes, $"data-val-{uniqueValidationType}-enumsmap", EnumsMap.ToJson()); } Debug.Assert(MethodsList != null); if (MethodsList.Any()) { MergeAttribute(context.Attributes, $"data-val-{uniqueValidationType}-methodslist", MethodsList.ToJson()); } Debug.Assert(ParsersMap != null); if (ParsersMap.Any()) { MergeAttribute(context.Attributes, $"data-val-{uniqueValidationType}-parsersmap", ParsersMap.ToJson()); } Debug.Assert(ErrFieldsMap != null); if (ErrFieldsMap.Any()) { MergeAttribute(context.Attributes, $"data-val-{uniqueValidationType}-errfieldsmap", ErrFieldsMap.ToJson()); } } catch (Exception e) { throw new ValidationException( $"{GetType().Name}: collecting of client validation rules for {FieldName} field failed.", e); } }
/// <summary> /// Test if public methods on the service has Invoke or Query Attribute /// and generates from this methods their invocation method descriptions /// </summary> /// <returns></returns> private MethodsList GetMethodDescriptions(Type thisType) { MethodsList res = null; if (BaseDomainService._tInvokesInfo.TryGetValue(thisType, out res)) { return(res); } res = new MethodsList(); var methList = thisType.GetMethods(BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.Public).Select(m => new { method = m, isQuery = m.IsDefined(typeof(QueryAttribute), false), isInvoke = m.IsDefined(typeof(InvokeAttribute), false) }).Where(m => (m.isInvoke || m.isQuery)).ToArray(); Array.ForEach(methList, (info) => { res.Add(MethodDescription.FromMethodInfo(info.method, info.isQuery, this.DataHelper)); }); BaseDomainService._tInvokesInfo.TryAdd(thisType, res); return(res); }
private void AssertNoNamingCollisionsAtCorrespondingSegments() { string name; int level; var prefix = "Naming collisions cannot be accepted by client-side"; var collision = FieldsMap.Keys.SegmentsCollide(ConstsMap.Keys, out name, out level) || FieldsMap.Keys.SegmentsCollide(EnumsMap.Keys, out name, out level) || ConstsMap.Keys.SegmentsCollide(EnumsMap.Keys, out name, out level); // combination (3 2) => 3!/(2!1!) = 3 if (collision) { throw new InvalidOperationException( $"{prefix} - {name} part at level {level} is ambiguous."); } // instead of extending the checks above to combination (4 2), check for collisions with methods is done separately to provide more accurate messages: var fields = FieldsMap.Keys.Select(x => x.Split('.').First()); name = MethodsList.Intersect(fields).FirstOrDefault(); if (name != null) { throw new InvalidOperationException( $"{prefix} - method {name}(...) is colliding with {FieldsMap.Keys.First(x => x.StartsWith(name))} field identifier."); } var consts = ConstsMap.Keys.Select(x => x.Split('.').First()); name = MethodsList.Intersect(consts).FirstOrDefault(); if (name != null) { throw new InvalidOperationException( $"{prefix} - method {name}(...) is colliding with {ConstsMap.Keys.First(x => x.StartsWith(name))} const identifier."); } var enums = EnumsMap.Keys.Select(x => x.Split('.').First()); name = MethodsList.Intersect(enums).FirstOrDefault(); if (name != null) { throw new InvalidOperationException( $"{prefix} - method {name}(...) is colliding with {EnumsMap.Keys.First(x => x.StartsWith(name))} enum identifier."); } }
public override void AddValidation(ClientModelValidationContext context) { SetupValidator(context.ModelMetadata); var validationId = GetUniqueValidationId(context); var formattedErrorMessage = GetErrorMessage(context); MergeAttribute(context.Attributes, "data-val", "true"); MergeAttribute(context.Attributes, $"data-val-{validationId}", formattedErrorMessage); MergeExpressiveAttribute(context, validationId, "expression", Attribute.Expression); if (AllowEmpty.HasValue) { MergeExpressiveAttribute(context, validationId, "allowempty", AllowEmpty); } if (FieldsMap != null && FieldsMap.Any()) { MergeExpressiveAttribute(context, validationId, "fieldsmap", FieldsMap); } if (ConstsMap != null && ConstsMap.Any()) { MergeExpressiveAttribute(context, validationId, "constsmap", ConstsMap); } if (EnumsMap != null && EnumsMap.Any()) { MergeExpressiveAttribute(context, validationId, "enumsmap", EnumsMap); } if (MethodsList != null && MethodsList.Any()) { MergeExpressiveAttribute(context, validationId, "methodslist", MethodsList); } if (ParsersMap != null && ParsersMap.Any()) { MergeExpressiveAttribute(context, validationId, "parsersmap", ParsersMap); } if (ErrFieldsMap != null && ErrFieldsMap.Any()) { MergeExpressiveAttribute(context, validationId, "errfieldsmap", ErrFieldsMap); } }
private void InitSvcMethods(MethodsList methods, MethodMap svcMethods, DbSetsDictionary dbSets, ILookup <Type, DbSetInfo> dbSetsByTypeLookUp) { methods.ForEach(md => { if (md.isQuery) { //First check QueryAtrribute if it contains info for Entity Type or DbSet Name QueryAttribute queryAttribute = (QueryAttribute)md.GetMethodData().MethodInfo.GetCustomAttributes(typeof(QueryAttribute), false).FirstOrDefault(); string dbSetName = queryAttribute.DbSetName; if (!string.IsNullOrWhiteSpace(dbSetName)) { if (!dbSets.ContainsKey(dbSetName)) { throw new DomainServiceException(string.Format("Can not determine the DbSet for a query method: {0} by DbSetName {1}", md.methodName, dbSetName)); } svcMethods.Add(dbSetName, md); } else { System.Type entityType = queryAttribute.EntityType ?? md.GetMethodData().EntityType; IEnumerable <DbSetInfo> entityTypeDbSets = dbSetsByTypeLookUp[entityType]; if (!entityTypeDbSets.Any()) { throw new DomainServiceException(string.Format("Can not determine the DbSet for a query method: {0}", md.methodName)); } foreach (DbSetInfo dbSetInfo in entityTypeDbSets) { svcMethods.Add(dbSetInfo.dbSetName, md); } } } else { svcMethods.Add("", md); } }); }
private List <StiToken> PostProcessTokensList(List <StiToken> tokensList) { List <StiToken> newList = new List <StiToken>(); tokenPos = 0; while (tokenPos < tokensList.Count) { StiToken token = tokensList[tokenPos]; tokenPos++; if (token.Type == StiTokenType.Identifier) { StiDataSource ds = report.Dictionary.DataSources[token.Value]; StiBusinessObject bos = report.Dictionary.BusinessObjects[token.Value]; #region check for DataSource field if (ds != null) { StringBuilder fieldPath = new StringBuilder(StiNameValidator.CorrectName(token.Value)); while (tokenPos + 1 < tokensList.Count && tokensList[tokenPos].Type == StiTokenType.Dot) { token = tokensList[tokenPos + 1]; string nextName = StiNameValidator.CorrectName(token.Value); StiDataRelation dr = GetDataRelationByName(nextName, ds); if (dr != null) { ds = dr.ParentSource; tokenPos += 2; fieldPath.Append("."); fieldPath.Append(dr.NameInSource); continue; } if (ds.Columns.Contains(nextName)) { tokenPos += 2; fieldPath.Append("."); fieldPath.Append(nextName); break; } foreach (StiDataColumn column in ds.Columns) { if (StiNameValidator.CorrectName(column.Name) == nextName) { tokenPos += 2; fieldPath.Append("."); fieldPath.Append(column.NameInSource); break; } } CheckDataSourceField(ds.Name, nextName); tokenPos += 2; fieldPath.Append("."); fieldPath.Append(nextName); //token = tokensList[tokenPos - 1]; break; } token.Type = StiTokenType.DataSourceField; //надо оптимизировать и сохранять сразу массив строк !!!!! token.Value = fieldPath.ToString(); } #endregion #region check for BusinessObject field else if (bos != null) { StringBuilder fieldPath = new StringBuilder(token.Value); while (tokenPos + 1 < tokensList.Count && tokensList[tokenPos].Type == StiTokenType.Dot) //while (inputExpression[pos2] == '.') { token = tokensList[tokenPos + 1]; string nextName = token.Value; if (bos.Columns.Contains(nextName)) { tokenPos += 2; fieldPath.Append("."); fieldPath.Append(nextName); break; } bos = bos.BusinessObjects[nextName]; if (bos != null) { tokenPos += 2; fieldPath.Append("."); fieldPath.Append(bos.Name); continue; } break; } token.Type = StiTokenType.BusinessObjectField; //надо оптимизировать и сохранять сразу массив строк !!!!! token.Value = fieldPath.ToString(); } #endregion else if ((newList.Count > 0) && (newList[newList.Count - 1].Type == StiTokenType.Dot)) { if (MethodsList.Contains(token.Value)) { token.Type = StiTokenType.Method; } else if (PropertiesList.Contains(token.Value)) { token.Type = StiTokenType.Property; } else { ThrowError(ParserErrorCode.FieldMethodOrPropertyNotFound, token, token.Value); } } else if (TypesList.Contains(token.Value)) { token.Type = StiTokenType.Cast; if ((tokenPos + 1 < tokensList.Count) && (tokensList[tokenPos].Type == StiTokenType.Dot)) { string tempName = token.Value + "." + tokensList[tokenPos + 1].Value; if (FunctionsList.Contains(tempName)) { token.Type = StiTokenType.Function; token.Value = tempName; tokenPos += 2; } if (SystemVariablesList.Contains(tempName)) { token.Type = StiTokenType.SystemVariable; token.Value = tempName; tokenPos += 2; } } } else if (ComponentsList.Contains(token.Value)) { token.Type = StiTokenType.Component; if ((tokenPos + 1 < tokensList.Count) && (tokensList[tokenPos].Type == StiTokenType.Colon) && ComponentsList.Contains(tokensList[tokenPos + 1].Value)) { StiComponent comp = (StiComponent)ComponentsList[tokensList[tokenPos + 1].Value]; if (comp != null && comp is StiDataBand) { token.Value = (comp as StiDataBand).DataSourceName; token.Type = StiTokenType.DataSourceField; tokenPos += 2; } } } else if (FunctionsList.Contains(token.Value)) { while ((StiFunctionType)FunctionsList[token.Value] == StiFunctionType.NameSpace) { if (tokenPos + 1 >= tokensList.Count) { ThrowError(ParserErrorCode.UnexpectedEndOfExpression); } token.Value += "." + tokensList[tokenPos + 1].Value; tokenPos += 2; if (!FunctionsList.Contains(token.Value)) { ThrowError(ParserErrorCode.FunctionNotFound, token, token.Value); } } token.Type = StiTokenType.Function; } else if (SystemVariablesList.Contains(token.Value) && (token.Value != "value" || component is Stimulsoft.Report.CrossTab.StiCrossCell)) { token.Type = StiTokenType.SystemVariable; } //else if (token.Value.ToLowerInvariant() == "true" || token.Value.ToLowerInvariant() == "false") //{ // if (token.Value.ToLowerInvariant() == "true") // token.ValueObject = true; // else // token.ValueObject = false; // token.Type = StiTokenType.Number; //} //else if (token.Value.ToLowerInvariant() == "null") //{ // token.ValueObject = null; // token.Type = StiTokenType.Number; //} else if (ConstantsList.Contains(token.Value)) { while (ConstantsList[token.Value] == namespaceObj) { if (tokenPos + 1 >= tokensList.Count) { ThrowError(ParserErrorCode.UnexpectedEndOfExpression); } string oldTokenValue = token.Value; token.Value += "." + tokensList[tokenPos + 1].Value; tokenPos += 2; if (!ConstantsList.Contains(token.Value)) { ThrowError(ParserErrorCode.ItemDoesNotContainDefinition, token, oldTokenValue, tokensList[tokenPos + 1].Value); } } token.ValueObject = ConstantsList[token.Value]; token.Type = StiTokenType.Number; } else if (report.Dictionary.Variables.Contains(token.Value)) { token.Type = StiTokenType.Variable; } else if (token.Value == "or" || token.Value == "and" || token.Value == "not") { if (token.Value == "or") { token.Type = StiTokenType.DoubleOr; } if (token.Value == "and") { token.Type = StiTokenType.DoubleAnd; } if (token.Value == "not") { token.Type = StiTokenType.Not; } } else { if ((tokenPos < tokensList.Count) && (tokensList[tokenPos].Type != StiTokenType.Dot) || (tokenPos == tokensList.Count)) { CheckDataSourceField(defaultDataSourceName, token.Value); token.Type = StiTokenType.DataSourceField; token.Value = defaultDataSourceName + "." + token.Value; } else { if ((tokenPos + 1 < tokensList.Count) && (tokensList[tokenPos].Type == StiTokenType.Dot)) { CheckDataSourceField(token.Value, tokensList[tokenPos + 1].Value); token.Type = StiTokenType.DataSourceField; token.Value = token.Value + "." + tokensList[tokenPos + 1].Value; tokenPos += 2; } else { ThrowError(ParserErrorCode.NameDoesNotExistInCurrentContext, token, token.Value); } } } } newList.Add(token); } return(newList); }
public Parser(byte[] source) { if (source == null || source.Length <= 0) { return; } _Source = source; _Items = new ItemCollection(); // data to text string sourceString = GetSourceAsString(); // request // first line containt request method, path and version of HTTP protocol string httpInfo = sourceString.Substring(0, sourceString.IndexOf("\r\n")); Regex myReg = new Regex(@"(?<method>.+)\s+(?<path>.+)\s+HTTP/(?<version>[\d\.]+)", RegexOptions.Multiline); Console.WriteLine(httpInfo); if (myReg.IsMatch(httpInfo)) { Match m = myReg.Match(httpInfo); if (m.Groups["method"].Value.ToUpper() == "POST") { _Method = MethodsList.POST; } else if (m.Groups["method"].Value.ToUpper() == "CONNECT") { _Method = MethodsList.CONNECT; } else { _Method = MethodsList.GET; } // also you can detect method like this // _Method = (MethodsList)Enum.Parse(typeof(MethodsList), m.Groups["method"].Value.ToUpper()); _Path = m.Groups["path"].Value; _HTTPVersion = m.Groups["version"].Value; } else { // answer // first line contain status code myReg = new Regex(@"HTTP/(?<version>[\d\.]+)\s+(?<status>\d+)\s*(?<msg>.*)", RegexOptions.Multiline); Match m = myReg.Match(httpInfo); int.TryParse(m.Groups["status"].Value, out _StatusCode); _StatusMessage = m.Groups["msg"].Value; _HTTPVersion = m.Groups["version"].Value; } // extract headers (until two new line symbols) _HeadersTail = sourceString.IndexOf("\r\n\r\n"); if (_HeadersTail != -1) { // tail was found, separate headers sourceString = sourceString.Substring(sourceString.IndexOf("\r\n") + 2, _HeadersTail - sourceString.IndexOf("\r\n") - 2); } // parse headers and put its to collection myReg = new Regex(@"^(?<key>[^\x3A]+)\:\s{1}(?<value>.+)$", RegexOptions.Multiline); MatchCollection mc = myReg.Matches(sourceString); foreach (Match mm in mc) { string key = mm.Groups["key"].Value; if (!_Items.ContainsKey(key)) { _Items.AddItem(key, mm.Groups["value"].Value.Trim("\r\n ".ToCharArray())); } } }
public Parser(byte[] source) { if (source == null || source.Length <= 0) { return; } _Source = source; _Items = new ItemCollection(); string sourceString = GetSourceAsString(); string httpInfo = sourceString.Substring(0, sourceString.IndexOf("\r\n")); Regex myReg = new Regex(@"(?<method>.+)\s+(?<path>.+)\s+HTTP/(?<version>[\d\.]+)", RegexOptions.Multiline); if (myReg.IsMatch(httpInfo)) { Match m = myReg.Match(httpInfo); if (m.Groups["method"].Value.ToUpper() == "POST") { _Method = MethodsList.POST; } else if (m.Groups["method"].Value.ToUpper() == "CONNECT") { _Method = MethodsList.CONNECT; } else { _Method = MethodsList.GET; } _Path = m.Groups["path"].Value; _HTTPVersion = m.Groups["version"].Value; } else { myReg = new Regex(@"HTTP/(?<version>[\d\.]+)\s+(?<status>\d+)\s*(?<msg>.*)", RegexOptions.Multiline); Match m = myReg.Match(httpInfo); int.TryParse(m.Groups["status"].Value, out _StatusCode); _StatusMessage = m.Groups["msg"].Value; _HTTPVersion = m.Groups["version"].Value; } _HeadersTail = sourceString.IndexOf("\r\n\r\n"); if (_HeadersTail != -1) { sourceString = sourceString.Substring(sourceString.IndexOf("\r\n") + 2, _HeadersTail - sourceString.IndexOf("\r\n") - 2); } myReg = new Regex(@"^(?<key>[^\x3A]+)\:\s{1}(?<value>.+)$", RegexOptions.Multiline); MatchCollection mc = myReg.Matches(sourceString); foreach (Match mm in mc) { string key = mm.Groups["key"].Value; if (!_Items.ContainsKey(key)) { _Items.AddItem(key, mm.Groups["value"].Value.Trim("\r\n ".ToCharArray())); } } }
/// <summary> /// Test if public methods on the service has Invoke or Query Attribute /// and generates from this methods their invocation method descriptions /// </summary> /// <returns></returns> private static void ProcessMethodDescriptions(BaseDomainService domainService, CachedMetadata metadata) { Type thisType= domainService.GetType(); IServiceContainer services = domainService.ServiceContainer; Func<MethodInfo, MethodType> fn_getMethodType = (m) => { if (m.IsDefined(typeof(QueryAttribute), false)) return MethodType.Query; else if (m.IsDefined(typeof(InvokeAttribute), false)) return MethodType.Invoke; else if (m.IsDefined(typeof(InsertAttribute), false)) return MethodType.Insert; else if (m.IsDefined(typeof(UpdateAttribute), false)) return MethodType.Update; else if (m.IsDefined(typeof(DeleteAttribute), false)) return MethodType.Delete; else if (m.IsDefined(typeof(ValidateAttribute), false)) return MethodType.Validate; else if (m.IsDefined(typeof(RefreshAttribute), false)) return MethodType.Refresh; else return MethodType.None; }; var dbsetsLookUp = metadata.dbSets.Values.ToLookup(v => v.EntityType); var dbsetsByType = dbsetsLookUp.ToDictionary(v => v.Key); var methodInfos = thisType.GetMethods(BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.Public); var allList = methodInfos.Select(m => new { method = m, methodType = fn_getMethodType(m) }); var queryAndInvokes = allList.Where((info) => info.methodType == MethodType.Query || info.methodType == MethodType.Invoke).ToArray(); MethodsList methodList = new MethodsList(); Array.ForEach(queryAndInvokes, (info) => { methodList.Add(MethodDescription.FromMethodInfo(info.method, info.methodType, services)); }); metadata.InitMethods(methodList); var otherMethods = allList.Where((info) => !(info.methodType == MethodType.Query || info.methodType == MethodType.Invoke || info.methodType == MethodType.None)).ToArray(); Array.ForEach(otherMethods, (info) => { Type entityType = null; if (info.methodType == MethodType.Refresh) { entityType = RemoveTaskFromType(info.method.ReturnType); } else { entityType = info.method.GetParameters().First().ParameterType; } IGrouping<Type, DbSetInfo> dbSets = null; if (!dbsetsByType.TryGetValue(entityType, out dbSets)) return; foreach (var dbSet in dbSets) { switch (info.methodType) { case MethodType.Insert: dbSet.insertDataMethod = info.method.Name; break; case MethodType.Update: dbSet.updateDataMethod = info.method.Name; break; case MethodType.Delete: dbSet.deleteDataMethod = info.method.Name; break; case MethodType.Validate: dbSet.validateDataMethod = info.method.Name; break; case MethodType.Refresh: dbSet.refreshDataMethod = info.method.Name; break; default: throw new DomainServiceException(string.Format("Unknown Method Type: {0}", info.methodType)); } } }); }
private List <StiToken> PostProcessTokensList(List <StiToken> tokensList) { List <StiToken> newList = new List <StiToken>(); tokenPos = 0; while (tokenPos < tokensList.Count) { StiToken token = tokensList[tokenPos]; tokenPos++; if (token.Type == StiTokenType.Identifier) { if ((newList.Count > 0) && (newList[newList.Count - 1].Type == StiTokenType.Dot)) { if (MethodsList.Contains(token.Value)) { token.Type = StiTokenType.Method; } //Proryv else if (Equals(token.Value, "Value") || ProryvPropertiesList.Contains(token.Value) || PropertiesList.Contains(token.Value)) { token.Type = StiTokenType.Property; } else { ThrowError(ParserErrorCode.FieldMethodOrPropertyNotFound, token, token.Value); } } else if (TypesList.Contains(token.Value)) { token.Type = StiTokenType.Cast; if ((tokenPos + 1 < tokensList.Count) && (tokensList[tokenPos].Type == StiTokenType.Dot)) { string tempName = token.Value + "." + tokensList[tokenPos + 1].Value; if (FunctionsList.Contains(tempName)) { token.Type = StiTokenType.Function; token.Value = tempName; tokenPos += 2; } //Proryv else if (ProryvFunctionsList.Contains(tempName)) { token.Type = StiTokenType.ProryvFunction; token.Value = tempName; tokenPos += 2; } if (SystemVariablesList.Contains(tempName)) { token.Type = StiTokenType.SystemVariable; token.Value = tempName; tokenPos += 2; } } } //Proryv else if (ProryvFunctionsList.Contains(token.Value)) { token.Type = StiTokenType.ProryvFunction; } else if (_proryvSpreadsheetProperties != null && _proryvSpreadsheetProperties.ContainsKey(token.Value.ToLowerInvariant())) { token.Type = StiTokenType.ProryvSpreadsheetProperties; } else if (_proryvFreeHierarchyBalanceSignature != null && _proryvFreeHierarchyBalanceSignature.ContainsKey(token.Value.ToLowerInvariant())) { token.Type = StiTokenType.ProryvFreeHierarchyBalanceSignature; } else if (FunctionsList.Contains(token.Value)) { while ((ProryvFunctionType)FunctionsList[token.Value] == ProryvFunctionType.NameSpace) { if (tokenPos + 1 >= tokensList.Count) { ThrowError(ParserErrorCode.UnexpectedEndOfExpression); } var np = tokensList[tokenPos + 1].Value; token.Value += "." + np; tokenPos += 2; if (!FunctionsList.Contains(token.Value)) { if (FunctionsList.Contains(np)) { token.Value = np; } else { ThrowError(ParserErrorCode.FunctionNotFound, token, token.Value); } } } token.Type = StiTokenType.Function; } else if (SystemVariablesList.Contains(token.Value) && (token.Value != "value")) { token.Type = StiTokenType.SystemVariable; } //else if (token.Value.ToLowerInvariant() == "true" || token.Value.ToLowerInvariant() == "false") //{ // if (token.Value.ToLowerInvariant() == "true") // token.ValueObject = true; // else // token.ValueObject = false; // token.Type = StiTokenType.Number; //} //else if (token.Value.ToLowerInvariant() == "null") //{ // token.ValueObject = null; // token.Type = StiTokenType.Number; //} else if (ConstantsList.Contains(token.Value)) { while (ConstantsList[token.Value] == namespaceObj) { if (tokenPos + 1 >= tokensList.Count) { ThrowError(ParserErrorCode.UnexpectedEndOfExpression); } string oldTokenValue = token.Value; token.Value += "." + tokensList[tokenPos + 1].Value; tokenPos += 2; if (!ConstantsList.Contains(token.Value)) { ThrowError(ParserErrorCode.ItemDoesNotContainDefinition, token, oldTokenValue, tokensList[tokenPos + 1].Value); } } token.ValueObject = ConstantsList[token.Value]; token.Type = StiTokenType.Number; } else if (UserFunctionsList.Contains(token.Value)) { token.Type = StiTokenType.Function; } else { ThrowError(ParserErrorCode.NameDoesNotExistInCurrentContext, token, token.Value); } } newList.Add(token); } return(newList); }