System.Collections.Generic.List.Add(object)

Here are the examples of the csharp api System.Collections.Generic.List.Add(object) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

3557 Examples 7

19 Source : VssHost.cs
with MIT License
from alexis-

public void WriteTable(LogEventLevel level, StringTable table, int columnSpacing = 3, bool addVerticalSeparation = false)
    {
      if (table == null)
        throw new ArgumentNullException("table", "table is null.");

      StringBuilder builder = new StringBuilder();
      List<object> formatParams = new List<object>();

      for (int i = 0; i < table.Count; i++)
      {
        builder.AppendLine(String.Format("{{{0}}}{{{1}}}{{{2}}}{{{3}}}", 4 * i, 4 * i + 1, 4 * i + 2, 4 * i + 3));
        formatParams.Add(new String(' ', m_indent));
        formatParams.Add(table.Labels[i]);
        formatParams.Add(new String(' ', columnSpacing));
        formatParams.Add(table.Values[i]);
      }

      WriteForLevel(level, builder.ToString(), formatParams.ToArray());
    }

19 Source : VssHost.cs
with MIT License
from alexis-

public void WriteTable(LogEventLevel level, StringTable table, int columnSpacing = 3, bool addVerticalSeparation = false)
    {
      if (table == null)
        throw new ArgumentNullException("table", "table is null.");

      StringBuilder builder = new StringBuilder();
      List<object> formatParams = new List<object>();

      for (int i = 0; i < table.Count; i++)
      {
        builder.AppendLine(String.Format("{{{0}}}{{{1}}}{{{2}}}{{{3}}}", 4 * i, 4 * i + 1, 4 * i + 2, 4 * i + 3));
        formatParams.Add(new String(' ', m_indent));
        formatParams.Add(table.Labels[i]);
        formatParams.Add(new String(' ', columnSpacing));
        formatParams.Add(table.Values[i]);
      }

      WriteForLevel(level, builder.ToString(), formatParams.ToArray());
    }

19 Source : BotFactory.cs
with Apache License 2.0
from AlexWan

private static BotPanel Serialize(string path, string nameClreplaced, string name, StartProgram startProgram)
        {
            try
            {
                if (linksToDll == null)
                {
                    var replacedemblies = AppDomain.CurrentDomain.Getreplacedemblies();

                    string[] res = Array.ConvertAll<replacedembly, string>(replacedemblies, (x) =>
                    {
                        if (!x.IsDynamic)
                        {
                            return x.Location;
                        }

                        return null;
                    });

                    for (int i = 0; i < res.Length; i++)
                    {
                        if (string.IsNullOrEmpty(res[i]))
                        {
                            List<string> list = res.ToList();
                            list.RemoveAt(i);
                            res = list.ToArray();
                            i--;
                        }
                        else if (res[i].Contains("System.Runtime.Serialization")
                                 || i > 24)
                        {
                            List<string> list = res.ToList();
                            list.RemoveAt(i);
                            res = list.ToArray();
                            i--;
                        }
                    }

                    string dllPath = AppDomain.CurrentDomain.BaseDirectory + "System.Runtime.Serialization.dll";

                    List<string> listRes = res.ToList();
                    listRes.Add(dllPath);
                    res = listRes.ToArray();
                    linksToDll = res;
                }

                List<string> dllsToCompiler = linksToDll.ToList();

                List<string> dllsFromPath = GetDllsPathFromFolder(path);

                if (dllsFromPath != null && dllsFromPath.Count != 0)
                {
                    for (int i = 0; i < dllsFromPath.Count; i++)
                    {
                        string dll = dllsFromPath[i].Split('\\')[dllsFromPath[i].Split('\\').Length - 1];

                        if (dllsToCompiler.Find(d => d.Contains(dll)) == null)
                        {
                            dllsToCompiler.Add(dllsFromPath[i]);
                        }
                    }
                }

                CompilerParameters cp = new CompilerParameters(dllsToCompiler.ToArray());

                // Помечаем сборку, как временную
                cp.GenerateInMemory = true;
                cp.IncludeDebugInformation = true;
                cp.TempFiles.KeepFiles = false;


                string folderCur = AppDomain.CurrentDomain.BaseDirectory + "Engine\\Temp";

                if (Directory.Exists(folderCur) == false)
                {
                    Directory.CreateDirectory(folderCur);
                }

                folderCur += "\\Bots";

                if (Directory.Exists(folderCur) == false)
                {
                    Directory.CreateDirectory(folderCur);
                }

                if (_isFirstTime)
                {
                    _isFirstTime = false;

                    string[] files = Directory.GetFiles(folderCur);

                    for (int i = 0; i < files.Length; i++)
                    {
                        try
                        {
                            File.Delete(files[i]);
                        }
                        catch
                        {
                            // ignore
                        }
                    }
                }

                cp.TempFiles = new TempFileCollection(folderCur, false);

                BotPanel result = null;

                string fileStr = ReadFile(path);

                //Объявляем провайдер кода С#
                CSharpCodeProvider prov = new CSharpCodeProvider();

                // Обрабатываем CSC компилятором
                CompilerResults results = prov.CompilereplacedemblyFromSource(cp, fileStr);

                if (results.Errors != null && results.Errors.Count != 0)
                {
                    string errorString = "Error! Robot script runTime compilation problem! \n";
                    errorString += "Path to Robot: " + path + " \n";

                    int errorNum = 1;

                    foreach (var error in results.Errors)
                    {
                        errorString += "Error Number: " + errorNum + " \n";
                        errorString += error.ToString() + "\n";
                        errorNum++;
                    }

                    throw new Exception(errorString);
                }
                //string name, StartProgram startProgram)

                List<object> param = new List<object>();
                param.Add(name);
                param.Add(startProgram);

                result = (BotPanel)results.Compiledreplacedembly.CreateInstance(
                    results.Compiledreplacedembly.DefinedTypes.ElementAt(0).FullName, false, BindingFlags.CreateInstance, null,
                    param.ToArray(), CultureInfo.CurrentCulture, null);

                if (result == null)
                {
                    string errorString = "Error! Robot script runTime compilation problem! \n";
                    errorString += "Path to robot: " + path + " \n";

                    int errorNum = 1;

                    foreach (var error in results.Errors)
                    {
                        errorString += "Error Number: " + errorNum + " \n";
                        errorString += error.ToString() + "\n";
                        errorNum++;
                    }

                    throw new Exception(errorString);
                }

                return result;
            }
            catch (Exception e)
            {
                string errorString = e.ToString();
                throw new Exception(errorString);
            }
        }

19 Source : BotFactory.cs
with Apache License 2.0
from AlexWan

