Which Activator.CreateInstance overload function to call? - c#-3.0

Which Activator.CreateInstance overload function to call? I have a type returned from
"Type proxyType = GetProxyType(contractType);" and the constructorinfo is
"[System.Reflection.RuntimeConstructorInfo] = {Void .ctor(System.ServiceModel.InstanceContext)}
base {System.Reflection.MemberInfo} = {Void .ctor(System.ServiceModel.InstanceContext)}
[System.Reflection.RuntimeConstructorInfo] = {Void .ctor(System.ServiceModel.InstanceContext, System.String)}
base {System.Reflection.MethodBase} = {Void .ctor(System.ServiceModel.InstanceContext, System.String)}
[System.Reflection.RuntimeConstructorInfo] = {Void .ctor(System.ServiceModel.InstanceContext, System.String, System.String)}
base {System.Reflection.MethodBase} = {Void .ctor(System.ServiceModel.InstanceContext, System.String, System.String)}
[System.Reflection.RuntimeConstructorInfo] = {Void .ctor(System.ServiceModel.InstanceContext, System.String, System.ServiceModel.EndpointAddress)}
base {System.Reflection.MethodBase} = {Void .ctor(System.ServiceModel.InstanceContext, System.String, System.ServiceModel.EndpointAddress)}
[System.Reflection.RuntimeConstructorInfo] = {Void .ctor(System.ServiceModel.InstanceContext, System.ServiceModel.Channels.Binding, System.ServiceModel.EndpointAddress)}
base {System.Reflection.MethodBase} = {Void .ctor(System.ServiceModel.InstanceContext, System.ServiceModel.Channels.Binding, System.ServiceModel.EndpointAddress)}.
Thanks!!

It seems the type has a default constructor so Activator.CreateInstance(proxyType); should work. If you want to call some other constructor for example the one that take a string parameter you could do this:
var instance = Activator.CreateInstance(proxyType, "some string parameter");
or the one with two string parameters:
var instance = Activator.CreateInstance(proxyType, "param1", "param2");
UPDATE:
My mistake there's no parameterless constructor for this type defined. All constructors need at least one argument which is of type InstanceContext. So in order to create an instance of this type you will need to pass at least the instance context. For example if you are in a WCF you could try this:
var instance = Activator.CreateInstance(
proxyType,
OperationContext.Current.InstanceContext
);

Related

A value of type 'List<ClienteModel>' can't be assigned to a variable of type 'RxList<ClienteModel>'

A value of type 'List' can't be assigned to a variable of type 'RxList'. Try changing the type of the variable, or casting the right-hand type to 'RxList'.
List initial = [];
RxList data= RxList(initial);
use like this
List<clientModal> clientmodal = [] ;
RxList<clientModal> data = RxList(initial as List<clientModal> );

Constructor parameter validation code doesn't compile

I'm trying to write a simple abstract class in F# with some basic parameter validation:
[<AbstractClass>]
type Record(recordType: int16) =
let recordType: int16 = recordType
do
if recordType < 0s then
invalidArg (nameof recordType)
However, I'm getting an error on the last line: 'this if expression is missing an else branch.' I tried adding an else branch that just evaluates to null, but then the type system doesn't agree with my code. Am I doing something wrong? Should I be validating my arguments using some other method?
The problem is that invalidArg requires a parameter name (which you've passed as nameof recordType as well as an error message, which you left off, and your if branch returns a function (string -> 'a as the return type is unknown/unreachable since the exception is thrown).
If you look at the docs for invalidArg, you see this: invalidArg parameter-name error-message-string. Your code is effectively like this:
// This is a function: string -> 'a (as it raises an exception, the return type is unknown)
let partialInvalidArg = invalidArg (nameof recordType)
if recordType < 0s then
partialInvalidArg // You're returning a function, not unit, so the compiler complains
If you include the error message, the function is actually called in the branch, and this will compile fine:
[<AbstractClass>]
type Record(recordType: int16) =
let recordType: int16 = recordType
do
if recordType < 0s then
invalidArg (nameof recordType) "The recordType must be greater or equal to zero"

What are the brackets in constructor in dart

