System.Func.Invoke(string)

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

1892 Examples 7

19 Source : DynamicExpression.cs
with MIT License
from AliFlux

public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
        {
            this.tokens.Add(TransformToken(binder.Name));
            result = MethodCall(this, args);
            return true;
        }

19 Source : ExpressionBuilder.cs
with MIT License
from AliFlux

public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
        {
            if (ExecuteKey == "")
            {
                var token = TransformToken(binder.Name);

                var serializedArgs = args.Select(arg => serializeObject(arg));

                var call = token + "(" + string.Join(", ", serializedArgs) + ")";
                append(call);

                result = Execute(Expression);

                return true;
            }
            else if (ExecuteKey == binder.Name)
            {
                result = Execute(Expression);
                return true;
            }
            else// if (binder.Name != ExecuteKey)
            {
                var token = TransformToken(binder.Name);

                var serializedArgs = args.Select(arg => serializeObject(arg));

                var call = token + "(" + string.Join(", ", serializedArgs) + ")";
                append(call);

                result = this;
                return true;
            }
        }

19 Source : LogHeaderExtensions.cs
with MIT License
from aliyun

private static T? ParseNullable<T>(this String source, Func<String, T> parse) where T : struct
        {
            if (source.IsEmpty())
            {
                return null;
            }

            return parse(source);
        }

19 Source : LogHeaderExtensions.cs
with MIT License
from aliyun

private static T ParseNotNull<T>(this String source, Func<String, T> parse)
        {
            return parse(source);
        }

19 Source : SymbolResolver.cs
with MIT License
from allisterb

public static IntPtr LoadImage (ref string name)
        {
            var pathValues = Environment.GetEnvironmentVariable("PATH");
            var paths = new List<string>(pathValues == null ? new string[0] :
                pathValues.Split(Path.PathSeparator));
            paths.Insert(0, Directory.GetCurrentDirectory());
            paths.Insert(0, Path.GetDirectoryName(replacedembly.GetExecutingreplacedembly().Location));

            foreach (var format in formats)
            {
                // Search the Current or specified directory for the library
                string filename = string.Format(format, name);
                string attempted = null;
                foreach (var path in paths)
                {
                    var fullPath = Path.Combine(path, filename);
                    if (File.Exists(fullPath))
                    {
                        attempted = fullPath;
                        break;
                    }
                }
                if (!File.Exists(attempted))
                    continue;

                var ptr = loadImage (attempted);

                if (ptr == IntPtr.Zero)
                    continue;

                name = attempted;
                return ptr;
            }

            return IntPtr.Zero;
        }

19 Source : CSVReader.cs
with GNU Lesser General Public License v3.0
from Alois-xx

private void CreateParser(string[] columnNames)
        {
            for(int i=0;i<columnNames.Length;i++)
            {
                switch(columnNames[i])
                {
                    case Memreplacedyzer.AllocatedBytesColumn:
                        Parsers.Add((row, str) => { row.AllocatesBytes = LongColumnParsers[Memreplacedyzer.AllocatedBytesColumn](str); });
                        break;
                    case Memreplacedyzer.AllocatedKBColumn:
                        Parsers.Add((row, str) => { row.AllocatesBytes = LongColumnParsers[Memreplacedyzer.AllocatedKBColumn](str); });
                        break;
                    case Memreplacedyzer.AllocatedMBColumn:
                        Parsers.Add((row, str) => { row.AllocatesBytes = LongColumnParsers[Memreplacedyzer.AllocatedMBColumn](str); });
                        break;
                    case Memreplacedyzer.AllocatedGBColumn:
                        Parsers.Add((row, str) => { row.AllocatesBytes = LongColumnParsers[Memreplacedyzer.AllocatedGBColumn](str); });
                        break;
                    case Memreplacedyzer.InstancesColumn:
                        Parsers.Add((row, str) => { row.Instances = LongColumnParsers[Memreplacedyzer.InstancesColumn](str); });
                        break;
                    case Memreplacedyzer.TypeColumn:
                        Parsers.Add((row, str) => { row.Type = StringColumnParsers[Memreplacedyzer.TypeColumn](str); });
                        break;
                    case Memreplacedyzer.ProcessIdColumn:
                        Parsers.Add((row, str) => { row.ProcessContext.Pid = IntColumnParsers[Memreplacedyzer.ProcessIdColumn](str); });
                        break;
                    case Memreplacedyzer.AgeColumn:
                        Parsers.Add((row, str) => { row.ProcessContext.AgeIns = IntColumnParsers[Memreplacedyzer.AgeColumn](str); });
                        break;
                    case Memreplacedyzer.TimeColumn:
                        Parsers.Add((row, str) => { row.ProcessContext.Time = TimeColumnParsers[Memreplacedyzer.TimeColumn](str); });
                        break;
                    case Memreplacedyzer.CommandeLineColumn:
                        Parsers.Add((row, str) => { row.ProcessContext.CommandLine = StringColumnParsers[Memreplacedyzer.CommandeLineColumn](str); });
                        break;
                    case Memreplacedyzer.NameColumn:
                        Parsers.Add((row, str) => { row.ProcessContext.Name = StringColumnParsers[Memreplacedyzer.NameColumn](str); });
                        break;
                    case Memreplacedyzer.ContextColumn:
                        Parsers.Add((row, str) => { row.ProcessContext.Context = StringColumnParsers[Memreplacedyzer.ContextColumn](str); });
                        break;

                    default:
                        throw new NotSupportedException($"Column name {columnNames[i]} is not recognized as valid column. Cannot parse further.");
                }
            }
        }

19 Source : VerificationBox.cs
with MIT License
from alonfnt

public bool Verify()
        {
            var result = VerificationFunction?.Invoke(Text) ?? VerificationResult.None;
            switch (result)
            {
                case VerificationResult.None:
                    IsError = false;
                    IsSuccess = false;
                    return false;
                case VerificationResult.Fail:
                    IsError = true;
                    IsSuccess = false;
                    return true;
                case VerificationResult.Success:
                    IsError = false;
                    IsSuccess = true;
                    return true;
            }
            return false;
        }

19 Source : ServerForm.cs
with MIT License
from AmazingDM

private void ControlButton_Click(object sender, EventArgs e)
        {
            Utils.Utils.Componenreplacederator(this, component => Utils.Utils.ChangeControlForeColor(component, Color.Black));

            var flag = true;
            foreach (var pair in _checkActions.Where(pair => !pair.Value.Invoke(pair.Key.Text)))
            {
                Utils.Utils.ChangeControlForeColor(pair.Key, Color.Red);
                flag = false;
            }

            if (!flag)
            {
                return;
            }

            foreach (var pair in _saveActions)
            {
                switch (pair.Key)
                {
                    case CheckBox c:
                        pair.Value.Invoke(c.Checked);
                        break;
                    default:
                        pair.Value.Invoke(pair.Key.Text);
                        break;
                }
            }

            if (Global.Settings.Server.IndexOf(Server) == -1)
                Global.Settings.Server.Add(Server);

            MessageBoxX.Show(i18N.Translate("Saved"));

            Close();
        }