private static BotPanel Serialize(string path, string nameClreplaced, string name, StartProgram startProgram)
        {
            try
            {
                if (linksToDll == null)
                {
                    var replacedemblies = AppDomain.CurrentDomain.Getreplacedemblies();

                    string[] res = Array.ConvertAll<replacedembly, string>(replacedemblies, (x) =>
                    {
                        if (!x.IsDynamic)
                        {
                            return x.Location;
                        }

                        return null;
                    });

                    for (int i = 0; i < res.Length; i++)
                    {
                        if (string.IsNullOrEmpty(res[i]))
                        {
                            List<string> list = res.ToList();
                            list.RemoveAt(i);
                            res = list.ToArray();
                            i--;
                        }
                        else if (res[i].Contains("System.Runtime.Serialization")
                                 || i > 24)
                        {
                            List<string> list = res.ToList();
                            list.RemoveAt(i);
                            res = list.ToArray();
                            i--;
                        }
                    }

                    string dllPath = AppDomain.CurrentDomain.BaseDirectory + "System.Runtime.Serialization.dll";

                    List<string> listRes = res.ToList();
                    listRes.Add(dllPath);
                    res = listRes.ToArray();
                    linksToDll = res;
                }

                List<string> dllsToCompiler = linksToDll.ToList();

                List<string> dllsFromPath = GetDllsPathFromFolder(path);

                if (dllsFromPath != null && dllsFromPath.Count != 0)
                {
                    for (int i = 0; i < dllsFromPath.Count; i++)
                    {
                        string dll = dllsFromPath[i].Split('\\')[dllsFromPath[i].Split('\\').Length - 1];

                        if (dllsToCompiler.Find(d => d.Contains(dll)) == null)
                        {
                            dllsToCompiler.Add(dllsFromPath[i]);
                        }
                    }
                }

                CompilerParameters cp = new CompilerParameters(dllsToCompiler.ToArray());

                // Помечаем сборку, как временную
                cp.GenerateInMemory = true;
                cp.IncludeDebugInformation = true;
                cp.TempFiles.KeepFiles = false;


                string folderCur = AppDomain.CurrentDomain.BaseDirectory + "Engine\\Temp";

                if (Directory.Exists(folderCur) == false)
                {
                    Directory.CreateDirectory(folderCur);
                }

                folderCur += "\\Bots";

                if (Directory.Exists(folderCur) == false)
                {
                    Directory.CreateDirectory(folderCur);
                }

                if (_isFirstTime)
                {
                    _isFirstTime = false;

                    string[] files = Directory.GetFiles(folderCur);

                    for (int i = 0; i < files.Length; i++)
                    {
                        try
                        {
                            File.Delete(files[i]);
                        }
                        catch
                        {
                            // ignore
                        }
                    }
                }

                cp.TempFiles = new TempFileCollection(folderCur, false);

                BotPanel result = null;

                string fileStr = ReadFile(path);

                //Объявляем провайдер кода С#
                CSharpCodeProvider prov = new CSharpCodeProvider();

                // Обрабатываем CSC компилятором
                CompilerResults results = prov.CompilereplacedemblyFromSource(cp, fileStr);

                if (results.Errors != null && results.Errors.Count != 0)
                {
                    string errorString = "Error! Robot script runTime compilation problem! \n";
                    errorString += "Path to Robot: " + path + " \n";

                    int errorNum = 1;

                    foreach (var error in results.Errors)
                    {
                        errorString += "Error Number: " + errorNum + " \n";
                        errorString += error.ToString() + "\n";
                        errorNum++;
                    }

                    throw new Exception(errorString);
                }
                //string name, StartProgram startProgram)

                List<object> param = new List<object>();
                param.Add(name);
                param.Add(startProgram);

                result = (BotPanel)results.Compiledreplacedembly.CreateInstance(
                    results.Compiledreplacedembly.DefinedTypes.ElementAt(0).FullName, false, BindingFlags.CreateInstance, null,
                    param.ToArray(), CultureInfo.CurrentCulture, null);

                if (result == null)
                {
                    string errorString = "Error! Robot script runTime compilation problem! \n";
                    errorString += "Path to robot: " + path + " \n";

                    int errorNum = 1;

                    foreach (var error in results.Errors)
                    {
                        errorString += "Error Number: " + errorNum + " \n";
                        errorString += error.ToString() + "\n";
                        errorNum++;
                    }

                    throw new Exception(errorString);
                }

                return result;
            }
            catch (Exception e)
            {
                string errorString = e.ToString();
                throw new Exception(errorString);
            }
        }

19 Source : GarbageHolder.cs
with Apache License 2.0
from alexyakunin

[MethodImpl(MethodImplOptions.AggressiveInlining)]
        public void AddGarbage(object garbage, sbyte bucketIndex, sbyte generationIndex)
        {
            if (bucketIndex == 0 && generationIndex == 0)
                // Zero hold time = don't hold it
                return;
            _buckets[bucketIndex][generationIndex].Add(garbage);
        }

19 Source : SetAllocator.cs
with Apache License 2.0
from alexyakunin

public void Run()
        {
            var maxSetSize = MaxSetSize;
            var allocations = Allocations;
            var index = StartIndex;

            var result = new List<object[]>();
            var currentSet = new List<object>();
            for (var currentSize = 0L; currentSize < maxSetSize;) {
                var (arraySize, _, _) = allocations[index];
                currentSet.Add(GarbageAllocator.CreateGarbage(arraySize));
                currentSize += GarbageAllocator.ArraySizeToByteSize(arraySize);
                index = (index + 1) % BurnTester.AllocationSequenceLength;
                if (currentSet.Count > 1000_000_000) {
                    // Workaround for .NET array size restriction
                    result.Add(currentSet.ToArray());
                    currentSet = new List<object>();
                }
            };
            result.Add(currentSet.ToArray());
            Set = result.ToArray();
        }

19 Source : HateoasResultProvider.cs
with Apache License 2.0
from alexz76

public async Task<IActionResult> GetContentResultAsync(ObjectResult result)
		{
			var policies = GetFilteredPolicies(result);
			if (!policies.Any())
			{
				return null;
			}

			var content = default(JsonResult);

			async Task<IList<object>> GetLinksAsync(object item)
			{
				var links = new List<object>();

				foreach (var policy in policies.Where(p => p != null))
				{
					var lambdaResult = GetLambdaResult(policy.Expression, item);
					var link = await GetPolicyLinkAsync(policy, lambdaResult).ConfigureAwait(false);
					links.Add(link);
				}

				return links;
			}

			async Task<object> GetFinalJsonPayloadAsync(object item)
			{
				var links = await GetLinksAsync(item).ConfigureAwait(false);

				return await Task.FromResult(item.ToFinalPayload(links)).ConfigureAwait(false);
			}

			if (result.Value is IEnumerable<object> collection)
			{
				var links = await Task.WhenAll(collection.Select(item => GetFinalJsonPayloadAsync(item))).ConfigureAwait(false);
				var json = new List<object>(links);

				content = new JsonResult(json);
			}
			else
			{
				var links = await GetFinalJsonPayloadAsync(result.Value).ConfigureAwait(false);
				content = new JsonResult(links);
			}

			return await Task.FromResult(content).ConfigureAwait(false);
		}

