System.Type.GetType()

Here are the examples of the csharp api System.Type.GetType() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

610 Examples 7

19 Source : TccMaster.cs
with MIT License
from 2881099

static void SetTccState(ITccUnit unit, TccUnitInfo unitInfo)
        {
            if (string.IsNullOrWhiteSpace(unitInfo.StateTypeName)) return;
            if (unitInfo.State == null) return;
            var stateType = Type.GetType(unitInfo.StateTypeName);
            if (stateType == null) return;
            (unit as ITccUnitSetter)?.SetState(Newtonsoft.Json.JsonConvert.DeserializeObject(unitInfo.State, stateType));
        }

19 Source : SagaMaster.cs
with MIT License
from 2881099

static void SetSagaState(ISagaUnit unit, SagaUnitInfo unitInfo)
        {
            if (string.IsNullOrWhiteSpace(unitInfo.StateTypeName)) return;
            if (unitInfo.State == null) return;
            var stateType = Type.GetType(unitInfo.StateTypeName);
            if (stateType == null) return;
            (unit as ISagaUnitSetter)?.SetState(Newtonsoft.Json.JsonConvert.DeserializeObject(unitInfo.State, stateType));
        }

19 Source : SagaMaster.cs
with MIT License
from 2881099

async static Task CancelAsync(FreeSqlCloud<TDBKey> cloud, string tid, bool retry)
        {
            var masterInfo = await cloud._ormMaster.Select<SagaMasterInfo>().Where(a => a.Tid == tid && a.Status == SagaMasterStatus.Pending && a.RetryCount <= a.MaxRetryCount).FirstAsync();
            if (masterInfo == null) return;
            var unitInfos = await cloud._ormMaster.Select<SagaUnitInfo>().Where(a => a.Tid == tid).OrderBy(a => a.Index).ToListAsync();
#endif
            var units = unitInfos.Select(unitInfo =>
            {
                try
                {
                    var unitTypeDefault = Type.GetType(unitInfo.TypeName).CreateInstanceGetDefaultValue() as ISagaUnit;
                    if (unitTypeDefault == null)
                    {
                        if (cloud._distributeTraceEnable) cloud._distributedTraceCall($"SAGA({masterInfo.Tid}, {masterInfo.replacedle}) Data error, cannot create as ISagaUnit, {unitInfo.TypeName}");
                        throw new ArgumentException($"SAGA({masterInfo.Tid}, {masterInfo.replacedle}) Data error, cannot create as ISagaUnit, {unitInfo.TypeName}");
                    }
                    return unitTypeDefault;
                }
                catch
                {
                    if (cloud._distributeTraceEnable) cloud._distributedTraceCall($"SAGA({masterInfo.Tid}, {masterInfo.replacedle}) Data error, cannot create as ISagaUnit, {unitInfo.TypeName}");
                    throw new ArgumentException($"SAGA({masterInfo.Tid}, {masterInfo.replacedle}) Data error, cannot create as ISagaUnit, {unitInfo.TypeName}");
                }
            })
            .ToArray();
#if net40
            Cancel(cloud, masterInfo, unitInfos, units, retry);
#else
            await CancelAsync(cloud, masterInfo, unitInfos, units, retry);
#endif
        }

19 Source : TccMaster.cs
with MIT License
from 2881099

async static Task ConfimCancelAsync(FreeSqlCloud<TDBKey> cloud, string tid, bool retry)
        {
            var masterInfo = await cloud._ormMaster.Select<TccMasterInfo>().Where(a => a.Tid == tid && a.Status == TccMasterStatus.Pending && a.RetryCount <= a.MaxRetryCount).FirstAsync();
            if (masterInfo == null) return;
            var unitInfos = await cloud._ormMaster.Select<TccUnitInfo>().Where(a => a.Tid == tid).OrderBy(a => a.Index).ToListAsync();
#endif
            var units = unitInfos.Select(unitInfo =>
            {
                try
                {
                    var unitTypeDefault = Type.GetType(unitInfo.TypeName).CreateInstanceGetDefaultValue() as ITccUnit;
                    if (unitTypeDefault == null)
                    {
                        if (cloud._distributeTraceEnable) cloud._distributedTraceCall($"TCC ({masterInfo.Tid}, {masterInfo.replacedle}) Data error, cannot create as ITccUnit, {unitInfo.TypeName}");
                        throw new ArgumentException($"TCC ({masterInfo.Tid}, {masterInfo.replacedle}) Data error, cannot create as ITccUnit, {unitInfo.TypeName}");
                    }
                    return unitTypeDefault;
                }
                catch
                {
                    if (cloud._distributeTraceEnable) cloud._distributedTraceCall($"TCC ({masterInfo.Tid}, {masterInfo.replacedle}) Data error, cannot create as ITccUnit, {unitInfo.TypeName}");
                    throw new ArgumentException($"TCC ({masterInfo.Tid}, {masterInfo.replacedle}) Data error, cannot create as ITccUnit, {unitInfo.TypeName}");
                }
            })
            .ToArray();

#if net40
            ConfimCancel(cloud, masterInfo, unitInfos, units, retry);
#else
            await ConfimCancelAsync(cloud, masterInfo, unitInfos, units, retry);
#endif
        }

19 Source : AppenderFactory.cs
with MIT License
from Abc-Arbitrage

private static Type? GetAppenderType(AppenderDefinition definition)
        {
            if (string.IsNullOrEmpty(definition.AppenderTypeName))
                return null;

            // Check if we have an replacedembly-qualified name of a type
            if (definition.AppenderTypeName!.Contains(","))
                return Type.GetType(definition.AppenderTypeName, true, false);

            return AppDomain.CurrentDomain.Getreplacedemblies()
                            .Select(x => x.GetType(definition.AppenderTypeName))
                            .FirstOrDefault(x => x != null);
        }

19 Source : ImportService.cs
with Apache License 2.0
from Aguafrommars

private async Task<ImportFileResult> ImportFileAsync(IFormFile file)
        {
            var reader = new StreamReader(file.OpenReadStream());
            var content = await reader.ReadToEndAsync().ConfigureAwait(false);
            var metadata = JsonConvert.DeserializeObject<EnreplacedyMetadata>(content);
            var enreplacedyType = Type.GetType(metadata.Metadata.TypeName);
            var importerType = typeof(Importer<>).MakeGenericType(enreplacedyType);
            var importer = Activator.CreateInstance(importerType, _provider) as Importer;
            var result = await importer.ImportAsync(content).ConfigureAwait(false);
            result.FileName = file.FileName;
            return result;
        }

19 Source : EventStoreJournal.cs
with Apache License 2.0
from AkkaNetContrib

private IEventAdapter BuildDefaultJournalAdapter()
        {
            Func<DefaultEventAdapter> getDefaultAdapter = () => new DefaultEventAdapter(_serialization);

            if (_settings.Adapter.ToLowerInvariant() == "default")
            {
                return getDefaultAdapter();
            }
            else if (_settings.Adapter.ToLowerInvariant() == "legacy")
            {
                return new LegacyEventAdapter(_serialization);
            }

            try
            {
                var journalAdapterType = Type.GetType(_settings.Adapter);
                if (journalAdapterType == null)
                {
                    _log.Error(
                        $"Unable to find type [{_settings.Adapter}] Adapter for EventStoreJournal. Is the replacedembly referenced properly? Falling back to default");
                    return getDefaultAdapter();
                }

                var adapterConstructor = journalAdapterType.GetConstructor(new[] { typeof(Akka.Serialization.Serialization) });
                
                IEventAdapter journalAdapter = (adapterConstructor != null 
                    ? adapterConstructor.Invoke(new object[] { _serialization }) 
                    : Activator.CreateInstance(journalAdapterType)) as IEventAdapter;

                if (journalAdapter == null)
                {
                    _log.Error(
                        $"Unable to create instance of type [{journalAdapterType.replacedemblyQualifiedName}] Adapter for EventStoreJournal. Do you have an empty constructor, or one that takes in Akka.Serialization.Serialization? Falling back to default.");
                    return getDefaultAdapter();
                }

                return journalAdapter;
            }
            catch (Exception e)
            {
                _log.Error(e, "Error loading Adapter for EventStoreJournal. Falling back to default");
                return getDefaultAdapter();
            }
        }

19 Source : EventStoreSnapshotStore.cs
with Apache License 2.0
from AkkaNetContrib