19 Source : Interface.cs
with MIT License
from Aminator

private static byte[] LoadBinaryBufferUnchecked(Schema.Buffer buffer, Func<string, byte[]> externalReferenceSolver)
        {
            return TryLoadBase64BinaryBufferUnchecked(buffer, EMBEDDEDGLTFBUFFER)
                ?? TryLoadBase64BinaryBufferUnchecked(buffer, EMBEDDEDOCTETSTREAM)
                ?? externalReferenceSolver(buffer?.Uri);
        }

19 Source : Interface.cs
with MIT License
from Aminator

public static Stream OpenImageFile(this Gltf model, int imageIndex, Func<string, byte[]> externalReferenceSolver)
        {
            var image = model.Images[imageIndex];

            if (image.BufferView.HasValue)
            {
                var bufferView = model.BufferViews[image.BufferView.Value];

                var bufferBytes = model.LoadBinaryBuffer(bufferView.Buffer, externalReferenceSolver);

                return new MemoryStream(bufferBytes, bufferView.ByteOffset, bufferView.ByteLength);
            }

            if (image.Uri.StartsWith("data:image/")) return OpenEmbeddedImage(image);

            var imageData = externalReferenceSolver(image.Uri);

            return new MemoryStream(imageData);
        }

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

private static JsonConverter CreateJsonConverter<T>(Type baseType, string discriminatorProperty,
            Func<string, string> clreplacedNameFactory)
        {
            var subTypes = baseType.replacedembly.GetTypes().Where(x =>
                x.IsInNamespace(baseType.Namespace!) && !x.IsAbstract && x.IsreplacedignableTo<T>());

            var builder = JsonSubtypesConverterBuilder.Of<T>(discriminatorProperty);
            foreach (var type in subTypes)
            {
                var key = clreplacedNameFactory(type.Name);
                builder.RegisterSubtype(type, key);
            }

            return builder.SerializeDiscriminatorProperty().Build();
        }

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

public async ValueTask<IEnumerable<PermissionLayer>> FetchPermissionsForParticipant(Participant participant)
        {
            var synchronizedRooms =
                await _mediator.FetchSynchronizedObject<SynchronizedRooms>(participant.ConferenceId,
                    SynchronizedRooms.SyncObjId);

            if (!synchronizedRooms.Participants.TryGetValue(participant.Id, out var roomId))
                return Enumerable.Empty<PermissionLayer>();

            if (roomId == synchronizedRooms.DefaultRoomId)
                return Enumerable.Empty<PermissionLayer>();

            var breakoutRoomState = await _fetchBreakoutRoomInternalState(participant.ConferenceId);
            if (breakoutRoomState?.OpenedRooms.Contains(roomId) != true)
                return Enumerable.Empty<PermissionLayer>();

            var result = new List<PermissionLayer>();

            if (_options.Default.TryGetValue(PermissionType.BreakoutRoom, out var breakoutRoomPermissions))
                result.Add(CommonPermissionLayers.BreakoutRoomDefault(breakoutRoomPermissions));

            var conference = await _mediator.Send(new FindConferenceByIdRequest(participant.ConferenceId));
            if (conference.Permissions.TryGetValue(PermissionType.BreakoutRoom, out var permissions))
                result.Add(CommonPermissionLayers.BreakoutRoom(permissions));

            return result;
        }

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

private static string ModifyModelTypeAtDesignTimeInternal(string type)
        {
            string result = ModifyModelTypeAtDesignTime(type);
            return result;
        }

19 Source : WebSocketBehavior.cs
with MIT License
from andruzzzhka

private string checkHandshakeRequest (WebSocketContext context)
    {
      if (_originValidator != null) {
        if (!_originValidator (context.Origin))
          return "It includes no Origin header or an invalid one.";
      }

      if (_cookiesValidator != null) {
        var req = context.CookieCollection;
        var res = context.WebSocket.CookieCollection;
        if (!_cookiesValidator (req, res))
          return "It includes no cookie or an invalid one.";
      }

      return null;
    }

19 Source : ElementExtensions.cs
with MIT License
from AngleSharp

public static bool TryGetAttrValue<T>(this IElement element, string attributeName, Func<string, T> resultFunc, [NotNullWhen(true)] out T result) where T : notnull
        {
            if (element is null)
                throw new ArgumentNullException(nameof(element));
            if (resultFunc is null)
                throw new ArgumentNullException(nameof(resultFunc));

            if (element.Attributes[attributeName] is IAttr optAttr)
            {
                result = resultFunc(optAttr.Value);
                return true;
            }
            else
            {
#pragma warning disable CS8601 // Possible null reference replacedignment.
                result = default(T);
#pragma warning restore CS8601 // Possible null reference replacedignment.
                return false;
            }
        }

19 Source : ElementExtensions.cs
with MIT License
from AngleSharp

public static T GetInlineOptionOrDefault<T>(this IElement startElement, string optionName, Func<string, T> resultFunc, T defaultValue)
        {
            if (startElement is null)
                throw new ArgumentNullException(nameof(startElement));
            if (resultFunc is null)
                throw new ArgumentNullException(nameof(resultFunc));

            var element = startElement;

            while (element is not null)
            {
                if (element.Attributes[optionName] is IAttr attr)
                {
                    return resultFunc(attr.Value);
                }
                element = element.ParentElement;
            }

            return defaultValue;
        }

19 Source : ObjectPool.cs
with Apache License 2.0
from anpShawn

public void CreatePool(int inPoolSize)
    {
        pool = new T[inPoolSize];

        poolTypeName = "";
        FuncCreatePoolObject = (string n) => CreateClreplacedObject();

        for(int i=0; i<pool.Length; i++)
        {
            T newItem = FuncCreatePoolObject(poolTypeName);
            newItem.InitForPool();
            AddToPool(newItem);
        }
    }

19 Source : ObjectPool.cs
with Apache License 2.0
from anpShawn

public T GetNext()
    {
        for(int i=0; i<pool.Length; i++)
        {
            if(!pool[i].IsActiveInPool())
            {
                pool[i].ActivateForPool();
                return pool[i];
            }
        }

        //can we make an overflow object if no others are available?
        if(overflowIsAllowed)
        {
            T overflowObj = FuncCreatePoolObject(poolTypeName + "_overflow_" + overflow.Count);
            overflowObj.InitForPool();
            overflowObj.ActivateForPool();
            overflow.Add(overflowObj);
            return overflowObj;
        }
        else
            throw new Exception("Pool has no inactive members to distribute");
    }