19 Source : ParserExtensions.cs
with MIT License
from alfa-laboratory

public static IEnumerable<object> ToEnumerable(this Table table, VariableController variableController) {
            var enumerable = new List<object>();
            table.Rows.ToList().Count.Should().Be(0, "Table must have only 1 row: Values");
            foreach (var value in table.Header.ToList()) 
            {
                enumerable.Add(variableController.ReplaceVariables(value) ?? value);
            }
            return enumerable;
        }

19 Source : Style.cs
with MIT License
from AliFlux

private object interpolateValues(object startValue, object endValue, double zoomA, double zoomB, double zoom, double power, bool clamp = false)
        {
            if (startValue is string)
            {
                // TODO implement color mappings
                //var minValue = parseColor(startValue.Value<string>());
                //var maxValue = parseColor(endValue.Value<string>());


                //var newR = convertRange(zoom, zoomA, zoomB, minValue.ScR, maxValue.ScR, power, false);
                //var newG = convertRange(zoom, zoomA, zoomB, minValue.ScG, maxValue.ScG, power, false);
                //var newB = convertRange(zoom, zoomA, zoomB, minValue.ScB, maxValue.ScB, power, false);
                //var newA = convertRange(zoom, zoomA, zoomB, minValue.ScA, maxValue.ScA, power, false);

                //return Color.FromScRgb((float)newA, (float)newR, (float)newG, (float)newB);

                var minValue = startValue as string;
                var maxValue = endValue as string;

                if (Math.Abs(zoomA - zoom) <= Math.Abs(zoomB - zoom))
                {
                    return minValue;
                }
                else
                {
                    return maxValue;
                }

            }
            else if (startValue.GetType().IsArray)
            {
                List<object> result = new List<object>();
                var startArray = startValue as object[];
                var endArray = endValue as object[];

                for (int i = 0; i < startArray.Count(); i++)
                {
                    var minValue = startArray[i];
                    var maxValue = endArray[i];

                    var value = interpolateValues(minValue, maxValue, zoomA, zoomB, zoom, power, clamp);

                    result.Add(value);
                }

                return result.ToArray();
            }
            else if (isNumber(startValue))
            {
                var minValue = Convert.ToDouble(startValue);
                var maxValue = Convert.ToDouble(endValue);

                return interpolateRange(zoom, zoomA, zoomB, minValue, maxValue, power, clamp);
            }
            else
            {
                throw new NotImplementedException("Unimplemented interpolation");
            }
        }

19 Source : AopModelParser.cs
with Apache License 2.0
from alipay

public Object serializeArrayValue(ICollection collection)
        {
            if (collection == null)
            {
                return null;
            }

            List<object> ja = new List<object>();
            foreach (var item in collection)
            {
                ja.Add(serializeValue(item));
            }
            return ja;
        }

19 Source : SolanaRpcClient.cs
with MIT License
from allartprotocol

private async Task<RequestResult<T>> SendRequestAsync<T>(
            string method, IList<object> parameters, Dictionary<string, object> configurationObject
            )
        {
            var newList = parameters.ToList();

            if (configurationObject == null)
            {
                configurationObject = new Dictionary<string, object>
                {
                    {"encoding", "jsonParsed"}
                };
            }

            foreach (var key in configurationObject.Keys)
            {
                var ok = configurationObject.TryGetValue(key, out var value);
                if (!ok) continue;

                newList.Add(new Dictionary<string, object>
                {
                    { key, value}
                });
            }

            var req = BuildRequest<T>(method, newList);
            return await SendRequest<T>(req);
        }

19 Source : DataColumnAppender.cs
with MIT License
from aloneguid

public void Add(object value, LevelIndex[] indexes)
      {
         if (_isRepeated)
         {
            int rl = GetRepereplacedionLevel(indexes, _lastIndexes);

            if(!(value is string) && value is IEnumerable valueItems)
            {
               int count = 0;
               foreach (object valueItem in (IEnumerable)value)
               {
                  _values.Add(valueItem);
                  _rls.Add(rl);
                  rl = _dataField.MaxRepereplacedionLevel;
                  count += 1;
               }

               if(count == 0)
               {
                  //handle empty collections
                  _values.Add(null);
                  _rls.Add(0);
               }
            }
            else
            {
               _values.Add(value);
               _rls.Add(rl);
            }

            _lastIndexes = indexes;
         }
         else
         {
            //non-repeated fields can only appear on the first level and have no repereplacedion levels (obviously)
            _values.Add(value);
         }

      }

19 Source : DataColumnsToRowsConverter.cs
with MIT License
from aloneguid

private bool TryBuildNextRow(IReadOnlyCollection<Field> fields, Dictionary<string, LazyColumnEnumerator> pathToColumn, out Row row)
      {
         var rowList = new List<object>();
         foreach(Field f in fields)
         {
            if(!TryBuildNextCell(f, pathToColumn, out object cell))
            {
               row = null;
               return false;
            }

            rowList.Add(cell);
         }

         row = new Row(fields, rowList);
         return true;
      }

19 Source : TreeList.cs
with MIT License
from aloneguid

public void Add(object value)
      {
         if(_values == null)
         {
            _values = new List<object>();
         }
         _values.Add(value);
      }

19 Source : Pkcs8.cs
with Apache License 2.0
from aloneguid

private object[] ReadSequence()
            {
               int num = this._index + this.ReadLength();
               if(num < 0 || num > this._bytes.Length)
                  throw new InvalidDataException("Invalid sequence, too long.");
               List<object> objectList = new List<object>();
               while(this._index < num)
                  objectList.Add(this.Decode());
               return objectList.ToArray();
            }

19 Source : CacheService.cs
with MIT License
from alonsoalon

public IResponseEnreplacedy GetCacheKeyTemplates()
        {
            var list = new List<object>();
            var cacheKey = typeof(CacheKeyTemplate);
            var fields = cacheKey.GetFields(BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy);
            foreach (var field in fields)
            {
                var descriptionAttribute = field.GetCustomAttributes(typeof(DescriptionAttribute), false).FirstOrDefault() as DescriptionAttribute;

                list.Add(new
                {
                    field.Name,
                    Value = field.GetRawConstantValue().ToString(),
                    descriptionAttribute?.Description
                });
            }

            return ResponseEnreplacedy.Ok(list);
        }

19 Source : SerializationState.cs
with MIT License
from Alprog

public void RegNewObjectReference(object instance)
            {
                ObjectReferences[instance] = ObjectInstances.Count;
                ObjectInstances.Add(instance);
            }

19 Source : RequestTracker.cs
with BSD 3-Clause "New" or "Revised" License
from Altinn