private ISnapshotAdapter BuildDefaultSnapshotAdapter()
        {
            Func<DefaultSnapshotEventAdapter> getDefaultAdapter = () => new DefaultSnapshotEventAdapter(_serialization);

            if (_settings.Adapter.ToLowerInvariant() == "default")
            {
                return getDefaultAdapter();
            }
            else if (_settings.Adapter.ToLowerInvariant() == "legacy")
            {
                return new LegacySnapshotEventAdapter();
            }

            try
            {
                var journalAdapterType = Type.GetType(_settings.Adapter);
                if (journalAdapterType == null)
                {
                    _log.Error(
                        $"Unable to find type [{_settings.Adapter}] Adapter for EventStoreJournal. Is the replacedembly referenced properly? Falling back to default");
                    return getDefaultAdapter();
                }

                var adapterConstructor = journalAdapterType.GetConstructor(new[] { typeof(Akka.Serialization.Serialization) });

                ISnapshotAdapter journalAdapter = (adapterConstructor != null
                    ? adapterConstructor.Invoke(new object[] { _serialization })
                    : Activator.CreateInstance(journalAdapterType)) as ISnapshotAdapter;
                if (journalAdapter == null)
                {
                    _log.Error(
                        $"Unable to create instance of type [{journalAdapterType.replacedemblyQualifiedName}] Adapter for EventStoreJournal. Do you have an empty constructor? Falling back to default.");
                    return getDefaultAdapter();
                }

                return journalAdapter;
            }
            catch (Exception e)
            {
                _log.Error(e, "Error loading Adapter for EventStoreJournal. Falling back to default");
                return getDefaultAdapter();
            }
        }

19 Source : Hub.cs
with MIT License
from alaabenfatma

public static bool LoadVirtualData(VirtualControl vc, string str)
        {
            try
            {
                for (var index = 0; index < vc.Nodes.Count; index++)
                {
                    var node = vc.Nodes[index];
                    node.Delete();
                }
                var data = Cipher.DeSerializeFromString<VirtualControlData>(str);
                for (var index = data.Nodes.Count - 1; index >= 0; index--)
                {
                    var copiednode = data.Nodes[index];
                    var typename = copiednode.Name;
                    Node newNode = null;
                    foreach (var node in LoadedExternalNodes)
                    {
                        if (node.ToString() != typename) continue;
                        newNode = node.Clone();
                        vc.AddNode(newNode, copiednode.X, copiednode.Y);
                        newNode.DeSerializeData(copiednode.InputData, copiednode.OutputData);
                        newNode.Id = copiednode.Id;
                        break;
                    }
                    if (newNode != null) continue;
                    var type = Type.GetType(typename);
                    if (type != null)
                    {
                        var instance = Activator.CreateInstance(type, vc, false);
                        vc.AddNode(instance as Node, copiednode.X, copiednode.Y);
                        var node = instance as Node;
                        if (node != null) node.Id = copiednode.Id;
                    }
                }
                foreach (var eConn in data.ExecutionConnectors)
                {
                    var start = vc.GetNode(eConn.StartNode_ID);
                    var end = vc.GetNode(eConn.EndNode_ID);
                    NodesManager.CreateExecutionConnector(vc, start.OutExecPorts[eConn.StartPort_Index],
                        end.InExecPorts[eConn.EndPort_Index]);
                }
                foreach (var oConn in data.ObjectConnectors)
                {
                    var start = vc.GetNode(oConn.StartNode_ID);
                    var end = vc.GetNode(oConn.EndNode_ID);
                    NodesManager.CreateObjectConnector(vc, start.OutputPorts[oConn.StartPort_Index],
                        end.InputPorts[oConn.EndPort_Index]);
                }
                foreach (var divider in data.SpaghettiDividers)
                {
                    var node = vc.GetNode(divider.EndNode_ID);
                    var port = node.InputPorts[divider.Port_Index];
                    var conn = port.ConnectedConnectors[0];
                    var spaghettiDivider = new SpaghettiDivider(vc, conn, false)
                    {
                        X = divider.X,
                        Y = divider.Y
                    };
                    vc.AddNode(spaghettiDivider, spaghettiDivider.X, spaghettiDivider.Y);
                }
            }
            catch (Exception)
            {
                return false;
            }
            foreach (var node in vc.Nodes)
                node.Refresh();
            vc.NeedsRefresh = true;

            return true;
        }

19 Source : VirtualControl.cs
with MIT License
from alaabenfatma

public void Paste()
        {
            try
            {
                SelectedNodes.Clear();
                var dummyList = Cipher.DeSerializeFromString<List<NodeProperties>>(Clipboard.GetText());
                for (var index = dummyList.Count - 1; index >= 0; index--)
                {
                    var copiednode = dummyList[index];
                    var typename = copiednode.Name;
                    Node newNode = null;
                    foreach (var node in Hub.LoadedExternalNodes)
                    {
                        if (node.ToString() != typename) continue;
                        newNode = node.Clone();
                        AddNode(newNode, copiednode.X, copiednode.Y);
                        newNode.DeSerializeData(copiednode.InputData, copiednode.OutputData);
                        break;
                    }
                    if (newNode != null) continue;
                    var type = Type.GetType(typename);
                    try
                    {
                        var instance = Activator.CreateInstance(type, this, false);
                        AddNode(instance as Node, copiednode.X, copiednode.Y);
                    }
                    catch (Exception)
                    {
                        //Ignored
                    }
                }
            }
            catch
            {
                //ignored
            }
        }

19 Source : Components.cs
with MIT License
from Alan-FGR

public static Component CreateFromData(Enreplacedy enreplacedy, ComponentData componentData)
    {
        switch (componentData.typeId)
        {
            case ComponentTypes.DynamicBody: return new DynamicBody(enreplacedy, componentData.serialData);
            case ComponentTypes.StaticBody: return new StaticBody(enreplacedy, componentData.serialData);
            case ComponentTypes.LightOccluder: return new LightOccluder(enreplacedy, componentData.serialData);
            case ComponentTypes.LightProjector: return new LightProjector(enreplacedy, componentData.serialData);
            case ComponentTypes.QuadComponent: return new QuadComponent(enreplacedy, componentData.serialData);
            case ComponentTypes.EnreplacedyContainer: return new EnreplacedyContainer(enreplacedy, componentData.serialData);
//            case ComponentTypes.TileMapChunk: return new TileMapOfEnreplacedies(enreplacedy, componentData.serialData);
            case ComponentTypes.SoundPlayer: return new SoundPlayer(enreplacedy, componentData.serialData);
        }

        //scripts
        if (componentData.typeId == ComponentTypes.Script)
        {
            ScriptTypeAndData stad = MessagePackSerializer.Deserialize<ScriptTypeAndData>(componentData.serialData);
            return Activator.CreateInstance(Type.GetType(stad.ScriptType), new ScriptSerialData(enreplacedy, stad.ScriptData)) as Component;
        }

        throw new Exception("component type couldn't be resolved; make sure to add all component types to this method");
    }

19 Source : DialogNodeEditor.cs
with MIT License
from alee12131415

public string LoadCanvas(string path) {
        //SAME AS SAVE CANVAS
        try {
            //EditorSaveObject load = Resources.Load(path) as EditorSaveObject;
            EditorSaveObject load = replacedetDatabase.LoadreplacedetAtPath(path, typeof(EditorSaveObject)) as EditorSaveObject;

            //build new CP / Index
            List<ConnectionPoint> CPIndex = new List<ConnectionPoint>();
            for (int i = 0; i < load.NumberOfCP; i++) {
                CPIndex.Add(new ConnectionPoint());
            }

            //build nodes
            int spent = 0; //tracks index of used CP
            nodes = new List<Node>();
            for (int i = 0; i < load.nodeinfos.Count; i++) {
                Type t = Type.GetType(load.nodeinfos[i].type);
                ConstructorInfo ctor = t.GetConstructor(new[] { GetType(), typeof(NodeInfo) });
                Node n = (Node)Convert.ChangeType(ctor.Invoke(new object[] { this, load.nodeinfos[i] }), t);
                n.Rebuild(CPIndex.GetRange(spent, load.NodeCPIndex[i]));
                spent += load.NodeCPIndex[i];
                AddNode(n);
            }

            //build connections
            connections = new List<Connection>();
            for (int i = 0; i < load.ConnectionIndexIn.Count; i++) {
                connections.Add(new Connection(CPIndex[load.ConnectionIndexIn[i]], CPIndex[load.ConnectionIndexOut[i]], RemoveConnection));
            }

            offset = new Vector2(load.offset.x, load.offset.y);
            drag = Vector2.zero;
        } catch (Exception e) {
            return e.Message;
        }
        return null;
    }

19 Source : GraphProcessor.cs
with MIT License
from alelievr