19 Source : ColladaLoader.Utilities.cs
with MIT License
from ansel86castro

public string GetTexture(string filename, string type)
        {
            string file;
            for (int i = 0; i < _tags.Length; i++ )
            {
                string tag = _tags[i];
                var converter = _tagConv[i];
                int index = filename.IndexOf(tag);
                if (index >= 0)
                {
                    file = filename.Replace(tag, converter(type));
                    if (File.Exists(file))
                        return file;
                }
            }
            return null;                
        }

19 Source : TextSplitter.cs
with MIT License
from AntonyCorbett

public IReadOnlyCollection<string> GetLines(double width)
        {
            var result = new List<string>();

            var q = new Queue<string>();
            var words = _originalText.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

            foreach (var word in words)
            {
                q.Enqueue(word);
            }

            var sb = new StringBuilder();
            string currentLine = null;
            while (q.Any())
            {
                var word = q.Peek();
                if (sb.Length > 0)
                {
                    sb.Append(' ');
                }

                sb.Append(word);

                var sz = _measureStringFunc(sb.ToString());

                if (sz.Width > width)
                {
                    // too big...
                    if (currentLine != null)
                    {
                        result.Add(currentLine.Trim());
                        currentLine = null;
                        sb.Clear();
                    }
                    else
                    {
                        throw new TextTooLargeException(Properties.Resources.TEXT_TOO_LARGE);
                    }
                }
                else
                {
                    q.Dequeue();
                    currentLine = sb.ToString();
                }
            }

            if (currentLine != null)
            {
                result.Add(currentLine.Trim());
            }

            return result;
        }

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

public static bool PatchTextFile(string file, Func<string, string> CbReplace)
		{
			try
			{
				string[] contents = File.ReadAllLines(file, Encoding.UTF8);

				for (int i = 0, sz = contents.Length; i < sz; ++i)
				{
					contents[i] = CbReplace(contents[i]);
				}

				string content = string.Join("\n", contents);

				var buf = Encoding.UTF8.GetBytes(content);
				File.WriteAllBytes(file, buf);

				return true;
			}
			catch (Exception)
			{
				return false;
			}
		}

19 Source : ApexCleanCodeGenTests.cs
with MIT License
from apexsharp

[Test]
        public void NormalizeWorksAsExpected()
        {
            replacedert.AreEqual(null, Normalize(null));
            replacedert.AreEqual(string.Empty, Normalize(string.Empty));
            replacedert.AreEqual("  ", Normalize("  "));
            replacedert.AreEqual("FooBar+123", Normalize("FooBar+123"));
            replacedert.AreEqual("AbstractRecordField", Normalize("abstractrecordfield"));
            replacedert.AreEqual("getContext or fooBar + setRecord", Normalize("GetContext or fooBar + setrecord"));
        }

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

public static async Task<ParseResult<T>> Parse<T>(this RequestResult result, MediaTypeFormat messageTypeFormat, Func<string, ParseResult<T>> customDeserializer = null) where T : clreplaced
        {
            if (result.Exception != null)
                return new ParseResult<T> { Successful = false, Error = result.Exception.Message };

            if (result.ResponseCode == HttpStatusCode.NoContent)
                return new ParseResult<T> { Successful = true };

            var contentreplacedtring = await result.ResponseContent.ReadreplacedtringAsync();

            if (customDeserializer != null)
                return customDeserializer(contentreplacedtring);

            switch (messageTypeFormat)
            {
                case MediaTypeFormat.Json:
                    return TryParseJson<T>(contentreplacedtring);
                case MediaTypeFormat.Xml:
                    return TryParseXml<T>(contentreplacedtring);
                default:
                    return TryParseJson<T>(contentreplacedtring);
            }

        }

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

public virtual async Task<TModel> Get<TModel>(string url, Func<string, TModel> parseResult, string errorMessage = null, CancellationToken? cancellationToken = null, Action<HttpRequestMessage> requestTuneAction = null)
        {
            if (string.IsNullOrEmpty(url))
                throw new ArgumentNullException(nameof(url));

            var stopWatch = Stopwatch.StartNew();

            var result = await ConnectionService.GET(
                url,
                cancellationToken,
                requestTuneAction
            );

            stopWatch.Stop();

            Task.Run(() => WriteInOutput(url, result, stopWatch));

            if (result.Succeeded)
            {
                var contentreplacedtring = await ReadContentreplacedtring(result);
                return parseResult.Invoke(contentreplacedtring);
            }

            throw new ConnectionException(result);
        }

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

public virtual async Task<TModel> Post<TModel>(string url, HttpContent postData, Func<string, TModel> parseResult, string errorMessage = null, CancellationToken? cancellationToken = null, Action<HttpRequestMessage> requestTuneAction = null)
        {
            if (string.IsNullOrEmpty(url))
                throw new ArgumentNullException(nameof(url));
            if (postData == null)
                throw new ArgumentNullException(nameof(postData));

            var stopWatch = Stopwatch.StartNew();

            var result = await ConnectionService.POST(
                url,
                postData,
                cancellationToken,
                requestTuneAction
            );

            stopWatch.Stop();

            Task.Run(() => WriteInOutput(url, result, stopWatch, postData));

            if (result.Succeeded)
            {
                var contentreplacedtring = await ReadContentreplacedtring(result);
                return parseResult.Invoke(contentreplacedtring);
            }

            throw new ConnectionException(result);
        }

19 Source : AttachmentController.cs
with MIT License
from appsonsf

[HttpGet("{id}")]
        public async Task<IActionResult> DownloadFileAsync([Required]string id, string fileName)
        {
            try
            {
                var appService = _attachmentAppServiceFactory(id);
                var dto = await appService.GetByIdAsync(id);
                if (dto == null) return NotFound();
                if (dto.Status < UploadStatus.Uploaded) return NotFound();
                if (string.IsNullOrEmpty(dto.Location)) return NotFound();

                //ref: https://scottsauber.com/2019/02/25/dynamically-setting-content-type-in-asp-net-core-with-fileextensioncontenttypeprovider/
                var fileProvider = new FileExtensionContentTypeProvider();
                var fileNameWithExt = string.IsNullOrEmpty(fileName) ? Path.GetFileName(dto.Location) : fileName;
                if (!fileProvider.TryGetContentType(fileNameWithExt, out string contentType))
                {
                    contentType = "application/octet-stream";
                }

                var ms = new MemoryStream();
                await _attachmentFileStoreService.FillMemoryStreamAsync(dto, ms);
                ms.Position = 0;
                return File(ms, contentType, fileNameWithExt);
            }
            catch (Exception ex)
            {
                return BadRequest(LogError(_logger, ex));
            }
        }