public static void AddRequest(string requestKey, object request)
        {
            lock (DataLock)
            {
                if (!_tracker.ContainsKey(requestKey))
                {
                    _tracker.Add(requestKey, new List<object>());
                }

                _tracker[requestKey].Add(request);
            }
        }

19 Source : SelectionNode.cs
with MIT License
from amwx

private (bool, List<object>) OnItemsRemoved(int index, IList items)
        {
            var selectionInvalidated = false;
            var removed = new List<object>();
            var count = items.Count;
            var isSelected = false;

            for (int i = 0; i <= count - 1; i++)
            {
                if (IsSelected(index + i))
                {
                    isSelected = true;
                    removed.Add(items[i]);
                }
            }

            if (isSelected)
            {
                var removeRange = new IndexRange(index, index + count - 1);
                SelectedCount -= IndexRange.Remove(_selected, removeRange);
                selectionInvalidated = true;

                if (_selectedItems != null)
                {
                    foreach (var i in items)
                    {
                        _selectedItems.Remove(i);
                    }
                }
            }

            for (int i = 0; i < _selected.Count; i++)
            {
                var range = _selected[i];

                // The range is after the removed items, need to shift the range left
                if (range.End > index)
                {
                    // Shift the range to the left
                    _selected[i] = new IndexRange(range.Begin - count, range.End - count);
                    selectionInvalidated = true;
                }
            }

            // Update for non-leaf if we are tracking non-leaf nodes
            if (_childrenNodes.Count > 0)
            {
                selectionInvalidated = true;
                for (int i = 0; i < count; i++)
                {
                    if (_childrenNodes[index] != null)
                    {
                        removed.AddRange(_childrenNodes[index]!.SelectedItems);
                        RealizedChildrenNodeCount--;
                        _childrenNodes[index]!.Dispose();
                    }
                    _childrenNodes.RemoveAt(index);
                }
            }

            //Adjust the anchor
            if (AnchorIndex >= index)
            {
                AnchorIndex -= count;
            }

            return (selectionInvalidated, removed);
        }

19 Source : SelectionNode.cs
with MIT License
from amwx

private List<object> RecreateSelectionFromSelectedItems()
        {
            var removed = new List<object>();

            _selected.Clear();
            SelectedCount = 0;

            for (var i = 0; i < _selectedItems!.Count; ++i)
            {
                var item = _selectedItems[i];
                var index = ItemsSourceView!.IndexOf(item);

                if (index != -1)
                {
                    IndexRange.Add(_selected, new IndexRange(index, index));
                    ++SelectedCount;
                }
                else
                {
                    removed.Add(item);
                    _selectedItems.RemoveAt(i--);
                }
            }

            return removed;
        }

19 Source : SelectionNode.cs
with MIT License
from amwx

private void PopulateSelectedItemsFromSelectedIndices()
        {
            if (_selectedItems != null)
            {
                _selectedItems.Clear();

                foreach (var i in SelectedIndices)
                {
                    _selectedItems.Add(ItemsSourceView!.GetAt(i));
                }
            }
        }

19 Source : SelectionNode.cs
with MIT License
from amwx

private void AddRange(IndexRange addRange, bool raiseOnSelectionChanged)
        {
            var selected = new List<IndexRange>();

            SelectedCount += IndexRange.Add(_selected, addRange, selected);

            if (selected.Count > 0)
            {
                _operation?.Selected(selected);

                if (_selectedItems != null && ItemsSourceView != null)
                {
                    for (var i = addRange.Begin; i <= addRange.End; ++i)
                    {
                        _selectedItems.Add(ItemsSourceView!.GetAt(i));
                    }
                }

                if (raiseOnSelectionChanged)
                {
                    OnSelectionChanged();
                }
            }
        }

19 Source : RoomCreationServerHubsListViewController.cs
with MIT License
from andruzzzhka

public void SetServerHubs(List<ServerHubClient> hubs)
        {
            hubInfosList.Clear();

            if (hubs != null)
            {
                var availableHubs = hubs.OrderByDescending(x => x.serverHubCompatible ? 2 : (x.serverHubAvailable ? 1 : 0)).ThenBy(x => x.ping).ThenBy(x => x.availableRoomsCount).ToList();

                foreach (ServerHubClient room in availableHubs)
                {
                    hubInfosList.Add(new ServerHubListObject(room));
                }
            }

            hubsList.tableView.ReloadData();
        }

19 Source : Settings.cs
with MIT License
from andruzzzhka

void ListAllAvatars()
        {
            ModelSaberAPI.hashesCalculated -= ListAllAvatars;
            publicAvatars.Clear();
            foreach (var avatar in ModelSaberAPI.cachedAvatars)
            {
                publicAvatars.Add(avatar.Value);
            }

            if (publicAvatarSetting)
            {
                publicAvatarSetting.tableView.ReloadData();
                publicAvatarSetting.ReceiveValue();
            }
        }

19 Source : Settings.cs
with MIT License
from andruzzzhka

public void UpdateMicrophoneList(bool deviceWasChanged)
        {
            micSelectOptions.Clear();
            micSelectOptions.Add("DEFAULT MIC");
            foreach (var mic in Microphone.devices)
            {
                micSelectOptions.Add(mic);
            }

            if (micSelectSetting)
            {
                micSelectSetting.tableView.ReloadData();
                micSelectSetting.ReceiveValue();
            }

            voiceChatMicrophoneChanged?.Invoke(Config.Instance.VoiceChatMicrophone);
        }

19 Source : PresetsListViewController.cs
with MIT License
from andruzzzhka

public void SetPresets(List<RoomPreset> presets)
        {
            presetsListContents.Clear();

            if (presets != null)
            {
                foreach (RoomPreset preset in presets)
                {
                    presetsListContents.Add(new PresetListObject(preset));
                }
            }

            if(presetsList != null)
                presetsList.tableView.ReloadData();
        }

19 Source : PlayerManagementViewController.cs
with MIT License
from andruzzzhka

public void UpdatePlayerList(RoomState state)
        {
            
            var playersDict = InGameOnlineController.Instance.players;
                
            if (playersDict.Count != players.Count)
            {
                while(playersDict.Count > players.Count)
                {
                    players.Add(new PlayerListObject(null, this));
                }
                if (playersDict.Count < players.Count)
                    players.RemoveRange(playersDict.Count, players.Count - playersDict.Count);

                playersList.tableView.ReloadData();
            }

            int index = 0;
            foreach(var playerPair in playersDict)
            {
                (players[index] as PlayerListObject).Update(playerPair.Value.playerInfo, state);
                index++;
            }            
        }

19 Source : RoomListViewController.cs
with MIT License
from andruzzzhka

public void SetRooms(List<ServerHubRoom> rooms)
        {
            roomInfosList.Clear();

            if (rooms != null)
            {
                var availableRooms = rooms.OrderByDescending(y => y.roomInfo.players);

                foreach (ServerHubRoom room in availableRooms)
                {
                    roomInfosList.Add(new RoomListObject(room));
                }
            }

            if(rooms == null || rooms.Count == 0)
                _noRoomsText.enabled = true;
            else
                _noRoomsText.enabled = false;

            roomsList.tableView.ReloadData();

        }