bool CheckProcessErrors(NodeLink link, BaseNode node, bool realMode)
		{
			if (!realMode)
			{
				if (link.fromAnchor == null || link.toAnchor == null)
				{
					Debug.LogError("[PW Process] null anchors in link: " + link + ", from node: " + node + ", trying to removing this link");
					currentGraph.RemoveLink(link, false);
					return true;
				}
				
				var fromType = Type.GetType(link.fromNode.clreplacedAQName);
				var toType = Type.GetType(link.toNode.clreplacedAQName);

				if (!nodesDictionary.ContainsKey(link.toNode.id))
				{
					Debug.LogError("[PW Process] " + "node id (" + link.toNode.id + ") not found in nodes dictionary");
					return true;
				}

				if (nodesDictionary[link.toNode.id] == null)
				{
					Debug.LogError("[PW Process] " + "node id (" + link.toNode.id + ") is null in nodes dictionary");
					return true;
				}

				if (!bakedNodeFields.ContainsKey(link.fromNode.clreplacedAQName)
					|| !bakedNodeFields[link.fromNode.clreplacedAQName].ContainsKey(link.fromAnchor.fieldName))
				{
					Debug.LogError("[PW Process] Can't find field: "
						+ link.fromAnchor.fieldName + " in " + fromType);
					return true;
				}

				if (!bakedNodeFields.ContainsKey(link.toNode.clreplacedAQName)
					|| !bakedNodeFields[link.toNode.clreplacedAQName].ContainsKey(link.toAnchor.fieldName))
				{
					Debug.LogError("[PW Process] Can't find field: "
						+ link.toAnchor.fieldName + " in " + toType);
					return true;
				}
				
				if (bakedNodeFields[link.fromNode.clreplacedAQName][link.fromAnchor.fieldName].GetValue(node) == null)
				{
					if (currentGraph.processMode != GraphProcessMode.Once)
						Debug.Log("[PW Process] tring to replacedign null value from "
							+ fromType + "." + link.fromAnchor.fieldName);
					return true;
				}
			}

			return false;
		}

19 Source : JSON.cs
with MIT License
from AlenToma

private DataSet CreateDataset(Dictionary<string, object> reader, Dictionary<string, object> globalTypes)
        {
            DataSet ds = new DataSet();
            ds.EnforceConstraints = false;
            ds.BeginInit();

            // read dataset schema here
            var schema = reader["$schema"];

            if (schema is string)
            {
                TextReader tr = new StringReader((string)schema);
                ds.ReadXmlSchema(tr);
            }
            else
            {
                DatasetSchema ms = (DatasetSchema)ParseDictionary((Dictionary<string, object>)schema, globalTypes, typeof(DatasetSchema), null);
                ds.DataSetName = ms.Name;
                for (int i = 0; i < ms.Info.Count; i += 3)
                {
                    if (ds.Tables.Contains(ms.Info[i]) == false)
                        ds.Tables.Add(ms.Info[i]);
                    ds.Tables[ms.Info[i]].Columns.Add(ms.Info[i + 1], Type.GetType(ms.Info[i + 2]));
                }
            }

            foreach (KeyValuePair<string, object> pair in reader)
            {
                if (pair.Key == "$type" || pair.Key == "$schema") continue;

                List<object> rows = (List<object>)pair.Value;
                if (rows == null) continue;

                DataTable dt = ds.Tables[pair.Key];
                ReadDataTable(rows, dt);
            }

            ds.EndInit();

            return ds;
        }

19 Source : JSON.cs
with MIT License
from AlenToma

DataTable CreateDataTable(Dictionary<string, object> reader, Dictionary<string, object> globalTypes)
        {
            var dt = new DataTable();

            // read dataset schema here
            var schema = reader["$schema"];

            if (schema is string)
            {
                TextReader tr = new StringReader((string)schema);
                dt.ReadXmlSchema(tr);
            }
            else
            {
                var ms = (DatasetSchema)ParseDictionary((Dictionary<string, object>)schema, globalTypes, typeof(DatasetSchema), null);
                dt.TableName = ms.Info[0];
                for (int i = 0; i < ms.Info.Count; i += 3)
                {
                    dt.Columns.Add(ms.Info[i + 1], Type.GetType(ms.Info[i + 2]));
                }
            }

            foreach (var pair in reader)
            {
                if (pair.Key == "$type" || pair.Key == "$schema")
                    continue;

                var rows = (List<object>)pair.Value;
                if (rows == null)
                    continue;

                if (!dt.TableName.Equals(pair.Key, StringComparison.InvariantCultureIgnoreCase))
                    continue;

                ReadDataTable(rows, dt);
            }

            return dt;
        }

19 Source : ShapeCreateTool.cs
with Apache License 2.0
from Algoryx

private Utils.VisualPrimitive GetSelectedButtonVisualPrimitive()
    {
      Utils.VisualPrimitive vp = GetVisualPrimitive( m_visualPrimitiveName );

      if ( m_buttons.Selected == null || m_buttons.Selected.State.Axis == ShapeInitializationData.Axes.None ) {
        RemoveVisualPrimitive( m_visualPrimitiveName );
        return null;
      }

      var desiredType = Type.GetType( "AGXUnityEditor.Utils.VisualPrimitive" + m_buttons.Selected.State.ShapeType.ToString() + ", AGXUnityEditor" );

      // Desired type doesn't exist - remove current visual primitive if it exists.
      if ( desiredType == null ) {
        RemoveVisualPrimitive( m_visualPrimitiveName );
        return null;
      }

      // New visual primitive type. Remove old one.
      if ( vp != null && vp.GetType() != desiredType ) {
        RemoveVisualPrimitive( m_visualPrimitiveName );
        vp = null;
      }

      // Same type as selected button shape type.
      if ( vp != null )
        return vp;

      MethodInfo genericMethod = GetType().GetMethod( "GetOrCreateVisualPrimitive", BindingFlags.NonPublic | BindingFlags.Instance ).MakeGenericMethod( desiredType );
      vp = (Utils.VisualPrimitive)genericMethod.Invoke( this, new object[] { m_visualPrimitiveName, VisualPrimitiveShader } );
      if ( vp == null )
        return null;

      vp.Pickable = false;
      vp.Color = VisualPrimitiveColor;

      return vp;
    }

19 Source : StandardClassLibraryFormatter.cs
with Apache License 2.0
from allenai

public T Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options)
        {
            if (reader.TryReadNil())
            {
                return null;
            }

            return (T)Type.GetType(reader.ReadString(), throwOnError: true);
        }

19 Source : TypelessFormatter.cs
with Apache License 2.0
from allenai

private object DeserializeByTypeName(ArraySegment<byte> typeName, ref MessagePackReader byteSequence, MessagePackSerializerOptions options)
        {
            // try get type with replacedembly name, throw if not found
            Type type;
            if (!TypeCache.TryGetValue(typeName, out type))
            {
                var buffer = new byte[typeName.Count];
                Buffer.BlockCopy(typeName.Array, typeName.Offset, buffer, 0, buffer.Length);
                var str = StringEncoding.UTF8.GetString(buffer);
                type = options.LoadType(str);
                if (type == null)
                {
                    if (IsMscorlib && str.Contains("System.Private.CoreLib"))
                    {
                        str = str.Replace("System.Private.CoreLib", "mscorlib");
                        type = Type.GetType(str, true); // throw
                    }
                    else if (!IsMscorlib && str.Contains("mscorlib"))
                    {
                        str = str.Replace("mscorlib", "System.Private.CoreLib");
                        type = Type.GetType(str, true); // throw
                    }
                    else
                    {
                        type = Type.GetType(str, true); // re-throw
                    }
                }

                TypeCache.TryAdd(buffer, type);
            }

            options.ThrowIfDeserializingTypeIsDisallowed(type);

            var formatter = options.Resolver.GetFormatterDynamicWithVerify(type);

            if (!Deserializers.TryGetValue(type, out DeserializeMethod deserializeMethod))
            {
                lock (Deserializers)
                {
                    if (!Deserializers.TryGetValue(type, out deserializeMethod))
                    {
                        TypeInfo ti = type.GetTypeInfo();

                        Type formatterType = typeof(IMessagePackFormatter<>).MakeGenericType(type);
                        ParameterExpression param0 = Expression.Parameter(typeof(object), "formatter");
                        ParameterExpression param1 = Expression.Parameter(typeof(MessagePackReader).MakeByRefType(), "reader");
                        ParameterExpression param2 = Expression.Parameter(typeof(MessagePackSerializerOptions), "options");

                        MethodInfo deserializeMethodInfo = formatterType.GetRuntimeMethod("Deserialize", new[] { typeof(MessagePackReader).MakeByRefType(), typeof(MessagePackSerializerOptions) });

                        MethodCallExpression deserialize = Expression.Call(
                            Expression.Convert(param0, formatterType),
                            deserializeMethodInfo,
                            param1,
                            param2);

                        Expression body = deserialize;
                        if (ti.IsValueType)
                        {
                            body = Expression.Convert(deserialize, typeof(object));
                        }

                        deserializeMethod = Expression.Lambda<DeserializeMethod>(body, param0, param1, param2).Compile();

                        Deserializers.TryAdd(type, deserializeMethod);
                    }
                }
            }

            return deserializeMethod(formatter, ref byteSequence, options);
        }

19 Source : TypelessFormatter.cs
with Apache License 2.0
from allenai

private string BuildTypeName(Type type, MessagePackSerializerOptions options)
        {
            if (options.OmitreplacedemblyVersion)
            {
                string full = type.replacedemblyQualifiedName;

                var shortened = MessagePackSerializerOptions.replacedemblyNameVersionSelectorRegex.Replace(full, string.Empty);
                if (Type.GetType(shortened, false) == null)
                {
                    // if type cannot be found with shortened name - use full name
                    shortened = full;
                }

                return shortened;
            }
            else
            {
                return type.replacedemblyQualifiedName;
            }
        }

19 Source : ShaderGenerator.cs
with MIT License
from Aminator