19 Source : AttachmentController.cs
with MIT License
from appsonsf

[HttpGet("status/{id}")]
        public async Task<ActionResult<UploadStatus>> GetStatusAsync([Required]string id)
        {
            try
            {
                var appService = _attachmentAppServiceFactory(id);
                var dto = await appService.GetByIdAsync(id);
                if (dto == null) return UploadStatus.None;
                return dto.Status;
            }
            catch (Exception ex)
            {
                return BadRequest(LogError(_logger, ex));
            }
        }

19 Source : AttachmentController.cs
with MIT License
from appsonsf

[HttpGet("thumbnails/{id}")]
        public async Task<IActionResult> DownloadThumbnailsAsync([Required]string id, string fileName)
        {
            try
            {
                var fileNameWithExt = string.IsNullOrEmpty(fileName) ? id + ".jpg" : fileName;
                if (_cache.TryGetValue(id, out byte[] thumbnailsData))
                    return File(thumbnailsData, "image/jpeg", fileNameWithExt);

                var appService = _attachmentAppServiceFactory(id);
                var dto = await appService.GetByIdAsync(id);
                if (dto == null) return NotFound();
                if (dto.Status < UploadStatus.Uploaded) return NotFound();
                if (string.IsNullOrEmpty(dto.Location)) return NotFound();

                using (var ms = new MemoryStream())
                {
                    await _attachmentFileStoreService.FillMemoryStreamAsync(dto, ms);

                    ms.Position = 0;
                    var thumbnailsImage = Image.FromStream(ms, false, false);
                    var thumbnailsStream = new MemoryStream();
                    ms.Position = 0;
                    PhotoResizer.Resize(ms, thumbnailsStream, thumbnailsImage.Width, thumbnailsImage.Height);
                    thumbnailsData = thumbnailsStream.ToArray();
                    _cache.Set(id, thumbnailsData, TimeSpan.FromMinutes(30));
                    return File(thumbnailsData, "image/jpeg", fileNameWithExt);
                    
                }
            }
            catch (Exception ex)
            {
                return BadRequest(LogError(_logger, ex));
            }
        }

19 Source : GroupFileController.cs
with MIT License
from appsonsf

[Route("{groupId}/files")]
        [HttpGet]
        public async Task<ActionResult<IEnumerable<FileItemDto>>> GetGroupFilesAsync(Guid groupId, bool depGroup, int page, int size)
        {
            try
            {
                if (Guid.Empty.Equals(groupId) || page < 1)
                    return null;
                var uploaderId = GetEmployeeId();
                var group = !depGroup
                    ? await _groupAppService.GetByIdAsync(groupId)
                    : await _departmentAppService.GetDepGroupByIdAsync(groupId);
                if (group == null)
                    return null;
                if (!IsMemeberInGroup(group.Members, uploaderId))
                    return null;
                var fileItems = await _groupFileControlApp.GetFileItemsAsync(groupId, page, size);
                if (fileItems != null)
                {
                    #region 获取上传者信息
                    var employeeIds = fileItems.DistinctBy(f => new { f.UploaderId })
                        .Select(x => x.UploaderId).ToArray();

                    var employees = await _employeeCacheService.ByIdAsync(employeeIds);

                    foreach (var item in fileItems)
                    {
                        var employee = employees.Find(x => x.Id == item.UploaderId);
                        if (employee != null)
                            item.UploaderName = employee.Name;
                    }
                    #endregion

                    #region 获取文件信息
                    var fileMd5s = fileItems.DistinctBy(f => new { f.StoreId });
                    List<Task<Attachmenreplacedem>> attTasks = new List<Task<Attachmenreplacedem>>();
                    foreach (var item in fileMd5s)
                    {
                        attTasks.Add(_attachmentAppServiceFactory(item.StoreId).GetByIdAsync(item.StoreId));
                    }
                    await Task.WhenAll(attTasks);
                    attTasks.ForEach(t =>
                    {
                        var e = t.Result;
                        if (e != null)
                        {
                            var fs = fileItems.FindAll(f => f.StoreId.Equals(e.Id));
                            if (fs != null)
                                foreach (var f in fs) f.Size = e.Size;
                        }
                    });
                    #endregion
                }
                return fileItems;
            }
            catch (Exception ex)
            {
                return BadRequest(LogError(_logger, ex));
            }
        }

19 Source : GroupFileController.cs
with MIT License
from appsonsf

[Route("freespace/{groupId}")]
        [HttpGet]
        public async Task<ActionResult<FreeSpaceDto>> FreeSpaceAsync(Guid groupId)
        {
            if (this._cache.TryGetValue<FreeSpaceDto>(groupId, out var freeSpaceDto))
            {
                return freeSpaceDto;
            }
            var groupFiles = await this._groupFileControlApp.GetFileItemsAsync(groupId, 1, int.MaxValue);
            var storeIds = groupFiles.Select(u => u.StoreId).ToArray();
            int stordBytes = 0;
            foreach (var storeId in storeIds)
            {
                var attachment = await this._attachmentAppServiceFactory.Invoke(storeId).GetByIdAsync(storeId);
                if (attachment != null)
                    stordBytes += attachment.Size;
            }
            var freeSpace = MaxAttachmentSize - stordBytes;
            freeSpaceDto = new FreeSpaceDto()
            {
                TotalSpace = MaxAttachmentSize,
                FreeSpace = freeSpace < 0 ? 0 : freeSpace
            };
            this._cache.Set(groupId, freeSpaceDto);
            return freeSpaceDto;
        }

19 Source : AttachmentController.cs
with MIT License
from appsonsf

[HttpPost]
        public async Task<ActionResult<ResponseData<UploadStatus>>> UploadFileAsync([FromForm]UploadVm model)
        {
            if (model == null)
                throw new ArgumentNullException(nameof(model));

            if (model.File == null || string.IsNullOrEmpty(model.MD5))
                return ResponseData<UploadStatus>.BuildFailedResponse(message: "参数不正确");

            var appService = _attachmentAppServiceFactory(model.MD5);
            var dto = await appService.GetByIdAsync(model.MD5);
            if (dto != null && dto.Status > UploadStatus.Uploading)
                return ResponseData<UploadStatus>.BuildSuccessResponse(dto.Status);

            var now = DateTimeOffset.UtcNow;
            string objectName;
            try
            {
                objectName = await _attachmentFileStoreService.StoreFileAsync(model, now);

                if (dto == null)
                {
                    dto = new Attachmenreplacedem
                    {
                        ContextId = model.ContextId,
                        Id = model.MD5,
                    };
                }
                dto.Location = objectName;
                dto.Size = (int)(model.File.Length / 1000);
                dto.Status = UploadStatus.Uploaded;
                dto.UploadBy = GetUserId();
                dto.Uploaded = now;
                try
                {
                    await appService.AddOrUpdateAsync(dto);
                }
                catch (Exception e)
                {
                    await _attachmentFileStoreService.TryDeleteFileAsync(objectName);
                    return BadRequest(LogError(_logger,e));
                }
                return ResponseData<UploadStatus>.BuildSuccessResponse(dto.Status);
            }
            catch (Exception ex)
            {
                return ResponseData<UploadStatus>.BuildFailedResponse(message: LogError(_logger, ex));
            }
        }

