public static Query Parse(Type modelType, IQueryable source, QueryAttribute attr) { var query = new Query(modelType, source); if (attr != null) { query.Select = ParseSelect(modelType, attr); query.Where = ParseWhere(attr); query.OrderBy = ParseOrderBy(modelType, attr); //query.GroupBy = attr.GroupBy; query.Skip = ParseSkip(attr); query.Take = ParseTake(attr); query.CacheDuration = attr.CacheDuration; query.Includes = attr.Includes; query.Parameters = attr.Parameters; query.Paging = attr.Paging; query.PageSize = attr.PageSize > 0 ? attr.PageSize : Query.DefaultPageSize; query.Filter = attr.Filter; query.Id = attr.Id; } else { query.IsEmpty = true; } return(query); }
public void QueryAttribute_Properties() { QueryAttribute qa = new QueryAttribute(); // IsDefault can be set and reset qa.IsDefault = true; Assert.IsTrue(qa.IsDefault, "IsDefault should have been true after set"); qa.IsDefault = false; Assert.IsFalse(qa.IsDefault, "IsDefault should have been false after reset"); // IsComposable can be set and reset qa.IsComposable = true; Assert.IsTrue(qa.IsComposable, "IsComposable should have been true after set"); qa.IsComposable = false; Assert.IsFalse(qa.IsComposable, "IsComposable should have been false after reset"); // HasSideEffects can be set and reset qa.HasSideEffects = true; Assert.IsTrue(qa.HasSideEffects, "HasSideEffects should have been true after set"); qa.HasSideEffects = false; Assert.IsFalse(qa.HasSideEffects, "HasSideEffects should have been false after reset"); qa.ResultLimit = 5000; Assert.AreEqual(5000, qa.ResultLimit, "ResultLimit was not settable"); qa.ResultLimit = 0; Assert.AreEqual(0, qa.ResultLimit, "ResultLimit was not resettable"); }
private void GenerateEntityQueryMethodReturn(DomainOperationEntry domainOperationEntry, string parameterDictionaryName) { QueryAttribute queryAttribute = (QueryAttribute)domainOperationEntry.OperationAttribute; this.Write("return base.CreateQuery<"); this.Write(this.ToStringHelper.ToStringWithCulture(this.GetEntityQueryMethodElementReturnTypeName(domainOperationEntry))); this.Write(">(\""); this.Write(this.ToStringHelper.ToStringWithCulture(domainOperationEntry.Name)); this.Write("\", "); this.Write(this.ToStringHelper.ToStringWithCulture(parameterDictionaryName)); this.Write(", "); this.Write(this.ToStringHelper.ToStringWithCulture(CodeGenUtilities.GetBooleanString(queryAttribute.HasSideEffects, true))); this.Write(", "); this.Write(this.ToStringHelper.ToStringWithCulture(CodeGenUtilities.GetBooleanString(queryAttribute.IsComposable, true))); this.Write(");\r\n"); }
private static OrderBy ParseOrderBy(Type modelType, QueryAttribute spec) { if (!string.IsNullOrEmpty(spec.OrderBy)) { var orderBy = new OrderBy(); foreach (var element in spec.OrderBy.Split(OrderBy.ElementSeparator)) { if (OrderBy.IsValid(element)) { var parts = element.Split(OrderBy.Separator); var propertyName = parts[0]; var sortingDirection = parts[1]; if (string.IsNullOrEmpty(sortingDirection) || (!sortingDirection.ToLowerInvariant().Equals("asc") && !sortingDirection.ToLowerInvariant().Equals("desc"))) throw new InvalidOperationException(string.Format("Invalid sorting direction for the OtherBy clause of {0}'s query.", modelType.FullName)); orderBy.Elements.Add(propertyName, sortingDirection.ToLowerInvariant().Equals("asc") ? "ascending" : "descending"); } } return orderBy; } return null; }
private static OrderBy ParseOrderBy(Type modelType, QueryAttribute spec) { if (!string.IsNullOrEmpty(spec.OrderBy)) { var orderBy = new OrderBy(); foreach (var element in spec.OrderBy.Split(OrderBy.ElementSeparator)) { if (OrderBy.IsValid(element)) { var parts = element.Split(OrderBy.Separator); var propertyName = parts[0]; var sortingDirection = parts[1]; if (string.IsNullOrEmpty(sortingDirection) || (!sortingDirection.ToLowerInvariant().Equals("asc") && !sortingDirection.ToLowerInvariant().Equals("desc"))) { throw new InvalidOperationException(string.Format("Invalid sorting direction for the OtherBy clause of {0}'s query.", modelType.FullName)); } orderBy.Elements.Add(propertyName, sortingDirection.ToLowerInvariant().Equals("asc") ? "ascending" : "descending"); } } return(orderBy); } return(null); }
public void QueryAttribute_Default_Ctor() { QueryAttribute qa = new QueryAttribute(); Assert.IsFalse(qa.IsDefault, "IsDefault should be false using default ctor"); Assert.IsFalse(qa.HasSideEffects, "HasSideEffects should be false using default ctor"); Assert.AreEqual(0, qa.ResultLimit, "Result limit should be zero using default ctor"); Assert.IsTrue(qa.IsComposable, "IsComposable should be true using default ctor"); }
public HomeController(WelcomeMessage welcome, IHttpContextAccessor httpContextAccessor) { this.welcome = welcome; if (httpContextAccessor.HttpContext.User.Identity.IsAuthenticated) { var id = httpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value; } var options = new QueryAttribute().AllowedForProperty(typeof(string)); var select = QueryAttribute.QueryOptionsToEnum(options); }
private IQueryable <Series> ApplySeriesUidFilter(IQueryable <Series> series, QueryAttribute findQueryAttribute) { if (findQueryAttribute == null) { return(series); } // Exact match return(series.Where(x => x.SeriesDescription == findQueryAttribute.RawValue)); }
private IQueryable <Study> ApplyStudyUidFilter(IQueryable <Study> studies, QueryAttribute queryAttribute) { if (queryAttribute == null) { return(studies); } // Exact match return(studies.Where(x => x.StudyUid == queryAttribute.RawValue)); }
public static Query Parse(Uri requestUri) { var queryParams = HttpUtility.ParseQueryString(requestUri.Query); var query = new Query(); foreach (var queryParam in queryParams.AllKeys) { var value = queryParams[queryParam]; var queryParamLower = queryParam.ToLower(); if (queryParamLower == "includefield") { var values = value.Split(','); foreach (var splitValue in values) { var dicomTag = GetTag(splitValue); if (dicomTag == null) { query.Errors.Add(String.Format("include field specified unknown DICOM Keyword or Tag '{0}', skipping", queryParam)); continue; } query.IncludeFields.Add(dicomTag); } } else if (queryParamLower == "fuzzymatching") { query.FuzzyMatching = value.ToLower() == "false"; } else if (queryParamLower == "limit") { query.Limit = int.Parse(value); } else if (queryParamLower == "offset") { query.Offset = int.Parse(value); } else { // must be an attribute, var dicomTag = GetTag(queryParam); if (dicomTag == null) { query.Errors.Add(String.Format("unknown DICOM Keyword or Tag '{0}' specified, skipping", queryParam)); continue; } var queryAttribute = new QueryAttribute(); queryAttribute.RawKey = queryParam; queryAttribute.RawValue = value; queryAttribute.Tag = dicomTag; query.QueryAttributes.Add(dicomTag, queryAttribute); } } return(query); }
public void QueryAttribute_EmptyConstructor_PropertyCheck() { var attrib = new QueryAttribute(); Assert.AreEqual(GraphCollection.Query, attrib.FieldType); Assert.AreEqual(false, attrib.IsRootFragment); Assert.AreEqual(null, attrib.UnionTypeName); Assert.AreEqual(Constants.Routing.ACTION_METHOD_META_NAME, attrib.Template); Assert.AreEqual(TypeExpressions.Auto, attrib.TypeExpression); Assert.AreEqual(0, attrib.Types.Count); Assert.AreEqual(FieldResolutionMode.PerSourceItem, attrib.ExecutionMode); }
public void QueryAttribute_TemplateConstructor_PropertyCheck() { var attrib = new QueryAttribute("myQueryRoute"); Assert.AreEqual(GraphCollection.Query, attrib.FieldType); Assert.AreEqual(false, attrib.IsRootFragment); Assert.AreEqual(null, attrib.UnionTypeName); Assert.AreEqual("myQueryRoute", attrib.Template); Assert.AreEqual(TypeExpressions.Auto, attrib.TypeExpression); Assert.AreEqual(0, attrib.Types.Count); Assert.AreEqual(FieldResolutionMode.PerSourceItem, attrib.ExecutionMode); }
private bool ParameterBehavior(IHttpBehavior behavior, string paramName, QueryAttribute attr, EnctypeAttribute enctype, int argIndex, Encoding encoding, Formatters.IFormatter formatter) { if (attr == null) { return(false); } behavior.QueryKeys.Add(new HttpParameterBehavior(paramName, argIndex, encoding, formatter) { IsEncodeKey = attr.IsEncodeKey ?? enctype.DefaultEncodeKey, IsEncodeValue = true }); return(true); }
public void QueryAttribute_UnionConstructor_PropertyCheck() { var attrib = new QueryAttribute("myField", "myUnionType", typeof(AttributeDataIntegrityTests), typeof(GraphFieldAttribute)); Assert.AreEqual(GraphCollection.Query, attrib.FieldType); Assert.AreEqual(false, attrib.IsRootFragment); Assert.AreEqual("myUnionType", attrib.UnionTypeName); Assert.AreEqual("myField", attrib.Template); Assert.AreEqual(TypeExpressions.Auto, attrib.TypeExpression); Assert.AreEqual(2, attrib.Types.Count); Assert.AreEqual(typeof(AttributeDataIntegrityTests), attrib.Types[0]); Assert.AreEqual(typeof(GraphFieldAttribute), attrib.Types[1]); Assert.AreEqual(FieldResolutionMode.PerSourceItem, attrib.ExecutionMode); }
public static List <IPrefilterBase> GetQueryPrefilters(KeyValuePair <Type, string> property, QueryQueryCommand queryCommand, HttpInformation information, IServiceProvider serviceProvider) { ModelAttributesInfo modelAttributesInfo = property.Key.GetModelAttributesInfo(); QueryAttribute query = modelAttributesInfo.QueryAttributes .FirstOrDefault(q => q.QueryName.Equals(queryCommand.QueryName, StringComparison.InvariantCultureIgnoreCase)); DefaultQueryAttribute defaultQuery = modelAttributesInfo.DefaultQueryAttributes.SingleOrDefault(); if (query == null) { throw new QueryNotFoundException(queryCommand.ContextName, queryCommand.CollectionName, queryCommand.QueryName); } dynamic queryBuilder = Activator.CreateInstance(typeof(SapphireQueryBuilder <>).MakeGenericType(property.Key)); if (defaultQuery != null) { if (defaultQuery.FunctionLambda != null) { queryBuilder = defaultQuery.FunctionLambda(queryBuilder, information, queryCommand.Parameters); } else if (defaultQuery.FunctionInfo != null) { queryBuilder = defaultQuery.FunctionInfo.Invoke(null, defaultQuery.FunctionInfo.CreateParameters(information, serviceProvider, queryCommand.Parameters, (object)queryBuilder)); } } if (query.FunctionLambda != null) { queryBuilder = query.FunctionLambda(queryBuilder, information, queryCommand.Parameters); } else if (query.FunctionInfo != null) { queryBuilder = query.FunctionInfo.Invoke(null, query.FunctionInfo.CreateParameters(information, serviceProvider, queryCommand.Parameters, (object)queryBuilder)); } List <IPrefilterBase> prefilters = typeof(SapphireQueryBuilderBase <>) .MakeGenericType(property.Key) .GetField("prefilters")? .GetValue(queryBuilder); prefilters.ForEach(prefilter => prefilter.Initialize(property.Key)); return(prefilters); }
public void QueryAttribute_MultiTypeConstructor_PropertyCheck() { var attrib = new QueryAttribute(typeof(AttributeDataIntegrityTests), typeof(GraphFieldAttribute)); Assert.AreEqual(GraphCollection.Query, attrib.FieldType); Assert.AreEqual(false, attrib.IsRootFragment); Assert.AreEqual(null, attrib.UnionTypeName); Assert.AreEqual(Constants.Routing.ACTION_METHOD_META_NAME, attrib.Template); Assert.AreEqual(TypeExpressions.Auto, attrib.TypeExpression); Assert.AreEqual(2, attrib.Types.Count); Assert.AreEqual(typeof(AttributeDataIntegrityTests), attrib.Types[0]); Assert.AreEqual(typeof(GraphFieldAttribute), attrib.Types[1]); Assert.AreEqual(FieldResolutionMode.PerSourceItem, attrib.ExecutionMode); }
public string GetFormattedValue(object current) { var obj = Info.GetValue(current, null); string value = null; if (obj != null && Attributes.Count > 0) { QueryAttribute attribute = Attributes[0]; obj = attribute.Converter.Convert(obj, attribute.Format); var format = string.IsNullOrEmpty(attribute.Format) ? "{0}" : string.Format("{{0:{0}}}", attribute.Format); value = WebUtility.UrlEncode(string.Format(format, obj)); value = string.Format("{0}={1}", WebUtility.UrlEncode(attribute.Name), value); } return(value ?? string.Empty); }
public Query(QueryAttribute attribute) { if (null != attribute) { _domainName = attribute.DomainName; _queryName = attribute.QueryName; _uniqueIdentifier = attribute.UniqueIdentifier; // Make a query context _queryContext = new WriteContext() { Source = _queryName, CausationIdentifier = _uniqueIdentifier }; } }
private IQueryable <Series> ApplyModalityFilter(IQueryable <Series> series, QueryAttribute findQueryAttribute) { if (findQueryAttribute == null) { return(series); } // Handle wildcard matching if (findQueryAttribute.RawValue.EndsWith("*")) { var firstPart = findQueryAttribute.RawValue.Substring(0, findQueryAttribute.RawValue.Length - 1); return(series.Where(x => x.Modality != null && x.Modality.StartsWith(firstPart))); } // Exact match return(series.Where(x => x.Modality == findQueryAttribute.RawValue)); }
private IQueryable <Study> ApplyPatientIdFilter(IQueryable <Study> studies, QueryAttribute queryAttribute) { if (queryAttribute == null) { return(studies); } // Handle wildcard matching if (queryAttribute.RawValue.EndsWith("*")) { var firstPart = queryAttribute.RawValue.Substring(0, queryAttribute.RawValue.Length - 1); return(studies.Where(x => x.PatientId != null && x.PatientId.StartsWith(firstPart))); } // Exact match return(studies.Where(x => x.PatientId == queryAttribute.RawValue)); }
public SqlQuery(Type queryType, QueryAttribute attribute, IDapperWrapper dapperWrapper, string commandText = null) : base(queryType, attribute.QueryName, queryType.Name, attribute.MetricTransformEnum) { _dapperWrapper = dapperWrapper; QueryAttribute = attribute; if (attribute.MetricPattern != null) { MetricPattern = attribute.MetricPattern; } // Get the SQL resource from the same assembly as the type, when commandText is not supplied CommandText = commandText ?? queryType.Assembly.SearchForStringResource(attribute.ResourceName); // Get a pointer to the correctly typed Query method below with the QueryType as the generic parameter _genericMethod = typeof(IDatabaseMetric).IsAssignableFrom(queryType) ? _DatabaseMetricQueryMethod.MakeGenericMethod(queryType) : _QueryMethod.MakeGenericMethod(queryType); }
protected override object InvokeCore(object instance, object[] inputs, out object[] outputs) { outputs = ServiceUtility.EmptyObjectArray; ServiceQuery serviceQuery = null; QueryAttribute queryAttribute = (QueryAttribute)this.operation.OperationAttribute; if (queryAttribute.IsComposable) { object value; if (OperationContext.Current.IncomingMessageProperties.TryGetValue(ServiceQuery.QueryPropertyName, out value)) { serviceQuery = (ServiceQuery)value; } } IEnumerable <ValidationResult> validationErrors; int totalCount; QueryResult <TEntity> result; try { QueryOperationInvoker.SetOutputCachingPolicy(this.operation); result = QueryProcessor.Process <TEntity>((DomainService)instance, this.operation, inputs, serviceQuery, out validationErrors, out totalCount); } catch (Exception ex) { if (ex.IsFatal()) { throw; } QueryOperationInvoker.ClearOutputCachingPolicy(); throw ServiceUtility.CreateFaultException(ex); } if (validationErrors != null && validationErrors.Any()) { throw ServiceUtility.CreateFaultException(validationErrors); } return(result); }
private static Select ParseSelect(Type modelType, QueryAttribute spec) { var select = new Select(); var descriptor = new ModelDescriptor(ModelMappingManager.FindByType(modelType)); var properties = descriptor.GetProperties().OfType<PropertyDescriptor>(); select.Properties.AddRange(properties); if (!string.IsNullOrEmpty(spec.Select)) { select.Properties.Clear(); var propertyNames = spec.Select.Split(Select.Separator); foreach (var propertyName in propertyNames) { var property = properties.FirstOrDefault(p => p.Name == propertyName); if (property != null) select.Properties.Add(property); } } return select; }
protected override async ValueTask <object> InvokeCoreAsync(DomainService instance, object[] inputs, bool disableStackTraces) { ServiceQuery serviceQuery = null; QueryAttribute queryAttribute = (QueryAttribute)this.operation.OperationAttribute; // httpContext is lost on await so need to save it for later ise HttpContext httpContext = HttpContext.Current; if (queryAttribute.IsComposable) { object value; if (OperationContext.Current.IncomingMessageProperties.TryGetValue(ServiceQuery.QueryPropertyName, out value)) { serviceQuery = (ServiceQuery)value; } } QueryResult <TEntity> result; try { QueryOperationInvoker.SetOutputCachingPolicy(httpContext, this.operation); result = await QueryProcessor.ProcessAsync <TEntity>(instance, this.operation, inputs, serviceQuery); } catch (Exception ex) { if (ex.IsFatal()) { throw; } QueryOperationInvoker.ClearOutputCachingPolicy(httpContext); throw ServiceUtility.CreateFaultException(ex, disableStackTraces); } if (result.ValidationErrors != null && result.ValidationErrors.Any()) { throw ServiceUtility.CreateFaultException(result.ValidationErrors, disableStackTraces); } return(result); }
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 IQueryable <Study> ApplyStudyDateFilter(IQueryable <Study> studies, QueryAttribute queryAttribute) { if (queryAttribute == null) { return(studies); } // TODO: Handle wildcard matching??? if (queryAttribute.RawValue.Length > 8) { // range query var startDate = queryAttribute.RawValue.Substring(0, 8); var endDate = queryAttribute.RawValue.Substring(9, 8); return(studies.Where(x => String.Compare(x.StudyDate, startDate, StringComparison.Ordinal) >= 0 && String.Compare(x.StudyDate, endDate, StringComparison.Ordinal) < 0)); } // Exact match return(studies.Where(x => x.StudyDate == queryAttribute.RawValue)); }
public static Query Parse(Type modelType, IQueryable source, QueryAttribute attr) { var query = new Query(modelType, source); if (attr != null) { query.Select = ParseSelect(modelType, attr); query.Where = ParseWhere(attr); query.OrderBy = ParseOrderBy(modelType, attr); query.Skip = ParseSkip(attr); query.Take = ParseTake(attr); query.CacheDuration = attr.CacheDuration; query.Include = attr.Include; query.Parameters = attr.Parameters; query.Paging = attr.Paging; query.PageSize = attr.PageSize > 0 ? attr.PageSize : Query.DefaultPageSize; query.Id = attr.Id; } else query.IsEmpty = true; return query; }
private static Select ParseSelect(Type modelType, QueryAttribute spec) { var select = new Select(); var descriptor = new ModelDescriptor(ModelMappingManager.FindByType(modelType)); var properties = descriptor.GetProperties().OfType <PropertyDescriptor>(); select.Properties.AddRange(properties); if (!string.IsNullOrEmpty(spec.Select)) { select.Properties.Clear(); var propertyNames = spec.Select.Split(Select.Separator); foreach (var propertyName in propertyNames) { var property = properties.FirstOrDefault(p => p.Name == propertyName); if (property != null) { select.Properties.Add(property); } } } return(select); }
public static Tuple <IList <PropertyInfo>, QueryAttribute> GetPath(Type t, string name) { Tuple <IList <PropertyInfo>, QueryAttribute> result; var search = new Tuple <Type, string>(t, name); if (paths.TryGetValue(search, out result)) { return(result); } string[] names = name.Split('.'); List <PropertyInfo> properties = new List <PropertyInfo>(); Type currType = t; PropertyInfo lastProp = null; int i = 0; foreach (var property in names) { lastProp = currType.GetTypeInfo().GetProperty(property, BindingFlags.Instance | BindingFlags.Public | BindingFlags.GetProperty); i++; if (lastProp == null) { throw new WrongPropertyNameException(string.Join(".", names, 0, i)); } properties.Add(lastProp); currType = lastProp.PropertyType; } QueryAttribute attribute = null; if (lastProp != null) { attribute = lastProp.GetCustomAttribute(typeof(QueryAttribute)) as QueryAttribute; } var res = new Tuple <IList <PropertyInfo>, QueryAttribute>(properties, attribute); paths.TryAdd(search, res); return(res); }
public void BeforeRequestTest() { var method = typeof(IAubTestApi).GetMethod("PostAsync"); var context = new TestActionContext( httpApiConfig: new HttpApiConfig(), apiActionDescriptor: new ApiActionDescriptor("http://api.dev/", method, HttpMethod.Post) { Url = new Uri("http://api.dev/api/test/order"), Method = HttpMethod.Post }, null); var attr = new QueryAttribute(); var p1 = new ApiParameterDescriptor(name: "orderid", value: "21", attributes: null); attr.BeforeRequest(context, p1); Assert.True(context.RequestMessage.RequestUri == new Uri("http://api.dev/api/test/order?orderid=21")); var p2 = new ApiParameterDescriptor(name: "date", value: "20191201", attributes: null); attr.BeforeRequest(context, p2); Assert.True(context.RequestMessage.RequestUri == new Uri("http://api.dev/api/test/order?orderid=21&date=20191201")); }
// public static Task <Query> BuildQueryFromAttribute(QueryAttribute attribute, ValueBindingContext context) { // Use this and the attribute to create a new query instance return(Task <Query> .FromResult(new Query(attribute))); }
/// <summary> Write a Query XML Element from attributes in a member. </summary> public virtual void WriteQuery(System.Xml.XmlWriter writer, System.Reflection.MemberInfo member, QueryAttribute attribute, BaseAttribute parentAttribute, System.Type mappedClass) { writer.WriteStartElement( "query" ); // Attribute: <name> writer.WriteAttributeString("name", attribute.Name==null ? DefaultHelper.Get_Query_Name_DefaultValue(member) : GetAttributeValue(attribute.Name, mappedClass)); // Attribute: <flush-mode> if(attribute.FlushMode != FlushMode.Unspecified) writer.WriteAttributeString("flush-mode", GetXmlEnumValue(typeof(FlushMode), attribute.FlushMode)); // Attribute: <cacheable> if( attribute.CacheableSpecified ) writer.WriteAttributeString("cacheable", attribute.Cacheable ? "true" : "false"); // Attribute: <cache-region> if(attribute.CacheRegion != null) writer.WriteAttributeString("cache-region", GetAttributeValue(attribute.CacheRegion, mappedClass)); // Attribute: <fetch-size> if(attribute.FetchSize != -9223372036854775808) writer.WriteAttributeString("fetch-size", attribute.FetchSize.ToString()); // Attribute: <timeout> if(attribute.Timeout != -1) writer.WriteAttributeString("timeout", attribute.Timeout.ToString()); // Attribute: <cache-mode> if(attribute.CacheMode != CacheMode.Unspecified) writer.WriteAttributeString("cache-mode", GetXmlEnumValue(typeof(CacheMode), attribute.CacheMode)); // Attribute: <read-only> if( attribute.ReadOnlySpecified ) writer.WriteAttributeString("read-only", attribute.ReadOnly ? "true" : "false"); // Attribute: <comment> if(attribute.Comment != null) writer.WriteAttributeString("comment", GetAttributeValue(attribute.Comment, mappedClass)); WriteUserDefinedContent(writer, member, null, attribute); // Write the content of this element (mixed="true") writer.WriteString(attribute.Content); writer.WriteEndElement(); }
private static Where ParseWhere(QueryAttribute spec) { return !string.IsNullOrEmpty(spec.Where) ? new Where(spec.Where) : null; }
private static int? ParseTake(QueryAttribute spec) { return spec.Take > 0 ? spec.Take : (int?)null; }
private static int? ParseSkip(QueryAttribute spec) { return spec.Skip > 0 ? spec.Skip : (int?)null; }
public static Query Parse(string query) { Query toReturn; List <QueryAttribute> attributes = new List <QueryAttribute>(); int k = 0; //neem alles achter "WHERE" string[] separator = new string[] { "WHERE" }; string everything = query.Split(separator, StringSplitOptions.None)[1]; //split op "AND" separator = new string[] { "AND" }; string[] and = everything.Split(separator, StringSplitOptions.None); //switch op "IN" en "=" List <string> ins = new List <string>(); List <string> isses = new List <string>(); foreach (string str in and) { if (str.Contains("IN")) { ins.Add(str); } else { isses.Add(str); } } separator = new string[] { "IN" }; foreach (string str in ins) { string[] In = str.Split(separator, StringSplitOptions.None); string column = In[0]; column = column.Replace(" ", string.Empty); object[] desiredValues; int l = str.IndexOf("("); string values; values = str.Substring(l + 1, str.Length - (2 + l)); desiredValues = values.Split(','); //retrieve the properties of any column and thereby determine the data type ColumnProperties properties = TableProccessor.ColumnProperties[column]; if (properties.numerical == null || properties.numerical.Value) { for (int i = 0; i < desiredValues.Length; i++) { desiredValues[i] = Convert.ToDecimal(desiredValues[i]); } QueryAttribute attr = new QueryAttribute(In[0], desiredValues, true); attributes.Add(attr); } else { QueryAttribute attr = new QueryAttribute(In[0], desiredValues, false); attributes.Add(attr); } } foreach (string str in isses) { string[] Is = str.Split('='); string column = Is[0]; column = column.Replace(" ", string.Empty); Is[1] = Is[1].Replace(" ", string.Empty); Is[1] = Is[1].Replace("'", string.Empty); //when k is given, save in variable if (column == "k") { k = Convert.ToInt32(Is[1]); } object[] desiredValues = new object[1]; desiredValues[0] = Is[1]; //retrieve the properties of column and determine datatype ColumnProperties properties = TableProccessor.ColumnProperties[column]; if (properties.numerical != null && properties.numerical.Value) { desiredValues[0] = Convert.ToDecimal(desiredValues[0]); QueryAttribute attr = new QueryAttribute(Is[0], desiredValues[0], true); attributes.Add(attr); } else { QueryAttribute attr = new QueryAttribute(Is[0], Is[1], false); attributes.Add(attr); } } if (k != 0) { toReturn = new Query(attributes, k); } else { toReturn = new Query(attributes); } return(toReturn); }
private static QueryMapping CreateQueryMapping(QueryAttribute query, TypeMapping type) { return new QueryMapping { ID = query.Id ?? Guid.NewGuid().ToString("N"), Name = string.IsNullOrEmpty(query.Name) ? "All Items" : query.Name, Type = type, Visible = true }; }