private void CollectMethod(MethodInfo methodInfo)
        {
            ShaderMethodAttribute? shaderMethodAttribute = GetShaderMethodAttribute(methodInfo);

            IEnumerable<Type> dependentTypes = shaderMethodAttribute?.DependentTypes != null
                ? shaderMethodAttribute.DependentTypes
                : ShaderMethodGenerator.GetDependentTypes(methodInfo).Select(t => Type.GetType(ShaderMethodGenerator.GetFullTypeName(t)));

            dependentTypes = dependentTypes.Concat(methodInfo.GetParameters().Select(p => p.ParameterType).Concat(new[] { methodInfo.ReturnType })).Distinct();

            foreach (Type type in dependentTypes)
            {
                AddType(type);
            }
        }

19 Source : MediatrNotificationConsumer.cs
with Apache License 2.0
from Anapher

public async Task Consume(ConsumeContext<IScheduledNotificationWrapper> context)
        {
            _logger.LogDebug("Received scheduled notification of type {typeName}: {message}", context.Message.TypeName,
                context.Message.JsonSerialized);

            var token = context.GetSchedulingTokenId();
            if (token == null)
                _logger.LogWarning("A scheduled notification {notification} was received, but the token id is null.",
                    context.Message);

            var type = Type.GetType(context.Message.TypeName);
            if (type == null)
            {
                _logger.LogWarning("The type {typeName} was not found, cannot process notification.",
                    context.Message.TypeName);
                return;
            }

            var notification =
                (IScheduledNotification?) JsonConvert.DeserializeObject(context.Message.JsonSerialized, type);
            if (notification == null)
            {
                _logger.LogError("Received null notification");
                return;
            }

            var tokenId = token?.ToString("N");
            notification.TokenId = tokenId;

            await _mediator.Publish(notification, context.CancellationToken);
        }

19 Source : ViewsManager.cs
with GNU General Public License v3.0
from AndreiFedarets

private static Type LocateTypeForModelTypeInternal(Type type, DependencyObject dependencyObject, object @object)
        {
            object[] attributes = type.GetCustomAttributes(typeof(ViewModelAttribute), false);
            ViewModelAttribute attribute = (ViewModelAttribute)attributes.FirstOrDefault();
            Type viewType = null;
            if (attribute != null && !string.IsNullOrWhiteSpace(attribute.ViewType))
            {
                viewType = Type.GetType(attribute.ViewType);
            }
            viewType = viewType ?? LocateTypeForModelType(type, dependencyObject, @object);
            return viewType;
        }

19 Source : CsvInputFormatter.cs
with GNU General Public License v3.0
from andysal

private object readStream(Type type, Stream stream)
        {
            // We only proocess an IList item at present and simple model type with properties
            IList list = (IList)Activator.CreateInstance(type);

            var reader = new StreamReader(stream);

            bool skipFirstLine = true;
            while (!reader.EndOfStream)
            {
                var line = reader.ReadLine();
                var values = line.Split(';');
                if (skipFirstLine)
                {
                    skipFirstLine = false;
                }
                else
                {
                    var itemTypeInGeneric = list.GetType().GetType().GenericTypeArguments[0];
                    var item = Activator.CreateInstance(itemTypeInGeneric);
                    var properties = item.GetType().GetProperties();
                    for (int i = 0; i < values.Length; i++)
                    {
                        properties[i].SetValue(item, Convert.ChangeType(values[i], properties[i].PropertyType), null);
                    }

                    list.Add(item);
                }

            }

            return list;
        }

19 Source : OpcodeTypeComponent.cs
with MIT License
from AnotherEnd15

public Type GetResponseType(Type request)
        {
            if (!this.requestResponse.TryGetValue(request, out Type response))
            {
                throw new Exception($"not found response type, request type: {request.GetType().Name}");
            }
            return response;
        }

19 Source : UnityTypeBindings.cs
with MIT License
from AnotherEnd15

public static void Register()
        {

            if (registerd) return;
            registerd = true;


            // 注册Type类型的Exporter
            JsonMapper.RegisterExporter<Type>((v, w) =>
            {
                w.Write(v.FullName);
            });

            JsonMapper.RegisterImporter<string, Type>((s) =>
            {
                return Type.GetType(s);
            });
#if !NOT_CLIENT
            // 注册Vector2类型的Exporter
            Action<UnityEngine.Vector2, JsonWriter> writeVector2 = (v, w) =>
            {
                w.WriteObjectStart();
                w.WriteProperty("x", v.x);
                w.WriteProperty("y", v.y);
                w.WriteObjectEnd();
            };

            JsonMapper.RegisterExporter<UnityEngine.Vector2>((v, w) =>
            {
                writeVector2(v, w);
            });

            // 注册Vector3类型的Exporter
            Action<UnityEngine.Vector3, JsonWriter> writeVector3 = (v, w) =>
            {
                w.WriteObjectStart();
                w.WriteProperty("x", v.x);
                w.WriteProperty("y", v.y);
                w.WriteProperty("z", v.z);
                w.WriteObjectEnd();
            };

            JsonMapper.RegisterExporter<UnityEngine.Vector3>((v, w) =>
            {
                writeVector3(v, w);
            });

            // 注册Vector4类型的Exporter
            JsonMapper.RegisterExporter<UnityEngine.Vector4>((v, w) =>
            {
                w.WriteObjectStart();
                w.WriteProperty("x", v.x);
                w.WriteProperty("y", v.y);
                w.WriteProperty("z", v.z);
                w.WriteProperty("w", v.w);
                w.WriteObjectEnd();
            });

            // 注册Quaternion类型的Exporter
            JsonMapper.RegisterExporter<UnityEngine.Quaternion>((v, w) =>
            {
                w.WriteObjectStart();
                w.WriteProperty("x", v.x);
                w.WriteProperty("y", v.y);
                w.WriteProperty("z", v.z);
                w.WriteProperty("w", v.w);
                w.WriteObjectEnd();
            });

            // 注册Color类型的Exporter
            JsonMapper.RegisterExporter<UnityEngine.Color>((v, w) =>
            {
                w.WriteObjectStart();
                w.WriteProperty("r", v.r);
                w.WriteProperty("g", v.g);
                w.WriteProperty("b", v.b);
                w.WriteProperty("a", v.a);
                w.WriteObjectEnd();
            });

            // 注册Color32类型的Exporter
            JsonMapper.RegisterExporter<UnityEngine.Color32>((v, w) =>
            {
                w.WriteObjectStart();
                w.WriteProperty("r", v.r);
                w.WriteProperty("g", v.g);
                w.WriteProperty("b", v.b);
                w.WriteProperty("a", v.a);
                w.WriteObjectEnd();
            });

            // 注册Bounds类型的Exporter
            JsonMapper.RegisterExporter<UnityEngine.Bounds>((v, w) =>
            {
                w.WriteObjectStart();

                w.WritePropertyName("center");
                writeVector3(v.center, w);

                w.WritePropertyName("size");
                writeVector3(v.size, w);

                w.WriteObjectEnd();
            });

            // 注册Rect类型的Exporter
            JsonMapper.RegisterExporter<UnityEngine.Rect>((v, w) =>
            {
                w.WriteObjectStart();
                w.WriteProperty("x", v.x);
                w.WriteProperty("y", v.y);
                w.WriteProperty("width", v.width);
                w.WriteProperty("height", v.height);
                w.WriteObjectEnd();
            });

            // 注册RectOffset类型的Exporter
            JsonMapper.RegisterExporter<UnityEngine.RectOffset>((v, w) =>
            {
                w.WriteObjectStart();
                w.WriteProperty("top", v.top);
                w.WriteProperty("left", v.left);
                w.WriteProperty("bottom", v.bottom);
                w.WriteProperty("right", v.right);
                w.WriteObjectEnd();
            });
#endif
        }

19 Source : ReflectionExtensions.cs
with GNU General Public License v3.0
from anydream

public static bool IsSZArray(this Type self) {
			if (self == null || !self.IsArray)
				return false;
			var prop = self.GetType().GetProperty("IsSzArray", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
			if (prop != null)
				return (bool)prop.GetValue(self, new object[0]);
			return (self.Name ?? string.Empty).EndsWith("[]");
		}

19 Source : EndpointConverter.cs
with GNU General Public License v3.0
from AnyStatus

public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            var token = JToken.ReadFrom(reader);

            if (token.HasValues)
            {
                var typeName = token.Value<string>("$type");

                if (typeName is string)
                {
                    var type = Type.GetType(typeName);

                    if (type is null)
                    {
                        var endpoint = new UnknownEndpoint
                        {
                            Name = "Unknown Endpoint"
                        };

                        serializer.Populate(token.CreateReader(), endpoint);

                        return endpoint;
                    }
                }
            }

            return serializer.Deserialize(token.CreateReader());
        }

19 Source : WidgetConverter.cs
with GNU General Public License v3.0
from AnyStatus