19 Source : GroupFileController.cs
with MIT License
from appsonsf

[Route("upload/{groupId}")]
        [HttpPut]
        public async Task<ActionResult<ResponseData<FileItemDto>>> UploadFileAsync(Guid groupId, string storeId, string fileName, bool depGroup = false)
        {
            try
            {
                if (string.IsNullOrEmpty(fileName) || string.IsNullOrEmpty(storeId) || Guid.Empty.Equals(groupId))
                    return ResponseData<FileItemDto>.BuildFailedResponse(message: "参数错误");
                var uploaderId = GetEmployeeId();
                var group = !depGroup
                    ? await _groupAppService.GetByIdAsync(groupId)
                    : await _departmentAppService.GetDepGroupByIdAsync(groupId);
                if (group == null)
                    return ResponseData<FileItemDto>.BuildFailedResponse(message: "群组不存在");
                if (!IsMemeberInGroup(group.Members, uploaderId))
                    return ResponseData<FileItemDto>.BuildFailedResponse(message: "无上传权限");
                var attachment = await _attachmentAppServiceFactory(storeId).GetByIdAsync(storeId);
                if (attachment == null)
                    return ResponseData<FileItemDto>.BuildFailedResponse(message: "文件上传失败");
                var input = new UploadInput
                {
                    FileName = fileName,
                    GroupId = groupId,
                    StoreId = storeId
                };
                await SendMessageAsync(groupId, GetUserId(), fileName, attachment);
                var result = await _groupFileControlApp.UploadFileAsync(input, uploaderId);
                _cache.Remove(groupId);
                if (result != null)
                {
                    result.Size = attachment.Size;
                    result.UploaderName = GetUserFullName();
                    return ResponseData<FileItemDto>.BuildSuccessResponse(result);
                }
                else
                    return ResponseData<FileItemDto>.BuildFailedResponse();
            }
            catch (Exception ex)
            {
                return BadRequest(LogError(_logger, ex));
            }
        }

19 Source : HtmlFormatter.cs
with MIT License
from arbelatech

private string GetStyleDefaults(string[] prefixes, bool usesPrefixes)
        {
            Func<string, string> prefix = cls =>
            {
                if (!string.IsNullOrEmpty(cls))
                    cls = "." + cls;

                return string.Join(", ", prefixes.Select(arg => (!string.IsNullOrEmpty(arg) ? arg + " " : "") + cls));
            };

            var lines = _cssToStyleMap
                .Where(kvp => kvp.Key != null && kvp.Value != null)
                .Select(kvp => Tuple.Create(kvp.Value.Depth, kvp.Value.TokenType, kvp.Key, kvp.Value.StyleRules))
                .OrderBy(t => t.Item1)
                .Select(s => $"{prefix(s.Item3)} {{ {s.Item4} }} /* {s.Item2} */")
                .ToList();

            if (usesPrefixes && !Options.NoBackground && _style.BackgroundColor != null)
            {
                var textStyle = "";
                if (_tokenToClreplacedMap.Contains(TokenTypes.Text))
                {
                    textStyle = " " + _cssToStyleMap[_tokenToClreplacedMap[TokenTypes.Text]].StyleRules;
                }

                lines.Insert(0, $"{prefix("")} {{ background: {_style.BackgroundColor}; {textStyle} }}");
            }

            if (_style.HighlightColor != null)
            {
                lines.Insert(0, $"{prefix("")}.hll {{ background-color: {_style.HighlightColor} }}");
            }

            return string.Join("\n", lines);
        }

19 Source : HtmlFormatter.cs
with MIT License
from arbelatech

private string GetStyleDefaults(string[] prefixes, bool usesPrefixes)
        {
            Func<string, string> prefix = cls =>
            {
                if (!string.IsNullOrEmpty(cls))
                    cls = "." + cls;

                return string.Join(", ", prefixes.Select(arg => (!string.IsNullOrEmpty(arg) ? arg + " " : "") + cls));
            };

            var lines = _cssToStyleMap
                .Where(kvp => kvp.Key != null && kvp.Value != null)
                .Select(kvp => Tuple.Create(kvp.Value.Depth, kvp.Value.TokenType, kvp.Key, kvp.Value.StyleRules))
                .OrderBy(t => t.Item1)
                .Select(s => $"{prefix(s.Item3)} {{ {s.Item4} }} /* {s.Item2} */")
                .ToList();

            if (usesPrefixes && !Options.NoBackground && _style.BackgroundColor != null)
            {
                var textStyle = "";
                if (_tokenToClreplacedMap.Contains(TokenTypes.Text))
                {
                    textStyle = " " + _cssToStyleMap[_tokenToClreplacedMap[TokenTypes.Text]].StyleRules;
                }

                lines.Insert(0, $"{prefix("")} {{ background: {_style.BackgroundColor}; {textStyle} }}");
            }

            if (_style.HighlightColor != null)
            {
                lines.Insert(0, $"{prefix("")}.hll {{ background-color: {_style.HighlightColor} }}");
            }

            return string.Join("\n", lines);
        }

19 Source : Sia2024Record.cs
with GNU General Public License v3.0
from architecture-building-systems

