Here are the examples of the csharp api System.Collections.IList.Add(object) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
1362 Examples
19
Source : Formatter.Array2.Helper.cs
with MIT License
from 1996v
with MIT License
from 1996v
public static void Fill_ImplIList<T>(ref T t, ref BssomReader reader, ref BssomDeserializeContext context, int count) where T : IList
{
IBssomFormatter<object> formatter = context.Option.FormatterResolver.GetFormatterWithVerify<object>();
IList coll = (IList)t;
for (int i = 0; i < count; i++)
{
context.CancellationToken.ThrowIfCancellationRequested();
coll.Add(formatter.Deserialize(ref reader, ref context));
}
}
19
Source : JsonData.cs
with MIT License
from 404Lcc
with MIT License
from 404Lcc
public int Add (object value)
{
JsonData data = ToJsonData (value);
json = null;
return EnsureList ().Add (data);
}
19
Source : JsonMapper.cs
with MIT License
from 404Lcc
with MIT License
from 404Lcc
private static object ReadValue (Type inst_type, JsonReader reader)
{
reader.Read ();
if (reader.Token == JsonToken.ArrayEnd)
return null;
//ILRuntime doesn't support nullable valuetype
Type underlying_type = inst_type;//Nullable.GetUnderlyingType(inst_type);
Type value_type = inst_type;
if (reader.Token == JsonToken.Null) {
if (inst_type.IsClreplaced || underlying_type != null) {
return null;
}
throw new JsonException (String.Format (
"Can't replacedign null to an instance of type {0}",
inst_type));
}
if (reader.Token == JsonToken.Double ||
reader.Token == JsonToken.Int ||
reader.Token == JsonToken.Long ||
reader.Token == JsonToken.String ||
reader.Token == JsonToken.Boolean) {
Type json_type = reader.Value.GetType();
var vt = value_type is ILRuntime.Reflection.ILRuntimeWrapperType ? ((ILRuntime.Reflection.ILRuntimeWrapperType)value_type).CLRType.TypeForCLR : value_type;
if (vt.IsreplacedignableFrom(json_type))
return reader.Value;
if (vt is ILRuntime.Reflection.ILRuntimeType && ((ILRuntime.Reflection.ILRuntimeType)vt).ILType.IsEnum)
{
if (json_type == typeof(int) || json_type == typeof(long) || json_type == typeof(short) || json_type == typeof(byte))
return reader.Value;
}
// If there's a custom importer that fits, use it
if (custom_importers_table.ContainsKey (json_type) &&
custom_importers_table[json_type].ContainsKey (
vt)) {
ImporterFunc importer =
custom_importers_table[json_type][vt];
return importer (reader.Value);
}
// Maybe there's a base importer that works
if (base_importers_table.ContainsKey (json_type) &&
base_importers_table[json_type].ContainsKey (
vt)) {
ImporterFunc importer =
base_importers_table[json_type][vt];
return importer (reader.Value);
}
// Maybe it's an enum
if (vt.IsEnum)
return Enum.ToObject (vt, reader.Value);
// Try using an implicit conversion operator
MethodInfo conv_op = GetConvOp (vt, json_type);
if (conv_op != null)
return conv_op.Invoke (null,
new object[] { reader.Value });
// No luck
throw new JsonException (String.Format (
"Can't replacedign value '{0}' (type {1}) to type {2}",
reader.Value, json_type, inst_type));
}
object instance = null;
if (reader.Token == JsonToken.ArrayStart) {
AddArrayMetadata (inst_type);
ArrayMetadata t_data = array_metadata[inst_type];
if (! t_data.IsArray && ! t_data.IsList)
throw new JsonException (String.Format (
"Type {0} can't act as an array",
inst_type));
IList list;
Type elem_type;
if (! t_data.IsArray) {
list = (IList) Activator.CreateInstance (inst_type);
elem_type = t_data.ElementType;
} else {
list = new ArrayList ();
elem_type = inst_type.GetElementType ();
}
while (true) {
object item = ReadValue (elem_type, reader);
if (item == null && reader.Token == JsonToken.ArrayEnd)
break;
var rt = elem_type is ILRuntime.Reflection.ILRuntimeWrapperType ? ((ILRuntime.Reflection.ILRuntimeWrapperType)elem_type).RealType : elem_type;
if (elem_type is ILRuntime.Reflection.ILRuntimeType && ((ILRuntime.Reflection.ILRuntimeType)elem_type).ILType.IsEnum)
{
item = (int) item;
}
else
{
item = rt.CheckCLRTypes(item);
}
list.Add (item);
}
if (t_data.IsArray) {
int n = list.Count;
instance = Array.CreateInstance (elem_type, n);
for (int i = 0; i < n; i++)
((Array) instance).SetValue (list[i], i);
} else
instance = list;
} else if (reader.Token == JsonToken.ObjectStart)
{
AddObjectMetadata(value_type);
ObjectMetadata t_data = object_metadata[value_type];
if (value_type is ILRuntime.Reflection.ILRuntimeType)
instance = ((ILRuntime.Reflection.ILRuntimeType) value_type).ILType.Instantiate();
else
instance = Activator.CreateInstance(value_type);
bool isIntKey = t_data.IsDictionary && value_type.GetGenericArguments()[0] == typeof(int);
while (true)
{
reader.Read();
if (reader.Token == JsonToken.ObjectEnd)
break;
string key = (string) reader.Value;
if (t_data.Properties.ContainsKey(key))
{
PropertyMetadata prop_data =
t_data.Properties[key];
if (prop_data.IsField)
{
((FieldInfo) prop_data.Info).SetValue(
instance, ReadValue(prop_data.Type, reader));
}
else
{
PropertyInfo p_info =
(PropertyInfo) prop_data.Info;
if (p_info.CanWrite)
p_info.SetValue(
instance,
ReadValue(prop_data.Type, reader),
null);
else
ReadValue(prop_data.Type, reader);
}
}
else
{
if (!t_data.IsDictionary)
{
if (!reader.SkipNonMembers)
{
throw new JsonException(String.Format(
"The type {0} doesn't have the " +
"property '{1}'",
inst_type, key));
}
else
{
ReadSkip(reader);
continue;
}
}
var dict = ((IDictionary) instance);
var elem_type = t_data.ElementType;
object readValue = ReadValue(elem_type, reader);
var rt = t_data.ElementType is ILRuntime.Reflection.ILRuntimeWrapperType
? ((ILRuntime.Reflection.ILRuntimeWrapperType) t_data.ElementType).RealType
: t_data.ElementType;
//value 是枚举的情况没处理,毕竟少
if (isIntKey)
{
var dictValueType = value_type.GetGenericArguments()[1];
IConvertible convertible = dictValueType as IConvertible;
if (convertible == null)
{
//自定义类型扩展
if (dictValueType == typeof(double)) //CheckCLRTypes() 没有double,也可以修改ilruntime源码实现
{
var v = Convert.ChangeType(readValue.ToString(), dictValueType);
dict.Add(Convert.ToInt32(key), v);
}
else
{
readValue = rt.CheckCLRTypes(readValue);
dict.Add(Convert.ToInt32(key), readValue);
// throw new JsonException (String.Format("The type {0} doesn't not support",dictValueType));
}
}
else
{
var v = Convert.ChangeType(readValue, dictValueType);
dict.Add(Convert.ToInt32(key), v);
}
}
else
{
readValue = rt.CheckCLRTypes(readValue);
dict.Add(key, readValue);
}
}
}
}
return instance;
}
19
Source : TypeFuzzer.cs
with Apache License 2.0
from 42skillz
with Apache License 2.0
from 42skillz
private IEnumerable GenerateListOf(Type type, int recursionLevel)
{
var typeGenericTypeArguments = type.GenericTypeArguments;
var listType = typeof(List<>);
var constructedListType = listType.MakeGenericType(typeGenericTypeArguments);
// Instantiates a collection of ...
var list = Activator.CreateInstance(constructedListType) as IList;
// Add 5 elements of this type
for (var i = 0; i < MaxCountToFuzzInLists; i++)
{
list.Add(GenerateInstanceOf(typeGenericTypeArguments.Single(), recursionLevel));
}
return list;
}
19
Source : JsonMapper.cs
with MIT License
from 404Lcc
with MIT License
from 404Lcc
private static IJsonWrapper ReadValue (WrapperFactory factory,
JsonReader reader)
{
reader.Read ();
if (reader.Token == JsonToken.ArrayEnd ||
reader.Token == JsonToken.Null)
return null;
IJsonWrapper instance = factory ();
if (reader.Token == JsonToken.String) {
instance.SetString ((string) reader.Value);
return instance;
}
if (reader.Token == JsonToken.Double) {
instance.SetDouble ((double) reader.Value);
return instance;
}
if (reader.Token == JsonToken.Int) {
instance.SetInt ((int) reader.Value);
return instance;
}
if (reader.Token == JsonToken.Long) {
instance.SetLong ((long) reader.Value);
return instance;
}
if (reader.Token == JsonToken.Boolean) {
instance.SetBoolean ((bool) reader.Value);
return instance;
}
if (reader.Token == JsonToken.ArrayStart) {
instance.SetJsonType (JsonType.Array);
while (true) {
IJsonWrapper item = ReadValue (factory, reader);
if (item == null && reader.Token == JsonToken.ArrayEnd)
break;
((IList) instance).Add (item);
}
}
else if (reader.Token == JsonToken.ObjectStart) {
instance.SetJsonType (JsonType.Object);
while (true) {
reader.Read ();
if (reader.Token == JsonToken.ObjectEnd)
break;
string property = (string) reader.Value;
((IDictionary) instance)[property] = ReadValue (
factory, reader);
}
}
return instance;
}
19
Source : ListDecorator.cs
with MIT License
from 404Lcc
with MIT License
from 404Lcc
public override object Read(object value, ProtoReader source)
{
try
{
int field = source.FieldNumber;
object origValue = value;
if (value == null) value = Activator.CreateInstance(concreteType);
bool isList = IsList && !SuppressIList;
if (packedWireType != WireType.None && source.WireType == WireType.String)
{
SubItemToken token = ProtoReader.StartSubItem(source);
if (isList)
{
IList list = (IList)value;
while (ProtoReader.HreplacedubValue(packedWireType, source))
{
list.Add(Tail.Read(null, source));
}
}
else
{
object[] args = new object[1];
while (ProtoReader.HreplacedubValue(packedWireType, source))
{
args[0] = Tail.Read(null, source);
add.Invoke(value, args);
}
}
ProtoReader.EndSubItem(token, source);
}
else
{
if (isList)
{
IList list = (IList)value;
do
{
list.Add(Tail.Read(null, source));
} while (source.TryReadFieldHeader(field));
}
else
{
object[] args = new object[1];
do
{
args[0] = Tail.Read(null, source);
add.Invoke(value, args);
} while (source.TryReadFieldHeader(field));
}
}
return origValue == value ? null : value;
} catch(TargetInvocationException tie)
{
if (tie.InnerException != null) throw tie.InnerException;
throw;
}
}
19
Source : JSONParser.cs
with MIT License
from 5minlab
with MIT License
from 5minlab
internal static object ParseValue(Type type, string json) {
if (type == typeof(string)) {
if (json.Length <= 2)
return string.Empty;
string str = json.Substring(1, json.Length - 2);
return str.Replace("\\\\", "\"\"").Replace("\\", string.Empty).Replace("\"\"", "\\");
}
if (type == typeof(int)) {
int result;
int.TryParse(json, out result);
return result;
}
if (type == typeof(float)) {
float result;
float.TryParse(json, out result);
return result;
}
if (type == typeof(double)) {
double result;
double.TryParse(json, out result);
return result;
}
if (type == typeof(bool)) {
return json.ToLower() == "true";
}
if (json == "null") {
return null;
}
if (type.IsArray) {
Type arrayType = type.GetElementType();
if (json[0] != '[' || json[json.Length - 1] != ']')
return null;
List<string> elems = Split(json);
Array newArray = Array.CreateInstance(arrayType, elems.Count);
for (int i = 0; i < elems.Count; i++)
newArray.SetValue(ParseValue(arrayType, elems[i]), i);
splitArrayPool.Push(elems);
return newArray;
}
if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(List<>)) {
Type listType = type.GetGenericArguments()[0];
if (json[0] != '[' || json[json.Length - 1] != ']')
return null;
List<string> elems = Split(json);
var list = (IList)type.GetConstructor(new Type[] { typeof(int) }).Invoke(new object[] { elems.Count });
for (int i = 0; i < elems.Count; i++)
list.Add(ParseValue(listType, elems[i]));
splitArrayPool.Push(elems);
return list;
}
if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Dictionary<,>)) {
Type keyType, valueType;
{
Type[] args = type.GetGenericArguments();
keyType = args[0];
valueType = args[1];
}
//Refuse to parse dictionary keys that aren't of type string
if (keyType != typeof(string))
return null;
//Must be a valid dictionary element
if (json[0] != '{' || json[json.Length - 1] != '}')
return null;
//The list is split into key/value pairs only, this means the split must be divisible by 2 to be valid JSON
List<string> elems = Split(json);
if (elems.Count % 2 != 0)
return null;
var dictionary = (IDictionary)type.GetConstructor(new Type[] { typeof(int) }).Invoke(new object[] { elems.Count / 2 });
for (int i = 0; i < elems.Count; i += 2) {
if (elems[i].Length <= 2)
continue;
string keyValue = elems[i].Substring(1, elems[i].Length - 2);
object val = ParseValue(valueType, elems[i + 1]);
dictionary.Add(keyValue, val);
}
return dictionary;
}
if (type == typeof(object)) {
return ParseAnonymousValue(json);
}
if (json[0] == '{' && json[json.Length - 1] == '}') {
return ParseObject(type, json);
}
return null;
}
19
Source : SortedObservableCollectionTests.cs
with Microsoft Public License
from AArnott
with Microsoft Public License
from AArnott
[Fact]
public void Add_IList()
{
IList collection = this.collection;
collection.Add(5);
replacedert.Equal(5, replacedert.Single(collection));
}
19
Source : SortedObservableCollectionTests.cs
with Microsoft Public License
from AArnott
with Microsoft Public License
from AArnott
[Fact]
public void Indexer_IList()
{
IList collection = this.collection;
collection.Add(5);
replacedert.Equal(5, collection[0]);
replacedert.Throws<NotSupportedException>(() => collection[0] = 3);
}
19
Source : SortedObservableCollectionTests.cs
with Microsoft Public License
from AArnott
with Microsoft Public License
from AArnott
[Fact]
public void Remove_IList()
{
IList collection = this.collection;
collection.Remove(1);
collection.Add(3);
collection.Add(5);
collection.Remove(3);
collection.Remove(5);
}
19
Source : AddPatchOperation.cs
with MIT License
from actions
with MIT License
from actions
public override void Apply(TModel target)
{
this.Apply(
target,
(type, parent, current) =>
{
// Empty current means replace the whole object.
if (string.IsNullOrEmpty(current))
{
parent = this.Value;
}
else if (type.IsList())
{
var list = (IList)parent;
if (current == EndOfIndex)
{
list.Add(this.Value);
}
else
{
int index;
// When index == list.Count it's the same
// as doing an index append to the end.
if (int.TryParse(current, out index) &&
list.Count >= index)
{
list.Insert(index, this.Value);
}
else
{
// We can't insert beyond the length of the list.
throw new PatchOperationFailedException(PatchResources.IndexOutOfRange(this.Path));
}
}
}
else if (type.IsDictionary())
{
((IDictionary)parent)[current] = this.Value;
}
else
{
type.SetMemberValue(current, parent, this.Value);
}
});
}
19
Source : StateManagedCollection.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
public int Add(T parameter)
{
return ((IList)this).Add(parameter);
}
19
Source : CollectionBase.cs
with Mozilla Public License 2.0
from ahyahy
with Mozilla Public License 2.0
from ahyahy
public virtual int Add(object value)
{
return List.Add(value);
}
19
Source : InstranceMaker.cs
with MIT License
from AiursoftWeb
with MIT License
from AiursoftWeb
private static IList GetArrayWithInstanceInherts(Type itemType)
{
var listType = typeof(List<>);
var constructedListType = listType.MakeGenericType(itemType);
var instance = (IList)Activator.CreateInstance(constructedListType);
if (instance == null)
{
return new List<object>();
}
if (!itemType.IsAbstract)
{
instance.Add(Make(itemType));
}
foreach (var item in replacedembly.GetEntryreplacedembly()?.GetTypes().Where(t => !t.IsAbstract).Where(t => t.IsSubclreplacedOf(itemType)) ?? new List<Type>())
{
instance.Add(Make(item));
}
return instance;
}
19
Source : JsonSerializerInternalReader.cs
with MIT License
from akaskela
with MIT License
from akaskela
private object PopulateMultidimensionalArray(IList list, JsonReader reader, JsonArrayContract contract, JsonProperty containerProperty, string id)
{
int rank = contract.UnderlyingType.GetArrayRank();
if (id != null)
{
AddReference(reader, id, list);
}
OnDeserializing(reader, contract, list);
JsonContract collectionItemContract = GetContractSafe(contract.CollectionItemType);
JsonConverter collectionItemConverter = GetConverter(collectionItemContract, null, contract, containerProperty);
int? previousErrorIndex = null;
Stack<IList> listStack = new Stack<IList>();
listStack.Push(list);
IList currentList = list;
bool finished = false;
do
{
int initialDepth = reader.Depth;
if (listStack.Count == rank)
{
try
{
if (ReadForType(reader, collectionItemContract, collectionItemConverter != null))
{
switch (reader.TokenType)
{
case JsonToken.EndArray:
listStack.Pop();
currentList = listStack.Peek();
previousErrorIndex = null;
break;
default:
object value;
if (collectionItemConverter != null && collectionItemConverter.CanRead)
{
value = DeserializeConvertable(collectionItemConverter, reader, contract.CollectionItemType, null);
}
else
{
value = CreateValueInternal(reader, contract.CollectionItemType, collectionItemContract, null, contract, containerProperty, null);
}
currentList.Add(value);
break;
}
}
else
{
break;
}
}
catch (Exception ex)
{
JsonPosition errorPosition = reader.GetPosition(initialDepth);
if (IsErrorHandled(list, contract, errorPosition.Position, reader as IJsonLineInfo, reader.Path, ex))
{
HandleError(reader, true, initialDepth);
if (previousErrorIndex != null && previousErrorIndex == errorPosition.Position)
{
// reader index has not moved since previous error handling
// break out of reading array to prevent infinite loop
throw JsonSerializationException.Create(reader, "Infinite loop detected from error handling.", ex);
}
else
{
previousErrorIndex = errorPosition.Position;
}
}
else
{
throw;
}
}
}
else
{
if (reader.Read())
{
switch (reader.TokenType)
{
case JsonToken.StartArray:
IList newList = new List<object>();
currentList.Add(newList);
listStack.Push(newList);
currentList = newList;
break;
case JsonToken.EndArray:
listStack.Pop();
if (listStack.Count > 0)
{
currentList = listStack.Peek();
}
else
{
finished = true;
}
break;
case JsonToken.Comment:
break;
default:
throw JsonSerializationException.Create(reader, "Unexpected token when deserializing multidimensional array: " + reader.TokenType);
}
}
else
{
break;
}
}
} while (!finished);
if (!finished)
{
ThrowUnexpectedEndException(reader, contract, list, "Unexpected end when deserializing array.");
}
OnDeserialized(reader, contract, list);
return list;
}
19
Source : JsonSerializerInternalReader.cs
with MIT License
from akaskela
with MIT License
from akaskela
private object PopulateList(IList list, JsonReader reader, JsonArrayContract contract, JsonProperty containerProperty, string id)
{
IWrappedCollection wrappedCollection = list as IWrappedCollection;
object underlyingList = wrappedCollection != null ? wrappedCollection.UnderlyingCollection : list;
if (id != null)
{
AddReference(reader, id, underlyingList);
}
// can't populate an existing array
if (list.IsFixedSize)
{
reader.Skip();
return underlyingList;
}
OnDeserializing(reader, contract, underlyingList);
int initialDepth = reader.Depth;
if (contract.ItemContract == null)
{
contract.ItemContract = GetContractSafe(contract.CollectionItemType);
}
JsonConverter collectionItemConverter = GetConverter(contract.ItemContract, null, contract, containerProperty);
int? previousErrorIndex = null;
bool finished = false;
do
{
try
{
if (ReadForType(reader, contract.ItemContract, collectionItemConverter != null))
{
switch (reader.TokenType)
{
case JsonToken.EndArray:
finished = true;
break;
default:
object value;
if (collectionItemConverter != null && collectionItemConverter.CanRead)
{
value = DeserializeConvertable(collectionItemConverter, reader, contract.CollectionItemType, null);
}
else
{
value = CreateValueInternal(reader, contract.CollectionItemType, contract.ItemContract, null, contract, containerProperty, null);
}
list.Add(value);
break;
}
}
else
{
break;
}
}
catch (Exception ex)
{
JsonPosition errorPosition = reader.GetPosition(initialDepth);
if (IsErrorHandled(underlyingList, contract, errorPosition.Position, reader as IJsonLineInfo, reader.Path, ex))
{
HandleError(reader, true, initialDepth);
if (previousErrorIndex != null && previousErrorIndex == errorPosition.Position)
{
// reader index has not moved since previous error handling
// break out of reading array to prevent infinite loop
throw JsonSerializationException.Create(reader, "Infinite loop detected from error handling.", ex);
}
else
{
previousErrorIndex = errorPosition.Position;
}
}
else
{
throw;
}
}
} while (!finished);
if (!finished)
{
ThrowUnexpectedEndException(reader, contract, underlyingList, "Unexpected end when deserializing array.");
}
OnDeserialized(reader, contract, underlyingList);
return underlyingList;
}
19
Source : CollectionWrapper.cs
with MIT License
from akaskela
with MIT License
from akaskela
public virtual void Add(T item)
{
if (_genericCollection != null)
{
_genericCollection.Add(item);
}
else
{
_list.Add(item);
}
}
19
Source : DictionaryWrapper.cs
with MIT License
from akaskela
with MIT License
from akaskela
public void Add(KeyValuePair<TKey, TValue> item)
{
if (_dictionary != null)
{
((IList)_dictionary).Add(item);
}
#if !(NET40 || NET35 || NET20 || PORTABLE40)
else if (_readOnlyDictionary != null)
{
throw new NotSupportedException();
}
#endif
else if (_genericDictionary != null)
{
_genericDictionary.Add(item);
}
}
19
Source : EnumsCheckComboBox.xaml.cs
with MIT License
from AkiniKites
with MIT License
from AkiniKites
private static void OnSelectedFlagsChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var ecb = (EnumsCheckComboBox)d;
if (ecb._ignoreSelectedFlags) return;
ecb._ignoreSelectedFlags = true;
ecb.SelectedItems.Clear();
var flags = e.NewValue == null ? 0 : (int)e.NewValue;
if (flags != 0)
{
foreach (var item in ecb.ItemsCollection)
{
var obj = ecb.GereplacedemValue(item);
if (obj != null)
{
var itemValue = (int)obj;
if ((itemValue & flags) == itemValue)
ecb.SelectedItems.Add(item);
}
}
}
ecb._ignoreSelectedFlags = false;
}
19
Source : Extension.cs
with MIT License
from AlenToma
with MIT License
from AlenToma
internal static IList DataReaderConverter(Transaction.Transaction repository, IDataReader reader, ISqlCommand command, Type type)
{
var tType = type.GetActualType();
var attachable = tType.GetPrimaryKey() != null;
var baseListType = typeof(List<>);
var listType = baseListType.MakeGenericType(tType);
var iList = DeepCloner.CreateInstance(listType) as IList;
var props = DeepCloner.GetFastDeepClonerProperties(tType);
try
{
var colNames = new SafeValueType<int, string>();
var pp = new SafeValueType<int, IFastDeepClonerProperty>();
while (reader.Read())
{
object item = null;
object replacedem = null;
item = DeepCloner.CreateInstance(tType);
replacedem = attachable ? DeepCloner.CreateInstance(tType) : null;
var col = 0;
while (col < reader.FieldCount)
{
string columnName;
if (colNames.ContainsKey(col))
columnName = colNames[col];
else
{
columnName = reader.GetName(col);
colNames.TryAdd(col, columnName);
}
var value = reader[columnName];
IFastDeepClonerProperty prop;
if (!pp.ContainsKey(col))
{
prop = DeepCloner.GetProperty(tType, columnName);
if (prop == null)
prop = props.FirstOrDefault(x => string.Equals(x.GetPropertyName(), columnName, StringComparison.CurrentCultureIgnoreCase) || x.GetPropertyName().ToLower() == columnName);
pp.TryAdd(col, prop);
}
else prop = pp[col];
if (prop != null && value != DBNull.Value && value != null && prop.CanRead)
{
if (value as byte[] != null && prop.PropertyType.FullName.Contains("Guid"))
value = new Guid(value as byte[]);
var dataEncode = prop.GetCustomAttribute<DataEncode>();
if (prop.ContainAttribute<ToBase64String>())
{
if (value.ConvertValue<string>().IsBase64String())
value = MethodHelper.DecodeStringFromBase64(value.ConvertValue<string>());
else value = MethodHelper.ConvertValue(value, prop.PropertyType);
}
else if (dataEncode != null)
value = new DataCipher(dataEncode.Key, dataEncode.KeySize).Decrypt(value.ConvertValue<string>());
else if (prop.ContainAttribute<JsonDoreplacedent>())
value = value?.ToString().FromJson(prop.PropertyType);
else if (prop.ContainAttribute<XmlDoreplacedent>())
value = value?.ToString().FromXml();
else value = MethodHelper.ConvertValue(value, prop.PropertyType);
prop.SetValue(item, value);
if (attachable)
prop.SetValue(replacedem, value);
}
col++;
}
if (replacedem != null && !(repository?.IsAttached(replacedem) ?? true))
repository?.AttachNew(replacedem);
iList.Add(item);
}
}
catch (Exception e)
{
throw new EnreplacedyException(e.Message);
}
finally
{
reader.Close();
reader.Dispose();
if (repository.OpenedDataReaders.ContainsKey(reader))
repository.OpenedDataReaders.Remove(reader);
}
return iList;
}
19
Source : XmlUtility.cs
with MIT License
from AlenToma
with MIT License
from AlenToma
private static object FromXml(XmlNode doc)
{
var fullType = Type.GetType(doc.Attributes["FullName"].Value);
object item = fullType.CreateInstance();
var subtype = fullType.GetActualType();
foreach (XmlNode chil in doc.ChildNodes)
{
var prop = DeepCloner.GetProperty(subtype, chil.Name);
if (chil.Attributes["FullName"] != null && prop == null)
{
if (chil.Name != "List")
((IList)item).Add(FromXml(chil));
else foreach (var t in FromXml(chil) as IList)
((IList)item).Add(t);
continue;
}
if (prop != null && prop.IsInternalType)
prop.SetValue(item, chil.InnerText.ConvertValue(prop.PropertyType));
else if (chil.Attributes["FullName"] != null)
prop.SetValue(item, FromXml(chil));
else ((IList)item).Add(chil.InnerText.ConvertValue(item.GetType().GetActualType()));
}
return item;
}
19
Source : JSON.cs
with MIT License
from AlenToma
with MIT License
from AlenToma
private void DoParseList(IList parse, Type it, IList o)
{
Dictionary<string, object> globals = new Dictionary<string, object>();
foreach (var k in parse)
{
_usingglobals = false;
object v = k;
var a = k as Dictionary<string, object>;
if (a != null)
v = ParseDictionary(a, globals, it, null);
else
v = ChangeType(k, it);
o.Add(v);
}
}
19
Source : JSON.cs
with MIT License
from AlenToma
with MIT License
from AlenToma
private object CreateGenericList(List<object> data, Type pt, Type bt, Dictionary<string, object> globalTypes)
{
if (pt != typeof(object))
{
IList col = (IList)FastDeepCloner.DeepCloner.CreateInstance(pt);
var it = Reflection.Instance.GetGenericArguments(pt)[0];// pt.GetGenericArguments()[0];
// create an array of objects
foreach (object ob in data)
{
if (ob is IDictionary)
col.Add(ParseDictionary((Dictionary<string, object>)ob, globalTypes, it, null));
else if (ob is List<object>)
{
if (bt.IsGenericType)
col.Add((List<object>)ob);//).ToArray());
else
col.Add(((List<object>)ob).ToArray());
}
else
col.Add(ChangeType(ob, it));
}
return col;
}
return data;
}
19
Source : XmlUtility.cs
with MIT License
from AlenToma
with MIT License
from AlenToma
private static object FromXml(XmlNode doc)
{
var fullType = Type.GetType(doc.Attributes["FullName"].Value);
object item = fullType.CreateInstance();
var subtype = fullType.GetActualType();
foreach (XmlNode chil in doc.ChildNodes)
{
var prop = DeepCloner.GetProperty(subtype, chil.Name);
if (chil.Attributes["FullName"] != null && prop == null)
{
if (chil.Name != "List")
((IList)item).Add(FromXml(chil));
else foreach (var t in FromXml(chil) as IList)
((IList)item).Add(t);
continue;
}
if (prop != null && prop.IsInternalType)
prop.SetValue(item, chil.InnerText.ConvertValue(prop.PropertyType));
else if (chil.Attributes["FullName"] != null)
prop.SetValue(item, FromXml(chil));
else ((IList)item).Add(chil.InnerText.ConvertValue(item.GetType().GetActualType()));
}
return item;
}
19
Source : LightDataRowCollection.cs
with MIT License
from AlenToma
with MIT License
from AlenToma
public IList ToObject(Type type, Transaction.Transaction repository = null)
{
var tType = type.GetActualType();
var baseListType = typeof(List<>);
var listType = baseListType.MakeGenericType(tType);
var iList = listType.CreateInstance() as IList;
foreach (var item in this)
{
var replacedem = item.ToObject(tType);
iList?.Add(replacedem);
if (replacedem.GetPrimaryKey() != null && (!repository?.IsAttached(replacedem) ?? true))
repository?.Attach(replacedem);
}
return iList;
}
19
Source : LightDataRowCollection.cs
with MIT License
from AlenToma
with MIT License
from AlenToma
public List<T> ToObject<T>(Transaction.Transaction repository)
{
var tType = typeof(T).GetActualType();
var baseListType = typeof(List<>);
var listType = baseListType.MakeGenericType(tType);
var iList = listType.CreateInstance() as IList;
foreach (var item in this)
{
var replacedem = item.ToObject(tType);
iList?.Add(replacedem);
if (replacedem.GetPrimaryKey() != null && (!repository?.IsAttached(replacedem) ?? true))
repository?.Attach(replacedem);
}
return (List<T>)iList;
}
19
Source : LightDataTableRow.cs
with MIT License
from AlenToma
with MIT License
from AlenToma
public object ToObject(object t)
{
var type = t is Type ? (Type)t : t.GetType();
var o = type.CreateInstance();
var obj = type.GetActualType().CreateInstance();
foreach (var pr in DeepCloner.GetFastDeepClonerProperties(obj?.GetType()))
{
var name = pr.GetPropertyName();
if (!Columns.ContainsKey(name) || !pr.CanRead)
continue;
var value = this[name, true];
if (!(value is LightDataTable))
{
if (pr.ContainAttribute<ToBase64String>())
{
if (value != null && value.ConvertValue<string>().IsBase64String())
{
value = MethodHelper.DecodeStringFromBase64(value.ConvertValue<string>());
}
}
else if (value != null && pr.ContainAttribute<DataEncode>())
value = new DataCipher(pr.GetCustomAttribute<DataEncode>().Key, pr.GetCustomAttribute<DataEncode>().KeySize).Decrypt(value.ConvertValue<string>());
else if (pr.ContainAttribute<JsonDoreplacedent>())
value = value?.ToString().FromJson(pr.PropertyType);
else if (pr.ContainAttribute<XmlDoreplacedent>())
value = value?.ToString().FromXml();
TypeValidation(ref value, pr.PropertyType, true);
}
else
{
var table = value as LightDataTable;
if (table == null || !table.Rows.Any())
continue;
value = table.Rows.ToObject(pr.PropertyType);
if (pr.PropertyType == pr.PropertyType.GetActualType())
value = (value as IList)?.Cast<object>().FirstOrDefault();
}
try
{
pr.SetValue(obj, value);
}
catch
{
// ignored
}
}
if (o is IList)
{
((IList)o).Add(obj);
return o;
}
else
return obj;
}
19
Source : LightDataTableRow.cs
with MIT License
from AlenToma
with MIT License
from AlenToma
public T ToObject<T>()
{
var o = typeof(T).CreateInstance();
var obj = o is IList
?
o.GetType().GetActualType().CreateInstance()
: typeof(T).CreateInstance();
foreach (var pr in DeepCloner.GetFastDeepClonerProperties(obj.GetType()))
{
var name = pr.GetPropertyName();
if (!Columns.ContainsKey(name) || !pr.CanRead)
continue;
var value = this[name, true];
if (!(value is LightDataTable))
{
if (value != null && pr.ContainAttribute<ToBase64String>())
{
if (value.ConvertValue<string>().IsBase64String())
{
value = MethodHelper.DecodeStringFromBase64(value.ConvertValue<string>());
}
}
else if (value != null && pr.ContainAttribute<DataEncode>())
{
value = new DataCipher(pr.GetCustomAttribute<DataEncode>().Key, pr.GetCustomAttribute<DataEncode>().KeySize).Decrypt(value.ConvertValue<string>());
}
else if (pr.ContainAttribute<JsonDoreplacedent>())
value = value?.ToString().FromJson(pr.PropertyType);
else if (pr.ContainAttribute<XmlDoreplacedent>())
value = value?.ToString().FromXml();
TypeValidation(ref value, pr.PropertyType, true);
}
else
{
var table = value as LightDataTable;
if (table == null || !table.Rows.Any())
continue;
value = table.Rows.ToObject(pr.PropertyType);
if (pr.PropertyType == pr.PropertyType.GetActualType())
value = (value as IList)?.Cast<object>().FirstOrDefault();
}
try
{
pr.SetValue(obj, value);
}
catch
{
// ignored
}
}
if (o is IList)
{
((IList)o).Add(obj);
return (T)o;
}
else
return (T)obj;
}
19
Source : ListModel.cs
with MIT License
from AlexGyver
with MIT License
from AlexGyver
public void AddRange(IEnumerable items)
{
foreach (object obj in items)
_list.Add(obj);
OnStructureChanged(new TreePathEventArgs(TreePath.Empty));
}
19
Source : ListModel.cs
with MIT License
from AlexGyver
with MIT License
from AlexGyver
public void Add(object item)
{
_list.Add(item);
OnNodesInserted(new TreeModelEventArgs(TreePath.Empty, new int[] { _list.Count - 1 }, new object[] { item }));
}
19
Source : ListFiller.cs
with MIT License
from AlexGyver
with MIT License
from AlexGyver
public void Fill(IList target, IEnumerable source)
{
PropertyInfo[] pi = null;
Type t = null;
foreach (var sourceItem in source)
{
if (pi == null || sourceItem.GetType() != t)
{
t = sourceItem.GetType();
pi = new PropertyInfo[this.properties.Count];
int i = 0;
foreach (var p in this.properties)
{
if (string.IsNullOrEmpty(p.Key))
{
i++;
continue;
}
pi[i] = t.GetProperty(p.Key);
if (pi[i] == null)
{
throw new InvalidOperationException(
string.Format("Could not find field {0} on type {1}", p.Key, t));
}
i++;
}
}
var item = new T();
int j = 0;
foreach (var p in this.properties)
{
if (pi[j] != null)
{
var value = pi[j].GetValue(sourceItem, null);
p.Value(item, value);
}
j++;
}
target.Add(item);
}
}
19
Source : DataPointSeries.cs
with MIT License
from AlexGyver
with MIT License
from AlexGyver
protected void AddDataPoints(IList dest, IEnumerable itemsSource, string dataFieldX, string dataFieldY)
{
PropertyInfo pix = null;
PropertyInfo piy = null;
Type t = null;
foreach (var o in itemsSource)
{
if (pix == null || o.GetType() != t)
{
t = o.GetType();
pix = t.GetProperty(dataFieldX);
piy = t.GetProperty(dataFieldY);
if (pix == null)
{
throw new InvalidOperationException(
string.Format("Could not find data field {0} on type {1}", this.DataFieldX, t));
}
if (piy == null)
{
throw new InvalidOperationException(
string.Format("Could not find data field {0} on type {1}", this.DataFieldY, t));
}
}
double x = this.ToDouble(pix.GetValue(o, null));
double y = this.ToDouble(piy.GetValue(o, null));
var pp = new DataPoint(x, y);
dest.Add(pp);
}
//var filler = new ListFiller<DataPoint>();
//filler.Add(dataFieldX, (item, value) => item.X = this.ToDouble(value));
//filler.Add(dataFieldY, (item, value) => item.Y = this.ToDouble(value));
//filler.Fill(dest, itemsSource);
}
19
Source : AopJsonReader.cs
with Apache License 2.0
from alipay
with Apache License 2.0
from alipay
public IList GetListObjects(string listName, string itemName, Type type, DAopConvert convert)
{
IList listObjs = null;
Object jsonObject = json[listName];
IList jsonList = null;
if (jsonObject is IList)
{
jsonList = jsonObject as IList;
}
else if (jsonObject is IDictionary)
{
IDictionary jsonMap = jsonObject as IDictionary;
if (jsonMap != null && jsonMap.Count > 0)
{
Object itemTmp = jsonMap[itemName];
if (itemTmp == null && listName != null)
{
itemTmp = jsonMap[listName.Substring(0, listName.Length - 1)];
}
if (itemTmp is IList)
{
jsonList = itemTmp as IList;
}
}
}
if (jsonList != null && jsonList.Count > 0)
{
Type listType = typeof(List<>).MakeGenericType(new Type[] { type });
listObjs = Activator.CreateInstance(listType) as IList;
foreach (object item in jsonList)
{
if (typeof(JObject).IsreplacedignableFrom(item.GetType())) // object
{
JObject subMap = item as JObject;
object subObj = convert(new AopJsonReader(subMap), type);
if (subObj != null)
{
listObjs.Add(subObj);
}
}
else if (typeof(IList).IsreplacedignableFrom(item.GetType())) // list/array
{
// TODO not support yet
}
else if (typeof(long).IsreplacedignableFrom(type))
{
JValue tmp = item as JValue;
if (tmp.Value != null)
{
listObjs.Add(((IConvertible)tmp).ToInt64(null));
}
else
{
listObjs.Add(null);
}
}
else if (typeof(int).IsreplacedignableFrom(type))
{
JValue tmp = item as JValue;
if (tmp.Value != null)
{
listObjs.Add(((IConvertible)tmp).ToInt32(null));
}
else
{
listObjs.Add(null);
}
}
else if (typeof(double).IsreplacedignableFrom(type))
{
JValue tmp = item as JValue;
if (tmp.Value != null)
{
listObjs.Add(((IConvertible)tmp).ToDouble(null));
}
else
{
listObjs.Add(null);
}
}
else if (typeof(bool).IsreplacedignableFrom(type))
{
JValue tmp = item as JValue;
if (tmp.Value != null)
{
listObjs.Add(((IConvertible)tmp).ToBoolean(null));
}
else
{
listObjs.Add(null);
}
}
else if (typeof(string).IsreplacedignableFrom(type))
{
JValue tmp = item as JValue;
if (tmp.Value != null)
{
listObjs.Add(((IConvertible)tmp).ToString(null));
}
else
{
listObjs.Add(null);
}
}
else
{
JValue tmp = item as JValue;
listObjs.Add(tmp.Value);
}
}
}
return listObjs;
}
19
Source : CollectionFormatter.cs
with Apache License 2.0
from allenai
with Apache License 2.0
from allenai
public T Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options)
{
if (reader.TryReadNil())
{
return default(T);
}
IMessagePackFormatter<object> formatter = options.Resolver.GetFormatterWithVerify<object>();
var count = reader.ReadArrayHeader();
var list = new T();
options.Security.DepthStep(ref reader);
try
{
for (int i = 0; i < count; i++)
{
reader.CancellationToken.ThrowIfCancellationRequested();
list.Add(formatter.Deserialize(ref reader, options));
}
}
finally
{
reader.Depth--;
}
return list;
}
19
Source : EditorUI.cs
with MIT License
from allenwp
with MIT License
from allenwp
static unsafe void SubmitFieldPropertyInspector(FieldPropertyListInfo info, object enreplacedyComponent, bool showMidi = true)
{
ImGui.PushID(GetIdString(info, enreplacedyComponent));
EditorHelper.RangeAttribute rangeAttribute = null;
if (info.MemberInfo != null)
{
rangeAttribute = CustomAttributeExtensions.GetCustomAttribute<EditorHelper.RangeAttribute>(info.MemberInfo, true);
}
var infoType = info.FieldPropertyType;
if (infoType == typeof(string))
{
string val = (string)info.GetValue();
if (val == null)
{
val = string.Empty;
}
if (ImGui.InputText(info.Name, ref val, 1000))
{
info.SetValue(val);
}
}
else if (infoType == typeof(bool))
{
if (showMidi) SubmitMidireplacedignment(enreplacedyComponent, info, MidiState.MidiControlDescriptionType.Button);
bool val = (bool)info.GetValue();
if (ImGui.Checkbox(info.Name, ref val))
{
info.SetValue(val);
}
}
else if (infoType == typeof(float))
{
if (showMidi) SubmitMidireplacedignment(enreplacedyComponent, info, MidiState.MidiControlDescriptionType.Knob);
float val = (float)info.GetValue();
bool result;
if (rangeAttribute != null
&& (rangeAttribute.RangeType == EditorHelper.RangeAttribute.RangeTypeEnum.Float
|| rangeAttribute.RangeType == EditorHelper.RangeAttribute.RangeTypeEnum.Int))
{
if (rangeAttribute.RangeType == EditorHelper.RangeAttribute.RangeTypeEnum.Float)
{
result = ImGui.SliderFloat(info.Name, ref val, rangeAttribute.MinFloat, rangeAttribute.MaxFloat);
}
else
{
result = ImGui.SliderFloat(info.Name, ref val, rangeAttribute.MinInt, rangeAttribute.MaxInt);
}
}
else
{
result = ImGui.DragFloat(info.Name, ref val, 0.1f);
}
if (result)
{
info.SetValue(val);
}
}
else if (infoType == typeof(Vector2))
{
if (showMidi) SubmitMidireplacedignment(enreplacedyComponent, info, MidiState.MidiControlDescriptionType.Knob);
Vector2 val = (Vector2)info.GetValue();
if (ImGui.DragFloat2(info.Name, ref val))
{
info.SetValue(val);
}
}
else if (infoType == typeof(Vector3))
{
if (showMidi) SubmitMidireplacedignment(enreplacedyComponent, info, MidiState.MidiControlDescriptionType.Knob);
Vector3 val = (Vector3)info.GetValue();
if (ImGui.DragFloat3(info.Name, ref val))
{
info.SetValue(val);
}
}
else if (infoType == typeof(Vector4))
{
if (showMidi) SubmitMidireplacedignment(enreplacedyComponent, info, MidiState.MidiControlDescriptionType.Knob);
Vector4 val = (Vector4)info.GetValue();
if (ImGui.DragFloat4(info.Name, ref val))
{
info.SetValue(val);
}
}
else if (infoType == typeof(Xna.Vector2))
{
if (showMidi) SubmitMidireplacedignment(enreplacedyComponent, info, MidiState.MidiControlDescriptionType.Knob);
Xna.Vector2 xnaVal = (Xna.Vector2)info.GetValue();
Vector2 val = new Vector2(xnaVal.X, xnaVal.Y);
if (ImGui.DragFloat2(info.Name, ref val))
{
xnaVal.X = val.X;
xnaVal.Y = val.Y;
info.SetValue(xnaVal);
}
}
else if (infoType == typeof(Xna.Vector3))
{
if (showMidi) SubmitMidireplacedignment(enreplacedyComponent, info, MidiState.MidiControlDescriptionType.Knob);
Xna.Vector3 xnaVal = (Xna.Vector3)info.GetValue();
Vector3 val = new Vector3(xnaVal.X, xnaVal.Y, xnaVal.Z);
if (ImGui.DragFloat3(info.Name, ref val))
{
xnaVal.X = val.X;
xnaVal.Y = val.Y;
xnaVal.Z = val.Z;
info.SetValue(xnaVal);
}
}
else if (infoType == typeof(Xna.Vector4))
{
if (showMidi) SubmitMidireplacedignment(enreplacedyComponent, info, MidiState.MidiControlDescriptionType.Knob);
Xna.Vector4 xnaVal = (Xna.Vector4)info.GetValue();
Vector4 val = new Vector4(xnaVal.X, xnaVal.Y, xnaVal.Z, xnaVal.W);
if (ImGui.DragFloat4(info.Name, ref val))
{
xnaVal.X = val.X;
xnaVal.Y = val.Y;
xnaVal.Z = val.Z;
xnaVal.W = val.W;
info.SetValue(xnaVal);
}
}
else if (infoType == typeof(int))
{
if (showMidi) SubmitMidireplacedignment(enreplacedyComponent, info, MidiState.MidiControlDescriptionType.Knob);
int val = (int)info.GetValue();
bool result;
if (rangeAttribute != null && rangeAttribute.RangeType == EditorHelper.RangeAttribute.RangeTypeEnum.Int)
{
result = ImGui.SliderInt(info.Name, ref val, rangeAttribute.MinInt, rangeAttribute.MaxInt);
}
else
{
result = ImGui.InputInt(info.Name, ref val);
}
if (result)
{
info.SetValue(val);
}
}
else if (infoType == typeof(uint))
{
if (showMidi) SubmitMidireplacedignment(enreplacedyComponent, info, MidiState.MidiControlDescriptionType.Knob);
int val = (int)((uint)info.GetValue());
bool result;
if (rangeAttribute != null && rangeAttribute.RangeType == EditorHelper.RangeAttribute.RangeTypeEnum.Int)
{
result = ImGui.SliderInt(info.Name, ref val, rangeAttribute.MinInt, rangeAttribute.MaxInt);
}
else
{
result = ImGui.InputInt(info.Name, ref val);
}
if (result)
{
if (val < 0)
{
val = 0;
}
info.SetValue((uint)val);
}
}
else if (infoType.IsEnum)
{
if (showMidi) SubmitMidireplacedignment(enreplacedyComponent, info, MidiState.MidiControlDescriptionType.Button);
var val = info.GetValue();
var enumNames = infoType.GetEnumNames();
int currentIndex = 0;
for (int i = 0; i < enumNames.Length; i++)
{
if (enumNames[i] == val.ToString())
{
currentIndex = i;
}
}
if (ImGui.Combo(info.Name, ref currentIndex, enumNames, enumNames.Length))
{
info.SetValue(infoType.GetEnumValues().GetValue(currentIndex));
}
}
else if (typeof(IList).IsreplacedignableFrom(infoType))
{
var listthing = info.GetValue();
IList list = listthing as IList;
ImGui.Text($"{info.Name} List ({list.Count} items)");
ImGui.SameLine();
if (ImGui.Button("-"))
{
if (list.Count > 0)
{
list.RemoveAt(list.Count - 1);
}
}
ImGui.SameLine();
if (ImGui.Button("+"))
{
Type lisreplacedemType = list.GetType().GetGenericArguments().First();
if (lisreplacedemType.IsValueType)
{
list.Add(Activator.CreateInstance(lisreplacedemType));
}
else
{
list.Add(null);
}
}
ImGui.Indent();
for (int i = 0; i < list.Count; i++)
{
FieldPropertyListInfo itemInfo = new FieldPropertyListInfo(list, i);
SubmitFieldPropertyInspector(itemInfo, list);
}
ImGui.Unindent();
}
else if (!infoType.IsValueType)
{
string valText;
var value = info.GetValue();
if (value != null)
{
valText = value.ToString();
}
else
{
valText = "null";
}
string label = $"{info.Name}: {valText}";
if (typeof(Component).IsreplacedignableFrom(infoType) || typeof(Enreplacedy).IsreplacedignableFrom(infoType))
{
if (ImGui.Selectable(label, false))
{
SelectedEnreplacedyComponent = value;
scrollEnreplacediesView = true;
scrollSceneGraphView = true;
}
}
else
{
ImGui.Text(label);
}
if (draggedObject != null && infoType.IsreplacedignableFrom(draggedObject.GetType()))
{
if (ImGui.BeginDragDropTarget())
{
var payload = ImGui.AcceptDragDropPayload(PAYLOAD_STRING);
if (payload.NativePtr != null) // Only when this is non-null does it mean that we've released the drag
{
info.SetValue(draggedObject);
draggedObject = null;
}
ImGui.EndDragDropTarget();
}
}
}
else
{
SubmitReadonlyFieldPropertyInspector(info);
}
ImGui.PopID();
SubmitHelpMarker(info);
}
19
Source : DateTimeOffsetDataTypeHandler.cs
with MIT License
from aloneguid
with MIT License
from aloneguid
private static void ReadAsInt64(BinaryReader reader, IList result)
{
while (reader.BaseStream.Position + 8 <= reader.BaseStream.Length)
{
result.Add(ReadAsInt64(reader));
}
}
19
Source : DateTimeOffsetDataTypeHandler.cs
with MIT License
from aloneguid
with MIT License
from aloneguid
private static void ReadAsInt96(BinaryReader reader, IList result)
{
while (reader.BaseStream.Position + 12 <= reader.BaseStream.Length)
{
result.Add(ReadAsInt96(reader));
}
}
19
Source : DecimalDataTypeHandler.cs
with MIT License
from aloneguid
with MIT License
from aloneguid
private void ReadAsInt32(Thrift.SchemaElement tse, BinaryReader reader, IList result)
{
decimal scaleFactor = (decimal)Math.Pow(10, -tse.Scale);
while(reader.BaseStream.Position + 4 <= reader.BaseStream.Length)
{
int iv = reader.ReadInt32();
decimal dv = iv * scaleFactor;
result.Add(dv);
}
}
19
Source : DecimalDataTypeHandler.cs
with MIT License
from aloneguid
with MIT License
from aloneguid
private void ReadAsInt64(Thrift.SchemaElement tse, BinaryReader reader, IList result)
{
decimal scaleFactor = (decimal)Math.Pow(10, -tse.Scale);
while (reader.BaseStream.Position + 8 <= reader.BaseStream.Length)
{
long lv = reader.ReadInt64();
decimal dv = lv * scaleFactor;
result.Add(dv);
}
}
19
Source : DecimalDataTypeHandler.cs
with MIT License
from aloneguid
with MIT License
from aloneguid
private void ReadAsFixedLengthByteArray(Thrift.SchemaElement tse, BinaryReader reader, IList result)
{
int typeLength = tse.Type_length;
//can't read if there is no type length set
if (typeLength == 0) return;
while (reader.BaseStream.Position + typeLength <= reader.BaseStream.Length)
{
byte[] itemData = reader.ReadBytes(typeLength);
decimal dc = new BigDecimal(itemData, tse);
result.Add(dc);
}
}
19
Source : JsonSubTypes.cs
with BSD 3-Clause "New" or "Revised" License
from Altinn
with BSD 3-Clause "New" or "Revised" License
from Altinn
private IList ReadArray(JsonReader reader, Type targetType, JsonSerializer serializer)
{
var elementType = GetElementType(targetType);
var list = CreateCompatibleList(targetType, elementType);
while (reader.TokenType != JsonToken.EndArray && reader.Read())
{
switch (reader.TokenType)
{
case JsonToken.Null:
list.Add(reader.Value);
break;
case JsonToken.Comment:
break;
case JsonToken.StartObject:
list.Add(ReadObject(reader, elementType, serializer));
break;
case JsonToken.EndArray:
break;
default:
throw new Exception("Array: Unrecognized token: " + reader.TokenType);
}
}
if (targetType.IsArray)
{
var array = Array.CreateInstance(targetType.GetElementType(), list.Count);
list.CopyTo(array, 0);
list = array;
}
return list;
}
19
Source : JsonSubTypes.cs
with BSD 3-Clause "New" or "Revised" License
from Altinn
with BSD 3-Clause "New" or "Revised" License
from Altinn
private IList ReadArray(JsonReader reader, Type targetType, JsonSerializer serializer)
{
var elementType = GetElementType(targetType);
var list = CreateCompatibleList(targetType, elementType);
while (reader.TokenType != JsonToken.EndArray && reader.Read())
{
switch (reader.TokenType)
{
case JsonToken.Null:
list.Add(reader.Value);
break;
case JsonToken.Comment:
break;
case JsonToken.StartObject:
list.Add(ReadObject(reader, elementType, serializer));
break;
case JsonToken.EndArray:
break;
default:
throw new Exception("Array: Unrecognized token: " + reader.TokenType);
}
}
if (targetType.IsArray)
{
var array = Array.CreateInstance(targetType.GetElementType(), list.Count);
list.CopyTo(array, 0);
list = array;
}
return list;
}
19
Source : NetworkConnectionCollection.cs
with MIT License
from AmazingDM
with MIT License
from AmazingDM
public int Add(NetworkConnection conValue)
{
return List.Add(conValue);
}
19
Source : Utils.cs
with MIT License
from AmazingDM
with MIT License
from AmazingDM
private static IList PortIsUsed()
{
//获取本地计算机的网络连接和通信统计数据的信息
IPGlobalProperties ipGlobalProperties = IPGlobalProperties.GetIPGlobalProperties();
//返回本地计算机上的所有Tcp监听程序
IPEndPoint[] ipsTCP = ipGlobalProperties.GetActiveTcpListeners();
//返回本地计算机上的所有UDP监听程序
IPEndPoint[] ipsUDP = ipGlobalProperties.GetActiveUdpListeners();
//返回本地计算机上的Internet协议版本4(IPV4 传输控制协议(TCP)连接的信息。
TcpConnectionInformation[] tcpConnInfoArray = ipGlobalProperties.GetActiveTcpConnections();
IList allPorts = new ArrayList();
foreach (IPEndPoint ep in ipsTCP)
{
allPorts.Add(ep.Port);
}
foreach (IPEndPoint ep in ipsUDP)
{
allPorts.Add(ep.Port);
}
foreach (TcpConnectionInformation conn in tcpConnInfoArray)
{
allPorts.Add(conn.LocalEndPoint.Port);
}
return allPorts;
}
19
Source : ListMarshaler.cs
with GNU General Public License v3.0
from AndreiFedarets
with GNU General Public License v3.0
from AndreiFedarets
public object DemarshalObject(Stream stream)
{
int count = Int32Marshaler.Demarshal(stream);
IList list = (IList)Activator.CreateInstance(ManagedType);
for (int i = 0; i < count; i++)
{
object element = _elementMarshaler.DemarshalObject(stream);
list.Add(element);
}
return list;
}
19
Source : CsvInputFormatter.cs
with GNU General Public License v3.0
from andysal
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 : VerticalTabControl.cs
with MIT License
from AngeloCresta
with MIT License
from AngeloCresta
public VerticalTabPage Add(string text)
{
VerticalTabPage tabPage = new VerticalTabPage(text);
this.List.Add(tabPage);
return tabPage;
}
19
Source : VerticalTabControl.cs
with MIT License
from AngeloCresta
with MIT License
from AngeloCresta
public int Add(VerticalTabPage tabPage)
{
return this.List.Add(tabPage);
}
19
Source : AxisScaleSegments.cs
with MIT License
from AngeloCresta
with MIT License
from AngeloCresta
public int Add(AxisScaleSegment segment)
{
return this.List.Add(segment);
}
19
Source : JsonMapper.cs
with MIT License
from AnotherEnd15
with MIT License
from AnotherEnd15
private static object ReadValue(Type inst_type, JsonReader reader)
{
reader.Read();
if (reader.Token == JsonToken.ArrayEnd)
return null;
Type underlying_type = Nullable.GetUnderlyingType(inst_type);
Type value_type = underlying_type ?? inst_type;
if (reader.Token == JsonToken.Null)
{
#if NETSTANDARD1_5
if (inst_type.IsClreplaced() || underlying_type != null) {
return null;
}
#else
if (inst_type.IsClreplaced || underlying_type != null)
{
return null;
}
#endif
throw new JsonException(String.Format("Can't replacedign null to an instance of type {0}",
inst_type));
}
if (reader.Token == JsonToken.Double ||
reader.Token == JsonToken.Int ||
reader.Token == JsonToken.Long ||
reader.Token == JsonToken.String ||
reader.Token == JsonToken.Boolean)
{
Type json_type = reader.Value.GetType();
if (value_type.IsreplacedignableFrom(json_type))
return reader.Value;
// If there's a custom importer that fits, use it
if (custom_importers_table.ContainsKey(json_type) &&
custom_importers_table[json_type].ContainsKey(value_type))
{
ImporterFunc importer =
custom_importers_table[json_type][value_type];
return importer(reader.Value);
}
// Maybe there's a base importer that works
if (base_importers_table.ContainsKey(json_type) &&
base_importers_table[json_type].ContainsKey(value_type))
{
ImporterFunc importer =
base_importers_table[json_type][value_type];
return importer(reader.Value);
}
// Maybe it's an enum
#if NETSTANDARD1_5
if (value_type.IsEnum())
return Enum.ToObject (value_type, reader.Value);
#else
if (value_type.IsEnum)
return Enum.ToObject(value_type, reader.Value);
#endif
// Try using an implicit conversion operator
MethodInfo conv_op = GetConvOp(value_type, json_type);
if (conv_op != null)
return conv_op.Invoke(null,
new object[] { reader.Value });
// No luck
throw new JsonException(String.Format("Can't replacedign value '{0}' (type {1}) to type {2}",
reader.Value, json_type, inst_type));
}
object instance = null;
if (reader.Token == JsonToken.ArrayStart)
{
AddArrayMetadata(inst_type);
ArrayMetadata t_data = array_metadata[inst_type];
if (!t_data.IsArray && !t_data.IsList)
throw new JsonException(String.Format("Type {0} can't act as an array",
inst_type));
IList list;
Type elem_type;
if (!t_data.IsArray)
{
list = (IList) Activator.CreateInstance(inst_type);
elem_type = t_data.ElementType;
}
else
{
list = new ArrayList();
elem_type = inst_type.GetElementType();
}
while (true)
{
object item = ReadValue(elem_type, reader);
if (item == null && reader.Token == JsonToken.ArrayEnd)
break;
list.Add(item);
}
if (t_data.IsArray)
{
int n = list.Count;
instance = Array.CreateInstance(elem_type, n);
for (int i = 0; i < n; i++)
((Array) instance).SetValue(list[i], i);
}
else
instance = list;
}
else if (reader.Token == JsonToken.ObjectStart)
{
AddObjectMetadata(value_type);
ObjectMetadata t_data = object_metadata[value_type];
instance = Activator.CreateInstance(value_type);
while (true)
{
reader.Read();
if (reader.Token == JsonToken.ObjectEnd)
break;
string property = (string) reader.Value;
if (t_data.Properties.ContainsKey(property))
{
PropertyMetadata prop_data =
t_data.Properties[property];
if (prop_data.IsField)
{
((FieldInfo) prop_data.Info).SetValue(instance, ReadValue(prop_data.Type, reader));
}
else
{
PropertyInfo p_info =
(PropertyInfo) prop_data.Info;
if (p_info.CanWrite)
p_info.SetValue(instance,
ReadValue(prop_data.Type, reader),
null);
else
ReadValue(prop_data.Type, reader);
}
}
else
{
if (!t_data.IsDictionary)
{
if (!reader.SkipNonMembers)
{
throw new JsonException(String.Format("The type {0} doesn't have the " +
"property '{1}'",
inst_type, property));
}
ReadSkip(reader);
continue;
}
var dicTypes = instance.GetType().GetGenericArguments();
var converter = System.ComponentModel.TypeDescriptor.GetConverter(dicTypes[0]);
object key = property;
if (converter != null)
{
key = converter.ConvertFromString(property);
t_data.ElementType = dicTypes[1];
}
((IDictionary) instance).Add(key, ReadValue(t_data.ElementType, reader));
}
}
}
return instance;
}
See More Examples