19 Source : DynamicParameters.cs
with MIT License
from anet-team

public void AddDynamicParams(object param)
        {
            var obj = param;
            if (obj != null)
            {
                var subDynamic = obj as DynamicParameters;
                if (subDynamic == null)
                {
                    var dictionary = obj as IEnumerable<KeyValuePair<string, object>>;
                    if (dictionary == null)
                    {
                        templates = templates ?? new List<object>();
                        templates.Add(obj);
                    }
                    else
                    {
                        foreach (var kvp in dictionary)
                        {
                            Add(kvp.Key, kvp.Value, null, null, null);
                        }
                    }
                }
                else
                {
                    if (subDynamic.parameters != null)
                    {
                        foreach (var kvp in subDynamic.parameters)
                        {
                            parameters.Add(kvp.Key, kvp.Value);
                        }
                    }

                    if (subDynamic.templates != null)
                    {
                        templates = templates ?? new List<object>();
                        foreach (var t in subDynamic.templates)
                        {
                            templates.Add(t);
                        }
                    }
                }
            }
        }

19 Source : Picker.cs
with MIT License
from angelobelchior

private IEnumerable<object> CastObjectToList()
        {
            if (this.ItemsSource is Enum)
            {
                var items = new List<object>();
                foreach (var item in Enum.GetValues(this.ItemsSource.GetType()))
                    items.Add(item);

                return items;
            }
            else if (this.ItemsSource is IEnumerable)
                return ItemsSource as IEnumerable<object>;

            return null;
        }

19 Source : ObjectQueryExecutor.cs
with MIT License
from angshuman

private ObjectQueryResponse ApplyAggregates(IEnumerable<Triple> rsp, AggregateQuery[] aggregates)
        {
            var responses = new List<object>();
            foreach (var aggregate in aggregates) {
                switch (aggregate.Type) {
                    case AggregateType.Count:
                        var count = rsp.Count();
                        responses.Add(count);
                        break;
                    default:
                        throw new InvalidOperationException("unknown aggregate");
                }
            }
            return new ObjectQueryResponse {
                Aggregates = new object[]
                {
                    responses
                }
            };
        }

19 Source : EventSystem.cs
with MIT License
from AnotherEnd15

public void Add(replacedembly replacedembly)
		{
			this.replacedemblies[replacedembly.ManifestModule.ScopeName] = replacedembly;
			this.types.Clear();
			foreach (replacedembly value in this.replacedemblies.Values)
			{
				foreach (Type type in value.GetTypes())
				{
					if (type.IsAbstract)
					{
						continue;
					}

					object[] objects = type.GetCustomAttributes(typeof(BaseAttribute), true);
					if (objects.Length == 0)
					{
						continue;
					}

					foreach (BaseAttribute baseAttribute in objects)
					{
						this.types.Add(baseAttribute.AttributeType, type);
					}
				}
			}

			this.awakeSystems.Clear();
			this.lateUpdateSystems.Clear();
			this.updateSystems.Clear();
			this.startSystems.Clear();
			this.loadSystems.Clear();
			this.changeSystems.Clear();
			this.destroySystems.Clear();
			this.deserializeSystems.Clear();
			
			foreach (Type type in this.GetTypes(typeof(ObjectSystemAttribute)))
			{
				object obj = Activator.CreateInstance(type);
				switch (obj)
				{
					case IAwakeSystem objectSystem:
						this.awakeSystems.Add(objectSystem.Type(), objectSystem);
						break;
					case IUpdateSystem updateSystem:
						this.updateSystems.Add(updateSystem.Type(), updateSystem);
						break;
					case ILateUpdateSystem lateUpdateSystem:
						this.lateUpdateSystems.Add(lateUpdateSystem.Type(), lateUpdateSystem);
						break;
					case IStartSystem startSystem:
						this.startSystems.Add(startSystem.Type(), startSystem);
						break;
					case IDestroySystem destroySystem:
						this.destroySystems.Add(destroySystem.Type(), destroySystem);
						break;
					case ILoadSystem loadSystem:
						this.loadSystems.Add(loadSystem.Type(), loadSystem);
						break;
					case IChangeSystem changeSystem:
						this.changeSystems.Add(changeSystem.Type(), changeSystem);
						break;
					case IDeserializeSystem deserializeSystem:
						this.deserializeSystems.Add(deserializeSystem.Type(), deserializeSystem);
						break;
				}
			}

			this.allEvents.Clear();
			foreach (Type type in types[typeof(EventAttribute)])
			{
				IEvent obj = Activator.CreateInstance(type) as IEvent;
				if (obj == null)
				{
					throw new Exception($"type not is AEvent: {obj.GetType().Name}");
				}

				Type eventType = obj.GetEventType();
				if (!this.allEvents.ContainsKey(eventType))
				{
					this.allEvents.Add(eventType, new List<object>());
				}
				this.allEvents[eventType].Add(obj);
			}
			
			this.Load();
		}

19 Source : EntityExtensions.cs
with MIT License
from ansel86castro

private static object ToDataList(ICollection list, HashSet<object> visited)
        {
            var encodedList = new List<object>(list.Count);
            foreach (var item in list)
            {               
                encodedList.Add(ToData(item, visited));
            }
            return encodedList;
        }

19 Source : EntityExtensions.cs
with MIT License
from ansel86castro

private static object ToDataList(IEnumerable list, HashSet<object> visited)
        {
            var encodedList = new List<object>();
            foreach (var item in list)
            {
                encodedList.Add(ToData(item, visited));
            }
            encodedList.TrimExcess();
            return encodedList;
        }

19 Source : Editor.razor.cs
with Apache License 2.0
from ant-design-blazor

protected override async Task OnInitializedAsync()
        {
            await base.OnInitializedAsync();

            Options ??= new Dictionary<string, object>();

            Options["Mode"] = Mode ?? "ir";
            Options["Placeholder"] = Placeholder ?? "";
            Options["Height"] = int.TryParse(Height, out var h) ? h : (object)Height;
            Options["Width"] = int.TryParse(Width, out var w) ? w : (object)Width;
            Options["MinHeight"] = int.TryParse(MinHeight, out var m) ? m : (object)MinHeight;
            Options["Options"] = Outline;

            if (Upload != null)
            {
                Options["Upload"] = Upload;
            }

            if (Toolbar != null)
            {
                List<object> bars = new List<object>();
                foreach (var item in Toolbar.Buttons)
                {
                    if (item is string)
                    {
                        bars.Add(item);
                    }
                    else if (item is CustomToolButton toolbar)
                    {
                        bars.Add(new Dictionary<string, object>()
                        {
                            ["hotkey"] = toolbar.Hotkey,
                            ["name"] = toolbar.Name,
                            ["tipPosition"] = toolbar.TipPosition,
                            ["tip"] = toolbar.Tip,
                            ["clreplacedName"] = toolbar.ClreplacedName,
                            ["icon"] = toolbar.Icon,
                        });
                    }
                }
                Options["Toolbar"] = bars;
            }
        }