public static Sia2024Record FromJson(string json)
        {
            var d = JsonConvert.DeserializeObject<Dictionary<string, object>>(json); // TODO why not deserialise to Sia2024Record with JsonProperty name set to german keys?
            Func<string, double?> readValueOrNull = key => d.ContainsKey(key) ? (double?) d[key] : null;
            Func<string, bool> readValueOrFalse = key => d.ContainsKey(key) ? (bool)d[key] : false;

            return new Sia2024Record
            {
                RoomType = d["description"] as string,
                RoomConstant = (double) d["Zeitkonstante"],
                CapacitancePerFloorArea = (double)d["Waermespeicherfaehigkeit des Raumes"],
                CoolingSetpoint = (double) d["Raumlufttemperatur Auslegung Kuehlung (Sommer)"],
                HeatingSetpoint = (double) d["Raumlufttemperatur Auslegung Heizen (Winter)"],
                CoolingSetback = (double)d["Raumlufttemperatur Auslegung Kuehlung (Sommer) - Absenktemperatur"],
                HeatingSetback = (double)d["Raumlufttemperatur Auslegung Heizen (Winter) - Absenktemperatur"],
                FloorArea = (double) d["Nettogeschossflaeche"],
                EnvelopeArea = (double) d["Thermische Gebaeudehuellflaeche"],
                GlazingRatio = (double) d["Glasanteil"],
                UValueOpaque = (double) d["U-Wert opake Bauteile"],
                UValueTransparent = (double) d["U-Wert Fenster"],
                GValue = (double) d["Gesamtenergiedurchlreplacedgrad Verglasung"],
                GValueTotal = (double)d["Gesamtenergiedurchlreplacedgrad Verglasung und Sonnenschutz"],
                ShadingSetpoint = (double)d["Strahlungsleistung fuer Betaetigung Sonnenschutz"],
                WindowFrameReduction = (double) d["Abminderungsfaktor fuer Fensterrahmen"],
                AirChangeRate = (double) d["Aussenluft-Volumenstrom (pro NGF)"],
                Infiltration = (double) d["Aussenluft-Volumenstrom durch Infiltration"],
                HeatRecovery = (double) d["Temperatur-Aenderungsgrad der Waermerueckgewinnung"],
                OccupantLoads = (double) d["Waermeeintragsleistung Personen (bei 24.0 deg C, bzw. 70 W)"],
                LightingLoads = (double) d["Waermeeintragsleistung der Raumbeleuchtung"],
                EquipmentLoads = (double) d["Waermeeintragsleistung der Geraete"],
                OccupantYearlyHours = (double) d["Vollaststunden pro Jahr (Personen)"],
                LightingYearlyHours = (double) d["Jaehrliche Vollaststunden der Raumbeleuchtung"],
                EquipmentYearlyHours = (double) d["Jaehrliche Vollaststunden der Geraete"],
                OpaqueCost = (double) d["Kosten opake Bauteile"],
                TransparentCost = (double) d["Kosten transparente Bauteile"],
                OpaqueEmissions = (double) d["Emissionen opake Bauteile"],
                TransparentEmissions = (double) d["Emissionen transparente Bauteile"],
                DomesticreplacedplacederLoads = (double) d["Jaehrlicher Waermebedarf fuer Warmwreplaceder"],

                _uValueFloors = readValueOrNull("U-Wert Boeden"),
                _uValueRoofs = readValueOrNull("U-Wert Daecher"),
                _uValueWalls = readValueOrNull("U-Wert Waende"),

                _capacityFloors = readValueOrNull("Waermespeicherfaehigkeit Boeden"),
                _capacityRoofs = readValueOrNull("Waermespeicherfaehigkeit Daecher"),
                _capacityWalls = readValueOrNull("Waermespeicherfaehigkeit Waende"),

                _costFloors = readValueOrNull("Kosten Boeden"),
                _costRoofs = readValueOrNull("Kosten Daecher"),
                _costWalls = readValueOrNull("Kosten Waende"),

                _emissionsFloors = readValueOrNull("Emissionen Boeden"),
                _emissionsRoofs = readValueOrNull("Emissionen Daecher"),
                _emissionsWalls = readValueOrNull("Emissionen Waende"),

                RunNaturalVentilation = readValueOrFalse("Natuerliche Belueftung"),
                RunAdaptiveComfort = readValueOrFalse("Adaptiver Komfort"),
                UseFixedTimeConstant = readValueOrFalse("Feste Zeitkonstante")
            };
        }

19 Source : HttpResponseInfo.cs
with MIT License
from Archomeda

protected static TResult ParseResponseHeader<TResult>(IReadOnlyDictionary<string, string> headers, string key, Func<string, TResult> parser)
        {
            if (headers == null)
                return default!;
            if (parser == null)
                throw new ArgumentNullException(nameof(parser));

            headers.TryGetValue(key, out string? header);
            if (header == null)
                return default!;

            try
            {
                return parser(header);
            }
            catch (Exception ex)
            {
                if (ex is FormatException || ex is OverflowException)
                    return default!;
                throw;
            }
        }

19 Source : MutatedSecretNameSecretProvider.cs
with MIT License
from arcus-azure

protected async Task SafeguardMutateSecretAsync(string secretName, Func<string, Task> asyncFuncAfterMutation)
        {
            Guard.NotNullOrWhitespace(secretName, nameof(secretName), "Requires a non-blank secret name when mutating secret names");
            Guard.NotNull(asyncFuncAfterMutation, nameof(asyncFuncAfterMutation), "Requires a function to run after the secret name mutation");

            await SafeguardMutateSecretAsync(secretName, async mutatedSecretName =>
            {
                await asyncFuncAfterMutation(mutatedSecretName);

                // Return something unimportant because the method works with task results.
                return 0;
            });
        }

19 Source : MutatedSecretNameSecretProvider.cs
with MIT License
from arcus-azure

protected async Task<T> SafeguardMutateSecretAsync<T>(string secretName, Func<string, Task<T>> asyncFuncAfterMutation)
        {
            Guard.NotNullOrWhitespace(secretName, nameof(secretName), "Requires a non-blank secret name when mutating secret names");
            Guard.NotNull(asyncFuncAfterMutation, nameof(asyncFuncAfterMutation), "Requires a function to run after the secret name mutation");

            string mutatedSecretName = MutateSecretName(secretName);
            Task<T> task = asyncFuncAfterMutation(mutatedSecretName);

            if (task is null)
            {
                throw new InvalidOperationException(
                    $"Asynchronous failure during calling the secret provider with the mutated secret '{mutatedSecretName}'");
            }

            try
            {
                return await task;
            }
            catch (Exception exception)
            {
                Logger.LogWarning(
                    exception, "Failure during using secret '{MutatedSecretName}' that was mutated from '{OriginalSecretName}'", mutatedSecretName, secretName);

                throw;
            }
        }

19 Source : MutatedSecretNameSecretProvider.cs
with MIT License
from arcus-azure

private string MutateSecretName(string secretName)
        {
            Guard.NotNullOrWhitespace(secretName, nameof(secretName), "Requires a non-blank secret name when mutating secret names");

            try
            {
                Logger.LogTrace("Start mutating secret name '{SecretName}'...", secretName);
                string mutateSecretName = _mutateSecretName(secretName);
                Logger.LogTrace("Secret name '{OriginalSecretName}' mutated to '{MutatedSecretName}'", secretName, mutateSecretName);

                return mutateSecretName;
            }
            catch (Exception exception)
            {
                Logger.LogWarning(exception, "Failure during secret name mutation of '{SecretName}'", secretName);
                throw new NotSupportedException(
                    $"The secret '{secretName}' was not correct input for the secret name mutation expression", exception);
            }
        }

19 Source : TemplateProject.cs
with MIT License
from arcus-azure

