/// <summary> /// Initializes all the appliers /// </summary> /// <returns></returns> private static List <IStyleApplyer> InitAppliers() { List <Type> allTypes = TypeReflector.GetAllLoadedTypes(); var appliers = new List <IStyleApplyer>(); foreach (Type type in allTypes) { if (type.IsClass) { if (typeof(IStyleApplyer).IsAssignableFrom(type)) { //if (CoreReflector.HasClassAttributes<StyleAttribute>(type)) try { appliers.Add((IStyleApplyer)Activator.CreateInstance(type)); } catch (Exception ex) { throw new Exception("Cannot create style applier instance of " + type, ex); } } } } return(appliers); }
private bool PresumePathParaBind() { if (false == this.MethodWrap.NeedPathPara(this.Parameter.Name)) { return(false); } PathParaBind paraBind; if (TypeReflector.IsPrivateValue(this.Parameter.ParameterType)) { paraBind = this.MethodWrap.GetPathParaBind(this.Parameter.Name); if (paraBind == null) { paraBind = new PathParaBind(this.Parameter.Name); this.PathParaBindes.Add(paraBind); return(true); } else { return(false); } } else { return(false); } }
public override void GenerateMappingCode(CodeGenerationContext ctx, CodeMemberMethod method) { if (!String.IsNullOrEmpty(To)) { MappedProperty = TypeReflector.GetProperty(ctx.MappedObjectType, To); } CodeExpression segmentObj; if (MappedProperty != null) { // mappedObj.PropName = new SegmentType(); method.Statements.AddRange(GenerateSetMappedPropertyCode(ctx.MappedObject, new CodeObjectCreateExpression(_segmentType))); segmentObj = GetMappedProperty(ctx.MappedObject); } else { // this._segmentField = new SegmentType(); segmentObj = ctx.Builder.AddNewField(SegmentType); method.Statements.Add(new CodeAssignStatement(segmentObj, new CodeObjectCreateExpression(_segmentType))); } CodeGenerationContext segmentCtx = ctx.Clone(); segmentCtx.MappedObject = segmentObj; segmentCtx.MappedObjectType = _segmentType; method.Statements.AddRange(ctx.Builder.NewElementsMappingCode(segmentCtx, Nodes)); }
private bool PresumeQueryStringBind() { QueryStringBind queryStringBind; List <FieldInfo> fieldInfos = new List <FieldInfo>(this.Parameter.ParameterType.GetFields()); List <PropertyInfo> properties = new List <PropertyInfo>(this.Parameter.ParameterType.GetProperties()); if (this.MethodWrap.IsGet()) { if (TypeReflector.IsPrivateValue(this.Parameter.ParameterType)) { queryStringBind = new QueryStringBind(this.Parameter.Name); this.QueryStringBindes.Add(queryStringBind); return(true); } else { fieldInfos.ForEach(f => { queryStringBind = new QueryStringBind(f.Name, f); this.QueryStringBindes.Add(queryStringBind); }); properties.ForEach(p => { queryStringBind = new QueryStringBind(p.Name, p); this.QueryStringBindes.Add(queryStringBind); }); return(true); } } if (this.MethodWrap.IsPOST()) { return(false); } return(false); }
/// <summary> /// Initialisiert eine neue Instanz der class <see cref="TypeSerializer"/> für das /// nicht serialisierbare Objekt <paramref name="instance"/> für eine Serialisierung mittles /// Reflection. /// </summary> /// <param name="instance">The instance.</param> private TypeSerializer(object instance) { using (var log = new EnterExitLogger(s_log, "instance = {0}", instance)) { m_instance = instance; m_type = m_instance.GetType(); m_fields = new FieldSerializerDict(); m_constructors = new ConstructorReflectorDict(); foreach (var ci in m_type.GetConstructors(MemberReflector.AllInstanceDeclared)) { var ctor = new ConstructorReflector(ci); m_constructors.Add(TypeReflector.BuildMethodSignature(ci), ctor); if (ctor.IsDefaultConstructor) { m_defaultConstructor = ctor; } } var fields = m_type.GetFields(MemberReflector.AllInstanceDeclared); foreach (var fi in fields) { var fieldValue = fi.GetValue(m_instance); fieldValue = CreateSerializerWrapper(fieldValue); m_fields.Add(fi.Name, new FieldSerializer(fi, fieldValue)); } } }
/// <summary> /// Deserialisiert für den WebService-Proxytyp <paramref name="webServiceType"/> den zugehörigen SoapClientType und /// registriert diesen im statischen Cache von <see cref="WebClientProtocol"/>. /// </summary> /// <param name="webServiceType">Der WebService-Proxytyp.</param> public static void DeserializeClientType(Type webServiceType) { using (var log = new EnterExitLogger(s_log, Level.Info, "webServiceType = {0}", webServiceType)) { if (!IsCached(webServiceType)) { var filename = GetSerializerPath(webServiceType); if (File.Exists(filename)) { var formatter = new BinaryFormatter(); var webClientProtocolReflector = new TypeReflector(typeof(WebClientProtocol)); var cache = webClientProtocolReflector.GetField("cache"); var cacheReflector = new TypeReflector(cache.GetType()); //debug: var cacheHashtable = (Hashtable)cacheReflector.GetField(cache, "cache"); object deserializedClientType = null; using (var stream = new FileStream(filename, FileMode.Open)) { deserializedClientType = TypeSerializer.Deserialize(formatter, stream); webClientProtocolReflector.Invoke("AddToCache(System.Type, System.Object)", new object[] { webServiceType, deserializedClientType }); log.Log("added to WebClient cache: {0}", deserializedClientType); } } } } }
public void RegisterAsType(object locator, Type type) { if (locator == null) { throw new NullReferenceException("Locator cannot be null"); } if (type == null) { throw new NullReferenceException("Type cannot be null"); } Func <object, object> factory = (_) => { try { return(TypeReflector.CreateInstanceByType(type)); } catch { return(null); } }; _registrations.Add(new Registration(locator, factory)); }
public void Generate() { Microsoft.VisualStudio.Shell.ThreadHelper.ThrowIfNotOnUIThread(); try { var xamlFileClassName = Path.GetFileNameWithoutExtension(_dte2.ActiveDocument.Name); using (var typeReflector = new TypeReflector()) { var typeReflectorResult = typeReflector.SelectClassFromAllReferencedAssemblies(_activeProject, xamlFileClassName, "Data Form Generator", _projectType, _projectFrameworkVersion); if (typeReflectorResult != null) { var win = new XamlPowerToysWindow(); var vm = new CreateFormViewModel(typeReflectorResult.ClassEntity, typeReflectorResult.AvailableConverters, ApplyChanges); var view = new CreateFormView(); win.DataContext = vm; win.rootGrid.Children.Add(view); win.ShowDialog(); if (vm.SelectedAction == SelectedAction.Generate) { InsertXaml(vm.ResultXaml); } } } } catch (Exception ex) { DialogAssistant.ShowExceptionMessage(ex); } }
internal override HttpContent Bindbody(RequestCreContext requestCreContext) { List <KeyValuePair <String, String> > keyValues = new List <KeyValuePair <String, String> >(); if (this.parameterWraps.Count == 0) { } this.parameterWraps.ForEach(x => { string valueStr; if (TypeReflector.IsComplextClass(x.Parameter.ParameterType)) { List <KeyValuePair <string, object> > valuePairs = DeconstructUtil.Deconstruct(requestCreContext.ParameterValues.Value[x.Parameter.Position]); valuePairs.ForEach(kp => { valueStr = x.Serial(kp.Value); keyValues.Add(new KeyValuePair <string, string>(kp.Key, valueStr)); }); } else { valueStr = x.Serial(requestCreContext); valueStr = valueStr ?? ""; keyValues.Add(new KeyValuePair <string, string>(x.DataName, valueStr)); } }); FormUrlEncodedContent formContent = new FormUrlEncodedContent(keyValues); return(formContent); }
internal override void SaveToParameterContext(ParameterWrapContext parameterItem) { if (TypeReflector.IsComplextClass(parameterItem.Parameter.ParameterType)) { throw new NotSupportedException("暂时不支持复杂类型用于header、pathpara"); } parameterItem.pathParaAttribute = this; }
internal override HttpContent Bindbody(RequestCreContext requestCreContext) { StringBuilder stringBuilder = new StringBuilder(); Newtonsoft.Json.JsonTextWriter jsonWriter = new JsonTextWriter(new StringWriter(stringBuilder)); jsonWriter.Formatting = Formatting.Indented; if (this.parameterWraps.Count == 1) { ParameterWrapContext parameterWrapContext = this.parameterWraps[0]; string valueStr = parameterWrapContext.Serial(requestCreContext); if (valueStr == null) { throw new LarkException("parameter value can not be null!"); } if (string.IsNullOrEmpty(parameterWrapContext.Name) && TypeReflector.IsComplextClass(parameterWrapContext.Parameter.ParameterType)) { jsonWriter.WriteRaw(valueStr); } else { jsonWriter.WriteStartObject(); jsonWriter.WritePropertyName(parameterWrapContext.DataName); if (valueStr != null) { jsonWriter.WriteRawValue(valueStr); } jsonWriter.WriteEndObject(); } } else if (this.parameterWraps.Count > 1) { jsonWriter.WriteStartObject(); this.parameterWraps.ForEach(x => { jsonWriter.WritePropertyName(x.DataName); object value = requestCreContext.ParameterValues.Value[x.Parameter.Position]; string valueStr = x.Serial(value); if (valueStr != null) { jsonWriter.WriteRawValue(valueStr); } }); jsonWriter.WriteEndObject(); } else { // output :{} jsonWriter.WriteRaw("{}"); } jsonWriter.Flush(); StringContent stringContent = new StringContent(stringBuilder.ToString(), Encoding.UTF8, "application/json"); return(stringContent); }
public void PutFromConfig(ContainerConfig config) { foreach (var componentConfig in config) { object component = null; object locator = null; try { // Create component dynamically if (componentConfig.Type != null) { locator = componentConfig.Type; component = TypeReflector.CreateInstanceByDescriptor(componentConfig.Type); } // Or create component statically else if (componentConfig.Descriptor != null) { locator = componentConfig.Descriptor; IFactory factory = _builder.FindFactory(locator); component = _builder.Create(locator, factory); if (component == null) { throw new ReferenceException(null, locator); } locator = _builder.ClarifyLocator(locator, factory); } // Check that component was created if (component == null) { throw new CreateException("CANNOT_CREATE_COMPONENT", "Cannot create component") .WithDetails("config", config); } // Add component to the list _references.Put(locator, component); // Configure component var configurable = component as IConfigurable; configurable?.Configure(componentConfig.Config); // Set references to factories if (component is IFactory) { var referenceable = component as IReferenceable; referenceable?.SetReferences(this); } } catch (Exception ex) { throw new ReferenceException(null, locator).WithCause(ex); } } }
private static string ConvertToSqlWhere(QueryBinary queryBinary, TypeReflector typeReflector, List <KeyValuePair <int, object> > parameters, IDictionary <string, CrossApplyDefinition> crossApplyDefinitions) { Validate.NotNull(queryBinary.Left, nameof(queryBinary), "Left"); Validate.NotNull(queryBinary.Right, nameof(queryBinary), "Right"); return($"({BuildSqlWhere(queryBinary.Left, typeReflector, parameters, crossApplyDefinitions)})" + $" {(queryBinary.Op == LogicalOperator.And ? "AND" : "OR")} " + $"({BuildSqlWhere(queryBinary.Right, typeReflector, parameters, crossApplyDefinitions)})"); }
private INameScopeDictionary HuntAroundForARootNameScope(ObjectWriterFrame rootFrame) { object instance = rootFrame.Instance; if ((instance == null) && rootFrame.XamlType.IsNameScope) { throw new InvalidOperationException(System.Xaml.SR.Get("NameScopeOnRootInstance")); } INameScopeDictionary nameScopeDictionary = null; nameScopeDictionary = instance as INameScopeDictionary; if (nameScopeDictionary == null) { INameScope underlyingNameScope = instance as INameScope; if (underlyingNameScope != null) { nameScopeDictionary = new NameScopeDictionary(underlyingNameScope); } } if (nameScopeDictionary == null) { XamlType xamlType = rootFrame.XamlType; if (xamlType.UnderlyingType != null) { XamlMember nameScopeProperty = TypeReflector.LookupNameScopeProperty(xamlType); if (nameScopeProperty != null) { INameScope scope2 = (INameScope)this._runtime.GetValue(instance, nameScopeProperty, false); if (scope2 == null) { nameScopeDictionary = new NameScope(); this._runtime.SetValue(instance, nameScopeProperty, nameScopeDictionary); } else { nameScopeDictionary = scope2 as INameScopeDictionary; if (nameScopeDictionary == null) { nameScopeDictionary = new NameScopeDictionary(scope2); } } } } } if (((nameScopeDictionary == null) && (this._settings != null)) && this._settings.RegisterNamesOnExternalNamescope) { ObjectWriterFrame previous = (ObjectWriterFrame)rootFrame.Previous; nameScopeDictionary = previous.NameScopeDictionary; } if (nameScopeDictionary == null) { nameScopeDictionary = new NameScope(); } rootFrame.NameScopeDictionary = nameScopeDictionary; return(nameScopeDictionary); }
private static string ConvertToSqlWhere(QueryIsNotNull queryIsNotNull, TypeReflector typeReflector, List <KeyValuePair <int, object> > parameters, IDictionary <string, CrossApplyDefinition> crossApplyDefinitions) { var reflectedType = typeReflector.Navigate(queryIsNotNull.Field); if (reflectedType == null) { throw new InvalidOperationException($"Unable to find property '{queryIsNotNull.Field}' on type '{typeReflector}'"); } return($"JSON_VALUE(_document,'$.{queryIsNotNull.Field}') IS NOT NULL"); }
private BindingReflector CreatePublicNonPublic <T>() { var reflector = new TypeReflector <T>().Bind().Public.NonPublic; Assert.IsTrue(reflector.HasPublic); Assert.IsTrue(reflector.HasNonPublic); Assert.AreEqual(null, reflector.InstanceObject); Assert.AreEqual(typeof(T), reflector.Type); return(reflector); }
public void GenerateAccessReflector() { var reflector = new TypeReflector <object>(); var bindingReflector = reflector.Bind().Public.NonPublic; var acceser = bindingReflector.GenerateAccessReflector(); Assert.AreEqual(bindingReflector.InstanceObject, acceser.InstanceObject); Assert.AreEqual(typeof(object), acceser.Type); Assert.AreEqual(bindingReflector, acceser.BindingReflector); }
/// <summary> /// Initializes a new instance of the <see cref="PropertyMapperCustomBase{TEntity, TProperty}"/> class. /// </summary> /// <param name="srcePropertyExpression">The <see cref="LambdaExpression"/> to reference the source entity property.</param> /// <param name="destPropertyName">The name of the destination property (defaults to <see cref="SrcePropertyName"/> where null).</param> /// <param name="operationTypes">The <see cref="Mapper.OperationTypes"/> selection to enable inclusion or exclusion of property (default to <see cref="OperationTypes.Any"/>).</param> protected PropertyMapperCustomBase(Expression <Func <TSrce, TSrceProperty> > srcePropertyExpression, string destPropertyName, OperationTypes operationTypes = OperationTypes.Any) { SrcePropertyExpression = PropertyExpression.Create(srcePropertyExpression ?? throw new ArgumentNullException(nameof(srcePropertyExpression))); SrcePropertyInfo = TypeReflector.GetPropertyInfo(typeof(TSrce), SrcePropertyName); DestPropertyName = string.IsNullOrEmpty(destPropertyName) ? SrcePropertyExpression.Name : destPropertyName; OperationTypes = operationTypes; if (SrcePropertyInfo.PropertyType.IsClass && SrcePropertyInfo.PropertyType != typeof(string)) { SrceComplexTypeReflector = ComplexTypeReflector.Create(SrcePropertyInfo); } }
internal override void SaveToParameterContext(ParameterWrapContext parameterItem) { if (TypeReflector.IsComplextClass(parameterItem.Parameter.ParameterType)) { throw new NotSupportedException("暂时不支持复杂类型用于header、pathpara"); } if (false == string.IsNullOrEmpty(Value)) { throw new NotSupportedException("对于参数指定Value无效!"); } parameterItem.HeaderAttributes.Add(this); }
private static FieldType ResolveField(string originalPath, TypeReflector typeReflector, IDictionary <string, CrossApplyDefinition> crossApplyDefinitions, bool appendToGroupByClause = false) { var fieldTypes = typeReflector.Navigate(originalPath).ToList(); if (!fieldTypes.Any()) { throw new InvalidOperationException($"Property '{originalPath}' is invalid"); } var resultingPath = new List <string>(); var tempPath = new List <string>(); CrossApplyDefinition lastCrossApplyDefinition = null; foreach (var fieldType in fieldTypes) { if (fieldType.IsObjectArray) { if (fieldType == fieldTypes.Last()) { throw new InvalidOperationException(); } tempPath.Add(fieldType.Name); lastCrossApplyDefinition = new CrossApplyDefinition { Parent = fieldType.Parent?.Path != null ? crossApplyDefinitions[fieldType.Parent.Path] : null, Name = string.Join(".", tempPath) }; crossApplyDefinitions[lastCrossApplyDefinition.Name] = lastCrossApplyDefinition; if (appendToGroupByClause) { lastCrossApplyDefinition.AppendToGroupBy = true; } tempPath.Clear(); } else { resultingPath.Add(fieldType.Name); tempPath.Add(fieldType.Name); } } return(new FieldType() { Type = fieldTypes.Last(), Path = string.Join(".", resultingPath), ParentField = lastCrossApplyDefinition?.Path ?? "_document" }); }
/// <summary> /// Initializes a new instance of the <see cref="FileColumnReflector"/> class. /// </summary> internal FileRecordReflector(Type type, FileFormatBase ff) { Type = type; TypeInfo = type.GetTypeInfo(); if (!TypeInfo.IsClass) { throw new ArgumentException($"Type '{type.Name}' must be a class.", nameof(type)); } // Get all the property/column metadata. FileFormat = ff; int i = 0; var columns = new List <FileColumnReflector>(); var children = new List <FileHierarchyReflector>(); foreach (var pi in TypeReflector.GetProperties(Type)) { i++; var fca = pi.GetCustomAttribute <FileColumnAttribute>(); var fha = pi.GetCustomAttribute <FileHierarchyAttribute>(); if (fca != null && fha != null) { throw new InvalidOperationException($"Type '{type.Name}' property '{pi.Name}' cannot specify both a FileColumnAttribute and FileHierarchyAttribute."); } if (fca != null) { columns.Add(new FileColumnReflector(i, fca, pi, FileFormat)); } if (fha != null) { var fhr = new FileHierarchyReflector(i, fha, pi, ff); if (children.SingleOrDefault(x => x.RecordIdentifier == fhr.RecordIdentifier) != null) { throw new InvalidOperationException($"Type '{type.Name}' property '{pi.Name}' FileHierarchyAttribute has a duplicate Record Identifier '{fhr.RecordIdentifier}' (must be unique within Type)."); } children.Add(new FileHierarchyReflector(i, fha, pi, ff)); } } // Order the Columns and Children by Order and Index for usage. Columns = columns.OrderBy(x => x.Order).ThenBy(x => x.Index).ToList(); Children = children.OrderBy(x => x.Order).ThenBy(x => x.Index).ToList(); for (int j = 0; j < Children.Count; j++) { _childrenIndexes.Add(Children[j].RecordIdentifier, j); } }
public async Task <int> CountAsync(NsDatabase database, string tableName, TypeReflector typeReflector, Query.Query query = null) { Validate.NotNull(database, nameof(database)); Validate.NotNullOrEmptyOrWhiteSpace(tableName, nameof(tableName)); var sql = new List <string>(); var parameters = new List <KeyValuePair <int, object> >(); SqlUtils.ConvertToSql(sql, typeReflector, database.Name, tableName, parameters, query, selectCount: true); return((int)(await ExecuteNonQueryAsync(sql.ToArray(), parameters.ToDictionary(_ => $"@{_.Key}", _ => _.Value), executeAsScalar: true))); }
public static byte[] CmdToBytes <T>(NetCmdBase cmd, int prefixLength) { byte[] data = TypeReflector.ObjToBytes <T>(cmd, prefixLength); if (data == null) { LogMgr.Log("Unregister cmd type:" + cmd.GetCmdType()); } else { data[0] = (byte)data.Length; data[1] = (byte)(data.Length >> 8); } return(data); }
public static string Create() { var namespaces = new List <string>() { "System", "System.Collections.Generic", "UnityEngine" }; StringBuilder sb = new StringBuilder(); var allTypes = TypeReflector.GetAllLoadedTypes(); //foreach (var type in allTypes) for (int i = 0; i < allTypes.Count; i++) { var type = allTypes[i]; if (!namespaces.Contains(type.Namespace) && !string.IsNullOrEmpty(type.Namespace)) { namespaces.Add(type.Namespace); } if (i >= allTypes.Count - 1) { sb.Append(string.Format("typeof({0})", type.Name)); } else { sb.AppendLine(string.Format("typeof({0}),", type.Name)); } } StringBuilder ns = new StringBuilder(); foreach (string s in namespaces) { ns.AppendLine(string.Format("using {0};", s)); } return(string.Format(@"{0} internal static class TypeReflector {{ internal static List<Type> GetList() {{ var list = new List<Type>() {{ {1} }}; return list; }} }}", ns, sb)); }
public static byte[] CmdToBytes(SendCmdPack pack, int prefixSize) { byte[] data = TypeReflector.ObjToBytes(pack.Cmd, pack.Hash, prefixSize); if (data == null) { LogMgr.Log("Unregister cmd type:" + pack.Cmd.GetCmdType()); } else { int length = data.Length - prefixSize; data[prefixSize] = (byte)length; data[prefixSize + 1] = (byte)(length >> 8); } return(data); }
public void TypeReflectorTest() { var typePost = TypeReflector.Create <Post>(); Assert.IsNotNull(typePost); Assert.AreEqual(9, typePost.Properties.Count); Assert.AreEqual(typeof(string), typePost.Properties["Title"].PropertyType); Assert.AreEqual(typeof(List <Comment>), typePost.Properties["Comments"].PropertyType); Assert.AreEqual(typeof(string[]), typePost.Properties["Tags"].PropertyType); var userTypes = TypeReflector.Navigate <Post>("Author.Username").ToList(); Assert.IsNotNull(userTypes); Assert.AreEqual(typeof(User), userTypes[0].Type); Assert.AreEqual(typeof(string), userTypes[1].Type); var tagsType = TypeReflector.Navigate <Post>("Tags").ToList(); Assert.IsNotNull(tagsType); Assert.IsTrue(tagsType[0].IsValueArray); Assert.AreEqual(typeof(string), tagsType[0].Type); var commentsType = TypeReflector.Navigate <Post>("Comments.Content").ToList(); Assert.IsNotNull(commentsType); Assert.IsTrue(commentsType[0].IsObjectArray); Assert.AreEqual(typeof(Comment), commentsType[0].Type); Assert.AreEqual(typeof(string), commentsType[1].Type); userTypes = TypeReflector.Navigate <Post>("Comments.Author.Username").ToList(); Assert.IsNotNull(userTypes); Assert.IsTrue(userTypes[0].IsObjectArray); Assert.AreEqual(typeof(Comment), userTypes[0].Type); Assert.AreEqual(typeof(User), userTypes[1].Type); Assert.AreEqual(typeof(string), userTypes[2].Type); var replieTypes = TypeReflector.Navigate <Post>("Comments.Replies.Author.Username").ToList(); Assert.IsNotNull(replieTypes); Assert.IsTrue(replieTypes[0].IsObjectArray); Assert.AreEqual(typeof(Comment), replieTypes[0].Type); Assert.IsTrue(replieTypes[1].IsObjectArray); Assert.AreEqual(typeof(Reply), replieTypes[1].Type); Assert.AreEqual(typeof(User), replieTypes[2].Type); Assert.AreEqual(typeof(string), replieTypes[3].Type); }
public EvaluatorEngine() : base(null) { vars = new Dictionary <string, object>(); this.typeReflector = TypeReflector.GetTypeReflectorFor(Globals.TypeRefs.ToReferenceContext(this.GetType())); engine = new Microsoft.JScript.Vsa.VsaEngine(); engine.doFast = false; output = new StringBuilder(); StringWriter sw = new StringWriter(output); engine.InitVsaEngine("executerjscript.net", new VsaSite(sw)); imports = new List <string>(); List <string> asses = new List <string>(); foreach (Assembly assem in AppDomain.CurrentDomain.GetAssemblies()) { try { VsaReference reference = new VsaReference(engine, Path.GetFileNameWithoutExtension(assem.Location)); engine.Items.CreateItem(reference.AssemblyName, Microsoft.Vsa.VsaItemType.Reference, Microsoft.Vsa.VsaItemFlag.None); if (Path.GetExtension(assem.EscapedCodeBase).Equals(".dll", StringComparison.InvariantCultureIgnoreCase)) { string tmp = Path.GetFileNameWithoutExtension(assem.EscapedCodeBase); if (!imports.Contains(tmp)) { Import.JScriptImport(tmp, engine); } } Import.JScriptImport("System.Net", engine); Import.JScriptImport("System.IO", engine); //using System; //using System.IO; //using System.Net; //using System.Text; } catch { } } }
private static string ConvertToSqlOrderBy(SortDescription sort, TypeReflector typeReflector, IDictionary <string, CrossApplyDefinition> crossApplyDefinitions) { if (sort.Field == "_id") { return($"_id {(sort.Order == SortOrder.Descending ? "DESC" : "ASC")}"); } var reflectedType = ResolveField(sort.Field, typeReflector, crossApplyDefinitions, true); if (reflectedType.Type.Is(typeof(int))) { return($"CONVERT([int],JSON_VALUE([{reflectedType.ParentField}],'$.{reflectedType.Path}')) {(sort.Order == SortOrder.Descending ? "DESC" : "ASC")}"); } return ($"JSON_VALUE([{reflectedType.ParentField}],'$.{reflectedType.Path}') {(sort.Order == SortOrder.Descending ? "DESC" : "ASC")}"); }
public override void GenerateMappingCode(CodeGenerationContext ctx, CodeMemberMethod method) { if (!String.IsNullOrEmpty(To)) { MappedProperty = TypeReflector.GetProperty(ctx.MappedObjectType, To); } // byte[] bytes = reader.ReadBytes(length); method.Statements.Add(new CodeVariableDeclarationStatement(typeof(byte[]), "bytes", new CodeMethodInvokeExpression(ctx.DataReader, "ReadBytes", new CodePrimitiveExpression(Length)))); if (MappedProperty != null) { // MemoryStream stream2 = new MemoryStream(bytes); CodeVariableReferenceExpression bytes = new CodeVariableReferenceExpression("bytes"); method.Statements.Add(new CodeVariableDeclarationStatement( typeof(MemoryStream), "stream2", new CodeObjectCreateExpression(typeof(MemoryStream), bytes))); CodeVariableReferenceExpression stream2 = new CodeVariableReferenceExpression("stream2"); // BinaryReader newReader = new BinarryReader(stream2); method.Statements.Add(new CodeVariableDeclarationStatement( typeof(BinaryReader), "reader2", new CodeObjectCreateExpression(typeof(BinaryReader), stream2))); CodeVariableReferenceExpression reader2 = new CodeVariableReferenceExpression("reader2"); //Type value = ? method.Statements.Add(new CodeVariableDeclarationStatement( MappedValueType, "value", GetPropertyValueExpression(MappedValueType, reader2))); CodeVariableReferenceExpression value = new CodeVariableReferenceExpression("value"); // add operations code foreach (IOperation op in Operations) { method.Statements.AddRange(op.BuildOperation(ctx, this, value)); } method.Statements.AddRange(GenerateSetMappedPropertyCode(ctx.MappedObject, value)); // newReader.Dispose(); method.Statements.Add(new CodeMethodInvokeExpression(reader2, "Close")); // newStream.Dispose(); method.Statements.Add(new CodeMethodInvokeExpression(stream2, "Close")); } }
internal void AddParameterQueryString(RequestCreContext requestCreContext, ParameterWrapContext parameterWrap) { HttpContent httpContext = requestCreContext.httpRequestMessage.Content; object paraValue = requestCreContext.ParameterValues.Value[parameterWrap.Parameter.Position]; if (TypeReflector.IsPrivateValue(parameterWrap.Parameter.ParameterType)) { //todo valueStr :performance problem ? string valueStr = parameterWrap.Serial(paraValue); parameterWrap.QueryString = this.Name + "=" + valueStr; requestCreContext.QueryString.Add(this.Name, valueStr); } else { if (Field == null && Property == null) { string valueStr = parameterWrap.Serial(paraValue); parameterWrap.QueryString = this.Name + "=" + valueStr; requestCreContext.QueryString.Add(this.Name, valueStr); } else { object value; string queryName = null; if (Field != null) { queryName = Field.Name; value = Field.GetValue(paraValue); } else if (Property != null) { queryName = Property.Name; value = Property.GetValue(paraValue); } else { throw new SystemException(nameof(this.Name)); } string valueStr = parameterWrap.Serial(value); parameterWrap.QueryString = queryName + "=" + valueStr; requestCreContext.QueryString.Add(queryName, valueStr); } } }
public void CheckMappedOfSimpleEntityWithMetadaAttribute() { var mappedType = TypeMapperFactory.CreateByConventions().Map<PersonWithMetadata>(); mappedType.Source.Should().Be.EqualTo(typeof(PersonWithMetadata)); mappedType.Mapped.Should().Be.EqualTo(typeof(PersonMetadata)); var primitiveProperty = mappedType.Primitives.Single(); var reflector = new TypeReflector<PersonWithMetadata>(); primitiveProperty.Name.Should().Be.EqualTo(reflector.PropertyName(x => x.Name)); primitiveProperty.Required.Should("The required attribute was not recognized.").Be.True(); mappedType.Collections.Single() .Name.Should().Be.EqualTo(reflector.PropertyName(x => x.Addresses)); mappedType.References.Single() .Name.Should().Be.EqualTo(reflector.PropertyName(x => x.Parent)); }