Here are the examples of the csharp api System.Collections.Generic.IEnumerable.SingleOrDefault(System.Func) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
1727 Examples
19
Source : BitfinexSocketApi.cs
with MIT License
from aabiryukov
with MIT License
from aabiryukov
private void HandleSubscriptionEvent(BitfinexSubscriptionResponse subscription)
{
BitfinexEventRegistration pending;
lock(eventListLock)
pending = eventRegistrations.SingleOrDefault(r => r.ChannelName == subscription.ChannelName && !r.Confirmed);
if (pending == null) {
Log.Write(LogVerbosity.Warning, "Received registration confirmation but have nothing pending?");
return;
}
pending.ChannelId = subscription.ChannelId;
pending.Confirmed = true;
Log.Write(LogVerbosity.Info, $"Subscription confirmed for channel {subscription.ChannelName}, ID: {subscription.ChannelId}");
}
19
Source : BitfinexSocketApi.cs
with MIT License
from aabiryukov
with MIT License
from aabiryukov
private void HandleErrorEvent(BitfinexSocketError error)
{
Log.Write(LogVerbosity.Warning, $"Bitfinex socket error: {error.ErrorCode} - {error.ErrorMessage}");
BitfinexEventRegistration waitingRegistration;
lock (eventListLock)
waitingRegistration = eventRegistrations.SingleOrDefault(e => !e.Confirmed);
if (waitingRegistration != null)
waitingRegistration.Error = new BitfinexError(error.ErrorCode, error.ErrorMessage);
}
19
Source : BitfinexSocketApi.cs
with MIT License
from aabiryukov
with MIT License
from aabiryukov
private void HandleChannelEvent(JArray evnt)
{
var eventId = (int)evnt[0];
BitfinexEventRegistration registration;
lock (eventListLock)
registration = eventRegistrations.SingleOrDefault(s => s.ChannelId == eventId);
if(registration == null)
{
Log.Write(LogVerbosity.Warning, $"Received event but have no registration (eventId={eventId})");
return;
}
if (registration is BitfinexTradingPairTickerEventRegistration)
((BitfinexTradingPairTickerEventRegistration)registration).Handler(evnt[1].ToObject<BitfinexSocketTradingPairTick>());
if (registration is BitfinexFundingPairTickerEventRegistration)
((BitfinexFundingPairTickerEventRegistration)registration).Handler(evnt[1].ToObject<BitfinexSocketFundingPairTick>());
if (registration is BitfinexOrderBooksEventRegistration)
{
var evnt1 = evnt[1];
if (evnt1 is JArray)
{
BitfinexSocketOrderBook[] bookArray;
if (evnt1[0] is JArray)
{
bookArray = evnt1.ToObject<BitfinexSocketOrderBook[]>();
}
else
{
var book = evnt1.ToObject<BitfinexSocketOrderBook>();
bookArray = new BitfinexSocketOrderBook[] { book };
}
((BitfinexOrderBooksEventRegistration)registration).Handler(bookArray);
}
}
if (registration is BitfinexTradeEventRegistration)
{
if(evnt[1] is JArray)
((BitfinexTradeEventRegistration)registration).Handler(evnt[1].ToObject<BitfinexTradeSimple[]>());
else
((BitfinexTradeEventRegistration)registration).Handler(new[] { evnt[2].ToObject<BitfinexTradeSimple>() });
}
}
19
Source : ActivationSetting.cs
with MIT License
from ababik
with MIT License
from ababik
private static void Validate(ConstructorInfo constructor, ParameterInfo parameter, PropertyInfo property, PropertyInfo[] properties)
{
if (parameter.Member != constructor)
{
throw new Exception($"Invalid parameter '{parameter.Name}'. Parameter must be a member of '{constructor.DeclaringType}' constructor.");
}
if (properties.SingleOrDefault(x => CompareInstanceProperties(x, property)) is null)
{
throw new Exception($"Invalid property '{property.Name}'. Must be a member of '{constructor.DeclaringType}'.");
}
}
19
Source : InMemoryEventBusSubscriptionsManager.cs
with MIT License
from Abdulrhman5
with MIT License
from Abdulrhman5
private void DoRemoveHandler(string eventName, SubscriptionInfo subsToRemove)
{
if (subsToRemove != null)
{
_handlers[eventName].Remove(subsToRemove);
if (!_handlers[eventName].Any())
{
_handlers.Remove(eventName);
var eventType = _eventTypes.SingleOrDefault(e => e.Name == eventName);
if (eventType != null)
{
_eventTypes.Remove(eventType);
}
RaiseOnEventRemoved(eventName);
}
}
}
19
Source : InMemoryEventBusSubscriptionsManager.cs
with MIT License
from Abdulrhman5
with MIT License
from Abdulrhman5
private SubscriptionInfo DoFindSubscriptionToRemove(string eventName, Type handlerType)
{
if (!HreplacedubscriptionsForEvent(eventName))
{
return null;
}
return _handlers[eventName].SingleOrDefault(s => s.HandlerType == handlerType);
}
19
Source : InMemoryEventBusSubscriptionsManager.cs
with MIT License
from Abdulrhman5
with MIT License
from Abdulrhman5
public Type GetEventTypeByName(string eventName) => _eventTypes.SingleOrDefault(t => t.Name == eventName);
19
Source : HtmlExportHelper.cs
with MIT License
from ABTSoftware
with MIT License
from ABTSoftware
private static void ExportIndexToHtml(IModule module)
{
var replacedembly = typeof(HtmlExportHelper).replacedembly;
string[] names = replacedembly.GetManifestResourceNames();
var templateFile = names.SingleOrDefault(x => x.Contains(IndexTemplateFileName));
using (var s = replacedembly.GetManifestResourceStream(templateFile))
using (var sr = new StreamReader(s))
{
string lines = sr.ReadToEnd();
StringBuilder sb = new StringBuilder();
foreach (var categoryGroup in module.Examples.Values.GroupBy(x => x.TopLevelCategory))
{
sb.Append("<h2>").Append(categoryGroup.Key).Append("</h2>").Append(Environment.NewLine);
foreach (var exampleGroup in categoryGroup.GroupBy(x => x.Group))
{
sb.Append("<h4>").Append(exampleGroup.Key).Append("</h4>").Append(Environment.NewLine);
sb.Append("<ul>").Append(Environment.NewLine);
foreach (var example in exampleGroup)
{
var fileName = string.Format("wpf-{0}chart-example-{1}",
example.TopLevelCategory.ToUpper().Contains("3D") || example.replacedle.ToUpper().Contains("3D") ? "3d-" : string.Empty,
example.replacedle.ToLower().Replace(" ", "-"));
sb.Append("<li>").Append("<a href=\"").Append(fileName).Append("\">").Append(example.replacedle).Append("</a></li>");
}
sb.Append("</ul>").Append(Environment.NewLine);
}
}
lines = lines.Replace("[Index]", sb.ToString());
File.WriteAllText(Path.Combine(ExportPath, "wpf-chart-examples.html"), lines);
}
}
19
Source : HtmlExportHelper.cs
with MIT License
from ABTSoftware
with MIT License
from ABTSoftware
public static void ExportExampleToHtml(Example example, bool isUniqueExport = true)
{
if (isUniqueExport)
{
if (!GetPathForExport())
{
MessageBox.Show("Bad path. Please, try export once more.");
return;
}
}
var replacedembly = typeof (HtmlExportHelper).replacedembly;
string[] names = replacedembly.GetManifestResourceNames();
var templateFile = names.SingleOrDefault(x => x.Contains(TemplateFileName));
using (var s = replacedembly.GetManifestResourceStream(templateFile))
using (var sr = new StreamReader(s))
{
string lines = sr.ReadToEnd();
var exampleFolderPath = ExportPath;//string.Format("{0}{1}\\", ExportPath, example.replacedle);
//CreateExampleFolder(exampleFolderPath);
PrintMainWindow("scichart-wpf-chart-example-" + example.replacedle.ToLower().Replace(" ", "-"), exampleFolderPath);
lines = ReplaceTagsWithExample(lines, example);
var fileName = string.Format("wpf-{0}chart-example-{1}.html",
example.TopLevelCategory.ToUpper().Contains("3D") || example.replacedle.ToUpper().Contains("3D") ? "3d-" : string.Empty,
example.replacedle.ToLower().Replace(" ", "-"));
File.WriteAllText(Path.Combine(ExportPath, fileName), lines);
}
}
19
Source : MainViewModel.cs
with MIT License
from ABTSoftware
with MIT License
from ABTSoftware
public void RunNextTest()
{
if (_testQueue.Count == 0)
return;
var testCase = _testQueue.Dequeue();
LayoutRoot.Children.Add(testCase.SpeedTestUi);
testCase.Run((result) =>
{
LayoutRoot.Children.Remove(testCase.SpeedTestUi);
// log the test run
_testRuns.Add(string.Format("({0:N2}) - {1} - {2}", result, testCase.TestCaseName, testCase.Version));
// add results to the table
var testResult = _testResults.SingleOrDefault(i => i.TestName == testCase.TestCaseName);
if (testResult == null)
{
testResult = new TestResult()
{
TestName = testCase.TestCaseName
};
_testResults.Add(testResult);
}
testResult[testCase.Version] = result;
string strPrefix = "LC";
if (_iTestResult % 2 == 0)
{
strPrefix = "SC";
}
else
{
strPrefix = "LC";
}
//Write to log
WriteLog(testCase.TestCaseName + ";" + result.ToString("0.0") + ";", System.AppDomain.CurrentDomain.BaseDirectory + "\\"+strPrefix+"_PerformanceComparisonDump.csv");
_iTestResult++;
// start the next test
TestFinished(testCase, result);
});
}
19
Source : ShellUpgradeTask.cs
with MIT License
from Accelerider
with MIT License
from Accelerider
protected override async void OnDownloadCompleted(UpgradeInfo info)
{
base.OnDownloadCompleted(info);
if (info.Version <= CurrentVersion) return;
var launcherPath = Directory
.GetFiles(GetInstallPath(info.Version))
.SingleOrDefault(item => Path.GetFileName(item) == ProcessController.LauncherName);
if (!string.IsNullOrEmpty(launcherPath))
{
try
{
if (File.Exists(ProcessController.LauncherPath))
{
File.Delete(ProcessController.LauncherPath);
}
File.Move(launcherPath, ProcessController.LauncherPath);
}
catch (Exception e)
{
Logger.Error($"[MOVE FILE] Move the {ProcessController.LauncherName} file failed. ", e);
}
}
await ShowUpgradeNotificationDialogAsync(info);
}
19
Source : NetworkManager.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from ACEmulator
public static Session FindOrCreateSession(ConnectionListener connectionListener, IPEndPoint endPoint)
{
Session session;
sessionLock.EnterUpgradeableReadLock();
try
{
session = sessionMap.SingleOrDefault(s => s != null && endPoint.Equals(s.EndPoint));
if (session == null)
{
sessionLock.EnterWriteLock();
try
{
for (ushort i = 0; i < sessionMap.Length; i++)
{
if (sessionMap[i] == null)
{
log.DebugFormat("Creating new session for {0} with id {1}", endPoint, i);
session = new Session(connectionListener, endPoint, i, ServerId);
sessionMap[i] = session;
break;
}
}
}
finally
{
sessionLock.ExitWriteLock();
}
}
}
finally
{
sessionLock.ExitUpgradeableReadLock();
}
return session;
}
19
Source : NetworkManager.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from ACEmulator
public static Session Find(uint accountId)
{
sessionLock.EnterReadLock();
try
{
return sessionMap.SingleOrDefault(s => s != null && s.AccountId == accountId);
}
finally
{
sessionLock.ExitReadLock();
}
}
19
Source : NetworkManager.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from ACEmulator
public static Session Find(string account)
{
sessionLock.EnterReadLock();
try
{
return sessionMap.SingleOrDefault(s => s != null && s.Account == account);
}
finally
{
sessionLock.ExitReadLock();
}
}
19
Source : ServiceInterfacesL0.cs
with MIT License
from actions
with MIT License
from actions
private static void Validate(replacedembly replacedembly, params Type[] whitelist)
{
// Iterate over all non-whitelisted interfaces contained within the replacedembly.
IDictionary<TypeInfo, Type> w = whitelist.ToDictionary(x => x.GetTypeInfo());
foreach (TypeInfo interfaceTypeInfo in replacedembly.DefinedTypes.Where(x => x.IsInterface && !w.ContainsKey(x)))
{
// Temporary hack due to shared code copied in two places.
if (interfaceTypeInfo.FullName.StartsWith("GitHub.DistributedTask"))
{
continue;
}
if (interfaceTypeInfo.FullName.Contains("IConverter"))
{
continue;
}
// replacedert the ServiceLocatorAttribute is defined on the interface.
CustomAttributeData attribute =
interfaceTypeInfo
.CustomAttributes
.SingleOrDefault(x => x.AttributeType == typeof(ServiceLocatorAttribute));
replacedert.True(attribute != null, $"Missing {nameof(ServiceLocatorAttribute)} for interface '{interfaceTypeInfo.FullName}'. Add the attribute to the interface or whitelist the interface in the test.");
// replacedert the interface is mapped to a concrete type.
CustomAttributeNamedArgument defaultArg =
attribute
.NamedArguments
.SingleOrDefault(x => String.Equals(x.MemberName, ServiceLocatorAttribute.DefaultPropertyName, StringComparison.Ordinal));
Type concreteType = defaultArg.TypedValue.Value as Type;
string invalidConcreteTypeMessage = $"Invalid Default parameter on {nameof(ServiceLocatorAttribute)} for the interface '{interfaceTypeInfo.FullName}'. The default implementation must not be null, must not be an interface, must be a clreplaced, and must implement the interface '{interfaceTypeInfo.FullName}'.";
replacedert.True(concreteType != null, invalidConcreteTypeMessage);
TypeInfo concreteTypeInfo = concreteType.GetTypeInfo();
replacedert.False(concreteTypeInfo.IsInterface, invalidConcreteTypeMessage);
replacedert.True(concreteTypeInfo.IsClreplaced, invalidConcreteTypeMessage);
replacedert.True(concreteTypeInfo.ImplementedInterfaces.Any(x => x.GetTypeInfo() == interfaceTypeInfo), invalidConcreteTypeMessage);
}
}
19
Source : Parser.cs
with MIT License
from adamant
with MIT License
from adamant
private static string? GetConfig(IEnumerable<string> lines, string config)
{
var start = Program.DirectiveMarker + config;
var line = lines.SingleOrDefault(l => l.StartsWith(start, StringComparison.InvariantCulture));
line = line?.Substring(start.Length);
line = line?.TrimEnd(';'); // TODO error if no semicolon
line = line?.Trim();
return line;
}
19
Source : Extensions.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
private static IEnumerable<Enreplacedy> ToChangedRelationship(IEnumerable<Enreplacedy> enreplacedies, EnreplacedyCollection collection)
{
foreach (var enreplacedy in enreplacedies)
{
var snapshot = collection != null
? collection.Enreplacedies.SingleOrDefault(e => Equals(e.ToEnreplacedyReference(), enreplacedy.ToEnreplacedyReference()))
: null;
var result = ToChangedEnreplacedy(enreplacedy, snapshot);
if (result != null)
{
yield return result;
}
}
}
19
Source : Extensions.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
private static IEnumerable<Enreplacedy> ToRemovedRelationship(EnreplacedyCollection collection, IEnumerable<Enreplacedy> enreplacedies)
{
foreach (var snapshot in enreplacedies)
{
var enreplacedy = collection != null
? collection.Enreplacedies.SingleOrDefault(e => Equals(e.ToEnreplacedyReference(), snapshot.ToEnreplacedyReference()))
: null;
var result = ToRemovedEnreplacedy(enreplacedy, snapshot);
if (result != null)
{
yield return result;
}
}
}
19
Source : StyleExtensions.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
private void Add(Tuple<string, string, int> fileName, string[] fileNameParts, ICollection<Node> nodes)
{
if (!fileNameParts.Any())
{
nodes.Add(new Node(TerminalNodeKey, fileName));
return;
}
var currentPart = fileNameParts.First();
var matchingNode = nodes.SingleOrDefault(node => string.Equals(node.Key, currentPart, StringComparison.OrdinalIgnoreCase));
if (matchingNode == null)
{
var newNode = new Node(currentPart);
nodes.Add(newNode);
Add(fileName, fileNameParts.Skip(1).ToArray(), newNode.Children);
}
else
{
Add(fileName, fileNameParts.Skip(1).ToArray(), matchingNode.Children);
}
}
19
Source : CellMetadata.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
private void ExtractMetadata()
{
if (AttributeMetadata.GetType() == typeof(BigIntAttributeMetadata))
{
var metadata = AttributeMetadata as BigIntAttributeMetadata;
MaxValue = metadata.MaxValue;
MinValue = metadata.MinValue;
}
else if (AttributeMetadata.GetType() == typeof(DateTimeAttributeMetadata))
{
var metadata = AttributeMetadata as DateTimeAttributeMetadata;
Format = metadata.Format.HasValue
? Enum.GetName(typeof(DateTimeFormat), metadata.Format.Value)
: null;
}
else if (AttributeMetadata.GetType() == typeof(DecimalAttributeMetadata))
{
var metadata = AttributeMetadata as DecimalAttributeMetadata;
MaxValue = metadata.MaxValue;
MinValue = metadata.MinValue;
}
else if (AttributeMetadata.GetType() == typeof(DoubleAttributeMetadata))
{
var metadata = AttributeMetadata as DoubleAttributeMetadata;
MaxValue = (decimal)metadata.MaxValue;
MinValue = (decimal)metadata.MinValue;
}
else if (AttributeMetadata.GetType() == typeof(IntegerAttributeMetadata))
{
var metadata = AttributeMetadata as IntegerAttributeMetadata;
Format = metadata.Format.HasValue
? Enum.GetName(typeof(IntegerFormat), metadata.Format.Value)
: null;
MaxValue = metadata.MaxValue;
MinValue = metadata.MinValue;
}
else if (AttributeMetadata.GetType() == typeof(MemoAttributeMetadata))
{
var metadata = AttributeMetadata as MemoAttributeMetadata;
Format = metadata.Format.HasValue
? Enum.GetName(typeof(StringFormat), metadata.Format.Value)
: null;
}
else if (AttributeMetadata.GetType() == typeof(MoneyAttributeMetadata))
{
var metadata = AttributeMetadata as MoneyAttributeMetadata;
MaxValue = (decimal)metadata.MaxValue;
MinValue = (decimal)metadata.MinValue;
}
else if (AttributeMetadata.GetType() == typeof(StringAttributeMetadata))
{
var metadata = AttributeMetadata as StringAttributeMetadata;
Format = metadata.Format.HasValue
? Enum.GetName(typeof(StringFormat), metadata.Format.Value)
: null;
}
var localiazedDescription = AttributeMetadata.Description.LocalizedLabels.SingleOrDefault(label => label.LanguageCode == LanguageCode);
if (localiazedDescription != null)
{
ToolTip = localiazedDescription.Label;
}
}
19
Source : ManageController.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
private async Task<LoginPair> ToExternalAuthenticationTypes(int id, IList<UserLoginInfo> userLogins, AuthenticationDescription p, CancellationToken cancellationToken)
{
var loginProvider = await ToLoginProvider(p.AuthenticationType, cancellationToken);
var user = userLogins.SingleOrDefault(u => u.LoginProvider == loginProvider);
var authenticationType = user == null ? p.AuthenticationType : loginProvider;
var properties = new Dictionary<string, object>(p.Properties, StringComparer.Ordinal);
var provider = new AuthenticationDescription(properties) { AuthenticationType = authenticationType };
return new LoginPair
{
Id = id,
Provider = provider,
User = user
};
}
19
Source : Extensions.cs
with MIT License
from AElfProject
with MIT License
from AElfProject
public static Type FindContractType(this replacedembly replacedembly)
{
var types = replacedembly.GetTypes();
return types.SingleOrDefault(t => typeof(ISmartContract).IsreplacedignableFrom(t) && !t.IsNested);
}
19
Source : Extensions.cs
with MIT License
from AElfProject
with MIT License
from AElfProject
public static Type FindContractBaseType(this replacedembly replacedembly)
{
var types = replacedembly.GetTypes();
return types.SingleOrDefault(t => typeof(ISmartContract).IsreplacedignableFrom(t) && t.IsNested);
}
19
Source : Extensions.cs
with MIT License
from AElfProject
with MIT License
from AElfProject
public static Type FindExecutionObserverProxyType(this replacedembly replacedembly)
{
return replacedembly.GetTypes().SingleOrDefault(t => t.Name == nameof(ExecutionObserverProxy));
}
19
Source : MultiTokenContractReferenceFeeTest.cs
with MIT License
from AElfProject
with MIT License
from AElfProject
private CalculateFeePieceCoefficients GetCalculateFeePieceCoefficients(
IEnumerable<CalculateFeePieceCoefficients> calculateFeePieceCoefficients, int pieceUpperBound)
{
return calculateFeePieceCoefficients.SingleOrDefault(c => c.Value[0] == pieceUpperBound);
}
19
Source : UserOnlyStore.cs
with Apache License 2.0
from Aguafrommars
with Apache License 2.0
from Aguafrommars
public async override Task RemoveClaimsAsync(TUser user, IEnumerable<Claim> claims, CancellationToken cancellationToken = default)
{
ThrowIfDisposed();
replacedertNotNull(user, nameof(user));
replacedertNotNull(claims, nameof(claims));
Dictionary<string, TUserClaim> data;
try
{
var response = await _client.GetAsync<Dictionary<string, TUserClaim>>(GetFirebasePath(UserClaimsTableName), cancellationToken, false, $"orderBy=\"UserId\"&equalTo=\"{user.Id}\"")
.ConfigureAwait(false);
data = response.Data;
}
catch (FirebaseException e)
when (e.FirebaseError != null && e.FirebaseError.Error.StartsWith("Index"))
{
await SetIndex(UserClaimsTableName, new UserClaimIndex(), cancellationToken)
.ConfigureAwait(false);
var response = await _client.GetAsync<Dictionary<string, TUserClaim>>(GetFirebasePath(UserClaimsTableName), cancellationToken, queryString: $"orderBy=\"UserId\"&equalTo=\"{user.Id}\"")
.ConfigureAwait(false);
data = response.Data;
}
if (data != null)
{
var taskList = new List<Task>(claims.Count());
foreach (var claim in claims)
{
var match = data.SingleOrDefault(kv => kv.Value.ClaimType == claim.Type && kv.Value.ClaimValue == claim.Value);
if (match.Key != null)
{
taskList.Add(_client.DeleteAsync(GetFirebasePath(UserClaimsTableName, match.Key), cancellationToken));
}
}
await Task.WhenAll(taskList.ToArray())
.ConfigureAwait(false);
}
}
19
Source : UserStore.cs
with Apache License 2.0
from Aguafrommars
with Apache License 2.0
from Aguafrommars
protected override async Task<TUserRole> FindUserRoleAsync(string userId, string roleId, CancellationToken cancellationToken)
{
var userRoles = await GetUserRolesAsync(userId)
.ConfigureAwait(false);
return userRoles.SingleOrDefault(r => r.RoleId.Equals(ConvertIdFromString(roleId)));
}
19
Source : UserStore.cs
with Apache License 2.0
from Aguafrommars
with Apache License 2.0
from Aguafrommars
protected override async Task<IdenreplacedyUserRole<string>> FindUserRoleAsync(string userId, string roleId, CancellationToken cancellationToken)
{
var userRoles = await GetUserRolesAsync(userId, cancellationToken)
.ConfigureAwait(false);
return userRoles.SingleOrDefault(r => r.RoleId.Equals(ConvertIdFromString(roleId)));
}
19
Source : BillsViewModel.cs
with MIT License
from ahmed-abdelrazek
with MIT License
from ahmed-abdelrazek
private void DoSearch()
{
try
{
if (ByItem)
{
if (ByName)
{
SearchItems = new ObservableCollection<object>(Items.Where(i => i.Group == ItemGroup.Other && i.Name.Contains(SearchText)));
if (SearchItems.Count > 0)
{
IsSearchDropDownOpen = true;
}
else
{
SearchSelectedValue = 0;
MessageBox.MaterialMessageBox.ShowWarning("لم يستطع ايجاد صنف بهذا الاسم", "غير موجود", true);
}
}
else if (ByBarCode)
{
SearchItems = new ObservableCollection<object>(Items.Where(i => i.Group == ItemGroup.Other && i.Barcode == SearchText));
if (SearchItems.Count > 0)
{
SearchSelectedValue = Items.SingleOrDefault(i => i.Group == ItemGroup.Other && i.Barcode == SearchText).Id;
IsSearchDropDownOpen = true;
}
else
{
SearchSelectedValue = 0;
MessageBox.MaterialMessageBox.ShowWarning("لم يستطع ايجاد صنف بهذا الباركود", "غير موجود", true);
}
}
else
{
SearchItems = new ObservableCollection<object>(Items.Where(i => i.Group == ItemGroup.Other && i.Shopcode == SearchText));
if (SearchItems.Count > 0)
{
SearchSelectedValue = Items.SingleOrDefault(i => i.Group == ItemGroup.Other && i.Shopcode == SearchText).Id;
IsSearchDropDownOpen = true;
}
else
{
SearchSelectedValue = 0;
MessageBox.MaterialMessageBox.ShowWarning("لم يستطع ايجاد صنف بكود المحل هذا", "غير موجود", true);
}
}
}
else if (ByCard)
{
if (ByName)
{
SearchItems = new ObservableCollection<object>(Items.Where(i => i.Group == ItemGroup.Card && i.Name.Contains(SearchText)));
if (SearchItems.Count > 0)
{
IsSearchDropDownOpen = true;
}
else
{
SearchSelectedValue = 0;
MessageBox.MaterialMessageBox.ShowWarning("لم يستطع ايجاد كارت شحن بهذا الاسم", "غير موجود", true);
}
}
else if (ByBarCode)
{
SearchItems = new ObservableCollection<object>(Items.Where(i => i.Group == ItemGroup.Card && i.Barcode == SearchText));
if (SearchItems.Count > 0)
{
SearchSelectedValue = Items.SingleOrDefault(i => i.Group == ItemGroup.Card && i.Barcode == SearchText).Id;
IsSearchDropDownOpen = true;
}
else
{
SearchSelectedValue = 0;
MessageBox.MaterialMessageBox.ShowWarning("لم يستطع ايجاد كارت شحن بهذا الباركود", "غير موجود", true);
}
}
else
{
SearchItems = new ObservableCollection<object>(Items.Where(i => i.Group == ItemGroup.Card && i.Shopcode == SearchText));
if (SearchItems.Count > 0)
{
SearchSelectedValue = Items.SingleOrDefault(i => i.Group == ItemGroup.Card && i.Shopcode == SearchText).Id;
IsSearchDropDownOpen = true;
}
else
{
SearchSelectedValue = 0;
MessageBox.MaterialMessageBox.ShowWarning("لم يستطع ايجاد كارت شحن بكود المحل هذا", "غير موجود", true);
}
}
}
else
{
SearchItems = new ObservableCollection<object>(Services.Where(s => s.Name.Contains(SearchText)));
if (SearchItems.Count > 0)
{
IsSearchDropDownOpen = true;
}
else
{
SearchSelectedValue = 0;
MessageBox.MaterialMessageBox.ShowWarning("لم يستطع ايجاد خدمه بهذا الاسم", "غير موجود", true);
}
}
}
catch (Exception ex)
{
SearchSelectedValue = 0;
Core.SaveException(ex);
}
}
19
Source : ThirdPartyController.cs
with MIT License
from AiursoftWeb
with MIT License
from AiursoftWeb
[Route("sign-in/{providerName}")]
public async Task<IActionResult> SignIn(SignInAddressModel model)
{
var provider = _authProviders.SingleOrDefault(t => t.GetName().ToLower() == model.ProviderName.ToLower());
if (provider == null)
{
return NotFound();
}
var oauthModel = model.BuildOAuthInfo();
IUserDetail info;
try
{
info = await provider.GetUserDetail(model.Code);
}
catch (AiurAPIModelException)
{
var refreshLink = provider.GetSignInRedirectLink(new AiurUrl("", new FinishAuthInfo
{
AppId = oauthModel.AppId,
RedirectUri = oauthModel.RedirectUri,
State = oauthModel.State,
}));
return Redirect(refreshLink);
}
var account = await _dbContext
.ThirdPartyAccounts
.Include(t => t.Owner)
.ThenInclude(t => t.Emails)
.Where(t => t.Owner != null)
.Where(t => t.OpenId != null)
.FirstOrDefaultAsync(t => t.OpenId == info.Id);
var app = (await _apiService.AppInfoAsync(oauthModel.AppId)).App;
if (account != null)
{
await _authLogger.LogAuthRecord(account.OwnerId, HttpContext, true, app.AppId);
await _signInManager.SignInAsync(account.Owner, true);
return await _authManager.FinishAuth(account.Owner, oauthModel, app.ForceConfirmation, app.TrustedApp);
}
var viewModel = new SignInViewModel
{
RedirectUri = oauthModel.RedirectUri,
State = oauthModel.State,
AppId = oauthModel.AppId,
UserDetail = info,
ProviderName = model.ProviderName,
AppImageUrl = app.IconPath,
CanFindAnAccountWithEmail = await _dbContext.UserEmails.AnyAsync(t => t.EmailAddress.ToLower() == info.Email.ToLower()),
Provider = provider
};
return View(viewModel);
}
19
Source : ThirdPartyController.cs
with MIT License
from AiursoftWeb
with MIT License
from AiursoftWeb
[Authorize]
[Route("bind-account/{providerName}")]
public async Task<IActionResult> BindAccount(BindAccountAddressModel model)
{
var user = await GetCurrentUserAsync();
if (user.ThirdPartyAccounts.Any(t => t.ProviderName == model.ProviderName))
{
var toDelete = await _dbContext.ThirdPartyAccounts
.Where(t => t.OwnerId == user.Id)
.Where(t => t.ProviderName == model.ProviderName)
.ToListAsync();
_dbContext.ThirdPartyAccounts.RemoveRange(toDelete);
await _dbContext.SaveChangesAsync();
}
var provider = _authProviders.SingleOrDefault(t => t.GetName().ToLower() == model.ProviderName.ToLower());
if (provider == null)
{
return NotFound();
}
IUserDetail info;
try
{
info = await provider.GetUserDetail(model.Code, true);
}
catch (AiurAPIModelException)
{
var refreshLink = provider.GetBindRedirectLink();
return Redirect(refreshLink);
}
if (await _dbContext.ThirdPartyAccounts.AnyAsync(t => t.OpenId == info.Id))
{
// The third-party account already bind an account.
return View(viewName: "BindFailed", model: new BindAccountViewModel
{
UserDetail = info,
Provider = provider,
User = user
});
}
var link = new ThirdPartyAccount
{
OwnerId = user.Id,
OpenId = info.Id,
ProviderName = provider.GetName(),
Name = info.Name
};
await _dbContext.ThirdPartyAccounts.AddAsync(link);
await _dbContext.SaveChangesAsync();
// Complete
var viewModel = new BindAccountViewModel
{
UserDetail = info,
Provider = provider,
User = user
};
return View(viewModel);
}
19
Source : EventSyncer.cs
with MIT License
from AiursoftWeb
with MIT License
from AiursoftWeb
private void PatchFriendRequest(Request request)
{
if (request.TargetId == BuildBot.Profile.Id)
{
// Sent to me from another user.
var inMemory = _requests.SingleOrDefault(t => t.Id == request.Id);
if (inMemory == null)
{
_requests.Add(request);
}
else
{
_requests.Remove(inMemory);
_requests.Add(request);
}
}
}
19
Source : EventSyncer.cs
with MIT License
from AiursoftWeb
with MIT License
from AiursoftWeb
private async Task InsertNewMessage(int conversationId, Message message, string previousMessageId)
{
var conversation = _contacts.SingleOrDefault(t => t.ConversationId == conversationId);
if (conversation == null)
{
_botLogger.LogDanger($"Comming new message from unknown conversation: '{conversationId}' but we can't find it in memory.");
return;
}
if (Guid.Parse(previousMessageId) != Guid.Empty) // On server, has previous message.)
{
if (conversation.LatestMessage.Id != Guid.Parse(previousMessageId) || // Local latest message is not latest.
conversation.Messages.All(t => t.Id != Guid.Parse(previousMessageId))) // Server side previous message do not exists locally.
{
// Some message was lost.
_botLogger.LogWarning("Some message was lost. Trying to sync...");
var missedMessages = await _conversationService.GetMessagesAsync(conversationId, 15, message.Id.ToString());
foreach (var missedMessage in missedMessages.Items)
{
if (!conversation.Messages.Any(t => t.Id == missedMessage.Id))
{
conversation.Messages.Add(missedMessage);
}
}
}
}
conversation.LatestMessage = message;
conversation.Messages.Add(message);
}
19
Source : GroupConversation.cs
with MIT License
from AiursoftWeb
with MIT License
from AiursoftWeb
public override int GetUnReadAmount(string userId)
{
var relation = Users.SingleOrDefault(t => t.UserId == userId);
if (relation == null)
{
return 0;
}
return Messages.Count(t => t.SendTime > relation.ReadTimeStamp);
}
19
Source : GroupConversation.cs
with MIT License
from AiursoftWeb
with MIT License
from AiursoftWeb
public override bool Muted(string userId)
{
return Users?.SingleOrDefault(t => t.UserId == userId)?.Muted ?? throw new ArgumentNullException();
}
19
Source : HomeController.cs
with MIT License
from AiursoftWeb
with MIT License
from AiursoftWeb
[APIProduces(typeof(IndexViewModel))]
public IActionResult Index()
{
var model = new IndexViewModel
{
Code = ErrorType.Success,
Mode = _env.EnvironmentName,
Message = $"Welcome to Aiursoft Kahla API! Running in {_env.EnvironmentName} mode.",
WikiPath = _serviceLocation.Wiki,
ServerTime = DateTime.Now,
UTCTime = DateTime.UtcNow,
APIVersion = _sdkVersion.GetSDKVersion(),
VapidPublicKey = _configuration.GetSection("VapidKeys")["PublicKey"],
ServerName = _configuration["ServerName"],
Domain = _appDomain.SingleOrDefault(t => t.Server.Split(':')[0] == Request.Host.Host),
Probe = _probeLocator,
AutoAcceptRequests = _configuration["AutoAcceptRequests"] == true.ToString().ToLower()
};
// This part of code is not beautiful. Try to resolve it in the future.
if (model.Domain != null)
{
model.Domain = new DomainSettings
{
Server = Request.Scheme + "://" + model.Domain.Server,
Client = model.Domain.Client
};
}
return this.Protocol(model);
}
19
Source : ThirdPartyController.cs
with MIT License
from AiursoftWeb
with MIT License
from AiursoftWeb
[HttpPost]
[Route("create-account-and-bind/{providerName}")]
public async Task<IActionResult> CreateAccountAndBind(SignInViewModel model)
{
var app = (await _apiService.AppInfoAsync(model.AppId)).App;
bool exists = _dbContext.UserEmails.Any(t => t.EmailAddress == model.UserDetail.Email.ToLower());
if (exists)
{
ModelState.AddModelError(string.Empty, $"An user with email '{model.UserDetail.Email}' already exists!");
model.AppImageUrl = app.IconPath;
model.CanFindAnAccountWithEmail = false;
model.Provider = _authProviders.SingleOrDefault(t => t.GetName().ToLower() == model.ProviderName.ToLower());
return View(nameof(SignIn), model);
}
var user = new GatewayUser
{
UserName = model.UserDetail.Email + $".from.{model.ProviderName}.com",
Email = model.UserDetail.Email,
NickName = model.UserDetail.Name,
PreferedLanguage = model.PreferedLanguage,
IconFilePath = AuthValues.DefaultImagePath,
RegisterIPAddress = HttpContext.Connection.RemoteIpAddress?.ToString()
};
var result = await _userManager.CreateAsync(user);
if (result.Succeeded)
{
var primaryMail = new UserEmail
{
EmailAddress = model.UserDetail.Email.ToLower(),
OwnerId = user.Id,
ValidateToken = Guid.NewGuid().ToString("N")
};
await _dbContext.UserEmails.AddAsync(primaryMail);
await _dbContext.SaveChangesAsync();
var link = new ThirdPartyAccount
{
OwnerId = user.Id,
ProviderName = model.ProviderName,
OpenId = model.UserDetail.Id,
Name = model.UserDetail.Name,
};
await _dbContext.ThirdPartyAccounts.AddAsync(link);
await _dbContext.SaveChangesAsync();
await _signInManager.SignInAsync(user, isPersistent: true);
await _authLogger.LogAuthRecord(user.Id, HttpContext, true, model.AppId);
return await _authManager.FinishAuth(user, model, app.ForceConfirmation, app.TrustedApp);
}
else
{
model.AppImageUrl = app.IconPath;
model.CanFindAnAccountWithEmail = await _dbContext.UserEmails.AnyAsync(t => t.EmailAddress.ToLower() == model.UserDetail.Email.ToLower());
model.Provider = _authProviders.SingleOrDefault(t => t.GetName().ToLower() == model.ProviderName.ToLower());
ModelState.AddModelError(string.Empty, result.Errors.First().Description);
return View(nameof(SignIn), model);
}
}
19
Source : SignInAddressModel.cs
with MIT License
from AiursoftWeb
with MIT License
from AiursoftWeb
public FinishAuthInfo BuildOAuthInfo()
{
try
{
var values = State
.TrimStart('?')
.Split('&')
.Select(t => t.Split('='))
.Select(t => new KeyValuePair<string, string>(t[0].ToLower(), WebUtility.UrlDecode(t[1])))
.ToArray();
return new FinishAuthInfo
{
AppId = values.SingleOrDefault(t => t.Key == "appid").Value,
RedirectUri = values.SingleOrDefault(t => t.Key == "redirect_uri").Value,
State = values.SingleOrDefault(t => t.Key == "state".ToLower()).Value,
};
}
catch (Exception e) when (e is IndexOutOfRangeException || e is NullReferenceException)
{
throw new AiurAPIModelException(ErrorType.InvalidInput, "State is invalid!");
}
}
19
Source : EnumUtils.cs
with MIT License
from akaskela
with MIT License
from akaskela
public static IList<T> GetFlagsValues<T>(T value) where T : struct
{
Type enumType = typeof(T);
if (!enumType.IsDefined(typeof(FlagsAttribute), false))
{
throw new ArgumentException("Enum type {0} is not a set of flags.".FormatWith(CultureInfo.InvariantCulture, enumType));
}
Type underlyingType = Enum.GetUnderlyingType(value.GetType());
ulong num = Convert.ToUInt64(value, CultureInfo.InvariantCulture);
IList<EnumValue<ulong>> enumNameValues = GetNamesAndValues<T>();
IList<T> selectedFlagsValues = new List<T>();
foreach (EnumValue<ulong> enumNameValue in enumNameValues)
{
if ((num & enumNameValue.Value) == enumNameValue.Value && enumNameValue.Value != 0)
{
selectedFlagsValues.Add((T)Convert.ChangeType(enumNameValue.Value, underlyingType, CultureInfo.CurrentCulture));
}
}
if (selectedFlagsValues.Count == 0 && enumNameValues.SingleOrDefault(v => v.Value == 0) != null)
{
selectedFlagsValues.Add(default(T));
}
return selectedFlagsValues;
}
19
Source : DiscriminatedUnionConverter.cs
with MIT License
from akaskela
with MIT License
from akaskela
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Null)
{
return null;
}
UnionCase caseInfo = null;
string caseName = null;
JArray fields = null;
// start object
reader.ReadAndreplacedert();
while (reader.TokenType == JsonToken.PropertyName)
{
string propertyName = reader.Value.ToString();
if (string.Equals(propertyName, CasePropertyName, StringComparison.OrdinalIgnoreCase))
{
reader.ReadAndreplacedert();
Union union = UnionCache.Get(objectType);
caseName = reader.Value.ToString();
caseInfo = union.Cases.SingleOrDefault(c => c.Name == caseName);
if (caseInfo == null)
{
throw JsonSerializationException.Create(reader, "No union type found with the name '{0}'.".FormatWith(CultureInfo.InvariantCulture, caseName));
}
}
else if (string.Equals(propertyName, FieldsPropertyName, StringComparison.OrdinalIgnoreCase))
{
reader.ReadAndreplacedert();
if (reader.TokenType != JsonToken.StartArray)
{
throw JsonSerializationException.Create(reader, "Union fields must been an array.");
}
fields = (JArray)JToken.ReadFrom(reader);
}
else
{
throw JsonSerializationException.Create(reader, "Unexpected property '{0}' found when reading union.".FormatWith(CultureInfo.InvariantCulture, propertyName));
}
reader.ReadAndreplacedert();
}
if (caseInfo == null)
{
throw JsonSerializationException.Create(reader, "No '{0}' property with union name found.".FormatWith(CultureInfo.InvariantCulture, CasePropertyName));
}
object[] typedFieldValues = new object[caseInfo.Fields.Length];
if (caseInfo.Fields.Length > 0 && fields == null)
{
throw JsonSerializationException.Create(reader, "No '{0}' property with union fields found.".FormatWith(CultureInfo.InvariantCulture, FieldsPropertyName));
}
if (fields != null)
{
if (caseInfo.Fields.Length != fields.Count)
{
throw JsonSerializationException.Create(reader, "The number of field values does not match the number of properties defined by union '{0}'.".FormatWith(CultureInfo.InvariantCulture, caseName));
}
for (int i = 0; i < fields.Count; i++)
{
JToken t = fields[i];
PropertyInfo fieldProperty = caseInfo.Fields[i];
typedFieldValues[i] = t.ToObject(fieldProperty.PropertyType, serializer);
}
}
object[] args = { typedFieldValues };
return caseInfo.Constructor.Invoke(args);
}
19
Source : JsonSchemaResolver.cs
with MIT License
from akaskela
with MIT License
from akaskela
public virtual JsonSchema GetSchema(string reference)
{
JsonSchema schema = LoadedSchemas.SingleOrDefault(s => string.Equals(s.Id, reference, StringComparison.Ordinal));
if (schema == null)
{
schema = LoadedSchemas.SingleOrDefault(s => string.Equals(s.Location, reference, StringComparison.Ordinal));
}
return schema;
}
19
Source : ReflectionUtils.cs
with MIT License
from akaskela
with MIT License
from akaskela
public static ConstructorInfo GetDefaultConstructor(Type t, bool nonPublic)
{
BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.Public;
if (nonPublic)
{
bindingFlags = bindingFlags | BindingFlags.NonPublic;
}
return t.GetConstructors(bindingFlags).SingleOrDefault(c => !c.GetParameters().Any());
}
19
Source : LanguageContainer.cs
with MIT License
from aksoftware98
with MIT License
from aksoftware98
public void AddExtension(IExtension extension)
{
// Add the extension if it is not exists
var value = _extensions.SingleOrDefault(r => r == extension);
if (value == null)
_extensions.Add(extension);
}
19
Source : ExternalFileKeysProvider.cs
with MIT License
from aksoftware98
with MIT License
from aksoftware98
protected override string GetFileName(string cultureName)
{
var files = GetLanguageFileNames();
var fileName = files.SingleOrDefault(file =>
file.Contains(cultureName) &&
(file.Contains($"{cultureName}.yml") || file.Contains($"{cultureName}.yaml")));
return fileName;
}
19
Source : KeysProvider.cs
with MIT License
from aksoftware98
with MIT License
from aksoftware98
public Keys GetKeys(CultureInfo culture)
{
var languageFileNames = GetLanguageFileNames();
// Get the keys from the file that has the current culture
var keys = InternalGetKeys(languageFileNames.SingleOrDefault(n => n.Contains($"{culture.Name}.yml") || n.Contains($"{culture.Name}.yaml")));
// Get the keys from a file that has the same language
if (keys == null)
{
var language = culture.Name.Split('-')[0];
keys = InternalGetKeys(languageFileNames.FirstOrDefault(n => n.Contains(language)));
}
// Get the keys from the english resource
if (keys == null && culture.Name != "en-US")
keys = InternalGetKeys(languageFileNames.SingleOrDefault(n => n.Contains($"en-US.yml")));
if (keys == null)
keys = InternalGetKeys(languageFileNames.FirstOrDefault());
if (keys == null)
throw new FileNotFoundException($"There are no language files existing in the Resource folder within '{_resourcesreplacedembly.GetName().Name}' replacedembly");
return keys;
}
19
Source : ProductsList.razor.cs
with MIT License
from aksoftware98
with MIT License
from aksoftware98
private void AddItemToCart(string itemId)
{
// Get the item from the store
var item = _items.SingleOrDefault(i => i.Id == itemId);
// Add the item to the cart
ItemsService.AddItemToCart(itemId);
// Send a message with the added item to the list holds the sender which is the current component, the kind of the message 'item_added' and the Item object as an argument
MessagingCenter.Send(this, "item_added", item);
}
19
Source : ShoppingCart.razor.cs
with MIT License
from aksoftware98
with MIT License
from aksoftware98
private void RemoveItemFromCart(string itemId)
{
// Get the item id
var item = ItemsService.ListAllItems().SingleOrDefault(i => i.Id == itemId);
// Remove the item from the cart
ItemsService.RemoveItemFromCart(itemId);
// remove the item from the list of the UI
var carreplacedem = _carreplacedems.SingleOrDefault(i => i.Id == itemId);
_carreplacedems.Remove(carreplacedem);
// Send a message to notify other components about the removing process and the total amount that has been removed
MessagingCenter.Send(this, "carreplacedem_removed", carreplacedem);
}
19
Source : ItemsService.cs
with MIT License
from aksoftware98
with MIT License
from aksoftware98
public void AddItemToCart(string itemId)
{
var item = _items.SingleOrDefault(i => i.Id == itemId);
if (item == null)
throw new ArgumentException("Item not found");
if (item.Quanreplacedy == 0)
throw new InvalidOperationException("Not available in the stock");
item.Quanreplacedy--;
_carreplacedems.Add(itemId);
}
19
Source : ItemsService.cs
with MIT License
from aksoftware98
with MIT License
from aksoftware98
public void RemoveItemFromCart(string itemId)
{
var item = _items.SingleOrDefault(i => i.Id == itemId);
if (item == null)
throw new ArgumentException("Item not found");
var carreplacedems = _carreplacedems.Where(i => i == itemId).ToArray();
item.Quanreplacedy += carreplacedems.Count();
foreach (var carreplacedem in carreplacedems)
{
_carreplacedems.Remove(carreplacedem);
}
}
19
Source : SerilogLogEntry.cs
with Apache License 2.0
from alefranz
with Apache License 2.0
from alefranz
private IReadOnlyList<LogEventPropertyValue> GetSerilogScopes()
{
var scopeSequence = Properties.SingleOrDefault(x => x.Key == "Scope").Value as SequenceValue;
return scopeSequence?.Elements ?? _emptyProperties;
}
See More Examples