public void UpdateFileInProject(string fileName, Func<string, string> updateContents)
        {
            Guard.NotNullOrWhitespace(fileName, nameof(fileName), "Requires a non-blank file name (no file path) to update the contents");
            Guard.NotNull(updateContents, nameof(updateContents), "Requires a function to update the project file contents");

            string destPath = Path.Combine(ProjectDirectory.FullName, fileName);
            if (!File.Exists(destPath))
            {
                string files = String.Join(", ", ProjectDirectory.GetFiles().Select(f => f.FullName));
                throw new FileNotFoundException($"No project file with the file name: '{fileName}' was found in the target project folder");
            }

            string content = File.ReadAllText(destPath);
            content = updateContents(content);
            File.WriteAllText(destPath, content);
        }

19 Source : WebApiProjectOptions.cs
with MIT License
from arcus-azure

private static void ReplaceProjectFileContent(DirectoryInfo projectDirectory, string fileName, Func<string, string> replacements)
        {
            string filePath = Path.Combine(projectDirectory.FullName, fileName);
            if (!File.Exists(filePath))
            {
                throw new FileNotFoundException($"Cannot find {filePath} to replace content", filePath);
            }

            string content = File.ReadAllText(filePath);
            content = replacements(content);

            File.WriteAllText(filePath, content);
        }

19 Source : StringCacheDictionary.cs
with MIT License
from ark-mod

public bool GetOrAdd(ReadOnlySpan<char> key, Func<string, TValue> create, out TValue value)
        {
            if (key == null)
            {
                throw new ArgumentNullException();
            }

            if (buckets == null) Initialize(0);
            //int hashCode = comparer.GetHashCode(key) & 0x7FFFFFFF;
            int hashCode = string.GetHashCode(key) & 0x7FFFFFFF;
            int targetBucket = hashCode % buckets.Length;


            for (int i = buckets[targetBucket]; i >= 0; i = entries[i].next)
            {
                //if (entries[i].hashCode == hashCode && comparer.Equals(entries[i].key, key))
                if (entries[i].hashCode == hashCode && MemoryExtensions.SequenceEqual(key, entries[i].key))
                {
                    value = entries[i].value;
                    return true;
                }

            }
            int index;
            if (freeCount > 0)
            {
                index = freeList;
                freeList = entries[index].next;
                freeCount--;
            }
            else
            {
                if (count == entries.Length)
                {
                    Resize();
                    targetBucket = hashCode % buckets.Length;
                }
                index = count;
                count++;
            }

            entries[index].hashCode = hashCode;
            entries[index].next = buckets[targetBucket];
            entries[index].key = key.ToString();
            entries[index].value = create != null ? create(key.ToString()) : typeof(TValue) == typeof(string) ? (dynamic)key.ToString() : default(TValue);
            buckets[targetBucket] = index;
            version++;

            value = entries[index].value;

            return false;
        }

19 Source : MetadataContainer.cs
with MIT License
from ARKlab

public T? GetMetadataValue<T>(string key, Func<string, T> converter, T? defaultValue = null)
            where T:struct
        {
            if (!TryGetValue(key, out var value))
            {
                return defaultValue;
            }

            return converter(value);
        }

19 Source : MetadataContainer.cs
with MIT License
from ARKlab

public T GetMetadataValue<T>(string key, Func<string, T> converter, T defaultValue = null)
            where T : clreplaced
        {
            if (!TryGetValue(key, out var value))
            {
                return defaultValue;
            }

            return converter(value);
        }

19 Source : ExpressionHelpers.cs
with MIT License
from artiomchi

