mardi 10 août 2021

Dynamically create instance of Repository pattern

I am using a repository pattern in 4.8 with DI and EF 6

This is my Repo

public class LookupRepositoryBase<TEntity> : Repository<TEntity> where TEntity : AbstractBase, new()
       {
              public readonly SampleModel _context; 
              public LookupRepositoryBase(SampleModel injectedContext) : base(injectedContext)
              {
                     _context = injectedContext;
               
              }
}

AS you can see it accepts any class that uses the AbstractBase normally DI handles the constructor of the SampleModel which is the EF Data Context

in my test console all I can simply do something like

LookupRepositoryBase<Bob> bobRepo = new LookupRepositoryBase<Bob>('insert ef data context here');

I am trying to do this dynamically since I have about 30 classes (all for drop downs) I need to load dynamically

here is what I have thus far

                     FileInfo fi = new FileInfo("Web.Data.dll");

                     Assembly assembly = Assembly.LoadFrom(fi.FullName);
                     Type genericClass = assembly.GetTypes().SingleOrDefault(s => s.Name == "LuBob");
                     Type typeArgument2 = assembly.GetTypes().SingleOrDefault(s => s.Name == "SampleModel");

                
                     Type genericClassRepo = typeof(LookupRepositoryBase<>);
           

                     //genericClass.

                     Type constructedClass = genericClass.MakeGenericType();
              
                     object created = Activator.CreateInstance(constructedClass);

my problem is how do I insert/ make the constructor for my LookupRepositoryBase 

I do not want to have to make a seperate method in the repo for setting it





lundi 9 août 2021

ReflectionTestUtils.setField - TypeMismatchException

I am trying to test a Spring service method, setting a private variable annotated with @Value via 'ReflectionTestUtils.setField' method.

Code: @Value("${temp-files-delete-time}") private int deleteTime;

Test: ReflectionTestUtils.setField(someService, "deleteTime", 1);

When it try to run it I get: java.lang.IllegalStateException: Failed to load ApplicationContext

org.springframework.beans.**TypeMismatchException**: Failed to convert value of type 'java.lang.String' to required type 'java.lang.Integer'; nested exception is java.lang.NumberFormatException: For input string: "${temp-files-delete-time}".

The variable I am trying to set is an int as well as the value I am using in the reflection method. Am I missing something ?





Is there a way to read property names from interface in typescript similar to reflections in c#

I have an interface defined and has multiple properties. Is there a way that I could read the property names in typescript/angular.

My interface looks is something similar as below

    export interface InterfaceName
   {
     property1: string;
     property2: string;
     property3: number;
   }




Spring Boot JUnit test beanFactory.getBean null pointer exception

I've a functioni'm trying to test via JUnit but I am not able to find how to overcome this issue:

in the service i have this declaration:

Warning_Log Warning_Log_FRAGMENT = beanFactory.getBean(Warning_Log.class);

I tried declaring the beanFactory object in the test class with the @MockBean annotation but i get a null pointer exception.

The cherry on top of the cake is that the function i'm testing is private so i'm using reflection to access it.

Do you know how the beanFactory(Warning_Log.class) can be implemented in the junit test function?

EDIT

the code in the service is the following:

try {
        JSONObject jsonFragmentRequestWarning_Log = new JSONObject();
        jsonFragmentRequestWarning_Log.put("messaggio", "Create Session Blocked [Assertion="+policy.getString("name")+"]|[flag_block_create_session="+gateway.flag_block_create_session+"]|[ApplicationName="+Request.getHeader("ApplicationName")+"]|[ErroreDaRitornare="+erroreDaRitornare+"]");
        jsonFragmentRequestWarning_Log.put("sanitize", false);

        Warning_Log Warning_Log_FRAGMENT = beanFactory.getBean(Warning_Log.class);
        
        String sFragmentResponseWarning_Log = Warning_Log_FRAGMENT.warning_Log(jsonFragmentRequestWarning_Log.toString(), httpHeaders);

        JSONObject jsonFragmentResponseWarning_Log = new JSONObject(sFragmentResponseWarning_Log);

    }

the beanFactory is autowired in the service like so:

@Autowired
private BeanFactory beanFactory;




Unespected result with type.GenericTypeArguments

with reflection I'm getting list of a Method of a Controller, successfully.

to get the arguments of a returntype of a method I'm using *.GenericTypeArguments in this way:

Some MethodInfo x.GenericTypeArguments.Select(a => a.Name);

When method is like it:

public async Task<ApiResult> SomeMethod();

im getting the good result: "ApiResult"

But when the return tyle has a list like:

public async Task<List<string>> SomeMethod();

I'm getting -> Task,List,System.Linq.Enumerable+SelectArrayIterator`2[System.Type,System.String] instead of Task,List,String

same for

public async Task<Dictionary<string,string>> SomeMethod();

expected Task,Dictionary,string,string

retrieved Task,Dictionary,System.Linq.Enumerable+SelectArrayIterator`2[System.Type,System.String]

Somebody can help to explain ?

Thankyou for help





dimanche 8 août 2021

How to write a C# Function that returns a class type speficifed as a parameter?

I am trying to write a JSON helper class for a C# MVC app that returns a class instance of the type that is specified as a parameter. The intent of this is to simplify deserializing a JSON into a Model of the right type. the Unfortunately i am running into an error of:

'ModelType' is a variable but used as a type.

Here is the code I am using:


        public ActionResult api_call() {
            // Parse/Map request stream containing a JSON to a C# object
            json_helper _o_json_helper = new json_helper();
            pollread_read_request _request = _o_json_helper.parse_json_to_object(Assembly.GetExecutingAssembly().GetType("pollread_read_request"), Request.InputStream); 
            // Create a business logic instance
            Pollmaker_business_logic _business_logic = new Pollmaker_business_logic();
            // process request using business logic
            List<pollread_read_response> _response = _business_logic.api_call(_request);
            // return result
            return Json(_response, JsonRequestBehavior.AllowGet);
        }

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Reflection;
namespace Umbrella.Abstracts {
    public class json_helper {
        public Object parse_json_to_object(Type ClassModelType, System.IO.Stream InputStream) {
            object _result = Activator.CreateInstance(ClassModelType);
            try {
                string _json_request = "";
                using (System.IO.Stream _oRequestStream = InputStream) {
                    _oRequestStream.Seek(0, System.IO.SeekOrigin.Begin);
                    _json_request = new System.IO.StreamReader(_oRequestStream).ReadToEnd();
                }
                if (!String.IsNullOrEmpty(_json_request)) {
                    _result = Newtonsoft.Json.JsonConvert.DeserializeObject<ClassModelType> (_json_request);
                }
            } catch { }
            return _result;               
        }
        public json_helper() {}
    }
}




VB.NET : Use System.Type in value binding

I am trying to use reflections in VB.NET to handle types.

    Public Function reflective(Of T)() As System.Type
        Dim t_ As T = Nothing
        Return t_.GetType()
    End Function
 
    Sub Main()
        Dim nbr_type As Type = reflective(Of Int32)() 'Works fine
        Console.Writeline("Number type is: " & nbr_type.Name) 'Works fine
        Dim nbr As nbr_type = Nothing 'Fails 'nbr_type' is not declared. It may be inac...
        'VB compiler completely fails to understand what I am trying to do
    End Sub

How do I initialize a variable using System.Type?