19 Source : Editor.razor.cs
with Apache License 2.0
from ant-design-blazor

protected override async Task OnInitializedAsync()
        {
            await base.OnInitializedAsync();

            Options ??= new Dictionary<string, object>();

            Options["Mode"] = Mode ?? "ir";
            Options["Placeholder"] = Placeholder ?? "";
            Options["Height"] = int.TryParse(Height, out var h) ? h : (object)Height;
            Options["Width"] = int.TryParse(Width, out var w) ? w : (object)Width;
            Options["MinHeight"] = int.TryParse(MinHeight, out var m) ? m : (object)MinHeight;
            Options["Options"] = Outline;

            if (Upload != null)
            {
                Options["Upload"] = Upload;
            }

            if (Toolbar != null)
            {
                List<object> bars = new List<object>();
                foreach (var item in Toolbar.Buttons)
                {
                    if (item is string)
                    {
                        bars.Add(item);
                    }
                    else if (item is CustomToolButton toolbar)
                    {
                        bars.Add(new Dictionary<string, object>()
                        {
                            ["hotkey"] = toolbar.Hotkey,
                            ["name"] = toolbar.Name,
                            ["tipPosition"] = toolbar.TipPosition,
                            ["tip"] = toolbar.Tip,
                            ["clreplacedName"] = toolbar.ClreplacedName,
                            ["icon"] = toolbar.Icon,
                        });
                    }
                }
                Options["Toolbar"] = bars;
            }
        }

19 Source : AmqpNmsStreamMessageFacadeTest.cs
with Apache License 2.0
from apache

[Test]
        public void TestResetPositionAfterPop()
        {
            global::Amqp.Message message = new global::Amqp.Message();
            List<object> list = new List<object>();
            list.Add(false);
            list.Add(true);
            message.BodySection = new AmqpSequence() {List = list};

            AmqpNmsStreamMessageFacade amqpNmsStreamMessageFacade = CreateReceivedStreamMessageFacade(message);

            replacedert.AreEqual(false, amqpNmsStreamMessageFacade.Peek(), "Unexpected value retrieved");
            amqpNmsStreamMessageFacade.Pop();

            amqpNmsStreamMessageFacade.Reset();

            replacedert.AreEqual(false, amqpNmsStreamMessageFacade.Peek(), "Unexpected value retrieved");
            amqpNmsStreamMessageFacade.Pop();

            replacedert.AreEqual(true, amqpNmsStreamMessageFacade.Peek(), "Unexpected value retrieved");
            amqpNmsStreamMessageFacade.Pop();
        }

19 Source : AmqpNmsStreamMessageFacadeTest.cs
with Apache License 2.0
from apache

[Test]
        public void TestRepeatedPeekAfterPopReturnsExpectedValue()
        {
            global::Amqp.Message message = new global::Amqp.Message();
            List<object> list = new List<object>();
            list.Add(false);
            list.Add(true);
            message.BodySection = new AmqpSequence() {List = list};

            AmqpNmsStreamMessageFacade amqpNmsStreamMessageFacade = CreateReceivedStreamMessageFacade(message);

            replacedert.AreEqual(false, amqpNmsStreamMessageFacade.Peek(), "Unexpected value retrieved");
            amqpNmsStreamMessageFacade.Pop();
            replacedert.AreEqual(true, amqpNmsStreamMessageFacade.Peek(), "Unexpected value retrieved");
        }

19 Source : AmqpNmsStreamMessageFacadeTest.cs
with Apache License 2.0
from apache

[Test]
        public void TestPeekUsingReceivedMessageWithAmqpValueBodyReturnsExpectedValue()
        {
            global::Amqp.Message message = new global::Amqp.Message();
            List<object> list = new List<object>();
            list.Add(false);
            message.BodySection = new AmqpValue() {Value = list};

            AmqpNmsStreamMessageFacade amqpNmsStreamMessageFacade = CreateReceivedStreamMessageFacade(message);

            replacedert.AreEqual(false, amqpNmsStreamMessageFacade.Peek(), "Unexpected value retrieved");
        }

19 Source : AmqpNmsStreamMessageFacadeTest.cs
with Apache License 2.0
from apache

[Test]
        public void TestPeekUsingReceivedMessageWithAmqpSequenceBodyReturnsExpectedValue()
        {
            global::Amqp.Message message = new global::Amqp.Message();
            List<object> list = new List<object>();
            list.Add(false);
            message.BodySection = new AmqpSequence() {List = list};

            AmqpNmsStreamMessageFacade amqpNmsStreamMessageFacade = CreateReceivedStreamMessageFacade(message);

            replacedert.AreEqual(false, amqpNmsStreamMessageFacade.Peek(), "Unexpected value retrieved");
        }

19 Source : AmqpNmsStreamMessageFacadeTest.cs
with Apache License 2.0
from apache

[Test]
        public void TestRepeatedPeekReturnsExpectedValue()
        {
            global::Amqp.Message message = new global::Amqp.Message();
            List<object> list = new List<object>();
            list.Add(false);
            list.Add(true);
            message.BodySection = new AmqpSequence() {List = list};

            AmqpNmsStreamMessageFacade amqpNmsStreamMessageFacade = CreateReceivedStreamMessageFacade(message);

            replacedert.True(amqpNmsStreamMessageFacade.HasBody(), "Message should report that it contains a body");
            replacedert.AreEqual(false, amqpNmsStreamMessageFacade.Peek(), "Unexpected value retrieved");
            replacedert.AreEqual(false, amqpNmsStreamMessageFacade.Peek(), "Unexpected value retrieved");
        }

19 Source : AmqpNmsStreamMessageFacadeTest.cs
with Apache License 2.0
from apache

[Test]
        public void TestResetPositionAfterPeekThrowsMEOFE()
        {
            global::Amqp.Message message = new global::Amqp.Message();
            List<object> list = new List<object>();
            list.Add(false);
            list.Add(true);
            message.BodySection = new AmqpSequence() {List = list};

            AmqpNmsStreamMessageFacade amqpNmsStreamMessageFacade = CreateReceivedStreamMessageFacade(message);

            replacedert.AreEqual(false, amqpNmsStreamMessageFacade.Peek(), "Unexpected value retrieved");
            amqpNmsStreamMessageFacade.Pop();
            replacedert.AreEqual(true, amqpNmsStreamMessageFacade.Peek(), "Unexpected value retrieved");
            amqpNmsStreamMessageFacade.Pop();

            replacedert.Throws<MessageEOFException>(() => amqpNmsStreamMessageFacade.Peek(), "expected exception to be thrown");

            amqpNmsStreamMessageFacade.Reset();

            replacedert.AreEqual(false, amqpNmsStreamMessageFacade.Peek(), "Unexpected value retrieved");
            amqpNmsStreamMessageFacade.Pop();
            replacedert.AreEqual(true, amqpNmsStreamMessageFacade.Peek(), "Unexpected value retrieved");
        }

