Here are the examples of the csharp api System.Func.Invoke(System.Guid) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
53 Examples
19
Source : GuidBinaryBits.cs
with MIT License
from 1996v
with MIT License
from 1996v
public static GuidBinaryBits GetGuidBinaryBits(Guid guid)
{
return GetGuidBinaryBitsFunc(guid);
}
19
Source : SiteMapNodeBlogDataAdapter.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
private static IBlogDataAdapter CreateBlogDataAdapter(
SiteMapNode node,
Func<Guid, IBlogDataAdapter> createAuthorArchiveAdapter,
Func<DateTime, DateTime, IBlogDataAdapter> createMonthArchiveAdapter,
Func<string, IBlogDataAdapter> createTagArchiveAdapter,
Func<IBlogDataAdapter> createDefaultAdapter)
{
Guid authorId;
if (BlogSiteMapProvider.TryGetAuthorArchiveNodeAttribute(node, out authorId))
{
return createAuthorArchiveAdapter(authorId);
}
DateTime monthArchiveDate;
if (BlogSiteMapProvider.TryGetMonthArchiveNodeAttribute(node, out monthArchiveDate))
{
return createMonthArchiveAdapter(monthArchiveDate.Date, monthArchiveDate.Date.AddMonths(1));
}
string tag;
if (BlogSiteMapProvider.TryGetTagArchiveNodeAttribute(node, out tag))
{
return createTagArchiveAdapter(tag);
}
return createDefaultAdapter();
}
19
Source : EntityListPackageRepositoryDataAdapter.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
private IEnumerable<Package> GetPackages(IEnumerable<IGrouping<Guid, Enreplacedy>> enreplacedyGroupings, Func<Guid, string> getPackageUrl)
{
var website = Dependencies.GetWebsite();
foreach (var enreplacedyGrouping in enreplacedyGroupings)
{
var enreplacedy = enreplacedyGrouping.FirstOrDefault();
if (enreplacedy == null)
{
continue;
}
var versions = GetPackageVersions(enreplacedyGrouping, website.Id)
.OrderByDescending(e => e.ReleaseDate)
.ToArray();
var currentVersion = versions.FirstOrDefault();
if (currentVersion == null)
{
continue;
}
PackageImage icon;
var images = GetPackageImages(enreplacedyGrouping, website.Id, enreplacedy.GetAttributeValue<EnreplacedyReference>("adx_iconid"), out icon)
.OrderBy(e => e.Name)
.ToArray();
yield return new Package
{
Categories = GetPackageCategories(enreplacedyGrouping).ToArray(),
Components = GetPackageComponents(enreplacedyGrouping, website.Id).OrderBy(e => e.Order).ThenBy(e => e.CreatedOn).ToArray(),
ContentUrl = currentVersion.Url,
Dependencies = GetPackageDependencies(enreplacedyGrouping, website.Id).OrderBy(e => e.Order).ThenBy(e => e.CreatedOn).ToArray(),
Description = enreplacedy.GetAttributeValue<string>("adx_description"),
DisplayName = enreplacedy.GetAttributeValue<string>("adx_name"),
HideFromPackageListing = enreplacedy.GetAttributeValue<bool?>("adx_hidefromlisting").GetValueOrDefault(false),
Icon = icon,
Images = images,
OverwriteWarning = enreplacedy.GetAttributeValue<bool?>("adx_overwritewarning").GetValueOrDefault(false),
PublisherName = enreplacedy.GetAttributeAliasedValue<string>("adx_name", "publisher"),
ReleaseDate = currentVersion.ReleaseDate,
RequiredInstallerVersion = currentVersion.RequiredInstallerVersion,
Summary = enreplacedy.GetAttributeValue<string>("adx_summary"),
Type = GetPackageType(enreplacedy.GetAttributeValue<OptionSetValue>("adx_type")),
UniqueName = enreplacedy.GetAttributeValue<string>("adx_uniquename"),
Uri = GetPackageUri(enreplacedy.GetAttributeValue<EnreplacedyReference>("adx_packagerepositoryid"), website.Id, enreplacedy.GetAttributeValue<string>("adx_uniquename")),
Url = getPackageUrl(enreplacedy.Id),
Version = currentVersion.Version,
Versions = versions,
Configuration = currentVersion.Configuration
};
}
}
19
Source : UserSettingController.cs
with MIT License
from appsonsf
with MIT License
from appsonsf
[HttpPost("infoVisibility")]
public async Task<ActionResult<ResponseData>> SetInfoVisibility(InfoVisibility model)
{
try
{
var userId = GetUserId();
await _userSettingAppServiceFactory(userId).SetInfoVisibilityAsync(userId, model);
return BuildSuccess();
}
catch (Exception ex)
{
return BadRequest(LogError(_logger, ex));
}
}
19
Source : UserSettingController.cs
with MIT License
from appsonsf
with MIT License
from appsonsf
[HttpGet("infoVisibility")]
public async Task<ActionResult<InfoVisibility>> GetInfoVisibility()
{
try
{
var userId = GetUserId();
var dto = await _userSettingAppServiceFactory(userId).GetInfoVisibilityAsync(userId);
return dto;
}
catch (Exception ex)
{
return BadRequest(LogError(_logger, ex));
}
}
19
Source : WorkbenchController.cs
with MIT License
from appsonsf
with MIT License
from appsonsf
[HttpPost("authcode")]
public async Task<ActionResult<bool>> CheckAuthCode(CheckAuthCodeVm model)
{
try
{
if (model == null)
throw new ArgumentNullException(nameof(model));
var mobile = GetUserMobile();
if (string.IsNullOrEmpty(mobile)) return false;
var verified = await _mobileCodeSender.CheckAsync(mobile, model.MobileCode);
if (!verified) return false;
var userId = GetUserId();
var userSettingAppService = _userSettingAppServiceFactory(userId);
await userSettingAppService.SetAppEntranceAuthStateAsync(userId, new AppEntranceAuthStateInput
{
AppEntranceId = model.AppEntranceId,
DeviceCode = model.DeviceCode
});
return true;
}
catch (Exception ex)
{
return BadRequest(LogError(_logger, ex));
}
}
19
Source : WorkbenchController.cs
with MIT License
from appsonsf
with MIT License
from appsonsf
[HttpGet("authstatus")]
public async Task<ActionResult<bool>> CheckAuthStatus(Guid appEntranceId, string deviceCode)
{
try
{
if (appEntranceId == Guid.Empty) throw new ArgumentOutOfRangeException(nameof(appEntranceId));
if (string.IsNullOrEmpty(deviceCode)) throw new ArgumentNullException(nameof(deviceCode));
var userId = GetUserId();
var userSettingAppService = _userSettingAppServiceFactory(userId);
return await userSettingAppService.GetAppEntranceAuthStateAsync(userId, deviceCode, appEntranceId);
}
catch (Exception ex)
{
return BadRequest(LogError(_logger, ex));
}
}
19
Source : EmployeeController.cs
with MIT License
from appsonsf
with MIT License
from appsonsf
[HttpGet("my")]
public async Task<ActionResult<List<EmployeeListVm>>> GetMy()
{
try
{
var userId = GetUserId();
await EnsureDepartmentListCacheAsync();
await EnsurePositionListCacheAsync();
var favs = await _userFavoriteAppServiceFactory(userId).GetEmployeesAsync(userId);
var dto = await _employeeAppService.GetListByIdsAsync(favs);
return GenerateEmployeeList(dto);
}
catch (Exception ex)
{
return BadRequest(LogError(_logger, ex));
}
}
19
Source : EmployeeController.cs
with MIT License
from appsonsf
with MIT License
from appsonsf
[HttpPost("fav/{employeeId}")]
public async Task<ActionResult<ResponseData>> AddFavorite(Guid employeeId)
{
try
{
var userId = GetUserId();
if (await _userFavoriteAppServiceFactory(userId).AddEmployeeAsync(userId, employeeId))
return BuildSuccess();
return BuildFaild();
}
catch (Exception ex)
{
return BadRequest(LogError(_logger, ex));
}
}
19
Source : EmployeeController.cs
with MIT License
from appsonsf
with MIT License
from appsonsf
[HttpDelete("fav/{employeeId}")]
public async Task<ActionResult<ResponseData>> RemoveFavorite(Guid employeeId)
{
try
{
var userId = GetUserId();
if (await _userFavoriteAppServiceFactory(userId).RemoveEmployeeAsync(userId, employeeId))
return BuildSuccess();
return BuildFaild();
}
catch (Exception ex)
{
return BadRequest(LogError(_logger, ex));
}
}
19
Source : EmployeeController.cs
with MIT License
from appsonsf
with MIT License
from appsonsf
private async Task<ActionResult<EmployeeDetailVm>> ReturnByOutputAsync(Guid id, Func<Guid, Task<EmployeeOutput>> getOutput)
{
var dto = await getOutput(id);
if (dto == null) return NotFound(id);
await EnsureDepartmentListCacheAsync();
await EnsurePositionListCacheAsync();
var vm = _mapper.Map<EmployeeOutput, EmployeeDetailVm>(dto, (opts) =>
{
opts.AfterMap((EmployeeOutput s, EmployeeDetailVm d) =>
{
if (_positionListCache.ContainsKey(s.PrimaryPositionId))
d.PositionName = _positionListCache[s.PrimaryPositionId].Name;
SetDepartmentNames(s, d);
SetParttimeJobs(s, d);
});
});
var userId = GetUserId();
var employeeId = GetEmployeeId();
var task1 = _groupAppService.CheckSameWhiteListGroupAsync(employeeId, id);
var task2 = _userFavoriteAppServiceFactory(userId).IsFavoritedAsync(userId, id);
var task3 = dto.UserId.HasValue
? _userSettingAppServiceFactory(userId).GetInfoVisibilityAsync(dto.UserId.Value)
: Task.FromResult(new InfoVisibility());
await Task.WhenAll(task1, task2, task3);
vm.SameWhiteListGroup = task1.Result;
vm.IsFavorited = task2.Result;
if (!task3.Result.Mobile)
vm.Mobile = "***";
return vm;
}
19
Source : GroupFileController.cs
with MIT License
from appsonsf
with MIT License
from appsonsf
private async Task SendMessageAsync(Guid groupId, Guid senderId, string fileName, Attachmenreplacedem attachment)
{
var fileMsg = new FileMessageVm
{
FileGuid = attachment.Id,
FileName = fileName,
FileSize = attachment.Size,
};
var msg = ConversationMsg.Create(groupId, senderId, fileMsg.GetJsonContent(), ConversationMsgType.File);
var conversationMsgAppService = _conversationMsgAppServiceFactory(msg.ConversationId);
await conversationMsgAppService?.SendMessageAsync(msg);
}
19
Source : BizSystemNotifyMsgConsumer.cs
with MIT License
from appsonsf
with MIT License
from appsonsf
private async Task<IEnumerable<INotifySessionActor>> GetUserSessionActorsAsync()
{
var userIds = msg.ReceiverUserIds?.Length > 0
? msg.ReceiverUserIds
: msg.ReceiverNumbers?.Length > 0
? (await _employeeCacheService.ByNumberAsync(msg.ReceiverNumbers)).Where(o => o.UserId.HasValue).Select(o => o.UserId.Value)
: new Guid[0];
return userIds.Select(o => _notifySessionActorFactory(o));
}
19
Source : InstantMessageController.cs
with MIT License
from appsonsf
with MIT License
from appsonsf
[HttpPost("message/getHistory")]
public async Task<ActionResult<List<MessageVm>>> GetMessageHistory(MessageNotifyDto model)
{
try
{
var service = _conversationMsgAppServiceFactory(model.TargetId.ToGuid());
var messages = await service.GetOldMessagesAsync(new GetOldMessagesInput()
{
Id = model.TargetId.ToGuid(),
OldestMsgId = model.LatestMsgId,
//Type = Enum.Parse<ConversationType>(model.TargetCategory.ToString())
});
var tasks = new List<Task<MessageVm>>();
foreach (var msg in messages)
{
tasks.Add(BuildMessageVmAsync(msg));
}
await Task.WhenAll(tasks);
return tasks.Select(o => o.Result).ToList();
}
catch (Exception ex)
{
return BadRequest(LogError(_logger, ex));
}
}
19
Source : GroupNotifiedConsumer.cs
with MIT License
from appsonsf
with MIT License
from appsonsf
public async Task Consume(ConsumeContext<GroupNotified> context)
{
try
{
var con = await _manager.GetByIdAsync(context.Message.Id);
if (con.HasValue)
{
var tasks = new List<Task>();
foreach (var userId in con.Value.Participants)
{
var notifySessionActor = _notifySessionActorFactory(userId);
tasks.Add(notifySessionActor.PushEventNotifiesAsync(context.Message.Notifies));
}
await Task.WhenAll(tasks);
}
}
catch (Exception ex)
{
_logger.Error(ex, ex.Message);
throw;
}
}
19
Source : ConversationMsgQueueProcessor.cs
with MIT License
from appsonsf
with MIT License
from appsonsf
private static async Task PushNotifyAsync(
IConversationCtrlAppService conversationCtrlAppService,
Func<Guid, INotifySessionActor> notifySessionActorFactory,
ConversationMsg item)
{
try
{
var enreplacedyConversationWrap = await conversationCtrlAppService.GetByIdAsync(item.ConversationId);
if (enreplacedyConversationWrap.HasValue)
{
var enreplacedyConversation = enreplacedyConversationWrap.Value;
var tasks = new List<Task>();
foreach (var userId in enreplacedyConversation.Participants)
{
var actorSession = notifySessionActorFactory(userId);
tasks.Add(actorSession.PushMsgNotifyAsync(new MessageNotifyDto
{
Target = NotifyTargetType.Conversation,
TargetId = item.ConversationId.ToString(),
TargetCategory = (int)enreplacedyConversation.Type,
LatestMsgId = item.Id,
}));
}
await Task.WhenAll(tasks);
}
}
catch (Exception ex)
{
//如果PushMsgNotifyAsync过程出错,也实现保存消息的过程,只是会出现接收方接收不到消息
Log.Error("ConversationMsgQueueProcessor PushMsgNotifyAsync Message: " +
$"ItemId is {item.Id}, ConversationId is {item.ConversationId}, SenderId is {item.SenderId}, Message is {ex.Message}");
if (IsInUnitTest) throw;
}
}
19
Source : EmployeeController.cs
with MIT License
from appsonsf
with MIT License
from appsonsf
private async Task<ActionResult<EmployeeDetailVm>> ReturnByOutputAsync(Guid id, Func<Guid, Task<EmployeeOutput>> getOutput)
{
var dto = await getOutput(id);
if (dto == null) return NotFound(id);
await EnsureDepartmentListCacheAsync();
await EnsurePositionListCacheAsync();
var vm = _mapper.Map<EmployeeOutput, EmployeeDetailVm>(dto, (opts) =>
{
opts.AfterMap((EmployeeOutput s, EmployeeDetailVm d) =>
{
if (_positionListCache.ContainsKey(s.PrimaryPositionId))
d.PositionName = _positionListCache[s.PrimaryPositionId].Name;
SetDepartmentNames(s, d);
SetParttimeJobs(s, d);
});
});
var userId = GetUserId();
var employeeId = GetEmployeeId();
var task1 = _groupAppService.CheckSameWhiteListGroupAsync(employeeId, id);
var task2 = _userFavoriteAppServiceFactory(userId).IsFavoritedAsync(userId, id);
var task3 = dto.UserId.HasValue
? _userSettingAppServiceFactory(userId).GetInfoVisibilityAsync(dto.UserId.Value)
: Task.FromResult(new InfoVisibility());
await Task.WhenAll(task1, task2, task3);
vm.SameWhiteListGroup = task1.Result;
vm.IsFavorited = task2.Result;
if (!task3.Result.Mobile)
vm.Mobile = "***";
return vm;
}
19
Source : InstantMessageController.cs
with MIT License
from appsonsf
with MIT License
from appsonsf
private async Task<SendMessageResult> SendAsync(ConversationMsg msg, ConversationType conversationType)
{
var enreplacedy = await _conversationCtrlAppService.GetByIdAsync(msg.ConversationId);
var conversationMsgAppService = _conversationMsgAppServiceFactory(msg.ConversationId);
if (enreplacedy.HasValue && !enreplacedy.Value.IsDeleted)
if (enreplacedy.Value.Participants.Contains(msg.SenderId))
{
await conversationMsgAppService.SendMessageAsync(msg);
return new SendMessageResult()
{
Success = true,
Message = "发送消息成功",
MessageId = msg.Id,
SendTime = msg.Time
};
}
else
return new SendMessageResult()
{
Success = false,
Message = conversationType == ConversationType.P2P ? "用户不属于此会话..." : "用户不在群组中..."
};
else
return new SendMessageResult()
{
Success = false,
Message = "对话不存在"
};
}
19
Source : PersonManager.cs
with MIT License
from Avanade
with MIT License
from Avanade
public async Task<PersonDetail?> GetDetailAsync(Guid id) => await ManagerInvoker.Current.InvokeAsync(this, async () =>
{
Cleaner.CleanUp(id);
await (_getDetailOnPreValidateAsync?.Invoke(id) ?? Task.CompletedTask).ConfigureAwait(false);
await MultiValidator.Create()
.Add(id.Validate(nameof(id)).Mandatory())
.Additional((__mv) => _getDetailOnValidate?.Invoke(__mv, id))
.RunAsync(throwOnError: true).ConfigureAwait(false);
await (_getDetailOnBeforeAsync?.Invoke(id) ?? Task.CompletedTask).ConfigureAwait(false);
var __result = await _dataService.GetDetailAsync(id).ConfigureAwait(false);
await (_getDetailOnAfterAsync?.Invoke(__result, id) ?? Task.CompletedTask).ConfigureAwait(false);
return Cleaner.Clean(__result);
}, BusinessInvokerArgs.Read).ConfigureAwait(false);
19
Source : PersonManager.cs
with MIT License
from Avanade
with MIT License
from Avanade
public async Task<string?> InvokeApiViaAgentAsync(Guid id) => await ManagerInvoker.Current.InvokeAsync(this, async () =>
{
Cleaner.CleanUp(id);
await (_invokeApiViaAgentOnPreValidateAsync?.Invoke(id) ?? Task.CompletedTask).ConfigureAwait(false);
await MultiValidator.Create()
.Additional((__mv) => _invokeApiViaAgentOnValidate?.Invoke(__mv, id))
.RunAsync(throwOnError: true).ConfigureAwait(false);
await (_invokeApiViaAgentOnBeforeAsync?.Invoke(id) ?? Task.CompletedTask).ConfigureAwait(false);
var __result = await _dataService.InvokeApiViaAgentAsync(id).ConfigureAwait(false);
await (_invokeApiViaAgentOnAfterAsync?.Invoke(__result, id) ?? Task.CompletedTask).ConfigureAwait(false);
return Cleaner.Clean(__result);
}, BusinessInvokerArgs.Unspecified).ConfigureAwait(false);
19
Source : PersonManager.cs
with MIT License
from Avanade
with MIT License
from Avanade
public async Task<Person?> GetWithEfAsync(Guid id) => await ManagerInvoker.Current.InvokeAsync(this, async () =>
{
Cleaner.CleanUp(id);
await (_getWithEfOnPreValidateAsync?.Invoke(id) ?? Task.CompletedTask).ConfigureAwait(false);
await MultiValidator.Create()
.Add(id.Validate(nameof(id)).Mandatory())
.Additional((__mv) => _getWithEfOnValidate?.Invoke(__mv, id))
.RunAsync(throwOnError: true).ConfigureAwait(false);
await (_getWithEfOnBeforeAsync?.Invoke(id) ?? Task.CompletedTask).ConfigureAwait(false);
var __result = await _dataService.GetWithEfAsync(id).ConfigureAwait(false);
await (_getWithEfOnAfterAsync?.Invoke(__result, id) ?? Task.CompletedTask).ConfigureAwait(false);
return Cleaner.Clean(__result);
}, BusinessInvokerArgs.Read).ConfigureAwait(false);
19
Source : PersonData.cs
with MIT License
from Avanade
with MIT License
from Avanade
public Task DeleteAsync(Guid id) => DataInvoker.Current.InvokeAsync(this, async () =>
{
var __dataArgs = DbMapper.Default.CreateArgs("[Demo].[spPersonDelete]");
await (_deleteOnBeforeAsync?.Invoke(id, __dataArgs) ?? Task.CompletedTask).ConfigureAwait(false);
await _db.DeleteAsync(__dataArgs, id).ConfigureAwait(false);
await (_deleteOnAfterAsync?.Invoke(id) ?? Task.CompletedTask).ConfigureAwait(false);
}, new BusinessInvokerArgs { ExceptionHandler = _deleteOnException });
19
Source : PersonData.cs
with MIT License
from Avanade
with MIT License
from Avanade
public Task DeleteWithEfAsync(Guid id) => DataInvoker.Current.InvokeAsync(this, async () =>
{
var __dataArgs = EfDbArgs.Create(_mapper);
await (_deleteWithEfOnBeforeAsync?.Invoke(id, __dataArgs) ?? Task.CompletedTask).ConfigureAwait(false);
await _ef.DeleteAsync<Person, EfModel.Person>(__dataArgs, id).ConfigureAwait(false);
await (_deleteWithEfOnAfterAsync?.Invoke(id) ?? Task.CompletedTask).ConfigureAwait(false);
}, new BusinessInvokerArgs { ExceptionHandler = _deleteWithEfOnException });
19
Source : PersonDataSvc.cs
with MIT License
from Avanade
with MIT License
from Avanade
public Task DeleteAsync(Guid id) => DataSvcInvoker.Current.InvokeAsync(this, async () =>
{
await _data.DeleteAsync(id).ConfigureAwait(false);
await (_deleteOnAfterAsync?.Invoke(id) ?? Task.CompletedTask).ConfigureAwait(false);
await _evtPub.PublishValue(new Person { Id = id }, new Uri($"/person/{_evtPub.FormatKey(id)}", UriKind.Relative), $"Demo.Person.{_evtPub.FormatKey(id)}", "Delete", id).SendAsync().ConfigureAwait(false);
_cache.Remove<Person>(new UniqueKey(id));
}, new BusinessInvokerArgs { IncludeTransactionScope = true });
19
Source : PersonDataSvc.cs
with MIT License
from Avanade
with MIT License
from Avanade
public Task DeleteWithEfAsync(Guid id) => DataSvcInvoker.Current.InvokeAsync(this, async () =>
{
await _data.DeleteWithEfAsync(id).ConfigureAwait(false);
await (_deleteWithEfOnAfterAsync?.Invoke(id) ?? Task.CompletedTask).ConfigureAwait(false);
await _evtPub.PublishValue(new Person { Id = id }, new Uri($"/person/{_evtPub.FormatKey(id)}", UriKind.Relative), $"Demo.Person.{id}", "Delete", id).SendAsync().ConfigureAwait(false);
_cache.Remove<Person>(new UniqueKey(id));
}, new BusinessInvokerArgs { IncludeTransactionScope = true });
19
Source : PersonManager.cs
with MIT License
from Avanade
with MIT License
from Avanade
public async Task DeleteAsync(Guid id) => await ManagerInvoker.Current.InvokeAsync(this, async () =>
{
Cleaner.CleanUp(id);
await (_deleteOnPreValidateAsync?.Invoke(id) ?? Task.CompletedTask).ConfigureAwait(false);
await MultiValidator.Create()
.Add(id.Validate(nameof(id)).Mandatory())
.Additional((__mv) => _deleteOnValidate?.Invoke(__mv, id))
.RunAsync(throwOnError: true).ConfigureAwait(false);
await (_deleteOnBeforeAsync?.Invoke(id) ?? Task.CompletedTask).ConfigureAwait(false);
await _dataService.DeleteAsync(id).ConfigureAwait(false);
await (_deleteOnAfterAsync?.Invoke(id) ?? Task.CompletedTask).ConfigureAwait(false);
}, BusinessInvokerArgs.Delete).ConfigureAwait(false);
19
Source : PersonManager.cs
with MIT License
from Avanade
with MIT License
from Avanade
public async Task DeleteWithEfAsync(Guid id) => await ManagerInvoker.Current.InvokeAsync(this, async () =>
{
Cleaner.CleanUp(id);
await (_deleteWithEfOnPreValidateAsync?.Invoke(id) ?? Task.CompletedTask).ConfigureAwait(false);
await MultiValidator.Create()
.Add(id.Validate(nameof(id)).Mandatory())
.Additional((__mv) => _deleteWithEfOnValidate?.Invoke(__mv, id))
.RunAsync(throwOnError: true).ConfigureAwait(false);
await (_deleteWithEfOnBeforeAsync?.Invoke(id) ?? Task.CompletedTask).ConfigureAwait(false);
await _dataService.DeleteWithEfAsync(id).ConfigureAwait(false);
await (_deleteWithEfOnAfterAsync?.Invoke(id) ?? Task.CompletedTask).ConfigureAwait(false);
}, BusinessInvokerArgs.Delete).ConfigureAwait(false);
19
Source : WebClientStore.cs
with MIT License
from azist
with MIT License
from azist
private async Task<MinIdpUserData> guardedIdpAccess(Func<Guid, Task<MinIdpUserData>> body)
{
var rel = Guid.NewGuid();
try
{
if (ComponentEffectiveLogLevel < MessageType.Trace)
WriteLog(MessageType.DebugA, nameof(guardedIdpAccess), "#001 IDP.Call", related: rel);
var result = await body(rel).ConfigureAwait(false);
if (ComponentEffectiveLogLevel < MessageType.Trace)
WriteLog(MessageType.DebugA, nameof(guardedIdpAccess), "#002 IDP.Call result. User name: `{0}`".Args(result?.Name), related: rel);
return result;
}
catch(Exception cause)
{
if (ComponentEffectiveLogLevel < MessageType.Trace)
WriteLog(MessageType.DebugError, nameof(guardedIdpAccess), "#003 IDP.Call result exception: {0}".Args(cause.ToMessageWithType()), related: rel);
if (cause is WebCallException wce && wce.HttpStatusCode == 404)
{
if (ComponentEffectiveLogLevel < MessageType.Trace)
WriteLog(MessageType.DebugA, nameof(guardedIdpAccess), "#004 Got WCE-404", related: rel);
return null;//404 is treated as "user not found"
}
var error = new SecurityException(StringConsts.SECURITY_IDP_UPSTREAM_CALL_ERROR.Args(cause.ToMessageWithType()), cause);
WriteLog(MessageType.CriticalAlert, nameof(guardedIdpAccess), error.Message, error: error, related: rel);
throw error;
}
}
19
Source : RefreshCommand.cs
with MIT License
from bert2
with MIT License
from bert2
private static async Task Execute(Func<Guid, Task> refreshCodeLens, OleMenuCmdEventArgs e) {
try {
await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
var arg = e.InValue as string
?? throw new InvalidOperationException($"{nameof(RefreshCommand)} requires an argument.");
if (!Guid.TryParse(arg, out var dataPointId))
throw new InvalidOperationException($"{nameof(RefreshCommand)} requires an argument of type Guid.");
await refreshCodeLens(dataPointId).Caf();
} catch (Exception ex) {
LogVS(ex);
throw;
}
}
19
Source : StronglyTypedId.cs
with MIT License
from joaofbantunes
with MIT License
from joaofbantunes
public static bool TryParse(string? input, Type stronglyTypedIdType, [MaybeNullWhen(false)] out object result)
{
if (Guid.TryParse(input, out var id))
{
result = GetConstructor(stronglyTypedIdType)(id);
return true;
}
result = default;
return false;
}
19
Source : CalibrationHelper.cs
with GNU General Public License v2.0
from Kinovea
with GNU General Public License v2.0
from Kinovea
public PointF GetPointAtTime(PointF p, long time)
{
if (calibratorType == CalibratorType.None || calibrationDrawingId == Guid.Empty)
return GetPoint(p);
PointF result;
PointF query = distortionHelper.Undistort(p);
// Tracking mechanics.
// Both the calibration object and the system's origin can be tracked, but not at the same time.
// If they are both tracked, the calibration object takes precedence and redefines the origin.
bool trackedCalibrator = hasTrackingData(calibrationDrawingId);
if (trackedCalibrator)
{
// Get the state of the calibration object at the specified time, and init a temporary calibrator object.
QuadrilateralF quadImage = getCalibrationQuad(time, calibratorType, calibrationDrawingId);
if (calibratorType == CalibratorType.Line)
quadImage = CalibrationPlane.MakeQuad(quadImage.A, quadImage.B, calibrationPlane.CalibrationAxis);
QuadrilateralF undistorted = distortionHelper.Undistort(quadImage);
CalibrationPlane calibrator = calibrationPlane.Clone();
calibrator.Update(undistorted);
// Force the system's origin to the bottom-left point of the quad.
PointF origin = undistorted.D;
result = calibrator.Transform(query, origin);
}
else
{
// In this case we just use the static calibration.
// However the system's origin might still be tracked so get its value for that time.
PointF origin = distortionHelper.Undistort(getCalibrationOrigin(time));
result = calibrationPlane.Transform(query, origin);
}
return result;
}
19
Source : WebServerContext.cs
with MIT License
from Kooboo
with MIT License
from Kooboo
internal static User _GetUserFromToken(HttpRequest request)
{
string token = RequestManager.GetHttpValue(request, "AccessToken");
if (!string.IsNullOrEmpty(token))
{
Guid userid = Kooboo.Data.Cache.AccessTokenCache.GetUserId(token);
if (userid != default(Guid))
{
return GetUserFunc(userid);
}
var user = Kooboo.Data.GlobalDb.Users.GetByToken(token);
if (user != null)
{
Data.Cache.AccessTokenCache.SetToken(user.Id, token);
}
if (user != null)
{
if (!Kooboo.Data.Service.UserLoginService.IsAllow(user.Id))
{
return null;
}
}
return user;
}
return null;
}
19
Source : WebServerContext.cs
with MIT License
from Kooboo
with MIT License
from Kooboo
internal static User _GetUserFromCookie(HttpRequest request)
{
foreach (var item in request.Cookies)
{
if (item.Key == Kooboo.DataConstants.UserApiSessionKey)
{
Guid userid = default(Guid);
if (System.Guid.TryParse(item.Value, out userid))
{
return GetUserFunc(userid);
}
}
}
return null;
}
19
Source : MakeTransferEndpoint.cs
with MIT License
from la-yumba
with MIT License
from la-yumba
public Task<IActionResult> Transfer([FromBody] MakeTransfer command)
{
Task<Validation<AccountState>> outcome =
from cmd in Async(validate(command))
from acc in GetAccount(cmd.DebitedAccountId)
from result in Async(Account.Debit(acc, cmd))
from _ in SaveAndPublish(result.Event).Map(Valid)
select result.NewState;
//Task<Validation<AccountState>> a = validate(command)
// .Traverse(cmd => getAccount(cmd.DebitedAccountId)
// .Bind(acc => Account.Debit(acc, cmd)
// .Traverse(result => saveAndPublish(result.Event)
// .Map(_ => result.NewState))))
// .Map(vva => vva.Bind(va => va)); // flatten the nested validation inside the task
return outcome.Map(
Faulted: ex => StatusCode(500, Errors.UnexpectedError),
Completed: val => val.Match(
Invalid: errs => BadRequest(new { Errors = errs }),
Valid: newState => Ok(new { Balance = newState.Balance }) as IActionResult));
}
19
Source : Controller.cs
with MIT License
from la-yumba
with MIT License
from la-yumba
public IActionResult MakeTransfer([FromBody] MakeTransfer cmd)
=> validate(cmd)
.Bind(t => getAccount(t.DebitedAccountId).Debit(t))
.Do(result => saveAndPublish(result.Item1))
.Match<IActionResult>(
Invalid: errs => BadRequest(new { Errors = errs }),
Valid: result => Ok(new { Balance = result.Item2.Balance }));
19
Source : Controller.cs
with MIT License
from la-yumba
with MIT License
from la-yumba
public IActionResult MakeTransfer([FromBody] MakeTransfer cmd)
{
var account = getAccount(cmd.DebitedAccountId);
// performs the transfer
var (evt, newState) = account.Debit(cmd);
saveAndPublish(evt);
// returns information to the user about the new state
return Ok(new { Balance = newState.Balance });
}
19
Source : Endpoints.cs
with MIT License
from la-yumba
with MIT License
from la-yumba
public static void ConfigureMakeTransferEndpoint
(
this WebApplication app,
Func<Guid, AccountState> getAccount,
Action<Event> saveAndPublish
)
=> app.MapPost("/Transfer/Make", (Func<MakeTransfer, IResult>)((MakeTransfer cmd) =>
{
var account = getAccount(cmd.DebitedAccountId);
// performs the transfer
var (evt, newState) = account.Debit(cmd);
saveAndPublish(evt);
// returns information to the user about the new state
return Ok(new { newState.Balance });
}));
19
Source : Endpoints.cs
with MIT License
from la-yumba
with MIT License
from la-yumba
public static void ConfigureMakeTransferEndpoint
(
this WebApplication app,
Func<MakeTransfer, Validation<MakeTransfer>> validate,
Func<Guid, Option<AccountState>> getAccount,
Action<Event> saveAndPublish
)
=> app.MapPost("/Transfer/Make", (Func<MakeTransfer, IResult>)((MakeTransfer transfer)
=> validate(transfer)
.Bind(t => getAccount(t.DebitedAccountId)
.ToValidation($"No account found for {t.DebitedAccountId}"))
.Bind(acc => acc.Debit(transfer))
.Do(result => saveAndPublish(result.Event))
.Match(
Invalid: errs => BadRequest(new { Errors = errs }),
Valid: result => Ok(new { result.NewState.Balance }))));
19
Source : MakeTransferEndpoint.cs
with MIT License
from la-yumba
with MIT License
from la-yumba
public static void ConfigureMakeTransferEndpoint
(
this WebApplication app,
Validator<MakeTransfer> validate,
Func<Guid, Task<Option<AccountState>>> getAccount,
Func<Event, Task> saveAndPublish
)
{
var getAccountVal = (Guid id) => getAccount(id)
.Map(opt => opt.ToValidation(Errors.UnknownAccountId(id)));
var saveAndPublishF = async (Event e) =>
{
await saveAndPublish(e);
return Unit();
};
app.MapPost("/Transfer/Make", (Func<MakeTransfer, Task<IResult>>)((MakeTransfer transfer) =>
{
Task<Validation<AccountState>> outcome =
from tr in Async(validate(transfer))
from acc in getAccountVal(tr.DebitedAccountId)
from result in Async(Account.Debit(acc, tr))
from _ in saveAndPublish.ToFunc()(result.Event).Map(Valid)
select result.NewState;
return outcome.Map(
Faulted: ex => StatusCode(StatusCodes.Status500InternalServerError),
Completed: val => val.Match(
Invalid: errs => BadRequest(new { Errors = errs }),
Valid: newState => Ok(new { Balance = newState.Balance })));
}));
}
19
Source : MakeTransferEndpoint.cs
with MIT License
from la-yumba
with MIT License
from la-yumba
public Task<IActionResult> MakeTransfer([FromBody] MakeTransfer command)
{
Task<Validation<AccountState>> outcome =
from cmd in Async(Validate(command))
from acc in GetAccount(cmd.DebitedAccountId)
from result in acc.Handle(cmd)
select result.NewState;
return outcome.Map(
Faulted: ex => StatusCode(500, Errors.UnexpectedError),
Completed: val => val.Match(
Invalid: errs => BadRequest(new { Errors = errs }),
Valid: newState => Ok(new { Balance = newState.Balance }) as IActionResult));
}
19
Source : MenuController.cs
with MIT License
from lampo1024
with MIT License
from lampo1024
public static List<MenuTree> BuildTree(this List<MenuTree> menus, string selectedGuid = null)
{
var lookup = menus.ToLookup(x => x.ParentGuid);
Func<Guid?, List<MenuTree>> build = null;
build = pid =>
{
return lookup[pid]
.Select(x => new MenuTree()
{
Guid = x.Guid,
ParentGuid = x.ParentGuid,
replacedle = x.replacedle,
Expand = (x.ParentGuid == null || x.ParentGuid == Guid.Empty),
Selected = selectedGuid == x.Guid,
Children = build(new Guid(x.Guid)),
})
.ToList();
};
var result = build(null);
return result;
}
19
Source : FileCacheManager.cs
with GNU General Public License v2.0
from lfz233002072
with GNU General Public License v2.0
from lfz233002072
public TResult Get(Guid key, Func<Guid, TResult> func, Func<Guid, TResult, bool> hasChanged = null)
{
TResult result = null;
var changeList = new List<ChangeMonitor>();
string cachefile = null;
//直接从缓存中获取数据
bool isFromFile = false;
result = _cacheManager.Get<Guid, TResult>(key);
if (result == null)
{
cachefile = GetCacheFile(key);
if (File.Exists(cachefile))
{
result = _cacheSerializater.Load<TResult>(cachefile);
isFromFile = true;
}
}
if (result != null && hasChanged != null && hasChanged(key, result))
{
//如果数据已经发生变化(比如直接修改数据库、或其他服务程序更新)
result = null;
}
if (result != null)
{
if (!isFromFile)
_cacheManager.Set(key, result, _defaultCacheTime, changeList);
return result;
}
//如果文件中加载的数据无效,那么重新从数据库中获取数据
result = func(key);
if (result == null) return null;
cachefile = cachefile ?? GetCacheFile(key);
if (_cacheSerializater.Save(result, cachefile))
changeList.Add(new HostFileChangeMonitor(new List<string>() { cachefile }));
//设置缓存值
_cacheManager.Set(key, result, _defaultCacheTime, changeList);
return result;
}
19
Source : SpeechCommandBase.cs
with MIT License
from msimecek
with MIT License
from msimecek
protected static int WaitForProcessing(Guid id, Func<Guid, object> probe)
{
_console.Write("Processing [.");
var done = false;
while (!done)
{
_console.Write(".");
Thread.Sleep(1000);
var resource = probe.Invoke(id);
if (resource is Enreplacedy)
{
if ((resource as Enreplacedy).Status == Constants.FAILED_STATUS)
{
_console.WriteLine(".]");
_console.Error.WriteLine("Processing failed.");
return -1;
}
done = (resource as Enreplacedy).Status == Constants.SUCCEEDED_STATUS;
}
else
{
// přišel ErrorResult nebo něco jiného
_console.Error.WriteLine("Unable to get status. " + (resource as ErrorContent).Message);
return -1;
}
}
_console.WriteLine(".] Done");
_console.WriteLine(id.ToString());
return 0;
}
19
Source : CachedTenantRepositoryDecorator.cs
with MIT License
from osstotalsoft
with MIT License
from osstotalsoft
public async Task<Tenant> Get(Guid id, CancellationToken token)
{
var cacheKey = CacheTenantByIdKey(id);
var cachedTenant = await GetTenantFromCache(cacheKey, token);
if (cachedTenant != null)
{
return cachedTenant;
}
var dbTenant = await _tenantRepository.Get(id, token);
if (dbTenant == null)
{
return null;
}
await SetTenantToCache(dbTenant, cacheKey, token);
return dbTenant;
}
19
Source : ClassifiedAdUpcasters.cs
with MIT License
from PacktPublishing
with MIT License
from PacktPublishing
public async Task Project(object @event)
{
switch (@event)
{
case ClreplacedifiedAdPublished e:
var photoUrl = await _getUserPhoto(e.OwnerId);
var newEvent = new V1.ClreplacedifiedAdPublished
{
Id = e.Id,
OwnerId = e.OwnerId,
ApprovedBy = e.ApprovedBy,
SellersPhotoUrl = photoUrl
};
await _eventStoreConnection.AppendEvents(
StreamName,
ExpectedVersion.Any,
newEvent);
break;
}
}
19
Source : ClassifiedAdDetailsProjection.cs
with MIT License
from PacktPublishing
with MIT License
from PacktPublishing
public Task Project(object @event)
{
switch (@event)
{
case ClreplacedifiedAdCreated e:
_items.Add(
new ClreplacedifiedAdDetails
{
ClreplacedifiedAdId = e.Id,
SellerId = e.OwnerId,
SellersDisplayName =
_getUserDisplayName(e.OwnerId)
}
);
break;
case ClreplacedifiedAdreplacedleChanged e:
UpdateItem(e.Id, ad => ad.replacedle = e.replacedle);
break;
case ClreplacedifiedAdTextUpdated e:
UpdateItem(e.Id, ad => ad.Description = e.AdText);
break;
case ClreplacedifiedAdPriceUpdated e:
UpdateItem(
e.Id, ad =>
{
ad.Price = e.Price;
ad.CurrencyCode = e.CurrencyCode;
}
);
break;
case UserDisplayNameUpdated e:
UpdateMultipleItems(
x => x.SellerId == e.UserId,
x => x.SellersDisplayName = e.DisplayName
);
break;
case V1.ClreplacedifiedAdPublished e:
UpdateItem(e.Id, ad => ad.SellersPhotoUrl = e.SellersPhotoUrl);
break;
}
return Task.CompletedTask;
}
19
Source : ClassifiedAdUpcasters.cs
with MIT License
from PacktPublishing
with MIT License
from PacktPublishing
public async Task Project(object @event)
{
switch (@event)
{
case ClreplacedifiedAdPublished e:
var photoUrl = _getUserPhoto(e.OwnerId);
var newEvent = new V1.ClreplacedifiedAdPublished
{
Id = e.Id,
OwnerId = e.OwnerId,
ApprovedBy = e.ApprovedBy,
SellersPhotoUrl = photoUrl
};
await _eventStoreConnection.AppendEvents(
StreamName,
ExpectedVersion.Any,
newEvent);
break;
}
}
19
Source : MyClassifiedAdsProjection.cs
with MIT License
from PacktPublishing
with MIT License
from PacktPublishing
public static Func<Task> GetHandler(
IAsyncDoreplacedentSession session,
object @event)
{
Func<Guid, string> getDbId = MyClreplacedifiedAds.GetDatabaseId;
return @event switch
{
V1.ClreplacedifiedAdCreated e =>
() => CreateOrUpdate(e.OwnerId,
myAds => myAds.MyAds.Add(
new MyClreplacedifiedAds.MyAd {Id = e.Id}
),
() => new MyClreplacedifiedAds
{
Id = getDbId(e.OwnerId),
MyAds = new List<MyClreplacedifiedAds.MyAd>()
}),
V1.ClreplacedifiedAdreplacedleChanged e =>
() => UpdateOneAd(e.OwnerId, e.Id,
myAd => myAd.replacedle = e.replacedle),
V1.ClreplacedifiedAdTextUpdated e =>
() => UpdateOneAd(e.OwnerId, e.Id,
myAd => myAd.Description = e.AdText),
V1.ClreplacedifiedAdPriceUpdated e =>
() => UpdateOneAd(e.OwnerId, e.Id,
myAd => myAd.Price = e.Price),
V1.PictureAddedToAClreplacedifiedAd e =>
() => UpdateOneAd(e.OwnerId, e.ClreplacedifiedAdId,
myAd => myAd.PhotoUrls.Add(e.Url)),
V1.ClreplacedifiedAdDeleted e =>
() => Update(e.OwnerId,
myAd => myAd.MyAds
.RemoveAll(x => x.Id == e.Id)),
_ => (Func<Task>) null
};
19
Source : BaseHostStub.cs
with Mozilla Public License 2.0
from SafeExamBrowser
with Mozilla Public License 2.0
from SafeExamBrowser
protected override bool OnConnect(Guid? token)
{
return OnConnectStub?.Invoke(token) == true;
}
19
Source : ObjectReferencePathGenerator.cs
with MIT License
from stride3d
with MIT License
from stride3d
protected override void VisitMemberNode([NotNull] IreplacedetMemberNode memberNode, int inNonIdentifiableType)
{
var value = memberNode.Retrieve();
if (propertyGraphDefinition.IsMemberTargetObjectReference(memberNode, value))
{
if (value == null)
return;
var identifiable = value as IIdentifiable;
if (identifiable == null)
throw new InvalidOperationException("IsObjectReference returned true for an object that is not IIdentifiable");
var id = identifiable.Id;
if (ShouldOutputReference?.Invoke(id) ?? true)
Result.Set(ConvertPath(CurrentPath, inNonIdentifiableType), id);
}
}
See More Examples