public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            var token = JToken.ReadFrom(reader);

            if (token.HasValues)
            {
                var name = token.Value<string>(_typeKey);

                if (!string.IsNullOrEmpty(name))
                {
                    if (Type.GetType(name) is null)
                    {
                        var widget = TryGetCompatibleWidget(name);

                        if (widget is UnknownWidget unknownWidget)
                        {
                            _logger.LogWarning("Unknown widget type: {type}", unknownWidget.TypeName);

                            widget.Clear();
                        }

                        serializer.Populate(token.CreateReader(), widget);

                        return widget;
                    }
                }
            }

            return serializer.Deserialize(token.CreateReader());
        }

19 Source : SerializationMaster.cs
with GNU Lesser General Public License v3.0
from ApexGameTools

private static object ReflectIn(StageElement element)
        {
            var typeName = element.AttributeValueOrDefault<string>("type", null);
            if (typeName == null)
            {
                throw new SerializationException("Invalid structure detected, missing type info.");
            }

            var itemType = Type.GetType(typeName, true);
            object instance;

            try
            {
                instance = Activator.CreateInstance(itemType, true);
            }
            catch (MissingMethodException mme)
            {
                throw new SerializationException(string.Format("Unable to create type {0}, ensure it has a parameterless constructor", itemType.Name), mme);
            }

            var forInit = instance as IInitializeAfterDeserialization;
            if (forInit != null)
            {
                if (_requiresInit == null)
                {
                    throw new InvalidOperationException("An enreplacedy requires initialization but was unable to register, call UnstageAndInitialize instead.");
                }

                _requiresInit.Add(forInit);
            }

            var properties = GetSerializedProperties(itemType);

            foreach (var p in properties)
            {
                var member = element.Item(p.Name);
                if (member == null)
                {
                    continue;
                }

                object val;
                if (TryUnstage(member, p.PropertyType, out val))
                {
                    p.SetValue(instance, val, null);
                }
            }

            var fields = GetSerializedFields(itemType);

            foreach (var f in fields)
            {
                var member = element.Item(f.Name);
                if (member == null)
                {
                    continue;
                }

                object val;
                if (TryUnstage(member, f.FieldType, out val))
                {
                    f.SetValue(instance, val);
                }
            }

            return instance;
        }

19 Source : RepairUtility.cs
with GNU Lesser General Public License v3.0
from ApexGameTools

internal void UpdateResolvedType(UnresolvedType t, TypeNameTokens typeName)
        {
            if (typeName != null && !_identifiedTypes.ContainsKey(typeName.completeTypeName))
            {
                _identifiedTypes[typeName.completeTypeName] = Type.GetType(typeName.completeTypeName);
            }
            else if (t.resolvedTypeName != null && typeName == null)
            {
                _identifiedTypes.Remove(t.resolvedTypeName.completeTypeName);
            }

            t.resolvedTypeName = typeName;
        }

19 Source : RepairUtility.cs
with GNU Lesser General Public License v3.0
from ApexGameTools

private IEnumerable<UnresolvedType> DoIdentifyUnresolvedTypes()
        {
            foreach (var doc in _stagedAis)
            {
                _identifiedTypes[doc.AttributeValue<string>("type")] = typeof(UtilityAI);

                var types = from el in doc.Descendants<StageElement>()
                            let type = el.Attribute("type")
                            where type != null
                            group el by type.value into typeGroup
                            select new
                            {
                                elements = typeGroup.ToArray(),
                                type = typeGroup.Key
                            };

                foreach (var t in types)
                {
                    var type = Type.GetType(t.type, false);
                    if (type == null)
                    {
                        yield return new UnresolvedType
                        {
                            elements = t.elements,
                            unresolvedTypeName = new TypeNameTokens(t.type),
                            baseType = ResolveExpectedBaseType(t.elements[0], true)
                        };
                    }
                    else
                    {
                        _identifiedTypes[t.type] = type;
                    }
                }
            }
        }

19 Source : RepairUtility.cs
with GNU Lesser General Public License v3.0
from ApexGameTools

private IEnumerable<MemberResolutionInfo> DoIdentifyUnresolvedMembers()
        {
            //Since not everything is serialized, e.g. null values, we cannot simply get the first element of a specific type and use that,
            //we have to get the union of all fields that are serialized across all elements of that type.
            var typeElements = from doc in _stagedAis
                               from el in doc.Descendants<StageElement>()
                               let type = el.Attribute("type")
                               where type != null
                               group el by type.value into typeGroup
                               select new
                               {
                                   type = typeGroup.Key,
                                   members = (from el in typeGroup
                                              from m in el.Items()
                                              let name = m.name
                                              orderby name
                                              group m by m.name into memberGroup
                                              select new
                                              {
                                                  name = memberGroup.Key,
                                                  items = memberGroup.ToArray()
                                              })
                               };

            //Next we check that each member found actually exists on the type.
            MemberResolutionInfo memberInfo = new MemberResolutionInfo();
            foreach (var t in typeElements.OrderBy(t => t.type))
            {
                var typeName = t.type;
                var type = Type.GetType(typeName, false);

                //This can still happen since the user can have opted to not resolve a type and it will be removed later.
                if (type == null)
                {
                    continue;
                }

                //Check fields and properties
                var fieldsAndPropNames = SerializationMaster.GetSerializedFields(type).Select(f => f.Name).Concat(SerializationMaster.GetSerializedProperties(type).Select(p => p.Name)).ToArray();
                foreach (var m in t.members)
                {
                    if (!fieldsAndPropNames.Contains(m.name, StringComparer.Ordinal))
                    {
                        memberInfo.unresolvedMembers.Add(
                            new Member
                            {
                                unresolvedName = m.name,
                                items = m.items
                            });
                    }
                    else
                    {
                        memberInfo.validMappedMembers.Add(m.name);
                    }
                }

                //There is no need to new up various instances if no unresolved members are found, so we do it this way
                if (memberInfo.unresolvedMembers.Count > 0)
                {
                    memberInfo.type = type;
                    memberInfo.typeName = new TypeNameTokens(typeName);
                    yield return memberInfo;

                    memberInfo = new MemberResolutionInfo();
                }
                else
                {
                    memberInfo.validMappedMembers.Clear();
                }
            }
        }

19 Source : DataContextOptions.cs
with MIT License
from aquilahkj

internal static DataContextOptions CreateOptions(IConnectionSetting setting)
        {
            if (setting == null) {
                throw new ArgumentNullException(nameof(setting));
            }

            var connection = setting.ConnectionString;

            var type = Type.GetType(setting.ProviderName, true);

            var dataBase = (DatabaseProvider)Activator.CreateInstance(type, setting.Name, setting.ConfigParam);
            if (dataBase == null) {
                throw new LightDataException(string.Format(SR.TypeIsNotDatabaseType, type.FullName));
            }
            var contextOptions = new DataContextOptions
            {
                Connection = connection,
                Database = dataBase
            };
            return contextOptions;
        }

19 Source : DataMapperConfiguration.cs
with MIT License
from aquilahkj