private static object? GetValueInternal<TSource>(this Expression expression, LambdaExpression container, Func<string, IProperty?> propertyFinder, bool useExpressionCompiler, bool nested)
        {
            switch (expression.NodeType)
            {
                case ExpressionType.Call:
                    {
                        var methodExp = (MethodCallExpression)expression;
                        var context = methodExp.Object?.GetValueInternal<TSource>(container, propertyFinder, useExpressionCompiler, true);
                        var arguments = methodExp.Arguments.Select(a => a.GetValueInternal<TSource>(container, propertyFinder, useExpressionCompiler, true)).ToArray();
                        return methodExp.Method.Invoke(context, arguments);
                    }

                case ExpressionType.Coalesce:
                    {
                        var coalesceExp = (BinaryExpression)expression;
                        var left = coalesceExp.Left.GetValueInternal<TSource>(container, propertyFinder, useExpressionCompiler, nested);
                        var right = coalesceExp.Right.GetValueInternal<TSource>(container, propertyFinder, useExpressionCompiler, nested);

                        if (left == null)
                            return right;
                        if (left is not IKnownValue)
                            return left;

                        if (left is not IKnownValue leftValue)
                            leftValue = new ConstantValue(left);
                        if (right is not IKnownValue rightValue)
                            rightValue = new ConstantValue(right);

                        return new KnownExpression(expression.NodeType, leftValue, rightValue);
                    }

                case ExpressionType.Conditional:
                    {
                        var conditionalExp = (ConditionalExpression)expression;
                        var ifTrue = conditionalExp.IfTrue.GetValueInternal<TSource>(container, propertyFinder, useExpressionCompiler, nested);
                        var ifFalse = conditionalExp.IfFalse.GetValueInternal<TSource>(container, propertyFinder, useExpressionCompiler, nested);
                        var conditionExp = conditionalExp.Test.GetValueInternal<TSource>(container, propertyFinder, useExpressionCompiler, nested);

                        if (conditionExp is not IKnownValue knownCondition)
                            knownCondition = new ConstantValue(conditionExp);
                        if (ifTrue is not IKnownValue knownTrue)
                            knownTrue = new ConstantValue(ifTrue);
                        if (ifFalse is not IKnownValue knownFalse)
                            knownFalse = new ConstantValue(ifFalse);

                        return new KnownExpression(expression.NodeType, knownTrue, knownFalse, knownCondition);
                    }

                case ExpressionType.Constant:
                    {
                        return ((ConstantExpression)expression).Value;
                    }

                case ExpressionType.Convert:
                    {
                        var convertExp = (UnaryExpression)expression;
                        if (!nested)
                            return convertExp.Operand.GetValueInternal<TSource>(container, propertyFinder, useExpressionCompiler, nested);

                        var value = convertExp.Operand.GetValueInternal<TSource>(container, propertyFinder, useExpressionCompiler, true);
                        return Convert.ChangeType(value, convertExp.Type, CultureInfo.InvariantCulture);
                    }

                case ExpressionType.MemberAccess:
                    {
                        var memberExp = (MemberExpression)expression;
                        switch (memberExp.Member)
                        {
                            case FieldInfo fInfo:
                                return fInfo.GetValue(memberExp.Expression?.GetValueInternal<TSource>(container, propertyFinder, useExpressionCompiler, true));

                            case PropertyInfo pInfo:
                                if (!nested && memberExp.Expression?.NodeType == ExpressionType.Parameter && typeof(TSource).Equals(memberExp.Expression.Type))
                                {
                                    var isLeftParam = memberExp.Expression.Equals(container.Parameters[0]);
                                    if (isLeftParam || memberExp.Expression.Equals(container.Parameters[1]))
                                    {
                                        var property = propertyFinder(pInfo.Name)
                                            ?? throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, Resources.UnknownProperty, pInfo.Name));
                                        return new PropertyValue(pInfo.Name, isLeftParam, property);
                                    }
                                }
                                return pInfo.GetValue(memberExp.Expression?.GetValueInternal<TSource>(container, propertyFinder, useExpressionCompiler, true));

                            default:
                                throw new UnsupportedExpressionException(expression);
                        }
                    }

                case ExpressionType.NewArrayInit:
                    {
                        var arrayExp = (NewArrayExpression)expression;
                        var result = Array.CreateInstance(arrayExp.Type.GetElementType()!, arrayExp.Expressions.Count);
                        for (int i = 0; i < arrayExp.Expressions.Count; i++)
                            result.SetValue(arrayExp.Expressions[i].GetValueInternal<TSource>(container, propertyFinder, useExpressionCompiler, true), i);
                        return result;
                    }

                case ExpressionType.Add:
                case ExpressionType.Divide:
                case ExpressionType.Modulo:
                case ExpressionType.Multiply:
                case ExpressionType.Subtract:
                case ExpressionType.LessThan:
                case ExpressionType.LessThanOrEqual:
                case ExpressionType.GreaterThan:
                case ExpressionType.GreaterThanOrEqual:
                case ExpressionType.Equal:
                case ExpressionType.NotEqual:
                case ExpressionType.AndAlso:
                case ExpressionType.OrElse:
                case ExpressionType.And:
                case ExpressionType.Or:
                    {
                        var exp = (BinaryExpression)expression;
                        if (!nested)
                        {
                            var leftArg = exp.Left.GetValueInternal<TSource>(container, propertyFinder, useExpressionCompiler, false);
                            if (leftArg is not IKnownValue leftArgKnown)
                                if (leftArg is KnownExpression leftArgExp)
                                    leftArgKnown = leftArgExp.Value1;
                                else
                                    leftArgKnown = new ConstantValue(leftArg);
                            var rightArg = exp.Right.GetValueInternal<TSource>(container, propertyFinder, useExpressionCompiler, false);
                            if (rightArg is not IKnownValue rightArgKnown)
                                if (rightArg is KnownExpression rightArgExp)
                                    rightArgKnown = rightArgExp.Value1;
                                else
                                    rightArgKnown = new ConstantValue(rightArg);

                            if (leftArgKnown != null && rightArgKnown != null)
                                return new KnownExpression(exp.NodeType, leftArgKnown, rightArgKnown);
                        }
                        if (exp.Method != null)
                            return exp.Method.Invoke(
                                null,
                                BindingFlags.Static | BindingFlags.Public,
                                null,
                                new[] {
                                    exp.Left.GetValueInternal<TSource>(container, propertyFinder, useExpressionCompiler, true),
                                    exp.Right.GetValueInternal<TSource>(container, propertyFinder, useExpressionCompiler, true)
                                },
                                CultureInfo.InvariantCulture);

                        break;
                    }
            }

            // If we can't translate it to a known expression, just get the value
            if (useExpressionCompiler)
                return Expression.Lambda<Func<object>>(
                    Expression.Convert(expression, typeof(object)))
                        .Compile()();
            throw new UnsupportedExpressionException(expression);
        }

19 Source : DataRecordExtensions.cs
with MIT License
from arttonoyan

public static HashSet<string> GetColumnNames(this IDataRecord reader, Func<string, string> predicate)
        {
            var items = new HashSet<string>();
            for (int i = 0; i < reader.FieldCount; i++)
            {
                string name = reader.GetName(i);
                items.Add(predicate(name));
            }
            return items;
        }

19 Source : FindReplaceWindow.cs
with MIT License
from ashblue

protected override IFindResult[] GetFindResults (Func<string, bool> IsValid) {
            var results = new List<IFindResult>();

            var graphIDs = replacedetDatabase.Findreplacedets("t:DialogueGraph");
            foreach (var graphID in graphIDs) {
                var path = replacedetDatabase.GUIDToreplacedetPath(graphID);
                var graph = replacedetDatabase.LoadreplacedetAtPath<DialogueGraph>(path);
                if (graph == null) continue;

                foreach (var node in graph.Nodes) {
                    if (IsValid(node.Text ?? "")) {
                        var result = new DialogueSearchResult(node.Text, node as UnityEngine.Object);
                        results.Add(result);
                    }

                    foreach (var choice in node.Choices) {
                        var result = new ChoiceSearchResult(choice.text, choice);
                        results.Add(result);
                    }
                }
            }

            return results.ToArray();
        }

19 Source : ParameterToken.cs
with GNU Affero General Public License v3.0
from asmejkal

private static async Task<T> TryConvert<T>(ParameterToken token, ParameterType type, Func<string, Task<T>> parser)
            where T : clreplaced
        {
            dynamic result;
            if (token._cache.TryGet(type, out result))
                return result;

            try
            {
                result = await parser(token.Raw);
            }
            catch (Exception)
            {
                result = null;
            }

            token._cache.Add(new DynamicValue(result, type));
            return result;
        }

19 Source : ParameterToken.cs
with GNU Affero General Public License v3.0
from asmejkal

private static T TryConvert<T>(ParameterToken token, ParameterType type, Func<string, T> parser)
            where T : clreplaced
        {
            dynamic result;
            if (token._cache.TryGet(type, out result))
                return result;

            try
            {
                result = parser(token.Raw);
            }
            catch (Exception)
            {
                result = null;
            }

            token._cache.Add(new DynamicValue(result, type));
            return result;
        }

19 Source : Communicator.cs
with GNU Affero General Public License v3.0
from asmejkal

public async Task<ICollection<IUserMessage>> SendMessage(IMessageChannel channel, string text, Func<string, string> chunkDecorator, int maxDecoratorOverhead = 0)
        {
            if (maxDecoratorOverhead >= DiscordConfig.MaxMessageSize)
                throw new ArgumentException($"Argument {nameof(maxDecoratorOverhead)} may not exceed the message length limit, {DiscordConfig.MaxMessageSize}.", nameof(maxDecoratorOverhead));

            var result = new List<IUserMessage>();
            foreach (var chunk in text.ChunkifyByLines(DiscordConfig.MaxMessageSize - maxDecoratorOverhead))
                result.Add(await channel.SendMessageAsync(chunkDecorator(chunk.ToString()).Sanitise()));

            return result;
        }

See More Examples