public static object LoadCollection(string serverConnectionString, string dbName, string collectionName) { object result = null; MongoClient client = new MongoClient(serverConnectionString); MongoServer mongoserver = client.GetServer(); var DyType = new { Name = "", Id = 0 }; //result = mongoserver.GetDatabase(dbName).GetCollection(collectionName).AsQueryable().ToList(); var filter = FilterDefinition <BsonDocument> .Empty; var collection = client.GetDatabase(dbName).GetCollection <BsonDocument>(collectionName); var Names = collection.Find(_ => true).ToList().Select(x => x.Names).FirstOrDefault().ToList(); var ty = MyTypeBuilder.CompileResultType(Names); result = client.GetDatabase(dbName).GetCollection <object>(collectionName).Find(_ => true).ToList(); var json = new JavaScriptSerializer().Serialize(result); File.WriteAllText("D:/jso.json", json); try { } catch { } return(result); }
static void Main(string[] args) { // Init List of method that I want to create var methods = new List <Method>(); methods.Add(new Method() { Name = "Add", Params = new List <MethodParam>() { new MethodParam() { Name = "a", Type = typeof(int) }, new MethodParam() { Name = "b", Type = typeof(int) } }, ReturnType = typeof(int) }); // Compile my type var myType = MyTypeBuilder.CompileResultType(methods); // Create instance of my type var myObject = Activator.CreateInstance(myType) as IFooContract; // Call Function var result = myObject.Add(5, 2); // Log Console.WriteLine(result); Console.Read(); }
public async Task <IResult> Confirm(AddMoneyDto addMoneyDto) //dto üzerinden onaylama { string adres = "https://api.genelpara.com/embed/doviz.json"; //json formatında döviz kurunun çekileceği link var myType = MyTypeBuilder.CompileResultType(new List <Field>() { new Field { FieldName = addMoneyDto.CurrencyType, FieldType = typeof(Money) } }); //json formatından nesneye dönüştürmek için nesne tipi üretiliyor var data = await WebApiHelper.GetMethod(adres, myType); //apiden veriler çekiliyor Money money = data.GetType().GetProperty(addMoneyDto.CurrencyType).GetValue(data) as Money; var result = _addMoneyDal.Get(a => a.Id == addMoneyDto.AddMoneyId);//id üzerinden bilgiler çekiliyor if (result.Status) { return(new ErrorResult()); } result.Status = true; //durum onaylandı yapılıyor _addMoneyDal.Update(result); var dovizKuru = money == null ? "1":money.Satis; //null ise döviz kuru 1 kabul ediliyor dovizKuru = dovizKuru.Replace('.', ','); decimal doviz = decimal.Parse(dovizKuru); doviz = doviz != (decimal)1.0 ? doviz : doviz; _walletService.AddMoney(new Wallet { Amount = addMoneyDto.Amount * doviz, UserId = result.UserId }); return(new SuccessResult("onaylandı")); }
public void CreateRuntimeClassInstanceTest() { var dic = new Dictionary <string, Type> { { "Id", typeof(int) } }; var ins = MyTypeBuilder.CreateNewObject(dic); Assert.True(ins.GetType().GetTypeInfo().GetProperty("Id") != null); }
public void ExceptionScanTest() { // generate a dynamic assembly. /* Purpose: dynamic assemblies do not support runtime type discovery and may break unit test framework exception*/ var tester = MyTypeBuilder.CreateNewObject(); // inject a type from the fuzzing assembly to check for some degenerative case /* Purpose: type in root namespace have a namespace property set as null that may be the source of NRE.*/ var temp = new NoNameSpaceType(); Check.That(ExceptionHelper.BuildException("Test")).IsInstanceOf <XunitException>(); Check.That(2).IsEqualTo(2); Check.ThatCode(() => Check.That(2).IsEqualTo(0)).IsAFailingCheck(); }
public void MakeDynamicType_PassInParameterInfo_AttachesAttributesToWrapperParameter() { // assemble var k = new MyTestKernel(); var attrTypes = new List <Type> { typeof(DulcetTonesAttribute) }; Type funcType = typeof(Func <int, Actor>); var paramInfo = typeof(DummyClass).GetConstructors().First().GetParameters().First(); // has "Thespian" attr on it // act Type dynamicType = MyTypeBuilder.MakeDynamicType(funcType, attrTypes, paramInfo); var ctorParamAttrs = dynamicType.GetConstructors().First().GetParameters().First().GetCustomAttribute <ThespianAttribute>(); // assert Assert.IsNotNull(ctorParamAttrs); }
private object CreateDataObject(IDictionary <string, Object> propData, out Type type) { #region Another trying //var fields = propData // .Select(p => p.Key) // .ToList(); //var properties = propData //.Select(p => new DynamicProperty(p.Key, typeof(object))) //.ToList(); //var resultType = DynamicClassFactory.CreateType(properties, false); //var definition = Activator.CreateInstance(resultType); #endregion var fieldList = new List <dynamic>(); foreach (var item in propData) { fieldList.Add(new { FieldName = item.Key, FieldType = item.Value != null ? item.Value.GetType() : typeof(object) }); } var newObject = MyTypeBuilder.CreateNewObject(fieldList, out Type newType); foreach (var item in propData) { var value = propData[item.Key]; if (value?.GetType().Name == "ExpandoObject") { var newJson = JsonConvert.SerializeObject(value); var newJsonExpando = JsonConvert.DeserializeObject <ExpandoObject>(newJson) as IDictionary <string, Object>; var newChildObj = CreateDataObject(newJsonExpando, out Type subType); newObject.GetType().GetProperty(item.Key).SetValue(newObject, newChildObj); } else { newObject.GetType().GetProperty(item.Key).SetValue(newObject, value); } } type = newType; return(newObject); }
private static void ByReflection(int total) { var fields = new Dictionary <string, Type>(); fields.Add("Id", typeof(int)); fields.Add("Nome", typeof(string)); var clientType = MyTypeBuilder.GetType("Client", fields); var listaCliente = new List <object>(total); for (int i = 0; i < total; i++) { var client = MyTypeBuilder.CreateNewObject(clientType); MyTypeBuilder.SetProperty(client, "Id", i); MyTypeBuilder.SetProperty(client, "Nome", $"Nome {i}"); listaCliente.Add(client); } ShowMemoryUsage("reflection"); }
public void MakeDynamicType_PassInAttrTypes_AttachesToClass() { // assemble var k = new MyTestKernel(); var attrTypes = new List <Type> { typeof(DulcetTonesAttribute) }; Type funcType = typeof(Func <int, Actor>); var dummyParamInfo = typeof(DummyClass).GetConstructors().First().GetParameters().First(); // act Type dynamicType = MyTypeBuilder.MakeDynamicType(funcType, attrTypes, dummyParamInfo); k.Bind(dynamicType).ToSelf(); var wrapperInstance = k.Get(dynamicType); var funcInstance = FuncValueGetter.GetFuncValue(wrapperInstance, dynamicType); MethodInfo mi = funcType.GetMethod(nameof(Func <int> .Invoke)); object result = mi.Invoke(funcInstance, new object[] { 2 }); // assert Assert.IsInstanceOf(typeof(Actor), result); }
public static void Main(string[] args) { // read the metadata from the table // foreach row in the metadata table // Create a class using dynamic class. List <IDynamicClassFields> dynamicClassFields = new List <IDynamicClassFields>() { new DynamicClassFields() { FieldName = "Id", FieldType = typeof(Int32) }, new DynamicClassFields() { FieldName = "Name", FieldType = typeof(string) } }; var DemoClass = MyTypeBuilder.CreateNewObject(dynamicClassFields, "Demo"); object value = "sharuk"; MyTypeBuilder.SetValue(DemoClass, "Name", value); CodeFirstDynamicModelEF codeFirstDynamicModelEF = new CodeFirstDynamicModelEF(); var configuration = new Configuration(); var migrator = new DbMigrator(configuration); migrator.Update(); codeFirstDynamicModelEF.MyEntities.Add(new MyEntity()); codeFirstDynamicModelEF.Set(DemoClass.GetType()).Add(DemoClass); codeFirstDynamicModelEF.SaveChanges(); }
private CodeTypeDeclaration GenerateClass() { if (!context.ContainsKey(schema)) { context.Add(schema, new GenerationResult() { TypeName = targetClass.Name, Type = MyTypeBuilder.CreateType(targetClass.Name), ClassGenerator = this }); } if (schema.Enum?.Count > 0) { return(GenerateClassFromEnumSchema()); } if (schema.Type?.Value is SimpleType && (schema.Type.Value as SimpleType).Value != SimpleType.Object) { var schemaType = schema.Type.Value as SimpleType; if (schemaType.Value == SimpleType.Integer) { return(GenerateClassFromIntegerSchema()); } if (schemaType.Value == SimpleType.Number) { return(GenerateClassFromNumberSchema()); } if (schemaType.Value == SimpleType.String) { return(GenerateClassFromStringSchema()); } if (schemaType.Value == SimpleType.Array) { return(GenerateClassFromArraySchema()); } } var definitions = schema.Definitions; if (definitions != null) { foreach (string definitionName in schema.Definitions.Keys) { var definition = definitions[definitionName]; if (!context.ContainsKey(definition)) { var nestedClassGenerator = new ClassGeneratorFromJsonSchema(definition, context); context[definition] = new GenerationResult() { Type = MyTypeBuilder.CreateType(nestedClassGenerator.targetClass.Name), TypeName = nestedClassGenerator.targetClass.Name, ClassGenerator = nestedClassGenerator }; nestedClassGenerator.GenerateClass(); } //context.Add(definition, new GenerationResult() { TypeName = nestedClassGenerator.targetClass.Name }); } } var properties = schema.Properties; var additionalProperties = schema.AdditionalProperties; //Oneof/AnyOf/AllOf are only supported when there are no properties or additionalProperties and when the schema type is not a primitive type or array type if (properties == null && additionalProperties == null) { if (schema.OneOf != null && schema.OneOf.Count > 0) { return(GenerateClassFromOneOfAnyOfSchema(true)); } if (schema.AnyOf != null && schema.AnyOf.Count > 0) { return(GenerateClassFromOneOfAnyOfSchema(false)); } if (schema.AllOf != null && schema.AllOf.Count > 0) { var mergedSchema = JSONSchema.MergeSchemas(schema.AllOf); var mergedClassGenerator = new ClassGeneratorFromJsonSchema(mergedSchema, this.targetClass.Name); targetClass = mergedClassGenerator.GenerateClass(); context[schema] = mergedClassGenerator.context[mergedSchema]; foreach (var jsonSchema in mergedClassGenerator.context.Keys) { if (jsonSchema != mergedSchema) { context[jsonSchema] = mergedClassGenerator.context[jsonSchema]; } } return(targetClass); } } if (properties != null) { foreach (string propertyName in properties.Keys) { var cleanPropertyName = Clean(propertyName); if (propertyNames.Contains(cleanPropertyName)) { //to avoid property names that would collide continue; } propertyNames.Add(cleanPropertyName); var property = properties[propertyName]; if (context.ContainsKey(property)) { targetClass.AddProperty(cleanPropertyName, context[property].TypeName); } else if (property.Type?.GetUnderlyingType() == typeof(SimpleType) && (property.Type.Value as SimpleType).Value != SimpleType.Object && (property.Type.Value as SimpleType).Value != SimpleType.Array && (property.Enum == null || property.Enum.Count < 1) ) { targetClass.AddProperty(cleanPropertyName, ComputeType((SimpleType)property.Type.GetValue())); } else { var nestedClassGenerator = new ClassGeneratorFromJsonSchema(property, context, cleanPropertyName); context[property] = new GenerationResult() { Type = MyTypeBuilder.CreateType(nestedClassGenerator.targetClass.Name), TypeName = nestedClassGenerator.targetClass.Name, ClassGenerator = nestedClassGenerator }; nestedClassGenerator.GenerateClass(); targetClass.AddProperty(cleanPropertyName, context[property].Type); } } } if (additionalProperties != null) { if (additionalProperties.Value is bool) { if ((bool)additionalProperties.Value == true) { targetClass.BaseTypes.Add(new CodeTypeReference(typeof(Dictionary <string, object>))); } } else { var additionalPropertiesSchema = additionalProperties.Value as JSONSchema; if (!context.ContainsKey(additionalPropertiesSchema)) { var nestedClassGenerator = new ClassGeneratorFromJsonSchema(additionalPropertiesSchema, context, context[schema].TypeName + "AdditionalProperties"); context[additionalPropertiesSchema] = new GenerationResult() { Type = MyTypeBuilder.CreateType(nestedClassGenerator.targetClass.Name), TypeName = nestedClassGenerator.targetClass.Name, ClassGenerator = nestedClassGenerator }; nestedClassGenerator.GenerateClass(); } targetClass.BaseTypes.Add(new CodeTypeReference("Dictionary", new CodeTypeReference(typeof(string)), new CodeTypeReference(context[additionalPropertiesSchema].Type))); context[schema].Imports.Add("System.Collections.Generic"); } } return(targetClass); }
private CodeTypeDeclaration GenerateClassFromOneOfAnyOfSchema(bool handleOneOf) { ISet <string> subSchemasSet = new HashSet <string>(); int index = 0; var schemaArray = handleOneOf ? schema.OneOf : schema.AnyOf; foreach (JSONSchema subSchema in schemaArray) { if (context.ContainsKey(subSchema)) { subSchemasSet.Add(context[subSchema].TypeName); } else if (subSchema.Type?.GetUnderlyingType() == typeof(SimpleType) && (subSchema.Type.Value as SimpleType).Value != SimpleType.Object && (subSchema.Type.Value as SimpleType).Value != SimpleType.Array ) { subSchemasSet.Add(ComputeType((SimpleType)subSchema.Type.GetValue()).Name); } else { var nestedClassGenerator = new ClassGeneratorFromJsonSchema(subSchema, context, string.Concat(targetClass.Name, handleOneOf?"OneOf":"AnyOf", index)); context[subSchema] = new GenerationResult() { Type = MyTypeBuilder.CreateType(nestedClassGenerator.targetClass.Name), TypeName = nestedClassGenerator.targetClass.Name, ClassGenerator = nestedClassGenerator }; nestedClassGenerator.GenerateClass(); subSchemasSet.Add(nestedClassGenerator.targetClass.Name); } index++; } targetClass = new CodeTypeDeclaration(targetClass.Name) { IsClass = true, TypeAttributes = TypeAttributes.Public }; var field = new CodeMemberField() { Attributes = MemberAttributes.Private | MemberAttributes.Final, Name = "Value", Type = new CodeTypeReference(typeof(object)) }; targetClass.Members.Add(field); CodeConstructor constructor = new CodeConstructor { Attributes = MemberAttributes.Private }; constructor.Comments.Add(new CodeCommentStatement("Hiding visiblity of default constructor")); targetClass.Members.Add(constructor); CodeStatement[] codeStatements = new CodeStatement[subSchemasSet.Count + 1]; index = 0; foreach (string subSchemaName in subSchemasSet) { codeStatements[index] = If(NewSnippet("value is " + subSchemaName), new CodeAssignStatement(new CodeVariableReferenceExpression("Value"), new CodeVariableReferenceExpression("value"))); index++; } codeStatements[index] = Throw(typeof(ArgumentException), "Value's type is not correct"); CodeConstructor publicConstructor = NewPublicConstructor( Array(NewParameter(typeof(object), "value")), codeStatements ); targetClass.Members.Add(publicConstructor); foreach (string subSchemaName in subSchemasSet) { var implicitOperator = new CodeSnippetTypeMember(string.Format("\t\tpublic static implicit operator {0}({1} d) => ({0})d.Value;", subSchemaName, targetClass.Name)); targetClass.Members.Add(implicitOperator); var explicitOperator = new CodeSnippetTypeMember(string.Format("\t\tpublic static explicit operator {0}({1} v) => new {0}(v);", targetClass.Name, subSchemaName)); targetClass.Members.Add(explicitOperator); } return(targetClass); }