#immutable
abstract class MyGithubReposState extends Equatable {
MyGithubReposState([List props = const []]) : super(props);
}
I have seen above code in one of the libraries I use. What does the [List props = const []] mean? List of list of props?
This is optional parameter as explained below.
A function can have two types of parameters:
required and optional.
The required parameters are listed first, followed by any optional parameters. Optional parameters can be named or positional.
Optional parameters can be either named or positional, but not both.
Named parameters
When calling a function, you can specify named parameters using paramName: value. For example:
this is calling of function
enableFlags(bold: true, hidden: false);
When defining a function, use {param1, param2, …} to specify named parameters:
this is how we define them
/// Sets the [bold] and [hidden] flags ...
void enableFlags({bool bold, bool hidden}) {...}
Positional parameters
Wrapping a set of function parameters in [] marks them as optional positional parameters:
String say(String from, String msg, [String device]) {
var result = '$from says $msg';
if (device != null) {
result = '$result with a $device';
}
return result;
}
so that we can call this function by two way
Without optional positional parameter
say('Bob', 'Howdy')
With optional positional parameter
say('Bob', 'Howdy', 'smoke signal')
Reference here
[within this is optional] means these parameters are optional
From the official docs,
Wrapping a set of function parameters in [] marks them as optional positional parameters
String say(String from, String msg, [String device]) {
var result = '$from says $msg';
if (device != null) {
result = '$result with a $device';
}
return result;
}
Here’s an example of calling this function without the optional parameter:
assert(say('Bob', 'Howdy') == 'Bob says Howdy');
And here’s an example of calling this function with the third parameter:
assert(say('Bob', 'Howdy', 'smoke signal') ==
'Bob says Howdy with a smoke signal');

Incorrect Instance Type for derived provided type in F# Erased Type Provider

I am working on a couple F# Type Providers to replace some half-baked code generation, and I'm having some issues with provided types that extend a base type. For instance, one of the providers is an Entity Framework provider where the metadata for the database schema is coming from an outside source, and I'm providing a type that uses DbContext as its base type. That type has properties to access the various DbSet<'table> members, but when I try to access those properties, I get the error Incorrect instance type. Parameter name: obj.
I believe this is due to the 'this' parameter (the first argument in the GetterCode and SetterCode of the provided property) actually being of type DbContext, and not my derived provided type. This would make sense, as my ProvidedConstructor for the context type is calling the DbContext constructor, but I'm not sure what else it could do. I can only surmise that I'm misunderstanding something about how the types are created. My code for the type definiton, constructor, and property are as follows. Please let me know if I'm doing something incorrectly.
let contextType = ProvidedTypeDefinition("MyContext", Some typeof<DbContext>)
let dbContextCtor = typeof<DbContext>.GetConstructor([|typeof<string>|])
let defaultCtor = // Use static parameter 'sqlConnection'
ProvidedConstructor(List.Empty,
BaseConstructorCall = (fun args -> dbContextCtor, args),
InvokeCode = fun args -> Expr.NewObject(dbContextCtor, [ <## sqlConnection ##> ]))
let stringCtor =
ProvidedConstructor([ProvidedParameter("sqlConnection", typeof<string>)],
BaseConstructorCall = (fun args -> dbContextCtor, args),
InvokeCode = fun args -> Expr.NewObject(dbContextCtor, [ args.[1] ]))
contextType.AddMember(defaultCtor)
contextType.AddMember(stringCtor)
...
// Add a DbSet field and property for each table to the context type
for providedType in providedTableTypes do
let fieldType = typedefof<DbSet<_>>.MakeGenericType([|providedType|])
let dbSetField = ProvidedField(sprintf "_%s" providedType.Name, fieldType)
let dbSetProperty =
ProvidedProperty(providedType.Name, fieldType,
GetterCode = (fun args -> Expr.FieldGet(args.[0], dbSetField)),
SetterCode = fun args -> Expr.FieldSet(args.[0], dbSetField, args.[1]))
dbSetField.SetFieldAttributes(FieldAttributes.HasDefault)
contextType.AddMember dbSetField
contextType.AddMember dbSetProperty
The table types are generated and DbSet properties are added to the context type, but when I attempt to access one of the properties, I receive the Incorrect instance type error when the GetterCode expression is evaluated.

How to dynamically create instances of objects in F#

I am having trouble finding out how to create a function that creates and instance of an object where the name of the variable that holds the function is specified in the parameter of the function.
I am writing an assignment where I do not know how many instances of the object that is to be created. I know how to call the constructor in a function, but I do not know how to give each instance a unique name?
let test() = class
let variable = 1
end
let createInstance (name : string) =
let name = new Test()
This is just a test example. This is what I have tried, but the function does not parse the string "name" to be the name of the object instance variable.
Thanks!