private static void LoadData(string configFilePath)
        {
            FileInfo fileInfo;
            if (UseEntryreplacedemblyDirectory) {
                fileInfo = FileHelper.GetFileInfo(configFilePath, out var absolute);
                if (!fileInfo.Exists && !absolute) {
                    fileInfo = new FileInfo(configFilePath);
                }
            }
            else {
                fileInfo = new FileInfo(configFilePath);
            }
            if (fileInfo.Exists) {
                using (var reader = fileInfo.OpenText()) {
                    var content = reader.ReadToEnd();
                    var dom = JObject.Parse(content);
                    var section = dom.GetValue("lightDataMapper");
                    if (section == null) {
                        return;
                    }
                    var optionList = section.ToObject<LightMapperOptions>();
                    if (optionList?.DataTypes != null && optionList.DataTypes.Length > 0) {
                        var typeIndex = 0;
                        foreach (var typeConfig in optionList.DataTypes) {
                            typeIndex++;
                            var typeName = typeConfig.Type;
                            if (typeName == null) {
                                throw new LightDataException(string.Format(SR.ConfigDataTypeNameIsNull, typeIndex));
                            }
                            var dataType = Type.GetType(typeName, true);
                            var dataTypeInfo = dataType.GetTypeInfo();
                            var dataTableMap = new DataTableMapperConfig(dataType);
                            var setting = new DataTableMapperSetting(dataTableMap);

                            dataTableMap.TableName = typeConfig.TableName;
                            dataTableMap.IsEnreplacedyTable = typeConfig.IsEnreplacedyTable ?? true;
                            var configParam = new ConfigParamSet();
                            var paramConfigs = typeConfig.ConfigParams;
                            if (paramConfigs != null && paramConfigs.Count > 0) {
                                foreach (var paramConfig in paramConfigs) {
                                    configParam.SetParamValue(paramConfig.Value, paramConfig.Value);
                                }
                            }
                            dataTableMap.ConfigParams = configParam;
                            var dataFieldConfigs = typeConfig.DataFields;

                            if (dataFieldConfigs != null && dataFieldConfigs.Length > 0) {
                                var fieldIndex = 0;
                                foreach (var fieldConfig in dataFieldConfigs) {
                                    fieldIndex++;
                                    var fieldName = fieldConfig.FieldName;
                                    if (fieldName == null) {
                                        throw new LightDataException(string.Format(SR.ConfigDataFieldNameIsNull, typeName, fieldIndex));
                                    }
                                    var property = dataTypeInfo.GetProperty(fieldName);
                                    if (property == null) {
                                        throw new LightDataException(string.Format(SR.ConfigDataFieldIsNotExists, typeName, fieldName));
                                    }

                                    object defaultValue;
                                    try {
                                        defaultValue = CreateDefaultValue(property.PropertyType, fieldConfig.DefaultValue);
                                    }
                                    catch (Exception ex) {
                                        throw new LightDataException(string.Format(SR.ConfigDataFieldLoadError, typeName, fieldName, ex.Message));
                                    }
                                    FunctionControl functionControl;
                                    try {
                                        functionControl = CreateFunctionControl(fieldConfig);
                                    }
                                    catch (Exception ex) {
                                        throw new LightDataException(string.Format(SR.ConfigDataFieldLoadError, typeName, fieldName, ex.Message));
                                    }
                                    var dataFieldMap = new DataFieldMapperConfig(fieldName) {
                                        Name = fieldConfig.Name,
                                        IsPrimaryKey = fieldConfig.IsPrimaryKey,
                                        IsIdenreplacedy = fieldConfig.IsIdenreplacedy,
                                        DbType = fieldConfig.DbType,
                                        DataOrder = fieldConfig.DataOrder,
                                        IsNullable = fieldConfig.IsNullable,
                                        DefaultValue = defaultValue,
                                        FunctionControl = functionControl
                                    };
                                    setting.AddDataFieldMapConfig(fieldName, dataFieldMap);
                                }
                            }
                            var relationFieldConfigs = typeConfig.RelationFields;
                            if (relationFieldConfigs != null && relationFieldConfigs.Length > 0) {
                                var fieldIndex = 0;
                                foreach (var fieldConfig in relationFieldConfigs) {
                                    fieldIndex++;
                                    if (fieldConfig.RelationPairs != null && fieldConfig.RelationPairs.Length > 0) {
                                        var fieldName = fieldConfig.FieldName;
                                        if (fieldName == null) {
                                            throw new LightDataException(string.Format(SR.ConfigDataFieldNameIsNull, typeName, fieldIndex));
                                        }
                                        var property = dataTypeInfo.GetProperty(fieldName);
                                        if (property == null) {
                                            throw new LightDataException(string.Format(SR.ConfigDataFieldIsNotExists, typeName, fieldName));
                                        }
                                        var dataFieldMap = new RelationFieldMapConfig(fieldName);
                                        foreach (var pair in fieldConfig.RelationPairs) {
                                            dataFieldMap.AddRelationKeys(pair.MasterKey, pair.RelateKey);
                                        }
                                        setting.AddRelationFieldMapConfig(fieldName, dataFieldMap);
                                    }
                                }
                            }
                            SettingDict[dataType] = setting;
                        }
                    }
                }
            }
        }

19 Source : DataContextSetting.cs
with MIT License
from aquilahkj

internal static DataContextSetting CreateSetting(IConnectionSetting setting, bool throwOnError)
        {
            if (setting == null) {
                throw new ArgumentNullException(nameof(setting));
            }

            var connection = setting.ConnectionString;

            var type = Type.GetType(setting.ProviderName, throwOnError);

            if (type == null) {
                return null;
            }

            if (!throwOnError) {
                var dataBaseType = typeof(DatabaseProvider);
                if (!type.IsInherit(dataBaseType)) {
                    return null;
                }
            }

            var dataBase = Activator.CreateInstance(type, setting.Name, setting.ConfigParam) as DatabaseProvider;
            if (dataBase == null)
            {
                if (!throwOnError) {
                    return null;
                }

                throw new LightDataException(string.Format(SR.TypeIsNotDatabaseType, type.FullName));
            }
            //dataBase.SetExtendParams(setting.ConfigParam);
            var context = new DataContextSetting(connection, dataBase);
            return context;
        }

19 Source : ReflectionHelper.cs
with GNU General Public License v3.0
from arduosoft

public List<Type> GetImplementors(Type t, List<replacedembly> bundledreplacedemblies)
        {
            _logger.LogDebug("Get implementors for {0} in {1}", t,
                string.Join(",", bundledreplacedemblies.Select(x => x.FullName).ToArray()));

            List<Type> result = new List<Type>();

            foreach (replacedembly replacedembly in bundledreplacedemblies)
            {
                // _logger.LogDebug("loading from" + replacedembly.FullName);
                Type[] types = replacedembly.GetTypes();
                foreach (Type type in types)
                {
                    try
                    {
                        if ((t.IsreplacedignableFrom(type) || (type.GetInterfaces().Any(i => i.IsGenericType && i.GetGenericTypeDefinition() == t)))
                            && !type.IsAbstract && !type.IsInterface && !type.IsGenericType)
                        {
                            result.Add(type);
                        }
                    }
                    catch (Exception err)
                    {
                        _logger.LogError(err, "- (unable to create an instance for EXCEPTION skipped) - " + type.Name + " | " + type.GetType().FullName);
                    }
                }
            }
            return result;
        }

19 Source : SerializedTypeDrawer.cs
with MIT License
from arimger

protected override void OnGUISafe(Rect position, SerializedProperty property, GUIContent label)
        {
            var validAttribute = GetVerifiedAttribute(attribute);

            var referenceProperty = property.FindPropertyRelative("clreplacedReference");
            var referenceValue = referenceProperty.stringValue;
            var currentType = !string.IsNullOrEmpty(referenceValue) ? Type.GetType(referenceValue) : null;

            var filteredTypes = GetFilteredTypes(validAttribute);

            var itemsCount = filteredTypes.Count + 1;
            var options = new string[itemsCount];
            var index = 0;

            //create labels for all types
            options[0] = "<None>";
            for (var i = 1; i < itemsCount; i++)
            {
                var menuType = filteredTypes[i - 1];
                var menuLabel = FormatGroupedTypeName(menuType, validAttribute.Grouping);
                if (menuType == currentType)
                {
                    index = i;
                }

                options[i] = menuLabel;
            }

            //draw the reference property
            label = EditorGUI.BeginProperty(position, label, property);
            label = property.name != "data" ? label : GUIContent.none;
            //draw the proper label field
            position = EditorGUI.PrefixLabel(position, label);

            //try to draw replacedociated popup
            if (validAttribute.AddTextSearchField)
            {
                var buttonLabel = new GUIContent(options[index]);
                ToolboxEditorGui.DrawSearchablePopup(position, buttonLabel, index, options, (i) =>
                {
                    try
                    {
                        referenceProperty.serializedObject.Update();
                        referenceProperty.stringValue = GetClreplacedReferencValue(i, filteredTypes);
                        referenceProperty.serializedObject.ApplyModifiedProperties();
                    }
                    catch (Exception e) when (e is ArgumentNullException || e is NullReferenceException)
                    {
                        ToolboxEditorLog.LogWarning("Invalid attempt to update disposed property.");
                    }
                });
            }
            else
            {
                using (new ZeroIndentScope())
                {
                    EditorGUI.BeginChangeCheck();
                    index = EditorGUI.Popup(position, index, options);
                    if (EditorGUI.EndChangeCheck())
                    {
                        referenceProperty.stringValue = GetClreplacedReferencValue(index, filteredTypes);
                    }
                }
            }

            EditorGUI.EndProperty();
        }

19 Source : SqliteJobRepository.cs
with MIT License
from aritchie

public IEnumerable<JobInfo> GetJobs() => this.conn.Jobs.ToList().Select(x => new JobInfo
        {
            Name = x.Name,
            Type = Type.GetType(x.TypeName),
            LastRunUtc = x.LastRunUtc,
            //RunPeriodic = x.RunPeriodic,
            //DeviceIdle = x.DeviceIdle,
            Repeat = x.Repeat,
            BatteryNotLow = x.BatteryNotLow,
            DeviceCharging = x.DeviceCharging,
            RequiredNetwork = (NetworkType)x.RequiredNetwork,
            Parameters = this.FromPayload(x.Payload)
        });

19 Source : DynamoDBProvider.cs
with Apache License 2.0
from asynkron

public async Task<long> GetEventsAsync(string actorName, long indexStart, long indexEnd, Action<object> callback)
        {
            var config = new QueryOperationConfig {ConsistentRead = true};
            config.Filter.AddCondition(_options.EventsTableHashKey, QueryOperator.Equal, actorName);
            config.Filter.AddCondition(_options.EventsTableSortKey, QueryOperator.Between, indexStart, indexEnd);
            var query = _eventsTable.Query(config);

            var lastIndex = -1L;

            while (true)
            {
                var results = await query.GetNextSetAsync();

                foreach (var doc in results)
                {
                    callback(GetData(doc));
                    lastIndex++;
                }

                if (query.IsDone) break;
            }

            return lastIndex;

            object GetData(Doreplacedent doc)
            {
                var dataTypeE = doc.GetValueOrThrow(_options.EventsTableDataTypeKey);
                var dataE = doc.GetValueOrThrow(_options.EventsTableDataKey);

                var dataType = Type.GetType(dataTypeE.replacedtring());
                return _dynamoDBContext.FromDoreplacedentDynamic(dataE.AsDoreplacedent(), dataType);
            }
        }

