Here are the examples of the csharp api System.Activator.CreateInstance(System.Type) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
5106 Examples
19
Source : SparseImpulseSeries3D.xaml.cs
with MIT License
from ABTSoftware
with MIT License
from ABTSoftware
private void PointMarkerCombo_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (ImpulseSeries3D != null && OpacitySlider != null && SizeSlider != null)
{
ImpulseSeries3D.PointMarker = (BaseMeshPointMarker3D)Activator.CreateInstance((Type)((ComboBox)sender).SelectedItem);
ImpulseSeries3D.PointMarker.Fill = ImpulseSeries3D.Stroke;
ImpulseSeries3D.PointMarker.Size = (float)SizeSlider.Value;
ImpulseSeries3D.PointMarker.Opacity = OpacitySlider.Value;
}
}
19
Source : CreateABubble3DChart.xaml.cs
with MIT License
from ABTSoftware
with MIT License
from ABTSoftware
private void PointMarkerCombo_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (ScatterSeries3D != null && OpacitySlider != null && SizeSlider != null)
{
ScatterSeries3D.PointMarker = (BasePointMarker3D) Activator.CreateInstance((Type) ((ComboBox) sender).SelectedItem);
ScatterSeries3D.PointMarker.Size = (float) SizeSlider.Value;
ScatterSeries3D.PointMarker.Opacity = OpacitySlider.Value;
}
}
19
Source : CreateAPointCloud3DChart.xaml.cs
with MIT License
from ABTSoftware
with MIT License
from ABTSoftware
private void PointMarkerCombo_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (ScatterSeries3D != null && OpacitySlider != null && SizeSlider != null)
{
var pmType = (Type) ((ComboBox) sender).SelectedItem;
// Special case. CustomPointMarker is defined in the XAML as it contains a custom brush
if (pmType == typeof(CustomPointMarker3D))
{
var pointMarker = (CustomPointMarker3D)this.TryFindResource("CustomPointMarkerResource");
ScatterSeries3D.PointMarker = pointMarker;
}
else
{
// Create an instance of the pointmarker we want to draw
var pointMarker = (BasePointMarker3D)Activator.CreateInstance(pmType);
ScatterSeries3D.PointMarker = pointMarker;
}
ScatterSeries3D.PointMarker.Fill = Color.FromArgb(0x77, 0xAD, 0xFF, 0x2F);
ScatterSeries3D.PointMarker.Size = (float)SizeSlider.Value;
ScatterSeries3D.PointMarker.Opacity = OpacitySlider.Value;
}
}
19
Source : CreateAScatter3DChart.xaml.cs
with MIT License
from ABTSoftware
with MIT License
from ABTSoftware
private void PointMarkerCombo_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (ScatterSeries3D != null && OpacitySlider != null && SizeSlider != null)
{
ScatterSeries3D.PointMarker = (BasePointMarker3D)Activator.CreateInstance((Type)((ComboBox)sender).SelectedItem);
ScatterSeries3D.PointMarker.Fill = Colors.LimeGreen;
ScatterSeries3D.PointMarker.Size = (float)SizeSlider.Value;
ScatterSeries3D.PointMarker.Opacity = OpacitySlider.Value;
}
}
19
Source : ApplicationPage.cs
with MIT License
from ABTSoftware
with MIT License
from ABTSoftware
public void NewViewModel()
{
_viewModel = _viewModelType != null ? (BaseViewModel)Activator.CreateInstance(_viewModelType) : null;
}
19
Source : ChangeRenderableSeriesTypeExampleView.xaml.cs
with MIT License
from ABTSoftware
with MIT License
from ABTSoftware
private void SeriesComboSelectionChanged(object sender, SelectionChangedEventArgs e)
{
// When the selected series type combo changes, update the selected series type
if (seriesTypesCombo.SelectedValue == null ||
!sciChart.SelectedRenderableSeries.Any()) return;
// Get the selected series
var oldSelectedSeries = sciChart.SelectedRenderableSeries.First();
oldSelectedSeries.IsSelected = false;
// Replace it with a new series of the requested type
int index = sciChart.RenderableSeries.IndexOf(oldSelectedSeries);
var oldRenderableSeries = sciChart.RenderableSeries[index];
var newSelectedSeries = (BaseRenderableSeries)Activator.CreateInstance((Type) seriesTypesCombo.SelectedValue);
newSelectedSeries.Stroke = oldSelectedSeries.Stroke;
sciChart.RenderableSeries[index] = newSelectedSeries;
newSelectedSeries.DataSeries = oldRenderableSeries.DataSeries;
}
19
Source : HostContext.cs
with MIT License
from actions
with MIT License
from actions
public T CreateService<T>() where T : clreplaced, IRunnerService
{
Type target;
if (!_serviceTypes.TryGetValue(typeof(T), out target))
{
// Infer the concrete type from the ServiceLocatorAttribute.
CustomAttributeData attribute = typeof(T)
.GetTypeInfo()
.CustomAttributes
.FirstOrDefault(x => x.AttributeType == typeof(ServiceLocatorAttribute));
if (attribute != null)
{
foreach (CustomAttributeNamedArgument arg in attribute.NamedArguments)
{
if (string.Equals(arg.MemberName, ServiceLocatorAttribute.DefaultPropertyName, StringComparison.Ordinal))
{
target = arg.TypedValue.Value as Type;
}
}
}
if (target == null)
{
throw new KeyNotFoundException(string.Format(CultureInfo.InvariantCulture, "Service mapping not found for key '{0}'.", typeof(T).FullName));
}
_serviceTypes.TryAdd(typeof(T), target);
target = _serviceTypes[typeof(T)];
}
// Create a new instance.
T svc = Activator.CreateInstance(target) as T;
svc.Initialize(this);
return svc;
}
19
Source : ExtensionManager.cs
with MIT License
from actions
with MIT License
from actions
private void Add<T>(List<IExtension> extensions, string replacedemblyQualifiedName) where T : clreplaced, IExtension
{
Trace.Info($"Creating instance: {replacedemblyQualifiedName}");
Type type = Type.GetType(replacedemblyQualifiedName, throwOnError: true);
var extension = Activator.CreateInstance(type) as T;
ArgUtil.NotNull(extension, nameof(extension));
extension.Initialize(HostContext);
extensions.Add(extension);
}
19
Source : Program.cs
with MIT License
from actions
with MIT License
from actions
public static int Main(string[] args)
{
Console.CancelKeyPress += Console_CancelKeyPress;
// Set encoding to UTF8, process invoker will use UTF8 write to STDIN
Console.InputEncoding = Encoding.UTF8;
Console.OutputEncoding = Encoding.UTF8;
try
{
ArgUtil.NotNull(args, nameof(args));
ArgUtil.Equal(2, args.Length, nameof(args.Length));
string pluginType = args[0];
if (string.Equals("action", pluginType, StringComparison.OrdinalIgnoreCase))
{
string replacedemblyQualifiedName = args[1];
ArgUtil.NotNullOrEmpty(replacedemblyQualifiedName, nameof(replacedemblyQualifiedName));
string serializedContext = Console.ReadLine();
ArgUtil.NotNullOrEmpty(serializedContext, nameof(serializedContext));
RunnerActionPluginExecutionContext executionContext = StringUtil.ConvertFromJson<RunnerActionPluginExecutionContext>(serializedContext);
ArgUtil.NotNull(executionContext, nameof(executionContext));
VariableValue culture;
ArgUtil.NotNull(executionContext.Variables, nameof(executionContext.Variables));
if (executionContext.Variables.TryGetValue("system.culture", out culture) &&
!string.IsNullOrEmpty(culture?.Value))
{
CultureInfo.DefaultThreadCurrentCulture = new CultureInfo(culture.Value);
CultureInfo.DefaultThreadCurrentUICulture = new CultureInfo(culture.Value);
}
replacedemblyLoadContext.Default.Resolving += Resolvereplacedembly;
try
{
Type type = Type.GetType(replacedemblyQualifiedName, throwOnError: true);
var taskPlugin = Activator.CreateInstance(type) as IRunnerActionPlugin;
ArgUtil.NotNull(taskPlugin, nameof(taskPlugin));
taskPlugin.RunAsync(executionContext, tokenSource.Token).GetAwaiter().GetResult();
}
catch (Exception ex)
{
// any exception throw from plugin will fail the task.
executionContext.Error(ex.Message);
executionContext.Debug(ex.StackTrace);
return 1;
}
finally
{
replacedemblyLoadContext.Default.Resolving -= Resolvereplacedembly;
}
return 0;
}
else
{
throw new ArgumentOutOfRangeException(pluginType);
}
}
catch (Exception ex)
{
// infrastructure failure.
Console.Error.WriteLine(ex.ToString());
return 1;
}
finally
{
Console.CancelKeyPress -= Console_CancelKeyPress;
}
}
19
Source : CredentialManager.cs
with MIT License
from actions
with MIT License
from actions
public ICredentialProvider GetCredentialProvider(string credType)
{
Trace.Info(nameof(GetCredentialProvider));
Trace.Info("Creating type {0}", credType);
if (!CredentialTypes.ContainsKey(credType))
{
throw new ArgumentException("Invalid Credential Type");
}
Trace.Info("Creating credential type: {0}", credType);
var creds = Activator.CreateInstance(CredentialTypes[credType]) as ICredentialProvider;
Trace.Verbose("Created credential type");
return creds;
}
19
Source : XmlSerializableDataContractExtensions.cs
with MIT License
from actions
with MIT License
from actions
public bool IsIgnorableDefaultValue(object value)
{
if (DataMember.EmitDefaultValue)
{
return false;
}
var serializedType = SerializedType;
if (serializedType.GetTypeInfo().IsValueType)
{
var defaultValue = DefaultValuesByType.GetOrAdd(serializedType, key => Activator.CreateInstance(key));
return Equals(value, defaultValue);
}
return value == null;
}
19
Source : VssConnection.cs
with MIT License
from actions
with MIT License
from actions
private Task<Object> GetServiceInstanceAsync(
Type managedType,
Guid serviceIdentifier,
CancellationToken cancellationToken)
{
CheckForDisposed();
IVssClientService clientService;
try
{
// Create our instance of the managed service object.
clientService = (IVssClientService)Activator.CreateInstance(managedType);
}
catch (MissingMemberException ex)
{
throw new ArgumentException(WebApiResources.GetServiceArgumentError(managedType), ex);
}
// We successfully created an object, initialize him and finally set the
// return value.
clientService.Initialize(this);
return Task.FromResult<Object>(clientService);
}
19
Source : DataGridMaskedStringColumn.cs
with MIT License
from Actipro
with MIT License
from Actipro
protected virtual MaskedTextBox GenerateMaskedTextBox(bool isEditing, DataGridCell cell) {
MaskedTextBox textBox = null;
if ((cell != null) && (typeof(MaskedTextBox).IsInstanceOfType(cell.Content)))
textBox = (MaskedTextBox)cell.Content;
if (textBox == null)
textBox = (MaskedTextBox)Activator.CreateInstance(typeof(MaskedTextBox));
this.ApplyStandardValues(textBox);
if (isEditing)
textBox.Style = this.EditingElementStyle;
else
textBox.Style = this.ElementStyle;
this.ApplyBinding(textBox, MaskedTextBox.TextProperty);
return textBox;
}
19
Source : DataGridPartEditBoxColumnBase.cs
with MIT License
from Actipro
with MIT License
from Actipro
protected virtual PartEditBoxBase<T> GenerateEditBox(bool isEditing, DataGridCell cell) {
var type = this.GetEditBoxType();
PartEditBoxBase<T> editBox = null;
if ((cell != null) && (type.IsInstanceOfType(cell.Content)))
editBox = (PartEditBoxBase<T>)cell.Content;
if (editBox == null)
editBox = (PartEditBoxBase<T>)Activator.CreateInstance(type);
this.ApplyStandardValues(editBox);
if (isEditing)
editBox.Style = this.EditingElementStyle;
else
editBox.Style = this.ElementStyle;
this.ApplyBinding(editBox, PartEditBoxBase<T>.ValueProperty);
return editBox;
}
19
Source : Cloner.cs
with GNU General Public License v3.0
from Adam-Wilkinson
with GNU General Public License v3.0
from Adam-Wilkinson
public static bool TryClone<T>(T toClone, out T newObject)
{
if (toClone.GetType().IsValueType)
{
newObject = toClone;
return true;
}
if (toClone is ICloneable cloneable)
{
newObject = (T)cloneable.Clone();
return true;
}
Debug.WriteLine(toClone.GetType());
if (Cloners.TryGetValue(toClone.GetType(), out IObjectCloner cloner))
{
newObject = (T)cloner.Clone(toClone);
return true;
}
if (toClone.GetType().GetConstructor(Type.EmptyTypes) == null)
{
newObject = (T)Activator.CreateInstance(toClone.GetType());
return false;
}
newObject = default;
return false;
}
19
Source : NodeExtensions.cs
with GNU General Public License v3.0
from Adam-Wilkinson
with GNU General Public License v3.0
from Adam-Wilkinson
public static T Clone<T>(this T nodeToClone) where T : INode
{
T newNode = (T)Activator.CreateInstance(typeof(T));
if (nodeToClone is InputNode inputNodeToClone && newNode is InputNode newInputNode)
{
newInputNode.InputID = inputNodeToClone.InputID;
newInputNode.LaminarValue = inputNodeToClone.LaminarValue;
return newNode;
}
foreach ((INodeComponent CloneFrom, INodeComponent CloneTo) in nodeToClone.Fields.Zip(newNode.Fields))
{
CloneFrom.CloneTo(CloneTo);
CloneTo.ParentNode = newNode;
}
return newNode;
}
19
Source : UserInterfaceRegister.cs
with GNU General Public License v3.0
from Adam-Wilkinson
with GNU General Public License v3.0
from Adam-Wilkinson
private static object PrepareForReturning(object internalUserInterface)
{
if (typeof(Type).IsreplacedignableFrom(internalUserInterface.GetType()))
{
return Activator.CreateInstance((Type)internalUserInterface);
}
return internalUserInterface;
}
19
Source : NodeContainerSerializer.cs
with GNU General Public License v3.0
from Adam-Wilkinson
with GNU General Public License v3.0
from Adam-Wilkinson
public INodeContainer DeSerialize(ISerializedObject<INodeContainer> serialized, ISerializer serializer, object deserializationContext)
{
if (serialized is not SerializedNodeContainer serializedNodeContainer)
{
throw new ArgumentException("Can only deserialize objects of type SerializedNodeContainer", nameof(serialized));
}
if (deserializationContext is not IAdvancedScript advancedScript)
{
throw new ArgumentException("NodeContainerSerializer needs a context of type IAdvancedScript to work");
}
INode coreNode;
INodeContainer output;
Type coreNodeType = _instance.GetNodeType(serializedNodeContainer.CoreNodeName, serializedNodeContainer.Plugin);
if (coreNodeType == typeof(InputNode))
{
coreNode = advancedScript.Inputs[serializedNodeContainer.Name];
output = (INodeContainer)_getNodeMethod.MakeGenericMethod(coreNodeType).Invoke(_nodeFactory, new object[] { coreNode, serializedNodeContainer.Guid });
}
else
{
coreNode = (INode)Activator.CreateInstance(coreNodeType);
MethodInfo GetNodeMethod = _getNodeMethod.MakeGenericMethod(coreNodeType);
output = (INodeContainer)GetNodeMethod.Invoke(_nodeFactory, new object[] { coreNode, serializedNodeContainer.Guid });
coreNode.GetNameLabel().Name.Value = serializedNodeContainer.Name;
foreach ((object serializedComponent, INodeComponent component) in serializedNodeContainer.SerializedComponents.Zip(coreNode.Fields))
{
component.ParentNode = coreNode;
DeserializeNodeComponentTo(serializedComponent, component, serializer);
}
}
output.Location.X = serializedNodeContainer.X;
output.Location.Y = serializedNodeContainer.Y;
return output;
}
19
Source : ObjectFactory.cs
with GNU General Public License v3.0
from Adam-Wilkinson
with GNU General Public License v3.0
from Adam-Wilkinson
public object CreateInstance(Type type)
{
if (type == typeof(IObjectFactory))
{
return this;
}
if (type == typeof(Instance))
{
return _instance;
}
if (TryGetImplementation(type, out Type implementationType))
{
return CreateInstance(implementationType);
}
if (type.GetConstructor(Type.EmptyTypes) is not null)
{
return Activator.CreateInstance(type);
}
ConstructorInfo info = type.GetConstructors()[0];
ParameterInfo[] parameters = info.GetParameters();
object[] parameterObjects = new object[parameters.Length];
int i = 0;
foreach (ParameterInfo parameter in info.GetParameters())
{
parameterObjects[i] = CreateInstance(parameter.ParameterType);
i++;
}
return Activator.CreateInstance(type, parameterObjects);
}
19
Source : RxElement.cs
with MIT License
from adospace
with MIT License
from adospace
protected override void OnMount()
{
base.OnMount();
if (!_styled)
{
var styleForMe = _theme?.GetStyleFor(this);
if (styleForMe != null)
{
var themedNode = (RxElement<T>)Activator.CreateInstance(GetType());
styleForMe(themedNode);
themedNode._nativeControl = _nativeControl;
themedNode.OnUpdate();
themedNode.OnMigrated(this);
}
_styled = true;
}
}
19
Source : RazorEngineCompiledTemplateT.cs
with MIT License
from adoconnection
with MIT License
from adoconnection
public async Task<string> RunAsync(Action<T> initializer)
{
T instance = (T) Activator.CreateInstance(this.templateType);
initializer(instance);
await instance.ExecuteAsync();
return await instance.ResultAsync();
}
19
Source : RemoteComponentLoader.cs
with MIT License
from adospace
with MIT License
from adospace
public RxComponent LoadComponent<T>() where T : RxComponent, new()
{
if (_latestreplacedembly == null)
return new T();
var type = _latestreplacedembly.GetType(typeof(T).FullName);
if (type == null)
{
return null;
//throw new InvalidOperationException($"Unable to hot relead component {typeof(T).FullName}: type not found in received replacedembly");
}
return(RxComponent)Activator.CreateInstance(type);
}
19
Source : RazorEngineCompiledTemplate.cs
with MIT License
from adoconnection
with MIT License
from adoconnection
public async Task<string> RunAsync(object model = null)
{
if (model != null && model.IsAnonymous())
{
model = new AnonymousTypeWrapper(model);
}
IRazorEngineTemplate instance = (IRazorEngineTemplate) Activator.CreateInstance(this.templateType);
instance.Model = model;
await instance.ExecuteAsync();
return await instance.ResultAsync();
}
19
Source : SearchManager.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
private static TProvider InstantiateProvider<TProvider>(ProviderSettings settings) where TProvider : ProviderBase
{
try
{
var typeSetting = settings.Type == null ? null : settings.Type.Trim();
if (string.IsNullOrEmpty(typeSetting))
{
throw new ArgumentException("Type_Name_Required_For_Provider_Exception (Key present in resx file with same string)");
}
var providerType = Type.GetType(settings.Type, true, true);
if (!typeof(TProvider).IsreplacedignableFrom(providerType))
{
throw new ArgumentException("Provider must implement the clreplaced {0}.".FormatWith(typeof(TProvider)));
}
var provider = (TProvider)Activator.CreateInstance(providerType);
var parameters = settings.Parameters;
var config = new NameValueCollection(parameters.Count, StringComparer.Ordinal);
foreach (string key in parameters)
{
config[key] = parameters[key];
}
provider.Initialize(settings.Name, config);
return provider;
}
catch (Exception e)
{
if (e is ConfigurationException)
{
throw;
}
var typePropertyInformation = settings.ElementInformation.Properties["type"];
if (typePropertyInformation == null)
{
throw;
}
throw new ConfigurationErrorsException(e.Message, typePropertyInformation.Source, typePropertyInformation.LineNumber);
}
}
19
Source : CrmConfigurationManager.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
private static CrmConfigurationProvider CreateProvider()
{
var section = ConfigurationManager.GetSection(CrmSection.SectionName) as CrmSection ?? new CrmSection();
if (!string.IsNullOrWhiteSpace(section.ConfigurationProviderType))
{
var typeName = section.ConfigurationProviderType;
var type = TypeExtensions.GetType(typeName);
if (type == null || !type.IsA<CrmConfigurationProvider>())
{
throw new ConfigurationErrorsException("The value '{0}' is not recognized as a valid type or is not of the type '{1}'.".FormatWith(typeName, typeof(CrmConfigurationProvider)));
}
return Activator.CreateInstance(type) as CrmConfigurationProvider;
}
return new CrmConfigurationProvider();
}
19
Source : CrmOrganizationServiceContext.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
object IUpdatable.CreateResource(string containerName, string fullTypeName)
{
Tracing.FrameworkInformation("CrmOrganizationServiceContext", "CreateResource", "containerName={0}, fullTypeName={1}", containerName, fullTypeName);
var enreplacedyType = TypeExtensions.GetType(fullTypeName);
if (enreplacedyType.IsA(typeof(Enreplacedy)))
{
var enreplacedy = Activator.CreateInstance(enreplacedyType) as Enreplacedy;
AddObject(enreplacedy);
return enreplacedy;
}
return Activator.CreateInstance(enreplacedyType);
}
19
Source : InitializableConfigurationElement.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
private static TDependency CreateDependency<TDefault>(
Type type,
Func<TDefault> createDefault,
params object[] args)
where TDefault : TDependency
{
if (type == typeof(TDefault)) return createDefault();
if (type.IsA(typeof(TDefault))) return (TDependency)Activator.CreateInstance(type, args);
return (TDependency)Activator.CreateInstance(type);
}
19
Source : InitializableConfigurationElement.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
private static TDependency CreateDependency<TDefault1, TDefault2>(
Type type,
Func<TDefault1> createDefault1,
object[] args1,
Func<TDefault2> createDefault2,
object[] args2)
where TDefault1 : TDefault2
where TDefault2 : TDependency
{
if (type == typeof(TDefault1)) return createDefault1();
if (type.IsA(typeof(TDefault1))) return (TDependency)Activator.CreateInstance(type, args1);
if (type == typeof(TDefault2)) return createDefault2();
if (type.IsA(typeof(TDefault2))) return (TDependency)Activator.CreateInstance(type, args2);
return (TDependency)Activator.CreateInstance(type);
}
19
Source : PortalCrmConfigurationManager.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
private static PortalCrmConfigurationProvider CreateProvider()
{
var section = ConfigurationManager.GetSection(PortalCrmSection.SectionName) as PortalCrmSection ?? new PortalCrmSection();
if (!string.IsNullOrWhiteSpace(section.ConfigurationProviderType))
{
var typeName = section.ConfigurationProviderType;
var type = TypeExtensions.GetType(typeName);
if (type == null || !type.IsA<PortalCrmConfigurationProvider>())
{
throw new ConfigurationErrorsException("The value '{0}' is not recognized as a valid type or is not of the type '{1}'.".FormatWith(typeName, typeof(PortalCrmConfigurationProvider)));
}
return Activator.CreateInstance(type) as PortalCrmConfigurationProvider;
}
return new PortalCrmConfigurationProvider();
}
19
Source : EntityExtensions.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
public static Enreplacedy Clone(this Enreplacedy enreplacedy, bool includeRelatedEnreplacedies = true)
{
var clone = Activator.CreateInstance(enreplacedy.GetType()) as Enreplacedy;
return Clone(enreplacedy, clone, includeRelatedEnreplacedies, new List<Tuple<Enreplacedy, Enreplacedy>> { new Tuple<Enreplacedy, Enreplacedy>(enreplacedy, clone) });
}
19
Source : EntityExtensions.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
private static EnreplacedyCollection CloneEnreplacedyCollection(EnreplacedyCollection enreplacedies, bool includeRelatedEnreplacedies, IEnumerable<Tuple<Enreplacedy, Enreplacedy>> path)
{
var clones = new EnreplacedyCollection
{
EnreplacedyName = enreplacedies.EnreplacedyName,
MinActiveRowVersion = enreplacedies.MinActiveRowVersion,
MoreRecords = enreplacedies.MoreRecords,
PagingCookie = enreplacedies.PagingCookie,
TotalRecordCount = enreplacedies.TotalRecordCount,
TotalRecordCountLimitExceeded = enreplacedies.TotalRecordCountLimitExceeded,
};
foreach (var enreplacedy in enreplacedies.Enreplacedies)
{
// cycle detection
// resolve access to modified closure
var e = enreplacedy;
var duplicate = path.FirstOrDefault(p => p.Item1 == e);
if (duplicate != null)
{
// found a cycle, link the parent to the matched enreplacedy
clones.Enreplacedies.Add(duplicate.Item2);
}
else
{
// not a cycle, continue the recursion
var clone = Activator.CreateInstance(enreplacedy.GetType()) as Enreplacedy;
var enreplacedyClone = Clone(enreplacedy, clone, includeRelatedEnreplacedies, path.Concat(new List<Tuple<Enreplacedy, Enreplacedy>> { new Tuple<Enreplacedy, Enreplacedy>(enreplacedy, clone) }));
clones.Enreplacedies.Add(enreplacedyClone);
}
}
return clones;
}
19
Source : CrmEntityFormView.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
protected virtual ICellTemplateFactory CreateCellTemplateFactory()
{
var factoryType = Type.GetType(CellTemplateFactoryType, true, true);
return (ICellTemplateFactory)Activator.CreateInstance(factoryType);
}
19
Source : Behavior.cs
with GNU General Public License v3.0
from aduskin
with GNU General Public License v3.0
from aduskin
protected override Freezable CreateInstanceCore()
{
return (Freezable) Activator.CreateInstance(GetType());
}
19
Source : LevelInfo.cs
with GNU General Public License v3.0
from aelariane
with GNU General Public License v3.0
from aelariane
public static LevelInfo GetInfo(string name, bool initLogic)
{
InitData();
foreach (LevelInfo levelInfo in Levels)
{
if (levelInfo.Name == name)
{
if (initLogic)
{
FengGameManagerMKII.FGM.logic = (GameLogic.GameLogic)System.Activator.CreateInstance(levelInfo.LogicType);
}
return levelInfo;
}
}
return null;
}
19
Source : BombSettings.cs
with GNU General Public License v3.0
from aelariane
with GNU General Public License v3.0
from aelariane
public static BombStats Load(Type calculatorType)
{
IDataStorage storage = Settings.Storage;
var calculator = Activator.CreateInstance(calculatorType) as BombStatsCalculator;
string key = calculatorType.Name;
var stats = new BombStats();
BombStats defaultStats = calculator.GetDefaultStats();
stats.Radius = storage.GetFloat(key + "Radius", defaultStats.Radius);
stats.Range = storage.GetFloat(key + "Range", defaultStats.Range);
stats.Speed = storage.GetFloat(key + "Speed", defaultStats.Speed);
stats.Cooldown = storage.GetFloat(key + "Cooldown", defaultStats.Cooldown);
stats = calculator.ValidateStats(stats);
WriteToStorage(stats, calculatorType);
return stats;
}
19
Source : StructuredState.cs
with MIT License
from AElfProject
with MIT License
from AElfProject
private void InitializeProperties()
{
foreach (var kv in _propertyInfos)
{
var propertyInfo = kv.Value;
var type = propertyInfo.PropertyType;
var instance = Activator.CreateInstance(type);
propertyInfo.SetValue(this, instance);
}
}
19
Source : SerializationHelper.cs
with MIT License
from AElfProject
with MIT License
from AElfProject
public static T Deserialize<T>(byte[] bytes)
{
if (bytes == null)
return default;
var type = typeof(T);
var primitiveDeserializer = GetPrimitiveDeserializer(type);
if (primitiveDeserializer != null)
{
if (bytes.Length > 0)
{
return (T) primitiveDeserializer(bytes);
}
return default;
}
if (type == typeof(string))
{
return (T) (object) Encoding.UTF8.GetString(bytes);
}
if (type.IsEnum)
{
return (T) (object) Deserialize<int>(bytes);
}
if (typeof(IMessage).IsreplacedignableFrom(type))
{
var instance = (IMessage) Activator.CreateInstance(type);
instance.MergeFrom(bytes);
return (T) instance;
}
throw new InvalidOperationException($"Invalid type {type}.");
}
19
Source : WebWebAppAElfModule.cs
with MIT License
from AElfProject
with MIT License
from AElfProject
public override object ReadJson(JsonReader reader,
Type objectType, object existingValue,
JsonSerializer serializer)
{
// The only way to find where this json object begins and ends is by
// reading it in as a generic ExpandoObject.
// Read an entire object from the reader.
var converter = new ExpandoObjectConverter();
object o = converter.ReadJson(reader, objectType, existingValue,
serializer);
// Convert it back to json text.
string text = JsonConvert.SerializeObject(o);
// And let protobuf's parser parse the text.
IMessage message = (IMessage) Activator
.CreateInstance(objectType);
return JsonParser.Default.Parse(text,
message.Descriptor);
}
19
Source : AssemblyHelper.cs
with MIT License
from AFei19911012
with MIT License
from AFei19911012
public static object CreateInternalInstance(string clreplacedName)
{
try
{
var type = Type.GetType($"{NameSpaceStr}.{clreplacedName}");
return type == null ? null : Activator.CreateInstance(type);
}
catch
{
return null;
}
}
19
Source : AllAnalyzersUnitTests.cs
with Apache License 2.0
from agoda-com
with Apache License 2.0
from agoda-com
[Test]
public void replacedyzer_MustHaveDescriptorreplacedle()
{
var types = typeof(TestMethodHelpers).replacedembly.GetTypes()
.Where(t => typeof(Diagnosticreplacedyzer).IsreplacedignableFrom(t) && !t.IsInterface && !t.IsAbstract);
replacedert.Multiple(() =>
{
foreach (var type in types)
{
var replacedyzer = (Diagnosticreplacedyzer) Activator.CreateInstance(type);
if (replacedyzer.SupportedDiagnostics.Any(d => string.IsNullOrEmpty(d.replacedle.ToString())))
{
replacedert.Fail($"replacedyzer {type} must define Descriptor.replacedle");
}
}
});
}
19
Source : ProfileService.cs
with Apache License 2.0
from Aguafrommars
with Apache License 2.0
from Aguafrommars
protected virtual Task<IEnumerable<Claim>> GetClaimsFromResource(Resource resource, ClaimsPrincipal subject, Client client, string caller, string providerTypeName)
{
var provider = _claimsProvider.FirstOrDefault(p => p.GetType().FullName == providerTypeName);
if (provider == null)
{
var path = resource.Properties[ProfileServiceProperties.ClaimProviderreplacedemblyPathKey];
#pragma warning disable S3885 // "replacedembly.Load" should be used
var replacedembly = replacedembly.LoadFrom(path);
#pragma warning restore S3885 // "replacedembly.Load" should be used
var type = replacedembly.GetType(providerTypeName);
provider = Activator.CreateInstance(type) as IProvideClaims;
}
return provider.ProvideClaims(subject, client, caller, resource);
}
19
Source : AdminStoreTestBase.cs
with Apache License 2.0
from Aguafrommars
with Apache License 2.0
from Aguafrommars
protected virtual object CreateParentEntiy(Type parentType)
{
return Activator.CreateInstance(parentType);
}
19
Source : ServiceCollectionExtensions.cs
with Apache License 2.0
from Aguafrommars
with Apache License 2.0
from Aguafrommars
public static IServiceCollection AddClaimsProviders(this IServiceCollection services, IConfiguration configuration)
{
var providerSetupOptions = configuration.GetSection("ClaimsProviderOptions").Get<IEnumerable<ClaimsProviderSetupOptions>>();
if (providerSetupOptions == null)
{
return services;
}
foreach(var options in providerSetupOptions)
{
#pragma warning disable S3885 // "replacedembly.Load" should be used
var replacedembly = replacedembly.LoadFrom(options.replacedemblyPath);
#pragma warning restore S3885 // "replacedembly.Load" should be used
var type = replacedembly.GetType(options.TypeName);
var setup = Activator.CreateInstance(type) as ISetupClaimsProvider;
setup.SetupClaimsProvider(services, configuration);
}
return services;
}
19
Source : AdminStore.cs
with Apache License 2.0
from Aguafrommars
with Apache License 2.0
from Aguafrommars
private async Task PopulateSubEnreplacediesAsync(string idName, string path, TEnreplacedy enreplacedy)
{
var property = _enreplacedyType.GetProperty(path);
var value = property.GetValue(enreplacedy);
if (value == null)
{
if (property.PropertyType.ImplementsGenericInterface(typeof(ICollection<>)))
{
value = Activator.CreateInstance(typeof(Collection<>).MakeGenericType(property.PropertyType.GetGenericArguments()));
}
else
{
value = Activator.CreateInstance(property.PropertyType);
}
property.SetValue(enreplacedy, value);
}
if (value is ICollection collection)
{
foreach (var v in collection)
{
await PopulateSubEnreplacedyAsync("Id", v).ConfigureAwait(false);
var idProperty = v.GetType().GetProperty(idName);
idProperty.SetValue(v, enreplacedy.Id);
}
return;
}
var parentIdProperty = _enreplacedyType.GetProperty($"{path}Id");
((IEnreplacedyId)value).Id = parentIdProperty.GetValue(enreplacedy) as string;
await PopulateSubEnreplacedyAsync("Id", value).ConfigureAwait(false);
parentIdProperty.SetValue(enreplacedy, ((IEnreplacedyId)value).Id);
}
19
Source : AdminStoreTestBase.cs
with Apache License 2.0
from Aguafrommars
with Apache License 2.0
from Aguafrommars
private async Task<TEnreplacedy> CreateEnreplacedyGraphAsync(IEnumerable<PropertyInfo> navigationProperties, ServiceProvider provider, IAdminStore<TEnreplacedy> sut)
{
var create = new TEnreplacedy
{
Id = Guid.NewGuid().ToString()
};
var parentPropetyName = GetParentIdName(create.GetType());
if (parentPropetyName != null)
{
var parentPropetyType = GetParentType(parentPropetyName);
await AddParentEnreplacedy(provider, create, parentPropetyName, parentPropetyType).ConfigureAwait(false);
}
var enreplacedy = await sut.CreateAsync(create).ConfigureAwait(false);
foreach (var property in navigationProperties)
{
var subEnreplacedyType = property.PropertyType;
if (subEnreplacedyType.ImplementsGenericInterface(typeof(ICollection<>)))
{
subEnreplacedyType = subEnreplacedyType.GetGenericArguments()[0];
var parentPropety = subEnreplacedyType.GetProperty(GetSubEnreplacedyParentIdName(enreplacedy.GetType()));
var subEnreplacedy = Activator.CreateInstance(subEnreplacedyType);
parentPropety.SetValue(subEnreplacedy, enreplacedy.Id);
var storeType = typeof(IAdminStore<>).MakeGenericType(subEnreplacedyType);
var subStore = provider.GetRequiredService(storeType) as IAdminStore;
await subStore.CreateAsync(subEnreplacedy).ConfigureAwait(false);
continue;
}
await AddParentEnreplacedy(provider, create, $"{property.Name}Id", property.PropertyType).ConfigureAwait(false);
}
await sut.UpdateAsync(enreplacedy).ConfigureAwait(false);
return enreplacedy;
}
19
Source : ProxyClaimsProvider.cs
with Apache License 2.0
from Aguafrommars
with Apache License 2.0
from Aguafrommars
private Task<IEnumerable<Claim>> GetClaimsFromResource(Resource resource, ClaimsPrincipal subject, Client client, string caller, string providerTypeName)
{
var provider = _claimsProviders.FirstOrDefault(p => p.GetType().FullName == providerTypeName);
if (provider == null)
{
var path = resource.Properties[ProfileServiceProperties.ClaimProviderreplacedemblyPathKey];
#pragma warning disable S3885 // "replacedembly.Load" should be used
var replacedembly = replacedembly.LoadFrom(path);
#pragma warning restore S3885 // "replacedembly.Load" should be used
var type = replacedembly.GetType(providerTypeName);
provider = Activator.CreateInstance(type) as IProvideClaims;
}
return provider.ProvideClaims(subject, client, caller, resource);
}
19
Source : RsaEncryptorDescriptor.cs
with Apache License 2.0
from Aguafrommars
with Apache License 2.0
from Aguafrommars
public static Func<T> CreateFactory<T>(Type implementation)
{
return ((IActivator<T>)Activator.CreateInstance(typeof(AlgorithmActivatorCore<>).MakeGenericType(implementation))).Creator;
}
19
Source : ValidationAspect.cs
with MIT License
from ahmet-cetinkaya
with MIT License
from ahmet-cetinkaya
protected override void OnBefore(IInvocation invocation)
{
var validator = (IValidator) Activator.CreateInstance(_validatorType);
var enreplacedyType = _validatorType.BaseType.GetGenericArguments()[0];
var enreplacedies = invocation.Arguments.Where(t => t.GetType() == enreplacedyType);
foreach (var enreplacedy in enreplacedies) ValidationTool.Validate(validator, enreplacedy);
}
19
Source : ViewLocator.cs
with MIT License
from ahopper
with MIT License
from ahopper
public IControl Build(object data)
{
var typeName = data.GetType().FullName;
if (typeName?.Replace("ViewModel", "View") is string name )
{
if(Type.GetType(name) is Type type)
{
if(Activator.CreateInstance(type) is Control control)
{
return control;
}
}
}
return new TextBlock { Text = $"View Not Found For: { typeName ?? data.GetType().Name }" };
}
19
Source : TypeExtensions.cs
with MIT License
from ahydrax
with MIT License
from ahydrax
private static object CreateSampleInstanceInternal(this Type type, int currentDepth, int maxDepth)
{
if (currentDepth > maxDepth) return GetDefaultValue(type);
var instance = Activator.CreateInstance(type);
foreach (var property in type.GetProperties())
{
var propertyType = property.PropertyType;
if (propertyType.CanBeInstantiated())
{
type.GetProperty(property.Name).SetValue(instance,
propertyType.CreateSampleInstanceInternal(currentDepth + 1, SampleMaxDepth));
}
if (typeof(IEnumerable).IsreplacedignableFrom(propertyType)
&& propertyType != typeof(string))
{
var elementType = propertyType.IsArray
? propertyType.GetElementType()
: propertyType.GenericTypeArguments[0];
var array = Array.CreateInstance(elementType, 1);
array.SetValue(
elementType.CanBeInstantiated()
? elementType.CreateSampleInstanceInternal(currentDepth + 1, SampleMaxDepth)
: GetDefaultValue(elementType),
0);
type.GetProperty(property.Name).SetValue(instance, array);
}
}
return instance;
}
See More Examples