Here are the examples of the csharp api System.Collections.Generic.IEnumerable.Union(System.Collections.Generic.IEnumerable) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
688 Examples
19
Source : HierarchicalResolver.cs
with MIT License
from Abc-Arbitrage
with MIT License
from Abc-Arbitrage
private static void AddNode(Node root, LoggerDefinition logger, IAppender[] appenders)
{
var parts = logger.Name?.Split(new[] { '.' }, StringSplitOptions.RemoveEmptyEntries) ?? Array.Empty<string>();
var node = root;
var path = "";
foreach (var part in parts)
{
path = (path + "." + part).Trim('.');
if (!node.Children.ContainsKey(part))
{
node.Children[part] = new Node
{
Appenders = node.Appenders,
Level = node.Level,
LogEventPoolExhaustionStrategy = node.LogEventPoolExhaustionStrategy,
LogEventArgumentExhaustionStrategy = node.LogEventArgumentExhaustionStrategy
};
}
node = node.Children[part];
}
node.Appenders = (logger.IncludeParentAppenders ? appenders.Union(node.Appenders) : appenders).Distinct();
node.LogEventPoolExhaustionStrategy = logger.LogEventPoolExhaustionStrategy;
node.LogEventArgumentExhaustionStrategy = logger.LogEventArgumentExhaustionStrategy;
node.Level = logger.Level;
}
19
Source : DynamoDBItem.cs
with MIT License
from abelperezok
with MIT License
from abelperezok
public DynamoDBItem MergeData(DynamoDBItem data)
{
var dataDict = data.ToDictionary();
var merged = _data.Union(dataDict).ToDictionary(k => k.Key, v => v.Value);
return new DynamoDBItem(merged);
}
19
Source : ScriptUtilities.cs
with Apache License 2.0
from abist-co-ltd
with Apache License 2.0
from abist-co-ltd
public static void AppendScriptingDefinitions(
BuildTargetGroup targetGroup,
string[] symbols)
{
if (symbols == null || symbols.Length == 0) { return; }
List<string> toAdd = new List<string>(symbols);
List<string> defines = new List<string>(PlayerSettings.GetScriptingDefineSymbolsForGroup(targetGroup).Split(';'));
PlayerSettings.SetScriptingDefineSymbolsForGroup(targetGroup, string.Join(";", defines.Union(toAdd).ToArray()));
}
19
Source : SolverHandler.cs
with Apache License 2.0
from abist-co-ltd
with Apache License 2.0
from abist-co-ltd
private void LateUpdate()
{
if (updateSolversList)
{
IEnumerable<Solver> inspectorOrderedSolvers = GetComponents<Solver>().Intersect(solvers);
Solvers = inspectorOrderedSolvers.Union(Solvers).ToReadOnlyCollection();
updateSolversList = false;
}
if (UpdateSolvers)
{
// Before calling solvers, update goal to be the transform so that working and transform will match
GoalPosition = transform.position;
GoalRotation = transform.rotation;
GoalScale = transform.localScale;
for (int i = 0; i < solvers.Count; ++i)
{
Solver solver = solvers[i];
if (solver != null && solver.enabled)
{
solver.SolverUpdateEntry();
}
}
}
}
19
Source : IdentityServerDataSeeder.cs
with MIT License
from abpframework
with MIT License
from abpframework
private async Task CreateSwaggerClientAsync(string name, string[] scopes = null)
{
var commonScopes = new[]
{
"email",
"openid",
"profile",
"role",
"phone",
"address"
};
scopes ??= new[] { name };
// Swagger Client
var swaggerClientId = $"{name}_Swagger";
if (!swaggerClientId.IsNullOrWhiteSpace())
{
var swaggerRootUrl = _configuration[$"IdenreplacedyServerClients:{name}:RootUrl"].TrimEnd('/');
await CreateClientAsync(
name: swaggerClientId,
scopes: commonScopes.Union(scopes),
grantTypes: new[] { "authorization_code" },
secret: "1q2w3e*".Sha256(),
requireClientSecret: false,
redirectUri: $"{swaggerRootUrl}/swagger/oauth2-redirect.html",
corsOrigins: new[] { swaggerRootUrl.RemovePostFix("/") }
);
}
}
19
Source : IdentityServerDataSeeder.cs
with MIT License
from abpframework
with MIT License
from abpframework
private async Task CreateClientsAsync()
{
var commonScopes = new[]
{
"email",
"openid",
"profile",
"role",
"phone",
"address"
};
//Public Web Client
var publicWebClientRootUrl = _configuration["IdenreplacedyServerClients:PublicWeb:RootUrl"]
.EnsureEndsWith('/');
await CreateClientAsync(
name: "PublicWeb",
scopes: commonScopes.Union(new[]
{
"AdministrationService"
}),
grantTypes: new[] { "hybrid" },
secret: "1q2w3e*".Sha256(),
redirectUri: $"{publicWebClientRootUrl}signin-oidc",
postLogoutRedirectUri: $"{publicWebClientRootUrl}signout-callback-oidc",
frontChannelLogoutUri: $"{publicWebClientRootUrl}Account/FrontChannelLogout",
corsOrigins: new[] { publicWebClientRootUrl.RemovePostFix("/") }
);
//Angular Client
var angularClientRootUrl =
_configuration["IdenreplacedyServerClients:Web:RootUrl"].TrimEnd('/');
await CreateClientAsync(
name: "Web",
scopes: commonScopes.Union(new[]
{
"IdenreplacedyService",
"AdministrationService",
"Sareplacedervice"
}),
grantTypes: new[] { "authorization_code", "LinkLogin" },
secret: "1q2w3e*".Sha256(),
requirePkce: true,
requireClientSecret: false,
redirectUri: $"{angularClientRootUrl}",
postLogoutRedirectUri: $"{angularClientRootUrl}",
corsOrigins: new[] { angularClientRootUrl }
);
//Administration Service Client
await CreateClientAsync(
name: "EShopOnAbp_AdministrationService",
scopes: commonScopes.Union(new[]
{
"IdenreplacedyService"
}),
grantTypes: new[] { "client_credentials" },
secret: "1q2w3e*".Sha256(),
permissions: new[] { IdenreplacedyPermissions.Users.Default }
);
}
19
Source : OVRDirectorySyncer.cs
with MIT License
from absurd-joy
with MIT License
from absurd-joy
private void DeleteOutdatedFilesFromTarget(SyncResult syncResult, CancellationToken cancellationToken)
{
var outdatedFiles = syncResult.Updated.Union(syncResult.Deleted);
foreach (var fileName in outdatedFiles)
{
File.Delete(Path.Combine(Target, fileName));
cancellationToken.ThrowIfCancellationRequested();
}
}
19
Source : OVRDirectorySyncer.cs
with MIT License
from absurd-joy
with MIT License
from absurd-joy
private void MoveRelevantFilesToTarget(SyncResult syncResult, CancellationToken cancellationToken)
{
// step 3: we move all new files to target
var newFiles = syncResult.Created.Union(syncResult.Updated);
foreach (var fileName in newFiles)
{
var sourceFileName = Path.Combine(Source, fileName);
var destFileName = Path.Combine(Target, fileName);
// target directory exists due to step CreateRelevantDirectoriesAtTarget()
File.Move(sourceFileName, destFileName);
cancellationToken.ThrowIfCancellationRequested();
}
}
19
Source : DigitalAnalyzerExampleViewModel.cs
with MIT License
from ABTSoftware
with MIT License
from ABTSoftware
private async Task GenerateData(List<byte[]> digitalChannels, List<float[]> replacedogChannels)
{
var digitalChannelsCount = digitalChannels.Count;
var replacedogChannelsCount = replacedogChannels.Count;
var totalChannelCount = digitalChannelsCount + replacedogChannelsCount;
var channelList = new List<ChannelViewModel>(totalChannelCount);
var channelIndex = ChannelViewModels.Count;
await Task.Run(async () =>
{
var xStart = 0d;
var xStep = 1d;
var digital = new List<Task<ChannelViewModel>>(digitalChannelsCount);
var replacedog = new List<Task<ChannelViewModel>>(replacedogChannelsCount);
foreach (var channel in digitalChannels)
{
var id = channelIndex++;
digital.Add(Task.Run(() => ChannelGenerationHelper.Instance.GenerateDigitalChannel(xStart, xStep, channel, id)));
}
foreach (var channel in replacedogChannels)
{
var id = channelIndex++;
replacedog.Add(Task.Run(() => ChannelGenerationHelper.Instance.GeneratereplacedogChannel(xStart, xStep, channel, id)));
}
await Task.WhenAll(digital.Union(replacedog));
foreach (var p in digital.Union(replacedog))
{
channelList.Add(p.Result);
}
});
channelList.ForEach(ch => ChannelViewModels.Add(ch));
}
19
Source : ListTermCashflowSet.cs
with BSD 3-Clause "New" or "Revised" License
from ActuarialIntelligence
with BSD 3-Clause "New" or "Revised" License
from ActuarialIntelligence
public void AddCashflows(IList<TermCashflowYieldSet> cashflows)
{
cashflowSet.Union(cashflows);
}
19
Source : AngleBracesBqlRewriter.cs
with GNU General Public License v3.0
from Acumatica
with GNU General Public License v3.0
from Acumatica
private IList<(List<TypeSyntax> nodes, GenericNameSyntax lastNode)> DeconstructLastNode(
GenericNameSyntax node,
out IdentifierNameSyntax identifierName)
{
IdentifierNameSyntax name = null;
var result = Enumerable
.Repeat((new List<TypeSyntax>(), node), 1)
.Union(DeconstructLastNodeRecursively(node, name_ => name = name_))
.ToArray();
identifierName = name;
return result;
}
19
Source : OrganizationServiceContextExtensions.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
public static IEnumerable<Enreplacedy> GetActiveCasesForContactByAccountId(this OrganizationServiceContext context, EnreplacedyReference contact, Guid accountid)
{
if (contact == null)
{
return Enumerable.Empty<Enreplacedy>();
}
// Get cases where the customer is the account of replacedigned to any caseaccess rule for the current contact that allows read and scoped to account
var accountcases = from incident in context.CreateQuery("incident")
join caseaccess in context.CreateQuery("adx_caseaccess")
on incident.GetAttributeValue<EnreplacedyReference>("customerid") equals caseaccess.GetAttributeValue<EnreplacedyReference>("adx_accountid")
where caseaccess.GetAttributeValue<EnreplacedyReference>("adx_contactid") == contact
&& caseaccess.GetAttributeValue<bool?>("adx_read").GetValueOrDefault(false) && caseaccess.GetAttributeValue<OptionSetValue>("adx_scope") != null && caseaccess.GetAttributeValue<OptionSetValue>("adx_scope").Value == (int)CaseAccessScope.Account
&& caseaccess.GetAttributeValue<EnreplacedyReference>("adx_accountid") == new EnreplacedyReference("account", accountid)
where incident.GetAttributeValue<OptionSetValue>("statecode") != null && incident.GetAttributeValue<OptionSetValue>("statecode").Value == (int)IncidentState.Active
select incident;
// Get cases where the customer is a contact and where the parent customer of the contact is an account replacedigned to any caseaccess rule for the current contact that allows read and scoped to account
var parentaccountcases = from incident in context.CreateQuery("incident")
join c in context.CreateQuery("contact") on incident.GetAttributeValue<EnreplacedyReference>("customerid").Id equals c.GetAttributeValue<Guid>("contactid")
join account in context.CreateQuery("account") on c.GetAttributeValue<EnreplacedyReference>("parentcustomerid").Id equals account.GetAttributeValue<Guid>("accountid")
join caseaccess in context.CreateQuery("adx_caseaccess") on account.GetAttributeValue<Guid>("accountid") equals caseaccess.GetAttributeValue<EnreplacedyReference>("adx_accountid").Id
where caseaccess.GetAttributeValue<EnreplacedyReference>("adx_contactid") == contact
&& caseaccess.GetAttributeValue<bool?>("adx_read").GetValueOrDefault(false) && caseaccess.GetAttributeValue<OptionSetValue>("adx_scope") != null && caseaccess.GetAttributeValue<OptionSetValue>("adx_scope").Value == (int)CaseAccessScope.Account
&& caseaccess.GetAttributeValue<EnreplacedyReference>("adx_accountid") == new EnreplacedyReference("account", accountid)
where incident.GetAttributeValue<OptionSetValue>("statecode") != null && incident.GetAttributeValue<OptionSetValue>("statecode").Value == (int)IncidentState.Active
select incident;
var cases = accountcases.AsEnumerable().Union(parentaccountcases.AsEnumerable()).Distinct();
return cases;
}
19
Source : OrganizationServiceContextExtensions.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
public static IEnumerable<Enreplacedy> GetClosedCasesForContactByAccountId(this OrganizationServiceContext context, EnreplacedyReference contact, Guid accountid)
{
if (contact == null)
{
return Enumerable.Empty<Enreplacedy>();
}
// Get cases where the customer is the account of replacedigned to any caseaccess rule for the current contact that allows read and scoped to account
var accountcases = from incident in context.CreateQuery("incident")
join caseaccess in context.CreateQuery("adx_caseaccess")
on incident.GetAttributeValue<Guid>("customerid") equals caseaccess.GetAttributeValue<Guid>("adx_accountid")
where caseaccess.GetAttributeValue<EnreplacedyReference>("adx_contactid") == contact
&& caseaccess.GetAttributeValue<bool?>("adx_read").GetValueOrDefault(false) && caseaccess.GetAttributeValue<OptionSetValue>("adx_scope") != null && caseaccess.GetAttributeValue<OptionSetValue>("adx_scope").Value == (int)CaseAccessScope.Account
&& caseaccess.GetAttributeValue<EnreplacedyReference>("adx_accountid") == new EnreplacedyReference("account", accountid)
where incident.GetAttributeValue<OptionSetValue>("statecode") != null && incident.GetAttributeValue<OptionSetValue>("statecode").Value != (int)IncidentState.Active
select incident;
// Get cases where the customer is a contact and where the parent customer of the contact is an account replacedigned to any caseaccess rule for the current contact that allows read and scoped to account
var parentaccountcases = from incident in context.CreateQuery("incident")
join c in context.CreateQuery("contact") on incident.GetAttributeValue<EnreplacedyReference>("customerid").Id equals c.GetAttributeValue<Guid>("contactid")
join account in context.CreateQuery("account") on c.GetAttributeValue<EnreplacedyReference>("parentcustomerid").Id equals account.GetAttributeValue<Guid>("accountid")
join caseaccess in context.CreateQuery("adx_caseaccess") on account.GetAttributeValue<Guid>("accountid") equals caseaccess.GetAttributeValue<EnreplacedyReference>("adx_accountid").Id
where caseaccess.GetAttributeValue<EnreplacedyReference>("adx_contactid") == contact
&& caseaccess.GetAttributeValue<bool?>("adx_read").GetValueOrDefault(false) && caseaccess.GetAttributeValue<OptionSetValue>("adx_scope") != null && caseaccess.GetAttributeValue<OptionSetValue>("adx_scope").Value == (int)CaseAccessScope.Account
&& caseaccess.GetAttributeValue<EnreplacedyReference>("adx_accountid") == new EnreplacedyReference("account", accountid)
where incident.GetAttributeValue<OptionSetValue>("statecode") != null && incident.GetAttributeValue<OptionSetValue>("statecode").Value != (int)IncidentState.Active
select incident;
var cases = accountcases.AsEnumerable().Union(parentaccountcases.AsEnumerable()).Distinct();
return cases;
}
19
Source : SolutionDefinition.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
private static SolutionDefinition Union(SolutionDefinition first, SolutionDefinition second)
{
if (first == null && second == null) return null;
if (first == null) return second;
if (second == null) return first;
var solutions = first.Solutions.Union(second.Solutions).ToArray();
var enreplacedies = Union(first.Enreplacedies, second.Enreplacedies, first.Solutions).ToDictionary(e => e.LogicalName, e => e);
var relationships = Union(first.ManyRelationships, second.ManyRelationships, first.Solutions).ToDictionary(r => r.SchemaName, r => r);
return new SolutionDefinition(solutions, enreplacedies, relationships);
}
19
Source : SolutionDefinition.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
private static IEnumerable<T> Union<T>(IEnumerable<T> first, IEnumerable<T> second)
{
if (first == null && second == null) return null;
if (first == null) return second;
if (second == null) return first;
return first.Union(second).ToArray();
}
19
Source : OrganizationServiceContextExtensions.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
public static IEnumerable<Enreplacedy> GetOpportunitiesForContactByAccountId(this OrganizationServiceContext context, Enreplacedy contact, Guid accountid)
{
contact.replacedertEnreplacedyName("contact");
if (contact == null)
{
return Enumerable.Empty<Enreplacedy>();
}
// Get opportunities where the Partner is the account of replacedigned to any opportunity access rule for the current contact that allows read and scoped to account
var accountopportunities = from opportunity in context.CreateQuery("opportunity")
join opportunityaccess in context.CreateQuery("adx_opportunitypermissions")
on opportunity.GetAttributeValue<EnreplacedyReference>("msa_partnerid") equals opportunityaccess.GetAttributeValue<EnreplacedyReference>("adx_accountid")
where opportunityaccess.GetAttributeValue<EnreplacedyReference>("adx_contactid") == contact.ToEnreplacedyReference()
&& opportunityaccess.GetAttributeValue<bool?>("adx_read").GetValueOrDefault(false) && opportunityaccess.GetAttributeValue<OptionSetValue>("adx_scope") != null && opportunityaccess.GetAttributeValue<OptionSetValue>("adx_scope").Value == (int)OpportunityAccessScope.Account
&& opportunityaccess.GetAttributeValue<EnreplacedyReference>("adx_accountid") == new EnreplacedyReference("account", accountid)
select opportunity;
// Get cases where the partner contact is not null and where the parent customer of the contact is an account replacedigned to any caseaccess rule for the current contact that allows read and scoped to account
var parentaccountopportunities = from opportunity in context.CreateQuery("opportunity")
join c in context.CreateQuery("contact") on opportunity.GetAttributeValue<EnreplacedyReference>("msa_partneroppid").Id equals c.GetAttributeValue<Guid>("contactid")
join account in context.CreateQuery("account") on c.GetAttributeValue<EnreplacedyReference>("parentcustomerid").Id equals account.GetAttributeValue<Guid>("accountid")
join opportunityaccess in context.CreateQuery("adx_opportunitypermissions") on account.GetAttributeValue<Guid>("accountid") equals opportunityaccess.GetAttributeValue<EnreplacedyReference>("adx_accountid").Id
where opportunity.GetAttributeValue<EnreplacedyReference>("msa_partneroppid") != null
where c.GetAttributeValue<EnreplacedyReference>("parentcustomerid") != null
where opportunityaccess.GetAttributeValue<EnreplacedyReference>("adx_contactid") == contact.ToEnreplacedyReference()
&& opportunityaccess.GetAttributeValue<bool?>("adx_read").GetValueOrDefault(false) && opportunityaccess.GetAttributeValue<OptionSetValue>("adx_scope") != null && opportunityaccess.GetAttributeValue<OptionSetValue>("adx_scope").Value == (int)OpportunityAccessScope.Account
&& opportunityaccess.GetAttributeValue<EnreplacedyReference>("adx_accountid") != null && opportunityaccess.GetAttributeValue<EnreplacedyReference>("adx_accountid") == new EnreplacedyReference("account", accountid)
select opportunity;
var opportunities = accountopportunities.AsEnumerable().Union(parentaccountopportunities.AsEnumerable()).Distinct();
return opportunities;
}
19
Source : OrganizationServiceContextExtensions.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
public static IEnumerable<Enreplacedy> GetOpportunitiesForContact(this OrganizationServiceContext context, Enreplacedy contact)
{
var accounts = context.GetAccountsRelatedToOpportunityAccessForContact(contact).OrderBy(a => a.GetAttributeValue<string>("name"));
var opportunities = context.GetOpportunitiesSpecificToContact(contact);
return accounts.Aggregate(opportunities, (current, account) => current.Union(context.GetOpportunitiesForContactByAccountId(contact, (Guid)account.GetAttributeValue<Guid>("accountid"))).Distinct());
}
19
Source : ProductFactory.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
private IEnumerable<ISalesAttachment> SelectSalesAttachments(Enreplacedy product, SalesLiteratureTypeCode type)
{
var salesAttachments = Enumerable.Empty<ISalesAttachment>();
var salesLiterature = product.GetRelatedEnreplacedies(_serviceContext, "productsalesliterature_replacedociation")
.Where(s =>
s.GetAttributeValue<bool?>("iscustomerviewable").GetValueOrDefault() &&
s.GetAttributeValue<OptionSetValue>("literaturetypecode") != null &&
s.GetAttributeValue<OptionSetValue>("literaturetypecode").Value == (int)type)
.ToArray();
if (!salesLiterature.Any())
{
return salesAttachments;
}
var salesliteratureitems = salesLiterature
.Select(literature => SelectSalesAttachments(literature.ToEnreplacedyReference()))
.Aggregate(salesAttachments, (current, attachments) => current.Union(attachments))
.OrderBy(e => e.FileName);
return salesliteratureitems;
}
19
Source : OrganizationServiceContextExtensions.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
public static IEnumerable<Enreplacedy> GetContactsForContact(this OrganizationServiceContext context, Enreplacedy contact)
{
var accounts = context.GetAccountsRelatedToContactAccessForContact(contact).OrderBy(a => a.GetAttributeValue<string>("name"));
var contacts = context.GetContactsSpecificToContact(contact);
return accounts.Aggregate(contacts, (current, account) => current.Union(context.GetContactsForContactByAccountId(contact, (Guid)account.GetAttributeValue<Guid>("accountid"))).Distinct());
}
19
Source : FilterOptionGroup.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
internal static IEnumerable<FilterOptionGroup> ToFilterOptionGroups(OrganizationServiceContext context, IPortalContext portalContext, EnreplacedyMetadata enreplacedyMetadata,
IEnumerable<Filter> filters, IEnumerable<Link> links, NameValueCollection query, SavedQueryView queryView, IViewConfiguration viewConfiguration, int languageCode)
{
return filters.Select(f => ToFilterOptionGroup(enreplacedyMetadata, f, query, queryView, viewConfiguration, languageCode))
.Union(links.Select(l => ToFilterOptionGroup(context, portalContext, l, query, languageCode)))
.OrderBy(f => f.Order)
.ToList();
}
19
Source : FilterOptionGroup.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
private static IEnumerable<FilterOptionGroup> ToFilterOptionGroups(OrganizationServiceContext context, IPortalContext portalContext,
EnreplacedyMetadata enreplacedyMetadata, IEnumerable<Filter> filters, IEnumerable<Link> links,
NameValueCollection query, int languageCode, IDictionary<string, string> overrideColumnNames)
{
return filters.Select(f => ToFilterOptionGroup(enreplacedyMetadata, f, query, languageCode, overrideColumnNames))
.Union(links.Select(l => ToFilterOptionGroup(context, portalContext, l, query, languageCode)))
.OrderBy(f => f.Order)
.ToList();
}
19
Source : UnorderedListDataPager.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
private static void AddCssClreplacedes(HtmlControl control, params string[] clreplacedes)
{
var includingExistingClreplaced = new[] { control.Attributes["clreplaced"] }.Union(clreplacedes);
var attributeValue = string.Join(" ", includingExistingClreplaced.Where(@clreplaced => !string.IsNullOrWhiteSpace(@clreplaced)));
if (!string.IsNullOrWhiteSpace(attributeValue))
{
control.Attributes["clreplaced"] = attributeValue;
}
}
19
Source : CrmRoleProvider.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
public override string[] GetRolesForUser(string username)
{
var context = ServiceContext;
var user = context.CreateQuery(_userEnreplacedyName).FirstOrDefault(u => u.GetAttributeValue<string>(_attributeMapUsername) == username);
if (user == null)
{
return new string[0];
}
var roleNames =
from role in user.GetRelatedEnreplacedies(context, _roleToUserRelationshipName)
where Equals(role.GetAttributeValue<EnreplacedyReference>(_attributeMapRoleWebsiteId), WebsiteID)
select role.GetAttributeValue<string>(_attributeMapRoleName);
// Merge in the authenticated users roles, if that option is defined.
if (_authenticatedUsersRolesEnabled)
{
var authenticatedUsersRoleNames =
from role in context.CreateQuery(_roleEnreplacedyName)
where (role.GetAttributeValue<EnreplacedyReference>(_attributeMapRoleWebsiteId) == WebsiteID) && (role.GetAttributeValue<bool?>(_attributeMapIsAuthenticatedUsersRole) == true)
select role.GetAttributeValue<string>(_attributeMapRoleName);
roleNames = roleNames.ToList().Union(authenticatedUsersRoleNames.ToList());
}
return roleNames.Distinct().ToArray();
}
19
Source : MapController.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
[AcceptVerbs(HttpVerbs.Post)]
[AjaxValidateAntiForgeryToken, SuppressMessage("ASP.NET.MVC.Security", "CA5332:MarkVerbHandlersWithValidateAntiforgeryToken", Justification = "Handled with the custom attribute AjaxValidateAntiForgeryToken")]
public ActionResult Search(int dateFilterCode, string dateFrom, string dateTo, int statusFilterCode, int priorityFilterCode, string[] types, bool includeAlerts)
{
dateFilterCode = (dateFilterCode >= 0) ? dateFilterCode : 0;
var status = (statusFilterCode > 0) ? statusFilterCode : 999;
var priority = (priorityFilterCode >= 0) ? priorityFilterCode : 0;
DateTime fromDate;
DateTime.TryParse(dateFrom, out fromDate);
DateTime toDate;
DateTime.TryParse(dateTo, out toDate);
var typesGuids = types == null || types.Length < 1 ? null : Array.ConvertAll(types, Guid.Parse);
var context = PortalCrmConfigurationManager.CreateServiceContext();
var serviceRequests = context.CreateQuery("adx_servicerequest").Where(s => s.GetAttributeValue<decimal?>("adx_lareplacedude") != null && s.GetAttributeValue<decimal?>("adx_longitude") != null)
.FilterServiceRequestsByPriority(priority)
.FilterServiceRequestsByStatus(status)
.FilterServiceRequestsByDate(dateFilterCode, fromDate, toDate.AddDays(1))
.FilterServiceRequestsByType(typesGuids)
.ToList();
var serviceRequestMapNodes = new List<MapNode>();
if (serviceRequests.Any())
{
serviceRequestMapNodes =
serviceRequests.Select(
s =>
new MapNode(
MapNode.NodeType.ServiceRequest,
s.GetAttributeValue<string>("adx_servicerequestnumber"),
s.GetAttributeValue<string>("adx_name"),
s.GetAttributeValue<string>("adx_location"),
string.Empty,
s.GetAttributeValue<OptionSetValue>("adx_servicestatus") == null ? 0 : s.GetAttributeValue<OptionSetValue>("adx_servicestatus").Value,
s.GetAttributeValue<OptionSetValue>("adx_priority") == null ? 0 : s.GetAttributeValue<OptionSetValue>("adx_priority").Value,
s.GetAttributeValue<DateTime>("adx_incidentdate"),
s.GetAttributeValue<DateTime>("adx_scheduleddate"),
s.GetAttributeValue<DateTime>("adx_closeddate"),
s.GetAttributeValue<decimal?>("adx_lareplacedude").GetValueOrDefault(0),
s.GetAttributeValue<decimal?>("adx_longitude").GetValueOrDefault(0),
ServiceRequestHelpers.GetPushpinImageUrl(context, s),
ServiceRequestHelpers.GetCheckStatusUrl(s))).ToList();
}
var alertMapNodes = new List<MapNode>();
if (includeAlerts)
{
var alerts = context.CreateQuery("adx_311alert").Where(a =>
a.GetAttributeValue<decimal?>("adx_lareplacedude") != null && a.GetAttributeValue<decimal?>("adx_longitude") != null && a.GetAttributeValue<bool?>("adx_publishtoweb").GetValueOrDefault(false) == true)
.FilterAlertsByDate(dateFilterCode, fromDate, toDate.AddDays(1)).ToList();
if (alerts.Any())
{
var alertIconImageUrl = ServiceRequestHelpers.GetAlertPushpinImageUrl();
alertMapNodes = alerts.Select(a => new MapNode(MapNode.NodeType.Alert, a.GetAttributeValue<string>("adx_name"), a.GetAttributeValue<string>("adx_address1_line1"), a.GetAttributeValue<string>("adx_description"), a.GetAttributeValue<DateTime?>("adx_scheduledstartdate"), a.GetAttributeValue<DateTime?>("adx_scheduledenddate"), a.GetAttributeValue<decimal?>("adx_lareplacedude") ?? 0, a.GetAttributeValue<decimal?>("adx_longitude") ?? 0, alertIconImageUrl)).ToList();
}
}
var mapNodes = serviceRequestMapNodes.Union(alertMapNodes).ToList();
var json = Json(mapNodes);
return json;
}
19
Source : RegisterClientService.cs
with Apache License 2.0
from Aguafrommars
with Apache License 2.0
from Aguafrommars
public async Task<ClientRegisteration> RegisterAsync(ClientRegisteration registration, HttpContext httpContext)
{
var uri = $"{httpContext.Request.Scheme}://{httpContext.Request.Host}/";
var discovery = await _discoveryResponseGenerator.CreateDiscoveryDoreplacedentAsync(uri, uri).ConfigureAwait(false);
ValidateCaller(registration, httpContext);
Validate(registration, discovery);
var clientName = registration.ClientNames?.FirstOrDefault(n => n.Culture == null)?.Value ??
registration.ClientNames?.FirstOrDefault()?.Value ?? Guid.NewGuid().ToString();
var existing = await _clientStore.GetAsync(clientName, null).ConfigureAwait(false);
registration.Id = existing != null ? Guid.NewGuid().ToString() : clientName;
registration.Id = registration.Id.Contains(' ') ? Guid.NewGuid().ToString() : registration.Id;
var secret = Guid.NewGuid().ToString();
var serializerSettings = new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore
};
var jwkKeys = registration.Jwks?.Keys;
var sercretList = jwkKeys != null ? jwkKeys.Select(k => new ClientSecret
{
Id = Guid.NewGuid().ToString(),
#if DUENDE
Type = Duende.IdenreplacedyServer.IdenreplacedyServerConstants.SecretTypes.JsonWebKey,
#else
Type = IdenreplacedyServer4.IdenreplacedyServerConstants.SecretTypes.JsonWebKey,
#endif
Value = JsonConvert.SerializeObject(k, serializerSettings)
}).ToList() : new List<ClientSecret>();
sercretList.Add(new ClientSecret
{
Id = Guid.NewGuid().ToString(),
#if DUENDE
Type = Duende.IdenreplacedyServer.IdenreplacedyServerConstants.SecretTypes.SharedSecret,
#else
Type = IdenreplacedyServer4.IdenreplacedyServerConstants.SecretTypes.SharedSecret,
#endif
Value = secret
});
var client = new Client
{
AllowedGrantTypes = registration.GrantTypes.Select(grant => new ClientGrantType
{
Id = Guid.NewGuid().ToString(),
GrantType = grant
}).ToList(),
AccessTokenLifetime = _defaultValues.AccessTokenLifetime,
AbsoluteRefreshTokenLifetime = _defaultValues.AbsoluteRefreshTokenLifetime,
AccessTokenType = (int)_defaultValues.AccessTokenType,
AllowOfflineAccess = registration.ApplicationType == "web" && registration.GrantTypes.Contains("refresh_token"),
AllowAccessTokensViaBrowser = registration.ApplicationType == "web",
AllowedScopes = new List<ClientScope>{
new ClientScope
{
Id = Guid.NewGuid().ToString(),
Scope = "openid"
},
new ClientScope
{
Id = Guid.NewGuid().ToString(),
Scope = "profile"
},
new ClientScope
{
Id = Guid.NewGuid().ToString(),
Scope = "address"
},
new ClientScope
{
Id = Guid.NewGuid().ToString(),
Scope = "email"
},
new ClientScope
{
Id = Guid.NewGuid().ToString(),
Scope = "phone"
}
},
AllowRememberConsent = _defaultValues.AllowRememberConsent,
AllowPlainTextPkce = _defaultValues.AllowPlainTextPkce,
AlwaysIncludeUserClaimsInIdToken = _defaultValues.AlwaysIncludeUserClaimsInIdToken,
AlwaysSendClientClaims = _defaultValues.AlwaysSendClientClaims,
AuthorizationCodeLifetime = _defaultValues.AuthorizationCodeLifetime,
BackChannelLogoutSessionRequired = !string.IsNullOrEmpty(_defaultValues.BackChannelLogoutUri),
BackChannelLogoutUri = _defaultValues.BackChannelLogoutUri,
ClientClaimsPrefix = _defaultValues.ClientClaimsPrefix,
ClientName = clientName,
ClientSecrets = sercretList,
ClientUri = registration.ClientUris?.FirstOrDefault(u => u.Culture == null)?.Value ?? registration.ClientUris?.FirstOrDefault()?.Value,
ConsentLifetime = _defaultValues.ConsentLifetime,
Description = _defaultValues.Description,
DeviceCodeLifetime = _defaultValues.DeviceCodeLifetime,
Enabled = true,
EnableLocalLogin = _defaultValues.EnableLocalLogin,
FrontChannelLogoutSessionRequired = !string.IsNullOrEmpty(_defaultValues.FrontChannelLogoutUri),
FrontChannelLogoutUri = _defaultValues.FrontChannelLogoutUri,
Id = registration.Id,
IdenreplacedyTokenLifetime = _defaultValues.IdenreplacedyTokenLifetime,
IncludeJwtId = _defaultValues.IncludeJwtId,
LogoUri = registration.LogoUris?.FirstOrDefault(u => u.Culture == null)?.Value ?? registration.LogoUris?.FirstOrDefault()?.Value,
NonEditable = false,
PairWiseSubjectSalt = _defaultValues.PairWiseSubjectSalt,
ProtocolType = _defaultValues.ProtocolType,
RedirectUris = registration.RedirectUris.Select(u => new ClientUri
{
Id = Guid.NewGuid().ToString(),
Kind = UriKinds.Cors | UriKinds.Redirect,
Uri = u
}).ToList(),
RefreshTokenExpiration = (int)_defaultValues.RefreshTokenExpiration,
RefreshTokenUsage = (int)_defaultValues.RefreshTokenUsage,
RequireClientSecret = false,
RequireConsent = _defaultValues.RequireConsent,
RequirePkce = false,
Resources = registration.ClientNames.Where(n => n.Culture != null)
.Select(n => new ClientLocalizedResource
{
Id = Guid.NewGuid().ToString(),
CultureId = n.Culture,
ResourceKind = EnreplacedyResourceKind.DisplayName,
Value = n.Value
})
.Union(registration.ClientUris != null ? registration.ClientUris.Where(u => u.Culture != null).Select(u => new ClientLocalizedResource
{
Id = Guid.NewGuid().ToString(),
CultureId = u.Culture,
ResourceKind = EnreplacedyResourceKind.ClientUri,
Value = u.Value
}) : new List<ClientLocalizedResource>(0))
.Union(registration.LogoUris != null ? registration.LogoUris.Where(u => u.Culture != null).Select(u => new ClientLocalizedResource
{
Id = Guid.NewGuid().ToString(),
CultureId = u.Culture,
ResourceKind = EnreplacedyResourceKind.LogoUri,
Value = u.Value
}) : new List<ClientLocalizedResource>(0))
.Union(registration.PolicyUris != null ? registration.PolicyUris.Where(u => u.Culture != null).Select(u => new ClientLocalizedResource
{
Id = Guid.NewGuid().ToString(),
CultureId = u.Culture,
ResourceKind = EnreplacedyResourceKind.PolicyUri,
Value = u.Value
}) : new List<ClientLocalizedResource>(0))
.Union(registration.TosUris != null ? registration.TosUris.Where(u => u.Culture != null).Select(u => new ClientLocalizedResource
{
Id = Guid.NewGuid().ToString(),
CultureId = u.Culture,
ResourceKind = EnreplacedyResourceKind.TosUri,
Value = u.Value
}) : new List<ClientLocalizedResource>(0))
.ToList(),
Properties = new List<ClientProperty>
{
new ClientProperty
{
Id = Guid.NewGuid().ToString(),
Key = "applicationType",
Value = registration.ApplicationType
}
}.Union(registration.Contacts != null ? new List<ClientProperty>
{
new ClientProperty
{
Id = Guid.NewGuid().ToString(),
Key = "contacts",
Value = string.Join("; ", registration.Contacts)
}
} : new List<ClientProperty>(0))
.ToList(),
SlidingRefreshTokenLifetime = _defaultValues.SlidingRefreshTokenLifetime,
UpdateAccessTokenClaimsOnRefresh = _defaultValues.UpdateAccessTokenClaimsOnRefresh,
UserCodeType = _defaultValues.UserCodeType,
UserSsoLifetime = _defaultValues.UserSsoLifetime,
PolicyUri = registration.TosUris?.FirstOrDefault(u => u.Culture == null)?.Value ?? registration.TosUris?.FirstOrDefault()?.Value,
TosUri = registration.TosUris?.FirstOrDefault(u => u.Culture == null)?.Value ?? registration.TosUris?.FirstOrDefault()?.Value,
};
client.RegistrationToken = Guid.NewGuid();
await _clientStore.CreateAsync(client).ConfigureAwait(false);
registration.RegistrationToken = client.RegistrationToken.ToString();
registration.RegistrationUri = $"{discovery["registration_endpoint"]}/{client.Id}";
registration.JwksUri = discovery["jwks_uri"].ToString();
registration.ClientSecret = secret;
registration.ClientSecretExpireAt = 0 ;
return registration;
}
19
Source : DBEntryUnitAircraftData.cs
with GNU General Public License v3.0
from akaAgar
with GNU General Public License v3.0
from akaAgar
internal void Merge(DBEntryUnitAircraftData aircraftData)
{
Liveries = Liveries.Union(aircraftData.Liveries).ToList();
PayloadTasks = PayloadTasks
.Union(aircraftData.PayloadTasks)
.GroupBy(g => g.Key)
.ToDictionary(pair => pair.Key, pair => pair.Last().Value);
}
19
Source : AuditGetLastUpdate.cs
with MIT License
from akaskela
with MIT License
from akaskela
protected DataTable BuildDataTable(CodeActivityContext context, IWorkflowContext workflowContext, IOrganizationService service)
{
DataTable table = new DataTable() { TableName = workflowContext.PrimaryEnreplacedyName };
table.Columns.AddRange(new DataColumn[] { new DataColumn("Attribute"), new DataColumn("Old Value"), new DataColumn("New Value") });
RetrieveRecordChangeHistoryRequest request = new RetrieveRecordChangeHistoryRequest()
{
Target = new EnreplacedyReference(workflowContext.PrimaryEnreplacedyName, workflowContext.PrimaryEnreplacedyId),
PagingInfo = new PagingInfo() { Count = 100, PageNumber = 1 }
};
RetrieveRecordChangeHistoryResponse response = service.Execute(request) as RetrieveRecordChangeHistoryResponse;
if (response != null && response.AuditDetailCollection.Count > 0)
{
string onlyIfField = LastUpdateWithThisField.Get(context);
AttributeAuditDetail detail = null;
for (int i = 0; i < response.AuditDetailCollection.Count; i++)
{
AttributeAuditDetail thisDetail = response.AuditDetailCollection[i] as AttributeAuditDetail;
if (thisDetail != null && (String.IsNullOrEmpty(onlyIfField) ||
(thisDetail.OldValue.Attributes.Keys.Contains(onlyIfField) ||
thisDetail.NewValue.Attributes.Keys.Contains(onlyIfField))))
{
detail = thisDetail;
break;
}
}
if (detail != null && detail.NewValue != null && detail.OldValue != null)
{
Microsoft.Xrm.Sdk.Messages.RetrieveEnreplacedyRequest retrieveEnreplacedyRequest = new Microsoft.Xrm.Sdk.Messages.RetrieveEnreplacedyRequest()
{
EnreplacedyFilters = EnreplacedyFilters.Attributes,
LogicalName = workflowContext.PrimaryEnreplacedyName
};
Microsoft.Xrm.Sdk.Messages.RetrieveEnreplacedyResponse retrieveEnreplacedyResponse = service.Execute(retrieveEnreplacedyRequest) as Microsoft.Xrm.Sdk.Messages.RetrieveEnreplacedyResponse;
EnreplacedyMetadata metadata = retrieveEnreplacedyResponse.EnreplacedyMetadata;
var details = detail.NewValue.Attributes.Keys.Union(detail.OldValue.Attributes.Keys)
.Distinct()
.Select(a => new
{
AttributeName = a,
DisplayName = this.GetDisplayLabel(metadata, a),
OldValue = String.Empty,
NewValue = String.Empty
})
.OrderBy(a => a.DisplayName);
foreach (var item in details)
{
DataRow newRow = table.NewRow();
newRow["Attribute"] = item.DisplayName;
newRow["Old Value"] = GetDisplayValue(detail.OldValue, item.AttributeName);
newRow["New Value"] = GetDisplayValue(detail.NewValue, item.AttributeName);
table.Rows.Add(newRow);
}
}
}
return table;
}
19
Source : AuditGetRecentUpdates.cs
with MIT License
from akaskela
with MIT License
from akaskela
protected DataTable BuildDataTable(CodeActivityContext context, IWorkflowContext workflowContext, IOrganizationService service)
{
TimeZoneSummary timeZone = StaticMethods.CalculateTimeZoneToUse(this.TimeZoneOption.Get(context), workflowContext, service);
DataTable table = new DataTable() { TableName = workflowContext.PrimaryEnreplacedyName };
table.Columns.AddRange(new DataColumn[] { new DataColumn("Date"), new DataColumn("User"), new DataColumn("Attribute"), new DataColumn("Old Value"), new DataColumn("New Value") });
DateTime oldestUpdate = DateTime.MinValue;
if (this.Units != null && this.Number != null && this.Number.Get<int>(context) != 0)
{
OptionSetValue value = this.Units.Get<OptionSetValue>(context);
if (value != null)
{
switch (value.Value)
{
case 222540000:
oldestUpdate = DateTime.Now.AddYears(this.Number.Get<int>(context) * -1);
break;
case 222540001:
oldestUpdate = DateTime.Now.AddMonths(this.Number.Get<int>(context) * -1);
break;
case 222540002:
oldestUpdate = DateTime.Now.AddDays(this.Number.Get<int>(context) * -7);
break;
case 222540003:
oldestUpdate = DateTime.Now.AddDays(this.Number.Get<int>(context) * -1);
break;
case 222540004:
oldestUpdate = DateTime.Now.AddHours(this.Number.Get<int>(context) * -1);
break;
default:
oldestUpdate = DateTime.Now.AddMinutes(this.Number.Get<int>(context) * -1);
break;
}
}
}
int maxUpdates = this.MaxAuditLogs.Get(context) > 100 || this.MaxAuditLogs.Get(context) < 1 ? 100 : this.MaxAuditLogs.Get(context);
RetrieveRecordChangeHistoryRequest request = new RetrieveRecordChangeHistoryRequest()
{
Target = new EnreplacedyReference(workflowContext.PrimaryEnreplacedyName, workflowContext.PrimaryEnreplacedyId),
PagingInfo = new PagingInfo() { Count = maxUpdates, PageNumber = 1 }
};
RetrieveRecordChangeHistoryResponse response = service.Execute(request) as RetrieveRecordChangeHistoryResponse;
var detailsToInclude = response.AuditDetailCollection.AuditDetails
.Where(ad => ad is AttributeAuditDetail && ad.AuditRecord.Contains("createdon") && ((DateTime)ad.AuditRecord["createdon"]) > oldestUpdate)
.OrderByDescending(ad => ((DateTime)ad.AuditRecord["createdon"]))
.ToList();
if (detailsToInclude.Any())
{
Microsoft.Xrm.Sdk.Messages.RetrieveEnreplacedyRequest retrieveEnreplacedyRequest = new Microsoft.Xrm.Sdk.Messages.RetrieveEnreplacedyRequest()
{
EnreplacedyFilters = EnreplacedyFilters.Attributes,
LogicalName = workflowContext.PrimaryEnreplacedyName
};
Microsoft.Xrm.Sdk.Messages.RetrieveEnreplacedyResponse retrieveEnreplacedyResponse = service.Execute(retrieveEnreplacedyRequest) as Microsoft.Xrm.Sdk.Messages.RetrieveEnreplacedyResponse;
EnreplacedyMetadata metadata = retrieveEnreplacedyResponse.EnreplacedyMetadata;
foreach (var detail in detailsToInclude.Select(d => d as AttributeAuditDetail).Where(d => d.NewValue != null && d.OldValue != null))
{
DateTime dateToModify = (DateTime)detail.AuditRecord["createdon"];
if (dateToModify.Kind != DateTimeKind.Utc)
{
dateToModify = dateToModify.ToUniversalTime();
}
LocalTimeFromUtcTimeRequest timeZoneChangeRequest = new LocalTimeFromUtcTimeRequest() { UtcTime = dateToModify, TimeZoneCode = timeZone.MicrosoftIndex };
LocalTimeFromUtcTimeResponse timeZoneResponse = service.Execute(timeZoneChangeRequest) as LocalTimeFromUtcTimeResponse;
DateTime timeZoneSpecificDateTime = timeZoneResponse.LocalTime;
var details = detail.NewValue.Attributes.Keys.Union(detail.OldValue.Attributes.Keys)
.Distinct()
.Select(a =>
new {
AttributeName = a,
DisplayName = GetDisplayLabel(metadata, a)
})
.OrderBy(a => a.DisplayName);
foreach (var item in details)
{
DataRow newRow = table.NewRow();
newRow["User"] = GetDisplayValue(detail.AuditRecord, "userid");
newRow["Date"] = timeZoneSpecificDateTime.ToString("MM/dd/yyyy h:mm tt");
newRow["Attribute"] = item.DisplayName;
newRow["Old Value"] = GetDisplayValue(detail.OldValue, item.AttributeName);
newRow["New Value"] = GetDisplayValue(detail.NewValue, item.AttributeName);
table.Rows.Add(newRow);
}
}
}
return table;
}
19
Source : WorkflowQueryBase.cs
with MIT License
from akaskela
with MIT License
from akaskela
protected List<ColumnInformation> BuildTableInformation(IOrganizationService service, string fetchXml, string layoutXml)
{
List<QueryAttribute> fetchXmlColumns = new List<QueryAttribute>();
XmlDoreplacedent doc = new XmlDoreplacedent();
doc.LoadXml(fetchXml);
XmlNode enreplacedyNode = doc["fetch"]["enreplacedy"];
string primaryEnreplacedy = enreplacedyNode.Attributes["name"].Value;
this.RetrieveQueryAttributeRecursively(enreplacedyNode, fetchXmlColumns);
List<QueryAttribute> layoutXmlColumns = new List<QueryAttribute>();
if (!String.IsNullOrEmpty(layoutXml))
{
doc = new XmlDoreplacedent();
doc.LoadXml(layoutXml);
foreach (XmlNode cell in doc["grid"]["row"].ChildNodes)
{
string columnPresentationValue = cell.Attributes["name"].Value;
if (columnPresentationValue.Contains("."))
{
layoutXmlColumns.Add(new QueryAttribute()
{
EnreplacedyAlias = columnPresentationValue.Split('.')[0],
Attribute = columnPresentationValue.Split('.')[1]
});
}
else
{
layoutXmlColumns.Add(new QueryAttribute() { Attribute = columnPresentationValue, EnreplacedyName = primaryEnreplacedy });
}
}
foreach (QueryAttribute attribute in layoutXmlColumns.Where(qa => !String.IsNullOrWhiteSpace(qa.EnreplacedyAlias)))
{
QueryAttribute attributeFromFetch = fetchXmlColumns.FirstOrDefault(f => f.EnreplacedyAlias == attribute.EnreplacedyAlias);
if (attributeFromFetch != null)
{
attribute.EnreplacedyName = attributeFromFetch.EnreplacedyName;
}
}
}
List<string> distintEnreplacedyNames = layoutXmlColumns.Select(lo => lo.EnreplacedyName).Union(fetchXmlColumns.Select(f => f.EnreplacedyName)).Distinct().ToList();
foreach (string enreplacedyName in distintEnreplacedyNames)
{
Microsoft.Xrm.Sdk.Messages.RetrieveEnreplacedyRequest request = new Microsoft.Xrm.Sdk.Messages.RetrieveEnreplacedyRequest()
{
EnreplacedyFilters = EnreplacedyFilters.Attributes,
LogicalName = enreplacedyName
};
Microsoft.Xrm.Sdk.Messages.RetrieveEnreplacedyResponse response = service.Execute(request) as Microsoft.Xrm.Sdk.Messages.RetrieveEnreplacedyResponse;
EnreplacedyMetadata metadata = response.EnreplacedyMetadata;
foreach (QueryAttribute queryAttribute in layoutXmlColumns.Union(fetchXmlColumns).Where(c => c.EnreplacedyName == enreplacedyName && !String.IsNullOrWhiteSpace(c.Attribute)))
{
if (!String.IsNullOrWhiteSpace(queryAttribute.AttribueAlias))
{
queryAttribute.AttributeLabel = queryAttribute.AttribueAlias;
}
else
{
AttributeMetadata attributeMetadata = metadata.Attributes.FirstOrDefault(a => a.LogicalName == queryAttribute.Attribute);
Label displayLabel = attributeMetadata.DisplayName;
if (displayLabel != null && displayLabel.UserLocalizedLabel != null)
{
queryAttribute.AttributeLabel = displayLabel.UserLocalizedLabel.Label;
}
}
}
}
List<ColumnInformation> returnColumns = new List<ColumnInformation>();
List<QueryAttribute> toReturn = (layoutXmlColumns.Count > 0) ? layoutXmlColumns : fetchXmlColumns;
foreach (QueryAttribute qa in toReturn)
{
ColumnInformation ci = new ColumnInformation();
ci.Header = qa.AttributeLabel;
if (!String.IsNullOrEmpty(qa.EnreplacedyAlias))
{
ci.QueryResultAlias = String.Format("{0}.{1}", qa.EnreplacedyAlias, qa.Attribute);
}
else if (!String.IsNullOrEmpty(qa.AttribueAlias))
{
ci.QueryResultAlias = qa.AttribueAlias;
}
else
{
ci.QueryResultAlias = qa.Attribute;
}
returnColumns.Add(ci);
returnColumns.Add(new ColumnInformation() { Header = String.Format(MetadataHeaderFormat, ci.Header, "RawValue") });
}
return returnColumns;
}
19
Source : OkHttpNetworkHandler.cs
with MIT License
from alexrainman
with MIT License
from alexrainman
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var java_uri = request.RequestUri.GetComponents(UriComponents.AbsoluteUri, UriFormat.UriEscaped);
var url = new Java.Net.URL(java_uri);
var body = default(RequestBody);
if (request.Content != null)
{
var bytes = await request.Content.ReadAsByteArrayAsync().ConfigureAwait(false);
var contentType = "text/plain";
if (request.Content.Headers.ContentType != null)
{
contentType = string.Join(" ", request.Content.Headers.GetValues("Content-Type"));
}
body = RequestBody.Create(bytes, MediaType.Parse(contentType));
}
var requestBuilder = new Request.Builder()
.Method(request.Method.Method.ToUpperInvariant(), body)
.Url(url);
if (DisableCaching)
{
requestBuilder.CacheControl(noCacheCacheControl);
}
var keyValuePairs = request.Headers
.Union(request.Content != null ?
request.Content.Headers :
Enumerable.Empty<KeyValuePair<string, IEnumerable<string>>>());
// Add Cookie Header if there's any cookie for the domain in the cookie jar
var stringBuilder = new StringBuilder();
if (client.CookieJar() != null)
{
var jar = client.CookieJar();
var cookies = jar.LoadForRequest(HttpUrl.Get(url));
foreach (var cookie in cookies)
{
stringBuilder.Append(cookie.Name() + "=" + cookie.Value() + ";");
}
}
foreach (var kvp in keyValuePairs)
{
if (kvp.Key == "Cookie")
{
foreach (var val in kvp.Value)
stringBuilder.Append(val + ";");
}
else
{
requestBuilder.AddHeader(kvp.Key, String.Join(getHeaderSeparator(kvp.Key), kvp.Value));
}
}
if (stringBuilder.Length > 0)
{
requestBuilder.AddHeader("Cookie", stringBuilder.ToString().TrimEnd(';'));
}
if (Timeout != null)
{
var clientBuilder = client.NewBuilder();
var timeout = (long)Timeout.Value.TotalSeconds;
clientBuilder.ConnectTimeout(timeout, TimeUnit.Seconds);
clientBuilder.WriteTimeout(timeout, TimeUnit.Seconds);
clientBuilder.ReadTimeout(timeout, TimeUnit.Seconds);
client = clientBuilder.Build();
}
cancellationToken.ThrowIfCancellationRequested();
var rq = requestBuilder.Build();
var call = client.NewCall(rq);
// NB: Even closing a socket must be done off the UI thread. Cray!
cancellationToken.Register(() => Task.Run(() => call.Cancel()));
var resp = default(Response);
try
{
resp = await call.EnqueueAsync().ConfigureAwait(false);
var newReq = resp.Request();
var newUri = newReq == null ? null : newReq.Url().Uri();
request.RequestUri = new Uri(newUri.ToString());
if (throwOnCaptiveNetwork && newUri != null)
{
if (url.Host != newUri.Host)
{
throw new CaptiveNetworkException(new Uri(java_uri), new Uri(newUri.ToString()));
}
}
}
catch (IOException ex)
{
if (ex.Message.ToLowerInvariant().Contains("canceled"))
{
throw new System.OperationCanceledException();
}
// Calling HttpClient methods should throw .Net Exception when fail #5
throw new HttpRequestException(ex.Message, ex);
}
var respBody = resp.Body();
cancellationToken.ThrowIfCancellationRequested();
var ret = new HttpResponseMessage((HttpStatusCode)resp.Code());
ret.RequestMessage = request;
ret.ReasonPhrase = resp.Message();
// ReasonPhrase is empty under HTTPS #8
if (string.IsNullOrEmpty(ret.ReasonPhrase))
{
try
{
ret.ReasonPhrase = ((ReasonPhrases)resp.Code()).ToString().Replace('_', ' ');
}
#pragma warning disable 0168
catch (Exception ex)
{
ret.ReasonPhrase = "Unreplacedigned";
}
#pragma warning restore 0168
}
if (respBody != null)
{
var content = new ProgressStreamContent(respBody.ByteStream(), CancellationToken.None);
content.Progress = getAndRemoveCallbackFromRegister(request);
ret.Content = content;
}
else
{
ret.Content = new ByteArrayContent(new byte[0]);
}
var respHeaders = resp.Headers();
foreach (var k in respHeaders.Names())
{
ret.Headers.TryAddWithoutValidation(k, respHeaders.Get(k));
ret.Content.Headers.TryAddWithoutValidation(k, respHeaders.Get(k));
}
return ret;
}
19
Source : NSUrlSessionHandler.cs
with MIT License
from alexrainman
with MIT License
from alexrainman
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var headers = request.Headers as IEnumerable<KeyValuePair<string, IEnumerable<string>>>;
var ms = new MemoryStream();
if (request.Content != null)
{
await request.Content.CopyToAsync(ms).ConfigureAwait(false);
headers = headers.Union(request.Content.Headers).ToArray();
}
// Add Cookie Header if any cookie for the domain in the cookie store
var stringBuilder = new StringBuilder();
var cookies = NSHttpCookieStorage.SharedStorage.Cookies
.Where(c => c.Domain == request.RequestUri.Host)
.Where(c => Utility.PathMatches(request.RequestUri.AbsolutePath, c.Path))
.ToList();
foreach (var cookie in cookies)
{
stringBuilder.Append(cookie.Name + "=" + cookie.Value + ";");
}
var rq = new NSMutableUrlRequest()
{
AllowsCellularAccess = true,
Body = NSData.FromArray(ms.ToArray()),
CachePolicy = (!this.DisableCaching ? NSUrlRequestCachePolicy.UseProtocolCachePolicy : NSUrlRequestCachePolicy.ReloadIgnoringCacheData),
Headers = headers.Aggregate(new NSMutableDictionary(), (acc, x) => {
if (x.Key == "Cookie")
{
foreach (var val in x.Value)
stringBuilder.Append(val + ";");
}
else
{
acc.Add(new NSString(x.Key), new NSString(String.Join(getHeaderSeparator(x.Key), x.Value)));
}
return acc;
}),
HttpMethod = request.Method.ToString().ToUpperInvariant(),
Url = NSUrl.FromString(request.RequestUri.AbsoluteUri),
};
if (stringBuilder.Length > 0)
{
var copy = new NSMutableDictionary(rq.Headers);
copy.Add(new NSString("Cookie"), new NSString(stringBuilder.ToString().TrimEnd(';')));
rq.Headers = copy;
}
if (Timeout != null)
rq.TimeoutInterval = Timeout.Value.TotalSeconds;
var op = session.CreateDataTask(rq);
cancellationToken.ThrowIfCancellationRequested();
var ret = new TaskCompletionSource<HttpResponseMessage>();
cancellationToken.Register(() => ret.TrySetCanceled());
lock (inflightRequests)
{
inflightRequests[op] = new InflightOperation()
{
FutureResponse = ret,
Request = request,
Progress = getAndRemoveCallbackFromRegister(request),
ResponseBody = new ByteArrayListStream(),
CancellationToken = cancellationToken,
};
}
op.Resume();
return await ret.Task.ConfigureAwait(false);
}
19
Source : EntityAdmin.cs
with MIT License
from allenwp
with MIT License
from allenwp
public List<Component> GetNextTickComponents()
{
return Components.Where(comp => !componentsToRemove.Contains(comp)).Union(componentsToAdd).ToList();
}
19
Source : PluginHelper.cs
with Apache License 2.0
from allure-framework
with Apache License 2.0
from allure-framework
internal static TestResult StartTestCase(string containerId, FeatureContext featureContext,
ScenarioContext scenarioContext)
{
var featureInfo = featureContext?.FeatureInfo ?? emptyFeatureInfo;
var scenarioInfo = scenarioContext?.ScenarioInfo ?? emptyScenarioInfo;
var tags = GetTags(featureInfo, scenarioInfo);
var parameters = GetParameters(scenarioInfo);
var replacedle = scenarioInfo.replacedle;
var testResult = new TestResult
{
uuid = NewId(),
historyId = replacedle + parameters.hash,
name = replacedle,
fullName = replacedle,
labels = new List<Label>
{
Label.Thread(),
string.IsNullOrWhiteSpace(AllureLifecycle.Instance.AllureConfiguration.replacedle)
? Label.Host()
: Label.Host(AllureLifecycle.Instance.AllureConfiguration.replacedle),
Label.Feature(featureInfo.replacedle)
}
.Union(tags.Item1).ToList(),
links = tags.Item2,
parameters = parameters.parameters
};
AllureLifecycle.Instance.StartTestCase(containerId, testResult);
scenarioContext?.Set(testResult);
featureContext?.Get<HashSet<TestResult>>().Add(testResult);
return testResult;
}
19
Source : CsharpFromJsonExampleFactory.cs
with BSD 3-Clause "New" or "Revised" License
from Altinn
with BSD 3-Clause "New" or "Revised" License
from Altinn
public IEnumerable<TypeDescription> AllTypeDescriptions()
{
var children = from p in Properties where p.IsClreplaced && p.ObjectType != null select p.ObjectType;
return ThisTypeDescriptions().Union(CollectionChildTypes).Union(children);
}
19
Source : UdpReceiver.cs
with MIT License
from AndreiMisiukevich
with MIT License
from AndreiMisiukevich
internal bool TryRun(out int port)
{
lock (_lockObject)
{
port = -1;
Stop();
foreach (var possiblePort in Enumerable.Range(15000, 2).Union(Enumerable.Range(17502, 200)))
{
try
{
_udpClient = new UdpClient(possiblePort, AddressFamily.InterNetwork) { EnableBroadcast = true };
_udpTokenSource = new CancellationTokenSource();
var token = _udpTokenSource.Token;
Task.Run(() =>
{
while (!token.IsCancellationRequested)
{
try
{
var remoteEndPoint = new IPEndPoint(IPAddress.Any, 0);
var bytes = _udpClient.Receive(ref remoteEndPoint);
if (!token.IsCancellationRequested && (bytes?.Any() ?? false))
{
var message = Encoding.ASCII.GetString(bytes);
Received?.Invoke(message);
}
}
catch
{
if (token.IsCancellationRequested)
{
break;
}
}
}
});
port = possiblePort;
return true;
}
catch
{
continue;
}
}
return false;
}
}
19
Source : HotReloader.cs
with MIT License
from AndreiMisiukevich
with MIT License
from AndreiMisiukevich
public ReloaderStartupInfo Run(Application app, Configuration config = null)
{
config = config ?? new Configuration();
var devicePort = config.DeviceUrlPort;
_codeReloadingEnabled = config.CodeReloadingEnabled;
Stop();
App = app;
IsRunning = true;
if (app != null)
{
_replacedemblies.Add(app.GetType().replacedembly);
}
foreach (var asm in config.Appreplacedemblies ?? new replacedembly[0])
{
_replacedemblies.Add(asm);
}
TrySubscribeRendererPropertyChanged("Platform.RendererProperty", "CellRenderer.RendererProperty", "CellRenderer.RealCellProperty", "CellRenderer.s_realCellProperty");
_resourceMapping = new ConcurrentDictionary<string, ReloadItem>();
if (HasCodegenAttribute(app))
{
InitializeElement(app, true);
}
HttpListener listener = null;
var maxPort = devicePort + 1000;
while (devicePort < maxPort)
{
listener = new HttpListener
{
Prefixes =
{
$"http://*:{devicePort}/"
}
};
try
{
listener.Start();
break;
}
catch
{
++devicePort;
}
}
_daemonThread = new Thread(() =>
{
do
{
var context = listener.GetContext();
ThreadPool.QueueUserWorkItem((_) => HandleReloadRequest(context));
} while (true);
});
_daemonThread.Start();
var addresses = NetworkInterface.GetAllNetworkInterfaces()
.SelectMany(x => x.GetIPProperties().UnicastAddresses)
.Where(x => x.Address.AddressFamily == AddressFamily.InterNetwork)
.Select(x => x.Address.MapToIPv4())
.Where(x => x.ToString() != "127.0.0.1")
.ToArray();
foreach (var addr in addresses)
{
Console.WriteLine($"### [OLD] HOTRELOAD DEVICE's IP: {addr} ###");
}
Console.WriteLine($"### HOTRELOAD STARTED ON DEVICE's PORT: {devicePort} ###");
var loadXaml = XamlLoaderType.GetMethods(BindingFlags.Static | BindingFlags.Public)
?.FirstOrDefault(m => m.Name == "Load" && m.GetParameters().Length == 3);
_loadXaml = (obj, xaml, isPreviewer) =>
{
var isPreview = isPreviewer ?? config.PreviewerDefaultMode == PreviewerMode.On;
if (loadXaml != null && isPreview)
{
loadXaml.Invoke(null, new object[] { obj, xaml, true });
return;
}
obj.LoadFromXaml(xaml);
};
Task.Run(async () =>
{
var portsRange = Enumerable.Range(15000, 2).Union(Enumerable.Range(17502, 18));
var isFirstTry = true;
while (IsRunning)
{
foreach (var possiblePort in portsRange.Take(isFirstTry ? 20 : 5))
{
if (Device.RuntimePlatform == Device.Android || Device.RuntimePlatform == Device.Tizen)
{
try
{
using (var client = new UdpClient { EnableBroadcast = true })
{
client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
var emulatorData = Encoding.ASCII.GetBytes($"http://127.0.0.1:{devicePort}");
client.Send(emulatorData, emulatorData.Length, new IPEndPoint(IPAddress.Parse("10.0.2.2"), possiblePort));
client.Send(emulatorData, emulatorData.Length, new IPEndPoint(IPAddress.Parse("10.0.3.2"), possiblePort));
}
}
catch { }
}
foreach (var ip in addresses)
{
try
{
var remoteIp = new IPEndPoint(config.ExtensionIpAddress, possiblePort);
using (var client = new UdpClient(new IPEndPoint(ip, 0)) { EnableBroadcast = true })
{
client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
var data = Encoding.ASCII.GetBytes($"http://{ip}:{devicePort}");
client.Send(data, data.Length, remoteIp);
}
}
catch { }
}
}
isFirstTry = false;
await Task.Delay(12000);
}
});
if (config.CodeReloadingEnabled)
{
Task.Run(() =>
{
try
{
foreach (var asm in _replacedemblies)
{
HotCompiler.Current.TryLoadreplacedembly(asm);
}
var testType = HotCompiler.Current.Compile("public clreplaced TestHotCompiler { }", "TestHotCompiler");
HotCompiler.IsSupported = testType != null;
}
catch
{
HotCompiler.IsSupported = false;
}
});
}
else
{
HotCompiler.IsSupported = false;
}
return new ReloaderStartupInfo
{
SelectedDevicePort = devicePort,
IPAddresses = addresses
};
}
19
Source : HotReloader.cs
with MIT License
from AndreiMisiukevich
with MIT License
from AndreiMisiukevich
private void ReloadElements(string content, string path)
{
ReloadItem item = null;
string resKey = null;
Type csharpType = null;
var isCss = Path.GetExtension(path) == ".css";
var isCode = Path.GetExtension(path) == ".cs";
if (isCode)
{
content = content.Replace("InitializeComponent()", "HotReloader.Current.InjectComponentInitialization(this)");
var nameSpace = Regex.Match(content, "namespace[\\s]*(.+\\s)").Groups[1]?.Value?.Trim();
var clreplacedName = Regex.Match(content, "clreplaced[\\s]*(.+\\s)").Groups[1]?.Value?.Split(new char[] { ':', ' ' }).FirstOrDefault()?.Trim();
resKey = $"{nameSpace}.{clreplacedName}";
csharpType = HotCompiler.Current.Compile(content, resKey);
if (csharpType == null)
{
return;
}
if (!_resourceMapping.TryGetValue(resKey, out item))
{
Device.BeginInvokeOnMainThread(() =>
{
foreach (var page in _resourceMapping.Values.SelectMany(x => x.Objects).OfType<View>().Where(x => x.BindingContext?.GetType().FullName == resKey))
{
var newContext = Activator.CreateInstance(csharpType);
page.BindingContext = newContext;
}
});
return;
}
}
resKey = resKey ?? RetrieveClreplacedName(content);
if (string.IsNullOrWhiteSpace(resKey))
{
resKey = path.Replace("\\", ".").Replace("/", ".");
}
try
{
if (!_resourceMapping.TryGetValue(resKey, out item))
{
item = new ReloadItem();
_resourceMapping[resKey] = item;
}
if (isCss)
{
item.Css = content;
}
if (isCode)
{
item.Code = content;
}
else
{
item.Xaml.LoadXml(content);
//Remove ReSharper attributes
foreach (XmlNode node in item.Xaml.ChildNodes)
{
node?.Attributes?.RemoveNamedItem("d:DataContext");
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
Console.WriteLine("### HOTRELOAD ERROR: CANNOT PARSE XAML ###");
return;
}
Device.BeginInvokeOnMainThread(() =>
{
try
{
item.HasUpdates = true;
foreach (var element in item.Objects.ToArray())
{
ReloadElement(element, item, csharpType);
}
if (isCode)
{
return;
}
IEnumerable<ReloadItem> affectedItems;
if (isCss)
{
var nameParts = resKey?.Split('.');
affectedItems = _resourceMapping.Values.Where(e => ContainsResourceDictionary(e, resKey, nameParts));
}
else
{
switch (item.Xaml.DoreplacedentElement.Name)
{
case "Application":
affectedItems = _resourceMapping.Values.Where(x => x.Xaml.InnerXml.Contains("StaticResource"));
break;
case "ResourceDictionary":
var nameParts = resKey?.Split('.');
affectedItems = _resourceMapping.Values.Where(
e => ContainsResourceDictionary(e, resKey, nameParts));
break;
default:
return;
}
//reload all data in case of app resources update
if (affectedItems.Any(x => x.Objects.Any(r => r is Application)))
{
affectedItems = affectedItems.Union(_resourceMapping.Values.Where(x => x.Xaml.InnerXml.Contains("StaticResource")));
}
}
foreach (var affectedItem in affectedItems)
{
foreach (var obj in affectedItem.Objects)
{
ReloadElement(obj, affectedItem);
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
Console.WriteLine("### HOTRELOAD ERROR: CANNOT PARSE XAML ###");
}
});
}
19
Source : GameViewModel.cs
with Apache License 2.0
from AndreiMisiukevich
with Apache License 2.0
from AndreiMisiukevich
private static int[] GetEmptyMap(int mapSize)
=> Enumerable.Range(1, mapSize * mapSize - 1).Union(Enumerable.Repeat(0, 1)).ToArray();
19
Source : LogMessageTypeEx.cs
with BSD 3-Clause "New" or "Revised" License
from anoyetta
with BSD 3-Clause "New" or "Revised" License
from anoyetta
public static void RaiseLog(
DateTime timestamp,
LogMessageType type,
string[] data,
bool isImport = false)
{
var log = string.Join(
"|",
new[]
{
type.ToCode(),
timestamp.ToString("O")
}.Union(data));
ActGlobals.oFormActMain.BeginInvoke((MethodInvoker)delegate
{
ActGlobals.oFormActMain.ParseRawLogLine(isImport, timestamp, log);
});
}
19
Source : CategoriesFakeService.cs
with Apache License 2.0
from AppRopio
with Apache License 2.0
from AppRopio
public async Task<Category> LoadCategoryById(string categoryId)
{
await Task.Delay(500);
return _categories.Union(_subCategories).FirstOrDefault(c => c.Id == categoryId);
}
19
Source : FormatterUtils.cs
with MIT License
from ARKlab
with MIT License
from ARKlab
public static List<string> GetMemberNames(Type type)
{
var memberInfo = type.GetProperties(PublicInstanceBindingFlags)
.OfType<MemberInfo>()
.Union(type.GetFields(PublicInstanceBindingFlags));
var memberNames = from p in memberInfo
where !IsMemberIgnored(p)
orderby MemberOrder(p)
select p.Name;
return memberNames.ToList();
}
19
Source : FormatterUtils.cs
with MIT License
from ARKlab
with MIT License
from ARKlab
public static List<MemberInfo> GetMemberInfo(Type type)
{
var memberInfo = type.GetProperties(PublicInstanceBindingFlags)
.OfType<MemberInfo>()
.Union(type.GetFields(PublicInstanceBindingFlags));
var orderedMemberInfo = from p in memberInfo
where !IsMemberIgnored(p)
orderby MemberOrder(p)
select p;
return orderedMemberInfo.ToList();
}
19
Source : JwtTokenBuilder.cs
with MIT License
from ARKlab
with MIT License
from ARKlab
public JwtToken Build()
{
EnsureArguments();
var claims = new List<Claim>
{
new Claim(JwtRegisteredClaimNames.Sub, this.subject),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
}
.Union(this.claims);
var token = new JwtSecurityToken(
issuer: this.issuer,
audience: this.audience,
claims: claims,
expires: DateTime.UtcNow.AddMinutes(expiryInMinutes),
signingCredentials: new SigningCredentials(
this.securityKey,
SecurityAlgorithms.HmacSha256));
return new JwtToken(token);
}
19
Source : JwtTokenBuilder.cs
with MIT License
from ARKlab
with MIT License
from ARKlab
public JwtToken Build()
{
EnsureArguments();
var claims = new List<Claim>
{
new Claim(JwtRegisteredClaimNames.Sub, this.subject),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
}
.Union(this.claims);
var token = new JwtSecurityToken(
issuer: this.issuer,
audience: this.audience,
claims: claims,
expires: DateTime.UtcNow.AddMinutes(expiryInMinutes),
signingCredentials: new SigningCredentials(
this.securityKey,
SecurityAlgorithms.HmacSha256));
return new JwtToken(token);
}
19
Source : LineBrush.cs
with MIT License
from Aroueterra
with MIT License
from Aroueterra
public static IEnumerable<Vector2Int> GetPointsOnLine(Vector2Int startPos, Vector2Int endPos, bool fillGaps)
{
var points = GetPointsOnLine(startPos, endPos);
if (fillGaps)
{
var rise = endPos.y - startPos.y;
var run = endPos.x - startPos.x;
if (rise != 0 || run != 0)
{
var extraStart = startPos;
var extraEnd = endPos;
if (Mathf.Abs(rise) >= Mathf.Abs(run))
{
// up
if (rise > 0)
{
extraStart.y += 1;
extraEnd.y += 1;
}
// down
else // rise < 0
{
extraStart.y -= 1;
extraEnd.y -= 1;
}
}
else // Mathf.Abs(rise) < Mathf.Abs(run)
{
// right
if (run > 0)
{
extraStart.x += 1;
extraEnd.x += 1;
}
// left
else // run < 0
{
extraStart.x -= 1;
extraEnd.x -= 1;
}
}
var extraPoints = GetPointsOnLine(extraStart, extraEnd);
extraPoints = extraPoints.Except(new[] { extraEnd });
points = points.Union(extraPoints);
}
}
return points;
}
19
Source : Configuration.cs
with GNU General Public License v3.0
from askeladdk
with GNU General Public License v3.0
from askeladdk
public override IEnumerable<KeyValuePair<string, string>> Enumerate(string section)
{
return configs
.Select(x => x.Enumerate(section))
.Aggregate((a, b) => a.Union(b));
}
19
Source : ImmutableMemberSet.cs
with Apache License 2.0
from asynkron
with Apache License 2.0
from asynkron
public ImmutableMemberSet Union(ImmutableMemberSet other)
{
var both = Members.Union(other.Members);
return new ImmutableMemberSet(both);
}
19
Source : Book.cs
with GNU General Public License v3.0
from audiamus
with GNU General Public License v3.0
from audiamus
private void initRegexreplacedle (IreplacedleSettingsEx settings) {
if (settings is null) {
_rgxreplacedle = __rgxreplacedle0;
return;
}
if (string.IsNullOrWhiteSpace (settings.AddnlValreplacedlePunct) && settings.LongBookreplacedle == ELongreplacedle.no) {
if (settings.SeriesreplacedleLeft)
_rgxreplacedle = __rgxreplacedleL;
else
_rgxreplacedle = __rgxreplacedle0;
return;
}
string rgxreplacedle1 = RGX_replacedLE_1;
char[] chars = RGX_replacedLE_2.ToCharArray ();
if (!string.IsNullOrWhiteSpace (settings.AddnlValreplacedlePunct)) {
var chars1 = settings.AddnlValreplacedlePunct.ToCharArray ().Distinct ().ToArray ();
chars = chars.Union (chars1).ToArray ();
}
if (settings.LongBookreplacedle != ELongreplacedle.no) {
var chars2 = new[] { ':' };
chars = chars.Union (chars2).ToArray ();
} else if (settings.SeriesreplacedleLeft)
rgxreplacedle1 = RGX_replacedLE_1L;
string s = new string (chars);
while (true) {
var match = __rgxWord.Match (s);
if (!match.Success)
break;
s = s.Remove (match.Index, 1);
}
string addnlValreplacedlePunct = escape (s);
_rgxreplacedle = new Regex ($@"{rgxreplacedle1}{addnlValreplacedlePunct}{RGX_replacedLE_3}", RegexOptions.Compiled);
}
19
Source : Culture.cs
with GNU General Public License v3.0
from audiamus
with GNU General Public License v3.0
from audiamus
public static void SetCultures (this ComboBox combobox, Type type, ILanguageSetting setting) {
ResourceManager rm = type.GetDefaultResourceManager();
var replaced = Entryreplacedembly;
var exeDir = ApplDirectory;
IEnumerable<CultureInfo> cultures =
CultureInfo.GetCultures (CultureTypes.NeutralCultures).Where (c =>
{
var satDir = Path.Combine (exeDir, c.TwoLetterISOLanguageName);
return Directory.Exists (satDir) &&
new DirectoryInfo (satDir).GetFiles ("*.resources.dll").Count () > 0;
});
if (!string.IsNullOrWhiteSpace (NeutralCultureName)) {
var neutralCulture = new[] { new CultureInfo (NeutralCultureName) };
cultures = cultures.Union (neutralCulture);
}
combobox.Items.Clear ();
combobox.Items.Add (new CIItem (rm.GetStringEx("automatic")));
var sortedCultures = cultures.ToList ();
sortedCultures.Sort ((x, y) => x.ToString ().CompareTo (y.ToString ()));
foreach (CultureInfo culture in sortedCultures)
combobox.Items.Add (new CIItem (culture));
if (string.IsNullOrWhiteSpace(setting.Language)) {
combobox.SelectedIndex = 0;
return;
}
var idx = sortedCultures.FindIndex (c => c.Name == setting.Language);
if (idx < 0)
combobox.SelectedIndex = 0;
else
combobox.SelectedIndex = idx + 1;
}
19
Source : Localizer.cs
with MIT License
from Auros
with MIT License
from Auros
public void RecalculateLanguages()
{
IEnumerable<Locale> languages = kSupportedLanguages;
if (_config.showIncompleteTranslations)
{
languages = kSupportedLanguages.Union(GetLanguagesInSheets(_lockedreplacedetCache.Values.Where(x => x.shadowLocalization == false).Select(x => x.replacedet)));
}
Localization.Instance.SupportedLanguages.Clear();
Localization.Instance.SupportedLanguages.AddRange(languages.OrderBy(lang => lang).Select(lang => (Language)lang));
if (_config.language < 0)
{
Locale potential = AutoDetectLanguage();
if (Localization.Instance.SupportedLanguages.Contains((Language)potential))
{
_config.language = potential;
Localization.Instance.SelectLanguage((Language)_config.language);
}
}
Localization.Instance.InvokeOnLocalize();
}
See More Examples