19 Source : DynamoDBProvider.cs
with Apache License 2.0
from asynkron

public async Task<(object Snapshot, long Index)> GetSnapshotAsync(string actorName)
        {
            var config = new QueryOperationConfig {ConsistentRead = true, BackwardSearch = true, Limit = 1};
            config.Filter.AddCondition(_options.SnapshotsTableHashKey, QueryOperator.Equal, actorName);
            var query = _snapshotsTable.Query(config);
            var results = await query.GetNextSetAsync();
            var doc = results.FirstOrDefault();

            if (doc == null) return (null, 0);

            var snapshotIndexE = doc.GetValueOrThrow(_options.SnapshotsTableSortKey);
            var dataTypeE = doc.GetValueOrThrow(_options.SnapshotsTableDataTypeKey);
            var dataE = doc.GetValueOrThrow(_options.SnapshotsTableDataKey);

            var dataType = Type.GetType(dataTypeE.replacedtring());
            var data = _dynamoDBContext.FromDoreplacedentDynamic(dataE.AsDoreplacedent(), dataType);

            return (data, snapshotIndexE.AsLong());
        }

19 Source : MainSerializer.cs
with MIT License
from atenfyr

public static FProperty ReadFProperty(replacedetBinaryReader reader)
        {
            FName serializedType = reader.ReadFName();
            Type requestedType = Type.GetType("UreplacedetAPI.FieldTypes.F" + allNonLetters.Replace(serializedType.Value.Value, string.Empty));
            if (requestedType == null) requestedType = typeof(FGenericProperty);
            var res = (FProperty)Activator.CreateInstance(requestedType);
            res.SerializedType = serializedType;
            res.Read(reader);
            return res;
        }

19 Source : ParserTests.cs
with Apache License 2.0
from atifaziz

public static TheoryData<char, char?, char, string, bool,
                                 IEnumerable<string>,
                                 IEnumerable<(int LineNumber, string[] Fields)>,
                                 Type, string>
            GetData()
        {
            var type = MethodBase.GetCurrentMethod().DeclaringType;

            var config = new[] { "delimiter", "quote", "escape", "newline", "blanks" };
            var nils   = new[] { "null", "nil", "none", "undefined" };
            var proto  = new[] { new { ln = default(int), row = default(string[]) } };

            var data =
                from q in new[]
                {
                    from g in LineReader.ReadLinesFromStream(() => type.GetManifestResourceStream("Tests.md"))
                                        .Scan(new { Code = false, Line = default(string) },
                                              (s, line) => new
                                              {
                                                  Code = line.StartsWith("```", StringComparison.Ordinal) ? !s.Code : s.Code,
                                                  Line = line
                                              })
                                        .Skip(1) // skip seed
                                        .GroupAdjacent(e => e.Code)
                    select
                        from e in g.Skip(1) // skip "```"
                        select e.Line       // and keep just the lines
                }
                from e in q.Batch(4)
                select e.Pad(4) into e
                where e.All(s => s != null)
                select e.Fold((s, inp, _, exp) => new { Suppositions = string.Join(Environment.NewLine, s), Input = inp, Expected = exp }) into e
                let throws = '[' != e.Expected.FirstOrDefault()?.TrimStart()[0]
                select
                    config
                        .Select(p => Regex.Match(e.Suppositions, $@"(?<=\b{Regex.Escape(p)}( +is| *[=:]) *`)[^`]+(?=`)", RegexOptions.ExplicitCapture))
                        .Select(m => m.Success ? m.Value : null)
                        .Fold((d, q, esc, nl, blanks) => new
                        {
                            Delimiter  = d is string ds ? ds == @"\t" ? '\t' : ds[0] : ',',
                            Quote      = q == null
                                       ? '"'
                                       : nils.Contains(q, StringComparer.OrdinalIgnoreCase)
                                       ? (char?) null
                                       : q[0],
                            Escape     = esc?[0] ?? '"',
                            NewLine    = nl != null
                                       ? nils.Contains(nl, StringComparer.OrdinalIgnoreCase)
                                       ? null
                                       : Regex.Replace(nl, @"\\[rn]", m => m.Value[1] == 'r' ? "\r"
                                                                         : m.Value[1] == 'n' ? "\n"
                                                                         : throw new FormatException())
                                       : "\n",
                            SkipBlanks = "skip".Equals(blanks, StringComparison.OrdinalIgnoreCase),
                            e.Input,
                            Expected   = throws
                                       ? null
                                       : from r in Newtonsoft.Json.JsonConvert.DeserializeAnonymousType(string.Join(Environment.NewLine, e.Expected), proto)
                                         select (r.ln, r.row),
                            Error      = throws
                                       ? Regex.Match(e.Expected.First(), @"^ *([^: ]+) *: *(.+)").BindNum((t, m) => new
                                         {
                                             Type    = t.Success
                                                     ? Type.GetType(t.Value, throwOnError: true)
                                                     : throw new Exception("Test exception type name missing."),
                                             Message = m.Success
                                                     ? m.Value.Trim()
                                                     : throw new Exception("Test exception message missing."),
                                         })
                                       : null,
                        })
                into e
                select (e.Delimiter, e.Quote, e.Escape, e.NewLine, e.SkipBlanks,
                        e.Input, e.Expected,
                        e.Error?.Type, e.Error?.Message);

            return data.ToTheoryData();
        }

19 Source : ModuleManager.cs
with MIT License
from AvaloniaCommunity

protected virtual bool ModuleNeedsRetrieval(IModuleInfo moduleInfo)
        {
            if (moduleInfo == null)
                throw new ArgumentNullException(nameof(moduleInfo));

            if (moduleInfo.State == ModuleState.NotStarted)
            {
                // If we can instantiate the type, that means the module's replacedembly is already loaded into
                // the AppDomain and we don't need to retrieve it.
                bool isAvailable = Type.GetType(moduleInfo.ModuleType) != null;
                if (isAvailable)
                {
                    moduleInfo.State = ModuleState.ReadyForInitialization;
                }

                return !isAvailable;
            }

            return false;
        }

19 Source : ModuleManager.cs
with MIT License
from AvaloniaCommunity

protected virtual bool ModuleNeedsRetrieval(ModuleInfo moduleInfo)
        {
            if (moduleInfo == null)
                throw new ArgumentNullException(nameof(moduleInfo));

            if (moduleInfo.State == ModuleState.NotStarted)
            {
                // If we can instantiate the type, that means the module's replacedembly is already loaded into
                // the AppDomain and we don't need to retrieve it.
                bool isAvailable = Type.GetType(moduleInfo.ModuleType) != null;
                if (isAvailable)
                {
                    moduleInfo.State = ModuleState.ReadyForInitialization;
                }

                return !isAvailable;
            }

            return false;
        }

19 Source : CachePolicyConfig.cs
with MIT License
from Avanade

internal static void SetCachePolicyManager(CachePolicyManager manager, CachePolicyConfig config)
        {
            if (config == null)
                return;

            // Load the policies.
            var isDefaultSet = false;
            if (config.Policies == null)
                return;

            foreach (var pol in config.Policies)
            {
                if (string.IsNullOrEmpty(pol.Name))
                    throw new CachePolicyConfigException("A Policy has been defined with no Name.");

                if (string.IsNullOrEmpty(pol.Policy))
                    throw new CachePolicyConfigException($"Policy '{pol.Name}' has been defined with no Type.");

                try
                {
                    var type = Type.GetType(pol.Policy) ?? throw new CachePolicyConfigException($"Policy '{pol.Name}' Type '{pol.Policy}' could not be loaded/instantiated.");
                    var policy = (ICachePolicy)Activator.CreateInstance(type);
                    LoadPolicyProperties(pol, type, policy);
                    LoadCaches(manager, pol, policy);

                    if (pol.IsDefault)
                    {
                        if (isDefaultSet)
                            throw new CachePolicyConfigException($"Policy '{pol.Name}' can not set DefaultPolicy where already set.");

                        isDefaultSet = true;
                        manager.DefaultPolicy = policy;
                    }
                }
                catch (CachePolicyConfigException) { throw; }
                catch (Exception ex) { throw new CachePolicyConfigException($"Policy '{pol.Name}' Type '{pol.Policy}' could not be loaded/instantiated: {ex.Message}", ex); }
            }
        }

19 Source : DatabaseEventOutboxItem.cs
with MIT License
from Avanade

public EventData ToEventData()
        {
            if (EventData == null || EventData.Length == 0)
                throw new InvalidOperationException($"The {nameof(EventData)} property must have content to derserialize.");

            _jsonSerializer ??= JsonSerializer.CreateDefault();

            using var stream = new MemoryStream(EventData);
            using var reader = new StreamReader(stream, Encoding.UTF8);
            return (EventData)_jsonSerializer.Deserialize(reader, string.IsNullOrEmpty(ValueType) ? typeof(EventData) : typeof(EventData<>).MakeGenericType(Type.GetType(ValueType, true)))!;
        }