19 Source : AmqpNmsStreamMessageFacadeTest.cs
with Apache License 2.0
from apache

[Test]
        public void TestPopFullyReadListThrowsMEOFE()
        {
            global::Amqp.Message message = new global::Amqp.Message();
            List<object> list = new List<object>();
            list.Add(false);
            message.BodySection = new AmqpSequence() {List = list};

            AmqpNmsStreamMessageFacade amqpNmsStreamMessageFacade = CreateReceivedStreamMessageFacade(message);

            replacedert.AreEqual(false, amqpNmsStreamMessageFacade.Peek(), "Unexpected value retrieved");
            amqpNmsStreamMessageFacade.Pop();

            replacedert.Throws<MessageEOFException>(() => amqpNmsStreamMessageFacade.Pop());
        }

19 Source : EnumerableExpression.cs
with Apache License 2.0
from Appdynamics

public override CompileResult Compile()
        {
            var result = new List<object>();
            foreach (var childExpression in Children)
            {
                result.Add(_expressionCompiler.Compile(new List<Expression>{ childExpression }).Result);
            }
            return new CompileResult(result, DataType.Enumerable);
        }

19 Source : Choose.cs
with Apache License 2.0
from Appdynamics

public override CompileResult Execute(IEnumerable<FunctionArgument> arguments, ParsingContext context)
        {
            ValidateArguments(arguments, 2);
            var items = new List<object>();
            for (int x = 0; x < arguments.Count(); x++)
            {
                items.Add(arguments.ElementAt(x).ValueFirst);
            }

            var chooseIndeces = arguments.ElementAt(0).ValueFirst as IEnumerable<FunctionArgument>;
            if (chooseIndeces != null && chooseIndeces.Count() > 1)
            {
                IntArgumentParser intParser = new IntArgumentParser();
                object[] values = chooseIndeces.Select(chosenIndex => items[(int)intParser.Parse(chosenIndex.ValueFirst)]).ToArray();
                return CreateResult(values, DataType.Enumerable);
            }
            else
            {
                var index = ArgToInt(arguments, 0);
                return CreateResult(items[index].ToString(), DataType.String);
            }
        }

19 Source : ExcelRangeBase.cs
with Apache License 2.0
from Appdynamics

public ExcelRangeBase LoadFromText(string Text, ExcelTextFormat Format)
        {
            if (string.IsNullOrEmpty(Text))
            {
                var r = _worksheet.Cells[_fromRow, _fromCol];
                r.Value = "";
                return r;
            }

            if (Format == null) Format = new ExcelTextFormat();


            string[] lines;
            if (Format.TextQualifier==0)
            {
                lines = Regex.Split(Text, Format.EOL);
            }
            else
            {
                lines = GetLines(Text, Format);
            }
            //string splitRegex = String.Format("{0}(?=(?:[^{1}]*{1}[^{1}]*{1})*[^{1}]*$)", Format.EOL, Format.TextQualifier);
            //lines = Regex.Split(Text, splitRegex);

            int row = 0;
            int col = 0;
            int maxCol = col;
            int lineNo = 1;
            var values = new List<object>[lines.Length];
            foreach (string line in lines)
            {
                var items = new List<object>();
                values[row] = items;

                if (lineNo > Format.SkipLinesBeginning && lineNo <= lines.Length - Format.SkipLinesEnd)
                {
                    col = 0;
                    string v = "";
                    bool isText = false, isQualifier = false;
                    int QCount = 0;
                    int lineQCount = 0;
                    foreach (char c in line)
                    {
                        if (Format.TextQualifier != 0 && c == Format.TextQualifier)
                        {
                            if (!isText && v != "")
                            {
                                throw (new Exception(string.Format("Invalid Text Qualifier in line : {0}", line)));
                            }
                            isQualifier = !isQualifier;
                            QCount += 1;
                            lineQCount++;
                            isText = true;
                        }
                        else
                        {
                            if (QCount > 1 && !string.IsNullOrEmpty(v))
                            {
                                v += new string(Format.TextQualifier, QCount / 2);
                            }
                            else if (QCount > 2 && string.IsNullOrEmpty(v))
                            {
                                v += new string(Format.TextQualifier, (QCount - 1) / 2);
                            }

                            if (isQualifier)
                            {
                                v += c;
                            }
                            else
                            {
                                if (c == Format.Delimiter)
                                {
                                    items.Add(ConvertData(Format, v, col, isText));
                                    v = "";
                                    isText = false;
                                    col++;
                                }
                                else
                                {
                                    if (QCount % 2 == 1)
                                    {
                                        throw (new Exception(string.Format("Text delimiter is not closed in line : {0}", line)));
                                    }
                                    v += c;
                                }
                            }
                            QCount = 0;
                        }
                    }
                    if (QCount > 1 && (v!="" && QCount==2))
                    {
                        v += new string(Format.TextQualifier, QCount / 2);
                    }
                    if (lineQCount % 2 == 1)
                        throw (new Exception(string.Format("Text delimiter is not closed in line : {0}", line)));

                    //_worksheet.SetValueInner(row, col, ConvertData(Format, v, col - _fromCol, isText));
                    items.Add(ConvertData(Format, v, col, isText));
                    if (col > maxCol) maxCol = col;
                    row++;
                }
                lineNo++;
            }
            // flush
            _worksheet._values.SetRangeValueSpecial(_fromRow, _fromCol, _fromRow + values.Length - 1, _fromCol + maxCol,
                (List<ExcelCoreValue> list, int index, int rowIx, int columnIx, object value) =>
                {
                    rowIx -= _fromRow;
                    columnIx -= _fromCol;
                    var item = values[rowIx];
                    if (item == null || item.Count <= columnIx) return;

                    list[index] = new ExcelCoreValue { _value = item[columnIx], _styleId = list[index]._styleId };
                }, values);

            return _worksheet.Cells[_fromRow, _fromCol, _fromRow + row-1, _fromCol + maxCol];
        }

19 Source : ARFlatGroupAdapter.cs
with Apache License 2.0
from AppRopio