19 Source : CodeGenExecutor.cs
with MIT License
from Avanade

private async Task<(List<CodeGenScriptArgs> Scripts, ConfigType ConfigType, List<IConfigEditor> ConfigEditors)> LoadScriptConfigAsync(FileInfo scriptFile)
        {
            var list = new List<CodeGenScriptArgs>();
            var editors = new List<IConfigEditor>();

            // Load the script XML content.
            XElement xmlScript;
            if (scriptFile!.Exists)
            {
                using var fs = File.OpenText(scriptFile.FullName);
                xmlScript = await XElement.LoadAsync(fs, LoadOptions.None, CancellationToken.None).ConfigureAwait(false);
            }
            else
            {
                var c = await ResourceManager.GetScriptContentAsync(scriptFile.Name, _args.replacedemblies.ToArray()).ConfigureAwait(false);
                if (c == null)
                    throw new CodeGenException($"The Script XML '{scriptFile.Name}' does not exist (either as a file or as an embedded resource).");

                xmlScript = XElement.Parse(c);
            }

            if (xmlScript?.Name != "Script")
                throw new CodeGenException($"The Script XML '{scriptFile.Name}' must have a root element named 'Script'.");

            var ct = xmlScript.Attribute("ConfigType")?.Value ?? throw new CodeGenException($"The Script XML file '{scriptFile.FullName}' must have an attribute named 'ConfigType' within the root 'Script' element.");
            if (!Enum.TryParse<ConfigType>(ct, true, out var configType))
                throw new CodeGenException($"The Script XML '{scriptFile.Name}' attribute named 'ConfigType' has an invalid value '{ct}'.");

            var ia = xmlScript.Attribute("Inherits")?.Value;
            if (ia != null)
            {
                foreach (var ian in ia.Split(';', StringSplitOptions.RemoveEmptyEntries))
                {
                    var fi = new FileInfo(Path.Combine(scriptFile.DirectoryName, ian.Trim()));
                    var result = await LoadScriptConfigAsync(fi).ConfigureAwait(false);
                    if (result.ConfigType != configType)
                        throw new CodeGenException($"The Script XML '{scriptFile.Name}' inherits '{fi.FullName}' which has a different 'ConfigType'; this must be the same.");

                    list.AddRange(result.Scripts);
                    editors.AddRange(result.ConfigEditors);
                }
            }

            var ce = xmlScript.Attribute("ConfigEditor")?.Value;
            if (ce != null)
            {
                var t = Type.GetType(ce, false);
                if (t == null)
                    throw new CodeGenException($"The Script XML '{scriptFile.Name}' references CodeEditor Type '{ce}' which could not be found/loaded.");

                if (!typeof(IConfigEditor).IsreplacedignableFrom(t))
                    throw new CodeGenException($"The Script XML '{scriptFile.Name}' references CodeEditor Type '{ce}' which does not implement IConfigEditor.");

                editors.Add((IConfigEditor)(Activator.CreateInstance(t) ?? throw new CodeGenException($"The Script XML '{scriptFile.Name}' references CodeEditor Type '{ce}' which could not be instantiated.")));
            }

            if (ia == null && !xmlScript.Elements("Generate").Any())
                throw new CodeGenException($"The Script XML '{scriptFile.Name}' file must have at least a single 'Generate' element.");

            foreach (var scriptEle in xmlScript.Elements("Generate"))
            {
                var args = new CodeGenScriptArgs();
                foreach (var att in scriptEle.Attributes())
                {
                    switch (att.Name.LocalName)
                    {
                        case "GenType": args.GenType = att.Value; break;
                        case "FileName": args.FileName = att.Value; break;
                        case "Template": args.Template = att.Value; break;
                        case "OutDir": args.OutDir = att.Value; break;
                        case "GenOnce": args.GenOnce = string.Compare(att.Value, "true", true) == 0; break;
                        case "HelpText": args.HelpText = att.Value; break;
                        default: args.OtherParameters.Add(att.Name.LocalName, att.Value); break;
                    }
                }

                list.Add(args);
            }

            return (list, configType, editors);
        }

19 Source : SqlDataUpdater.cs
with MIT License
from Avanade

private static (object? value, string? message) GetSystemRuntimeValue(string param)
        {
            var ns = param.Split(",");
            if (ns.Length > 2)
                return (null, $"Runtime value parameter '{param}' is invalid; incorrect format.");

            var parts = ns[0].Split(".");
            if (parts.Length <= 1)
                return (null, $"Runtime value parameter '{param}' is invalid; incorrect format.");

            Type? type = null;
            int i = parts.Length;
            for (; i >= 0; i--)
            {
                if (ns.Length == 1)
                    type = Type.GetType(string.Join('.', parts[0..^(parts.Length - i)]));
                else
                    type = Type.GetType(string.Join('.', parts[0..^(parts.Length - i)]) + "," + ns[1]);

                if (type != null)
                    break;
            }

            if (type == null)
                return (null, $"Runtime value parameter '{param}' is invalid; no Type can be found.");

            return GetSystemPropertyValue(param, type, null, parts[i..]);
        }

19 Source : SqlDataUpdater.cs
with MIT License
from Avanade

private void Parse()
        {
            if (DbTables == null)
                throw new InvalidOperationException("RegisterDatabase must be invoked before parsing can occur.");

            // Get the identifier generator configuration where applicable.
            var idjson = _json["^Type"];
            if (idjson != null)
            {
                var typeName = idjson.ToObject<string>();
                if (string.IsNullOrEmpty(typeName))
                    throw new SqlDataUpdaterException($"Identifier generators property '^Type' is not a valid string.");

                var type = Type.GetType(typeName, false);
                if (type == null || type.GetConstructor(Array.Empty<Type>()) == null)
                    throw new SqlDataUpdaterException($"Identifier generators Type '{typeName}' does not exist or have a default (parameter-lesss) constructor.");

                var idgen = Activator.CreateInstance(type)!;
                IdentifierGenerators = idgen as IIdentifierGenerators;
                if (IdentifierGenerators == null)
                    throw new SqlDataUpdaterException($"Identifier generators Type '{typeName}' does not implement IIdentifierGenerators.");
            }

            // Loop through all the schemas.
            foreach (var js in _json.Children<JProperty>())
            {
                // Reserved; ignore.
                if (js.Name == "^Type")
                    continue;

                // Loop through the collection of tables.
                foreach (var jto in GetChildObjects(js))
                {
                    foreach (var jt in jto.Children<JProperty>())
                    {
                        var sdt = new SqlDataTable(js.Name, jt.Name);
                        if (Tables.Any(t => t.Schema == sdt.Schema && t.Name == sdt.Name))
                            throw new SqlDataUpdaterException($"Table '{sdt.Schema}.{sdt.Name}' has been specified more than once.");

                        // Loop through the collection of rows.
                        foreach (var jro in GetChildObjects(jt))
                        {
                            var row = new SqlDataRow(sdt);

                            foreach (var jr in jro.Children<JProperty>())
                            {
                                if (jr.Value.Type == JTokenType.Object)
                                {
                                    foreach (var jc in jro.Children<JProperty>())
                                    {
                                        var col = sdt.IsRefData ? DatabaseRefDataColumns.CodeColumnName : sdt.DbTable.Columns.Where(x => x.IsPrimaryKey).Select(x => x.Name).SingleOrDefault();
                                        if (!string.IsNullOrEmpty(col))
                                        {
                                            row.AddColumn(col, GetColumnValue(jc.Name));
                                            foreach (var jcv in jc.Values().Where(j => j.Type == JTokenType.Property).Cast<JProperty>())
                                            {
                                                row.AddColumn(jcv.Name, GetColumnValue(jcv.Value));
                                            }
                                        }
                                    }
                                }
                                else
                                {
                                    if (sdt.IsRefData && jro.Children().Count() == 1)
                                    {
                                        row.AddColumn(DatabaseRefDataColumns.CodeColumnName, GetColumnValue(jr.Name));
                                        row.AddColumn("Text", GetColumnValue(jr.Value));
                                    }
                                    else
                                        row.AddColumn(jr.Name, GetColumnValue(jr.Value));
                                }
                            }

                            sdt.AddRow(row);
                        }

                        if (sdt.Columns.Count > 0)
                        {
                            sdt.Prepare(IdentifierGenerators);
                            Tables.Add(sdt);
                        }
                    }
                }
            }
        }

19 Source : FileDB.cs
with MIT License
from Avanade

public override async Task<T> AddOrUpdateAsync<T>(T model)
        {
            await base.AddOrUpdateAsync(model);
            Guid id = Guid.NewGuid();
            dynamic lightModel = model;
            if (string.IsNullOrEmpty(lightModel.id))
                lightModel.id = id;

            CreateOrUpdateDoreplacedent(typeof(T).GetType().Name, lightModel);

            return await Task.FromResult<T>(lightModel);
        }

See More Examples