private void SetInnerItems()
        {
            if (ItemsSource == null)
            {
                _flareplacedems = null;
                _headersPostions = null;
                _footerPostions = null;
                _headersViewTypes = null;
                _footerViewTypes = null;
                return;
            }

            _flareplacedems = new List<object>();
            _headersPostions = new List<int>();
            _footerPostions = new List<int>();
            _footerViewTypes = new List<int>();
            _headersViewTypes = new List<int>();

            int currentPosition = 0;

            foreach (var item in ItemsSource)
            {
                var hasHeader = HasHeader?.Invoke(item) ?? false;
                var hasFooter = HasFooter?.Invoke(item) ?? false;

                if (hasHeader)
                {
                    _flareplacedems.Add(item);
                    _headersPostions.Add(currentPosition);
                    currentPosition++;
                }


                if (_innerItemsProvider != null)
                {
                    var innerItems = _innerItemsProvider(item);
                    foreach (var innerItem in innerItems)
                        _flareplacedems.Add(innerItem);

                    currentPosition += innerItems.Count();
                }
                else
                {
                    _flareplacedems.Add(item);
                    currentPosition++;
                }

                if (hasFooter)
                {
                    _flareplacedems.Add(item);
                    _footerPostions.Add(currentPosition);
                    currentPosition++;
                }
            }
        }

19 Source : AFMiniJSON.cs
with MIT License
from AppsFlyerSDK

List<object> ParseArray() {
                List<object> array = new List<object>();

                // ditch opening bracket
                json.Read();

                // [
                var parsing = true;
                while (parsing) {
                    TOKEN nextToken = NextToken;

                    switch (nextToken) {
                    case TOKEN.NONE:
                        return null;
                    case TOKEN.COMMA:
                        continue;
                    case TOKEN.SQUARED_CLOSE:
                        parsing = false;
                        break;
                    default:
                        object value = ParseByToken(nextToken);

                        array.Add(value);
                        break;
                    }
                }

                return array;
            }

19 Source : Program.cs
with MIT License
from appwrite

static void Main(string[] args)
        {
            Client client = new Client();
            client.SetEndPoint("[ENDPOINT]");
            client.SetProject("[PROJECT_ID]");
            client.SetKey("[API_KEY]");
            client.SetSelfSigned(true);

            string response;
            string collection;
            JObject parsed;

            Database database = new Database(client);
            Users users = new Users(client);

            /**
                Create User
            */
            try
            {
                Console.WriteLine("Running Create Users API");
                RunTask(users.Create($"{DateTime.Now.ToFileTime()}@example.com", "*******", "Lorem Ipsum")).GetAwaiter().GetResult();
                Console.WriteLine("Done");
            }
            catch (System.Exception e)
            {
                Console.WriteLine($"Error: {e}");
                throw;
            }

            /**
                List Doreplacedents
            */
            try
            {
                Console.WriteLine("Running List Doreplacedents API");
                response = RunTask(users.List()).GetAwaiter().GetResult();
                parsed = JObject.Parse(response);
                foreach (dynamic element in parsed["users"])
                {
                    Console.WriteLine($"- {element["name"]} ({element["email"]})");
                }
            }
            catch (System.Exception e)
            {
                Console.WriteLine($"Error: {e}");
                throw;
            }

            /**
                Create Collection
            */
            List<object> perms = new List<object>() {"*"};
            List<object> rules = new List<object>();

            Rule ruleName = new Rule();
            ruleName.Label = "Name";
            ruleName.Key = "name";
            ruleName.Type = "text";
            ruleName.Default = "Empty Name";
            ruleName.Required = true;
            ruleName.Array = false;
            rules.Add(ruleName);

            Rule ruleYear = new Rule();
            ruleYear.Label = "Release Year";
            ruleYear.Key = "release_year";
            ruleYear.Type = "numeric";
            ruleYear.Default = "1970";
            ruleYear.Required = true;
            ruleYear.Array = false;
            rules.Add(ruleYear);

            try
            {
                Console.WriteLine("Running Create Collection API");
                response = RunTask(database.CreateCollection("Movies", perms, perms, rules)).GetAwaiter().GetResult();
                parsed = JObject.Parse(response);
                collection = (string) parsed["$id"];
                Console.WriteLine("Done");
            }
            catch (System.Exception e)
            {
                Console.WriteLine($"Error: {e}");
                throw;
            }

            /**
                List Collection
            */
            try
            {
                Console.WriteLine("Running List Collection API");
                response = RunTask(database.ListCollections()).GetAwaiter().GetResult();
                parsed = JObject.Parse(response);
                foreach (dynamic element in parsed["collections"])
                {
                    Console.WriteLine($"- {element["name"]}");
                }
            }
            catch (System.Exception e)
            {
                Console.WriteLine($"Error: {e}");
                throw;
            }

            /**
                Add Doreplacedent
            */
            Movie movie1 = new Movie("Alien", 1979);
            Movie movie2 = new Movie("Equilibrium", 2002);
            try
            {
                Console.WriteLine("Running Create Doreplacedents API");
                RunTask(database.CreateDoreplacedent(collection, movie1, perms, perms)).GetAwaiter().GetResult();
                RunTask(database.CreateDoreplacedent(collection, movie2, perms, perms)).GetAwaiter().GetResult();
                Console.WriteLine("Done");
            }
            catch (System.Exception e)
            {
                Console.WriteLine($"Error: {e}");
                throw;
            }

            /**
                List Doreplacedents
            */
            try
            {
                Console.WriteLine("Running List Doreplacedents API");
                response = RunTask(database.ListDoreplacedents(collection)).GetAwaiter().GetResult();
                parsed = JObject.Parse(response);
                foreach (dynamic element in parsed["doreplacedents"])
                {
                    Console.WriteLine($"- {element["name"]} ({element["release_year"]})");
                }
            }
            catch (System.Exception e)
            {
                Console.WriteLine($"Error: {e}");
                throw;
            }

            /**
                List Functions
            */
            Functions functions = new Functions(client);
    
            try
            {
                Console.WriteLine("Running List Functions API");
                response = RunTask(functions.List()).GetAwaiter().GetResult();
                parsed = JObject.Parse(response);
                foreach (dynamic element in parsed["functions"])
                {
                    Console.WriteLine($"- {element["name"]} ({element["env"]})");
                }
            }
            catch (System.Exception e)
            {
                Console.WriteLine($"Error: {e}");
                throw;
            }
        }

19 Source : MockReturns.cs
with MIT License
from Apps72

private MockTable ConvertToMockTable<T>(T returns)
        {
            if (returns == null || returns is DBNull || typeof(T).IsPrimitive())
            {
                return new MockTable()
                {
                    Columns = Columns.WithNames(string.Empty),
                    Rows = new object[,]
                    {
                        { returns }
                    }
                };
            }
            else
            {
                Type type = typeof(T);
                PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
                var columns = new List<string>();
                var values = new List<object>();

                foreach (PropertyInfo property in properties)
                {
                    columns.Add(property.Name);
                    values.Add(GetValueOrDbNull(property.GetValue(returns)));
                }

                return new MockTable(columns.ToArray(),
                                     new object[][] { values.ToArray() }.ToTwoDimensionalArray());
            }
        }

See More Examples