Here are the examples of the csharp api System.Linq.IOrderedEnumerable.ThenBy(System.Func) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
542 Examples
19
View Source File : DbManager.cs
License : MIT License
Project Creator : 0x1000000
License : MIT License
Project Creator : 0x1000000
public async Task<IReadOnlyList<TableModel>> SelectTables()
{
var columnsRaw = await this.Database.LoadColumns();
var indexes = await this.Database.LoadIndexes();
var fk = await this.Database.LoadForeignKeys();
var acc = new Dictionary<TableRef, Dictionary<ColumnRef, ColumnModel>>();
foreach (var rawColumn in columnsRaw)
{
var table = rawColumn.DbName.Table;
if (!acc.TryGetValue(table, out var colList))
{
colList = new Dictionary<ColumnRef, ColumnModel>();
acc.Add(table, colList);
}
var colModel = BuildColumnModel(
rawColumn,
indexes.Pks.TryGetValue(table, out var pkCols) ? pkCols.Columns : null,
fk.TryGetValue(rawColumn.DbName, out var fkList) ? fkList : null);
colList.Add(colModel.DbName, colModel);
}
var sortedTables = SortTablesByForeignKeys(acc: acc);
var result = sortedTables.Select(t =>
new TableModel(
name: ToTableCrlName(tableRef: t),
dbName: t,
columns: acc[key: t]
.Select(p => p.Value)
.OrderBy(c => c.Pk?.Index ?? 10000)
.ThenBy(c => c.OrdinalPosition)
.ToList(),
indexes: indexes.Indexes.TryGetValue(key: t, value: out var tIndexes)
? tIndexes
: new List<IndexModel>(capacity: 0)))
.ToList();
EnsureTableNamesAreUnique(result, this.Database.DefaultSchemaName);
return result;
}
19
View Source File : DbManager.cs
License : MIT License
Project Creator : 0x1000000
License : MIT License
Project Creator : 0x1000000
private static IReadOnlyList<TableRef> SortTablesByForeignKeys(Dictionary<TableRef, Dictionary<ColumnRef, ColumnModel>> acc)
{
var tableGraph = new Dictionary<TableRef, int>();
var maxValue = 0;
foreach (var pair in acc)
{
CountTable(pair.Key, pair.Value, 1);
}
return acc
.Keys
.OrderByDescending(k => tableGraph.TryGetValue(k, out var value) ? value : maxValue)
.ThenBy(k => k)
.ToList();
void CountTable(TableRef table, Dictionary<ColumnRef, ColumnModel> columns, int value)
{
var parentTables = columns.Values
.Where(c => c.Fk != null)
.SelectMany(c => c.Fk!)
.Select(f => f.Table)
.Distinct()
.Where(pt => !pt.Equals(table))//Self ref
.ToList();
bool hasParents = false;
foreach (var parentTable in parentTables)
{
if (tableGraph.TryGetValue(parentTable, out int oldValue))
{
if (value >= 1000)
{
throw new SqExpressCodeGenException("Cycle in tables");
}
if (oldValue < value)
{
tableGraph[parentTable] = value;
}
}
else
{
tableGraph.Add(parentTable, value);
}
if (maxValue < value)
{
maxValue = value;
}
CountTable(parentTable, acc[parentTable], value + 1);
hasParents = true;
}
if (hasParents && !tableGraph.ContainsKey(columns.Keys.First().Table))
{
tableGraph.Add(table, 0);
}
}
}
19
View Source File : DmnDecisionTable.cs
License : MIT License
Project Creator : adamecr
License : MIT License
Project Creator : adamecr
private IOrderedEnumerable<DmnDecisionTableRule> OrderPositiveRulesByOutputPriority(
IReadOnlyCollection<DmnDecisionTableRule> positiveRules,
DmnDecisionTableRuleExecutionResults results,
string correlationId)
{
IOrderedEnumerable<DmnDecisionTableRule> ordered = null;
foreach (var output in Outputs)
{
//outputs without allowed values list are not part of ordering
if (output.AllowedValues == null || output.AllowedValues.Count <= 0) continue;
if (ordered == null)
{
ordered = positiveRules.OrderBy(i =>
{
var ruleOutput = i.Outputs.FirstOrDefault(o => o.Output.Index == output.Index);
//no such output in positive rule (ruleOutput==null) - at the end of the list
//no output result in positive rule (ruleOutput.ResultOutput==null) - at the end of the list
//no output result value in positive rule (ruleOutput.ResultOutput.Value==null) - at the end of the list
//all handled in GetIndexOfOutputValue: if (value == null) return int.MaxValue;
return GetIndexOfOutputValue(output.AllowedValues, results.GetResult(i, ruleOutput)?.Value, correlationId);
});
}
else
{
ordered = ordered.ThenBy(i =>
{
var ruleOutput = i.Outputs.FirstOrDefault(o => o.Output.Index == output.Index);
return GetIndexOfOutputValue(output.AllowedValues, results.GetResult(i, ruleOutput)?.Value, correlationId);
});
}
}
return ordered;
}
19
View Source File : GNFS.cs
License : GNU General Public License v3.0
Project Creator : AdamWhiteHat
License : GNU General Public License v3.0
Project Creator : AdamWhiteHat
public static List<Relation[]> GroupRoughNumbers(List<Relation> roughNumbers)
{
IEnumerable<Relation> input1 = roughNumbers.OrderBy(rp => rp.AlgebraicQuotient).ThenBy(rp => rp.RationalQuotient);
//IEnumerable<Relation> input2 = roughNumbers.OrderBy(rp => rp.RationalQuotient).ThenBy(rp => rp.AlgebraicQuotient);
Relation lasreplacedem = null;
List<Relation[]> results = new List<Relation[]>();
foreach (Relation pair in input1)
{
if (lasreplacedem == null)
{
lasreplacedem = pair;
}
else if (pair.AlgebraicQuotient == lasreplacedem.AlgebraicQuotient && pair.RationalQuotient == lasreplacedem.RationalQuotient)
{
results.Add(new Relation[] { pair, lasreplacedem });
lasreplacedem = null;
}
else
{
lasreplacedem = pair;
}
}
return results;
}
19
View Source File : QuoteFunctions.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
public static EnreplacedyReference CreateQuote(IEnumerable<LineItem> lineItems, EnreplacedyReference purchaseEnreplacedy, OrganizationServiceContext context,
OrganizationServiceContext serviceContextForWrite, EnreplacedyReference user, EnreplacedyReference priceList, string visitorId = null, EnreplacedyReference target = null,
Enreplacedy purchaseMetadata = null)
{
lineItems = lineItems.ToArray();
// Filter line items to only valid (active) products, that are in the current price list. If there are
// no line items remaining at that point either return null or throw an exception?
var validLineItems = GetValidLineItems(lineItems).ToArray();
if (!validLineItems.Any()) { return null; }
var productIds = validLineItems.Select(e => e.Product.Id).ToArray();
var priceLisreplacedems = context.CreateQuery("productpricelevel")
.Where(e => e.GetAttributeValue<EnreplacedyReference>("pricelevelid") == priceList)
.WhereIn(e => e.GetAttributeValue<Guid>("productid"), productIds)
.ToArray()
.ToLookup(e => e.GetAttributeValue<EnreplacedyReference>("productid").Id);
// Determine the UOM for each line item. If there is only one price list item for the product in the price list,
// use the UOM from that. If there is more than one, favour them in this order: explict UOM on line item, default
// product UOM... then random, basically?
var lineItemsWithUom = validLineItems
.Select(e => new { LineItem = e, UnitOfMeasure = e.GetUnitOfMeasure(priceLisreplacedems[e.Product.Id]) })
.Where(e => e.UnitOfMeasure != null)
.OrderBy(e => e.LineItem.Optional)
.ThenBy(e => e.LineItem.Order)
.ThenBy(e => e.LineItem.Product.GetAttributeValue<string>("adx_name"))
.ToArray();
if (!lineItemsWithUom.Any()) { return null; }
// Set quote customer to current portal user. If there is no current portal user, create a contact on the fly
// using the web form session anonymous visitor ID.
var quote = new Enreplacedy("quote");
var customer = GetQuoteCustomer(context, user, visitorId);
quote["pricelevelid"] = priceList;
quote["transactioncurrencyid"] = GetPriceListCurrency(context, priceList);
quote["customerid"] = customer;
quote["adx_specialinstructions"] = GetQuoteInstructions(lineItems);
quote["name"] = GetQuoteName(context, purchaseMetadata);
// If the purchase enreplacedy or target enreplacedy is a shopping cart, set that on the quote.
if (purchaseEnreplacedy.LogicalName == "adx_shoppingcart")
{
quote["adx_shoppingcartid"] = purchaseEnreplacedy;
}
else if (target != null && target.LogicalName == "adx_shoppingcart")
{
quote["adx_shoppingcartid"] = target;
}
if (user != null)
{
var contact = context.CreateQuery("contact")
.FirstOrDefault(e => e.GetAttributeValue<Guid>("contactid") == user.Id);
if (contact != null)
{
quote["billto_city"] = contact.GetAttributeValue<string>("address1_city");
quote["billto_country"] = contact.GetAttributeValue<string>("address1_country");
quote["billto_line1"] = contact.GetAttributeValue<string>("address1_line1");
quote["billto_line2"] = contact.GetAttributeValue<string>("address1_line2");
quote["billto_line3"] = contact.GetAttributeValue<string>("address1_line3");
quote["billto_name"] = contact.GetAttributeValue<string>("fullname");
quote["billto_postalcode"] = contact.GetAttributeValue<string>("address1_postalcode");
quote["billto_stateorprovince"] = contact.GetAttributeValue<string>("address1_stateorprovince");
quote["shipto_city"] = contact.GetAttributeValue<string>("address1_city");
quote["shipto_country"] = contact.GetAttributeValue<string>("address1_country");
quote["shipto_line1"] = contact.GetAttributeValue<string>("address1_line1");
quote["shipto_line2"] = contact.GetAttributeValue<string>("address1_line2");
quote["shipto_line3"] = contact.GetAttributeValue<string>("address1_line3");
quote["shipto_name"] = contact.GetAttributeValue<string>("fullname");
quote["shipto_postalcode"] = contact.GetAttributeValue<string>("address1_postalcode");
quote["shipto_stateorprovince"] = contact.GetAttributeValue<string>("address1_stateorprovince");
}
}
if (serviceContextForWrite == null) serviceContextForWrite = context;
serviceContextForWrite.AddObject(quote);
serviceContextForWrite.SaveChanges();
var quoteReference = quote.ToEnreplacedyReference();
var lineItemNumber = 1;
foreach (var lineItem in lineItemsWithUom)
{
var quoteProduct = new Enreplacedy("quotedetail");
quoteProduct["quoteid"] = quoteReference;
quoteProduct["productid"] = lineItem.LineItem.Product.ToEnreplacedyReference();
quoteProduct["quanreplacedy"] = lineItem.LineItem.Quanreplacedy;
quoteProduct["uomid"] = lineItem.UnitOfMeasure;
quoteProduct["description"] = lineItem.LineItem.Description;
quoteProduct["lineitemnumber"] = lineItemNumber;
quoteProduct["adx_isrequired"] = !lineItem.LineItem.Optional;
serviceContextForWrite.AddObject(quoteProduct);
lineItemNumber++;
}
serviceContextForWrite.SaveChanges();
return quoteReference;
}
19
View Source File : EntityListPackageRepositoryDataAdapter.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
private IEnumerable<Package> GetPackages(IEnumerable<IGrouping<Guid, Enreplacedy>> enreplacedyGroupings, Func<Guid, string> getPackageUrl)
{
var website = Dependencies.GetWebsite();
foreach (var enreplacedyGrouping in enreplacedyGroupings)
{
var enreplacedy = enreplacedyGrouping.FirstOrDefault();
if (enreplacedy == null)
{
continue;
}
var versions = GetPackageVersions(enreplacedyGrouping, website.Id)
.OrderByDescending(e => e.ReleaseDate)
.ToArray();
var currentVersion = versions.FirstOrDefault();
if (currentVersion == null)
{
continue;
}
PackageImage icon;
var images = GetPackageImages(enreplacedyGrouping, website.Id, enreplacedy.GetAttributeValue<EnreplacedyReference>("adx_iconid"), out icon)
.OrderBy(e => e.Name)
.ToArray();
yield return new Package
{
Categories = GetPackageCategories(enreplacedyGrouping).ToArray(),
Components = GetPackageComponents(enreplacedyGrouping, website.Id).OrderBy(e => e.Order).ThenBy(e => e.CreatedOn).ToArray(),
ContentUrl = currentVersion.Url,
Dependencies = GetPackageDependencies(enreplacedyGrouping, website.Id).OrderBy(e => e.Order).ThenBy(e => e.CreatedOn).ToArray(),
Description = enreplacedy.GetAttributeValue<string>("adx_description"),
DisplayName = enreplacedy.GetAttributeValue<string>("adx_name"),
HideFromPackageListing = enreplacedy.GetAttributeValue<bool?>("adx_hidefromlisting").GetValueOrDefault(false),
Icon = icon,
Images = images,
OverwriteWarning = enreplacedy.GetAttributeValue<bool?>("adx_overwritewarning").GetValueOrDefault(false),
PublisherName = enreplacedy.GetAttributeAliasedValue<string>("adx_name", "publisher"),
ReleaseDate = currentVersion.ReleaseDate,
RequiredInstallerVersion = currentVersion.RequiredInstallerVersion,
Summary = enreplacedy.GetAttributeValue<string>("adx_summary"),
Type = GetPackageType(enreplacedy.GetAttributeValue<OptionSetValue>("adx_type")),
UniqueName = enreplacedy.GetAttributeValue<string>("adx_uniquename"),
Uri = GetPackageUri(enreplacedy.GetAttributeValue<EnreplacedyReference>("adx_packagerepositoryid"), website.Id, enreplacedy.GetAttributeValue<string>("adx_uniquename")),
Url = getPackageUrl(enreplacedy.Id),
Version = currentVersion.Version,
Versions = versions,
Configuration = currentVersion.Configuration
};
}
}
19
View Source File : PackageDataAdapter.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
public Package SelectPackage()
{
var serviceContext = Dependencies.GetServiceContext();
var website = Dependencies.GetWebsite();
var fetch = new Fetch
{
Version = "1.0",
MappingType = MappingType.Logical,
Enreplacedy = new FetchEnreplacedy
{
Name = Package.LogicalName,
Attributes = FetchAttribute.All,
Filters = new[]
{
new Filter
{
Type = LogicalOperator.And,
Conditions = new[]
{
new Condition("adx_packageid", ConditionOperator.Equal, Package.Id),
new Condition("statecode", ConditionOperator.Equal, 0),
}
}
},
Links = new Collection<Link>()
}
};
AddPackageCategoryJoin(fetch.Enreplacedy);
AddPackageComponentJoin(fetch.Enreplacedy);
AddPackageDependencyJoin(fetch.Enreplacedy);
AddPackageImageJoin(fetch.Enreplacedy);
AddPackagePublisherJoin(fetch.Enreplacedy);
AddPackageVersionJoin(fetch.Enreplacedy);
var enreplacedyGrouping = FetchEnreplacedies(serviceContext, fetch)
.GroupBy(e => e.Id)
.FirstOrDefault();
if (enreplacedyGrouping == null)
{
return null;
}
var enreplacedy = enreplacedyGrouping.FirstOrDefault();
if (enreplacedy == null)
{
return null;
}
var versions = GetPackageVersions(enreplacedyGrouping, website.Id)
.OrderByDescending(e => e.ReleaseDate)
.ToArray();
var currentVersion = versions.FirstOrDefault();
if (currentVersion == null)
{
return null;
}
PackageImage icon;
var images = GetPackageImages(enreplacedyGrouping, website.Id, enreplacedy.GetAttributeValue<EnreplacedyReference>("adx_iconid"), out icon)
.OrderBy(e => e.Name)
.ToArray();
var packageRepository = enreplacedy.GetAttributeValue<EnreplacedyReference>("adx_packagerepository");
return new Package
{
Categories = GetPackageCategories(enreplacedyGrouping).ToArray(),
Components = GetPackageComponents(enreplacedyGrouping, website, packageRepository).OrderBy(e => e.Order).ThenBy(e => e.CreatedOn).ToArray(),
ContentUrl = currentVersion.Url,
Dependencies = GetPackageDependencies(enreplacedyGrouping, website, packageRepository).OrderBy(e => e.Order).ThenBy(e => e.CreatedOn).ToArray(),
Description = enreplacedy.GetAttributeValue<string>("adx_description"),
DisplayName = enreplacedy.GetAttributeValue<string>("adx_name"),
HideFromPackageListing = enreplacedy.GetAttributeValue<bool?>("adx_hidefromlisting").GetValueOrDefault(false),
Icon = icon,
Images = images,
OverwriteWarning = enreplacedy.GetAttributeValue<bool?>("adx_overwritewarning").GetValueOrDefault(false),
PublisherName = enreplacedy.GetAttributeAliasedValue<string>("adx_name", "publisher"),
ReleaseDate = currentVersion.ReleaseDate,
RequiredInstallerVersion = currentVersion.RequiredInstallerVersion,
Summary = enreplacedy.GetAttributeValue<string>("adx_summary"),
Type = GetPackageType(enreplacedy.GetAttributeValue<OptionSetValue>("adx_type")),
UniqueName = enreplacedy.GetAttributeValue<string>("adx_uniquename"),
Uri = GetPackageUri(packageRepository, website.Id, enreplacedy.GetAttributeValue<string>("adx_uniquename")),
Url = null,
Version = currentVersion.Version,
Versions = versions
};
}
19
View Source File : EnumerableFilters.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
public static IEnumerable ThenBy(IOrderedEnumerable<object> input, string key, string direction = "asc")
{
return string.Equals(direction, "desc", StringComparison.InvariantCultureIgnoreCase)
|| string.Equals(direction, "descending", StringComparison.InvariantCultureIgnoreCase)
? input.ThenByDescending(e => Get(e, key))
: input.ThenBy(e => Get(e, key));
}
19
View Source File : ModalLookupControlTemplate.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
protected virtual IHtmlString BuildLookupModal(Control container)
{
var html = Mvc.Html.EnreplacedyExtensions.GetHtmlHelper(Metadata.FormView.ContextName, container.Page.Request.RequestContext, container.Page.Response); //new HtmlHelper(new ViewContext(), new ViewPage());
var context = CrmConfigurationManager.CreateContext(Metadata.FormView.ContextName);
var portal = PortalCrmConfigurationManager.CreatePortalContext(Metadata.FormView.ContextName);
var user = portal == null ? null : portal.User;
var viewConfigurations = new List<ViewConfiguration>();
var defaultViewId = Metadata.LookupViewID;
var modalGridSearchPlaceholderText = html.SnippetLiteral("Portal/Lookup/Modal/Grid/Search/PlaceholderText");
var modalGridSearchTooltipText = html.SnippetLiteral("Portal/Lookup/Modal/Grid/Search/TooltipText");
var modalGridPageSize = html.IntegerSetting("Portal/Lookup/Modal/Grid/PageSize") ?? 10;
var modalSizeSetting = html.Setting("Portal/Lookup/Modal/Size");
var modalSize = BootstrapExtensions.BootstrapModalSize.Large;
if (modalSizeSetting != null && modalSizeSetting.ToLower() == "default") modalSize = BootstrapExtensions.BootstrapModalSize.Default;
if (modalSizeSetting != null && modalSizeSetting.ToLower() == "small") modalSize = BootstrapExtensions.BootstrapModalSize.Small;
var formEnreplacedyReferenceInfo = GetFormEnreplacedyReferenceInfo(container.Page.Request);
if (defaultViewId == Guid.Empty)
{
// By default a lookup field cell defined in the form XML does not contain view parameters unless the user has specified a view that is not the default for that enreplacedy and we must query to find the default view. Saved Query enreplacedy's QueryType code 64 indicates a lookup view.
viewConfigurations.AddRange(
Metadata.LookupTargets.Select(
target => new ViewConfiguration(new SavedQueryView(context, target, 64, true, Metadata.LanguageCode), modalGridPageSize)
{
Search = new ViewSearch(!Metadata.LookupDisableQuickFind) { PlaceholderText = modalGridSearchPlaceholderText, TooltipText = modalGridSearchTooltipText },
EnableEnreplacedyPermissions = Metadata.FormView.EnableEnreplacedyPermissions,
PortalName = Metadata.FormView.ContextName,
LanguageCode = Metadata.LanguageCode,
ModalLookupAttributeLogicalName = Metadata.DataFieldName,
ModalLookupEnreplacedyLogicalName = Metadata.TargetEnreplacedyName,
ModalLookupFormReferenceEnreplacedyId = formEnreplacedyReferenceInfo.Item2,
ModalLookupFormReferenceEnreplacedyLogicalName = formEnreplacedyReferenceInfo.Item1,
ModalLookupFormReferenceRelationshipName = formEnreplacedyReferenceInfo.Item3,
ModalLookupFormReferenceRelationshipRole = formEnreplacedyReferenceInfo.Item4
}));
}
else
{
viewConfigurations.Add(new ViewConfiguration(new SavedQueryView(context, defaultViewId, Metadata.LanguageCode), modalGridPageSize)
{
Search = new ViewSearch(!Metadata.LookupDisableQuickFind) { PlaceholderText = modalGridSearchPlaceholderText, TooltipText = modalGridSearchTooltipText },
EnableEnreplacedyPermissions = Metadata.FormView.EnableEnreplacedyPermissions,
PortalName = Metadata.FormView.ContextName,
LanguageCode = Metadata.LanguageCode,
ModalLookupAttributeLogicalName = Metadata.DataFieldName,
ModalLookupEnreplacedyLogicalName = Metadata.TargetEnreplacedyName,
ModalLookupFormReferenceEnreplacedyId = formEnreplacedyReferenceInfo.Item2,
ModalLookupFormReferenceEnreplacedyLogicalName = formEnreplacedyReferenceInfo.Item1,
ModalLookupFormReferenceRelationshipName = formEnreplacedyReferenceInfo.Item3,
ModalLookupFormReferenceRelationshipRole = formEnreplacedyReferenceInfo.Item4
});
}
if (!Metadata.LookupDisableViewPicker && !string.IsNullOrWhiteSpace(Metadata.LookupAvailableViewIds))
{
var addViewConfigurations = new List<ViewConfiguration>();
var viewids = Metadata.LookupAvailableViewIds.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
if (viewids.Length >= 1)
{
var viewGuids = Array.ConvertAll(viewids, Guid.Parse).AsEnumerable().OrderBy(o => o != defaultViewId).ThenBy(o => o).ToArray();
addViewConfigurations.AddRange(from viewGuid in viewGuids
from viewConfiguration in viewConfigurations
where viewConfiguration.ViewId != viewGuid
select new ViewConfiguration(new SavedQueryView(context, viewGuid, Metadata.LanguageCode), modalGridPageSize)
{
Search = new ViewSearch(!Metadata.LookupDisableQuickFind) { PlaceholderText = modalGridSearchPlaceholderText, TooltipText = modalGridSearchTooltipText },
EnableEnreplacedyPermissions = Metadata.FormView.EnableEnreplacedyPermissions,
PortalName = Metadata.FormView.ContextName,
LanguageCode = Metadata.LanguageCode,
ModalLookupAttributeLogicalName = Metadata.DataFieldName,
ModalLookupEnreplacedyLogicalName = Metadata.TargetEnreplacedyName,
ModalLookupFormReferenceEnreplacedyId = formEnreplacedyReferenceInfo.Item2,
ModalLookupFormReferenceEnreplacedyLogicalName = formEnreplacedyReferenceInfo.Item1,
ModalLookupFormReferenceRelationshipName = formEnreplacedyReferenceInfo.Item3,
ModalLookupFormReferenceRelationshipRole = formEnreplacedyReferenceInfo.Item4
});
}
viewConfigurations.AddRange(addViewConfigurations);
}
var applyRelatedRecordFilter = !string.IsNullOrWhiteSpace(Metadata.LookupFilterRelationshipName);
string filterFieldName = null;
if (!string.IsNullOrWhiteSpace(Metadata.LookupDependentAttributeName)) // enreplacedy.attribute (i.e. contact.adx_subject)
{
var pos = Metadata.LookupDependentAttributeName.IndexOf(".", StringComparison.InvariantCulture);
filterFieldName = pos >= 0
? Metadata.LookupDependentAttributeName.Substring(pos + 1)
: Metadata.LookupDependentAttributeName;
}
var modalreplacedle = html.SnippetLiteral("Portal/Lookup/Modal/replacedle");
var modalPrimaryButtonText = html.SnippetLiteral("Portal/Lookup/Modal/PrimaryButtonText");
var modalCancelButtonText = html.SnippetLiteral("Portal/Lookup/Modal/CancelButtonText");
var modalDismissButtonSrText = html.SnippetLiteral("Portal/Lookup/Modal/DismissButtonSrText");
var modalRemoveValueButtonText = html.SnippetLiteral("Portal/Lookup/Modal/RemoveValueButtonText");
var modalNewValueButtonText = html.SnippetLiteral("Portal/Lookup/Modal/NewValueButtonText");
var modalDefaultErrorMessage = html.SnippetLiteral("Portal/Lookup/Modal/DefaultErrorMessage");
var modalGridLoadingMessage = html.SnippetLiteral("Portal/Lookup/Modal/Grid/LoadingMessage");
var modalGridErrorMessage = html.SnippetLiteral("Portal/Lookup/Modal/Grid/ErrorMessage");
var modalGridAccessDeniedMessage = html.SnippetLiteral("Portal/Lookup/Modal/Grid/AccessDeniedMessage");
var modalGridEmptyMessage = html.SnippetLiteral("Portal/Lookup/Modal/Grid/EmptyMessage");
var modalGridToggleFilterText = html.SnippetLiteral("Portal/Lookup/Modal/Grid/ToggleFilterText");
return html.LookupModal(ControlID, viewConfigurations,
BuildControllerActionUrl("GetLookupGridData", "EnreplacedyGrid", new { area = "Portal", __portalScopeId__ = portal == null ? Guid.Empty : portal.Website.Id }), user, applyRelatedRecordFilter,
Metadata.LookupAllowFilterOff, Metadata.LookupFilterRelationshipName, Metadata.LookupDependentAttributeType,
filterFieldName, null, null, modalreplacedle, modalPrimaryButtonText, modalCancelButtonText, modalDismissButtonSrText,
modalRemoveValueButtonText, modalNewValueButtonText, null, null, modalGridLoadingMessage, modalGridErrorMessage, modalGridAccessDeniedMessage,
modalGridEmptyMessage, modalGridToggleFilterText, modalDefaultErrorMessage, null, null, null, Metadata.FormView.ContextName,
Metadata.LanguageCode, null, modalSize, Metadata.LookupReferenceEnreplacedyFormId, EvaluateCreatePrivilege(portal.ServiceContext),
ControlID == "enreplacedlementid" ? BuildControllerActionUrl("GetDefaultEnreplacedlements", "Enreplacedlements", new { area = "CaseManagement", __portalScopeId__ = portal == null ? Guid.Empty : portal.Website.Id }) : null);
}
19
View Source File : WebFormOrderConfirmation.ascx.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
private void ShowInvoice(OrganizationServiceContext serviceContext, Enreplacedy invoice)
{
var invoiceProducts = serviceContext.CreateQuery("invoicedetail")
.Where(e => e.GetAttributeValue<EnreplacedyReference>("invoiceid") == invoice.ToEnreplacedyReference())
.Where(e => e.GetAttributeValue<decimal>("quanreplacedy") > 0)
.ToArray();
var productIds = invoiceProducts
.Select(e => e.GetAttributeValue<EnreplacedyReference>("productid"))
.Where(product => product != null)
.Select(product => product.Id);
var products = serviceContext.CreateQuery("product")
.WhereIn(e => e.GetAttributeValue<Guid>("productid"), productIds)
.ToDictionary(e => e.Id, e => e);
var items = invoiceProducts
.Select(e => GetLineItemFromInvoiceProduct(e, products))
.Where(e => e != null)
.OrderBy(e => e.Number)
.ThenBy(e => e.Name);
InvoiceItems.DataSource = items;
InvoiceItems.DataBind();
InvoiceNumber.Text = invoice.GetAttributeValue<string>("invoicenumber");
var tax = invoice.GetAttributeValue<Money>("totaltax") ?? new Money(0);
InvoiceTotalTax.Visible = tax.Value > 0;
InvoiceTotalTaxAmount.Text = tax.Value.ToString("C2");
var shipping = invoice.GetAttributeValue<Money>("freightamount") ?? new Money(0);
InvoiceTotalShipping.Visible = shipping.Value > 0;
InvoiceTotalShippingAmount.Text = shipping.Value.ToString("C2");
var discount = invoice.GetAttributeValue<Money>("totaldiscountamount") ?? new Money(0);
InvoiceTotalDiscount.Visible = discount.Value > 0;
InvoiceTotalDiscountAmount.Text = discount.Value.ToString("C2");
var total = invoice.GetAttributeValue<Money>("totalamount") ?? new Money(0);
InvoiceTotal.Visible = total.Value > 0;
InvoiceTotalAmount.Text = total.Value.ToString("C2");
GeneralErrorMessage.Visible = false;
Order.Visible = false;
Invoice.Visible = true;
}
19
View Source File : OrderStatus.aspx.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
private void ShowInvoice(OrganizationServiceContext serviceContext, Enreplacedy invoice)
{
var invoiceProducts = serviceContext.CreateQuery("invoicedetail")
.Where(e => e.GetAttributeValue<EnreplacedyReference>("invoiceid") == invoice.ToEnreplacedyReference())
.Where(e => e.GetAttributeValue<decimal>("quanreplacedy") > 0)
.ToArray();
var productIds = invoiceProducts
.Select(e => e.GetAttributeValue<EnreplacedyReference>("productid"))
.Where(product => product != null)
.Select(product => product.Id);
var products = serviceContext.CreateQuery("product")
.WhereIn(e => e.GetAttributeValue<Guid>("productid"), productIds)
.ToDictionary(e => e.Id, e => e);
var items = invoiceProducts
.Select(e => GetLineItemFromInvoiceProduct(e, products))
.Where(e => e != null)
.OrderBy(e => e.Number)
.ThenBy(e => e.Name);
InvoiceItems.DataSource = items;
InvoiceItems.DataBind();
var tax = invoice.GetAttributeValue<Money>("totaltax") ?? new Money(0);
InvoiceTotalTax.Visible = tax.Value > 0;
InvoiceTotalTaxAmount.Text = tax.Value.ToString("C2");
var shipping = invoice.GetAttributeValue<Money>("freightamount") ?? new Money(0);
InvoiceTotalShipping.Visible = shipping.Value > 0;
InvoiceTotalShippingAmount.Text = shipping.Value.ToString("C2");
var discount = invoice.GetAttributeValue<Money>("totaldiscountamount") ?? new Money(0);
InvoiceTotalDiscount.Visible = discount.Value > 0;
InvoiceTotalDiscountAmount.Text = discount.Value.ToString("C2");
var total = invoice.GetAttributeValue<Money>("totalamount") ?? new Money(0);
InvoiceTotal.Visible = total.Value > 0;
InvoiceTotalAmount.Text = total.Value.ToString("C2");
Order.Visible = false;
Invoice.Visible = true;
}
19
View Source File : OrderStatus.aspx.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
private void ShowOrder(OrganizationServiceContext serviceContext, Enreplacedy order)
{
var orderProducts = serviceContext.CreateQuery("salesorderdetail")
.Where(e => e.GetAttributeValue<EnreplacedyReference>("salesorderid") == order.ToEnreplacedyReference())
.Where(e => e.GetAttributeValue<decimal>("quanreplacedy") > 0)
.ToArray();
var productIds = orderProducts
.Select(e => e.GetAttributeValue<EnreplacedyReference>("productid"))
.Where(product => product != null)
.Select(product => product.Id);
var products = serviceContext.CreateQuery("product")
.WhereIn(e => e.GetAttributeValue<Guid>("productid"), productIds)
.ToDictionary(e => e.Id, e => e);
var items = orderProducts
.Select(e => GetLineItemFromOrderProduct(e, products))
.Where(e => e != null)
.OrderBy(e => e.Number)
.ThenBy(e => e.Name);
OrderItems.DataSource = items;
OrderItems.DataBind();
var tax = order.GetAttributeValue<Money>("totaltax") ?? new Money(0);
OrderTotalTax.Visible = tax.Value > 0;
OrderTotalTaxAmount.Text = tax.Value.ToString("C2");
var shipping = order.GetAttributeValue<Money>("freightamount") ?? new Money(0);
OrderTotalShipping.Visible = shipping.Value > 0;
OrderTotalShippingAmount.Text = shipping.Value.ToString("C2");
var discount = order.GetAttributeValue<Money>("totaldiscountamount") ?? new Money(0);
OrderTotalDiscount.Visible = discount.Value > 0;
OrderTotalDiscountAmount.Text = discount.Value.ToString("C2");
var total = order.GetAttributeValue<Money>("totalamount") ?? new Money(0);
OrderTotal.Visible = total.Value > 0;
OrderTotalAmount.Text = total.Value.ToString("C2");
Order.Visible = true;
Invoice.Visible = false;
}
19
View Source File : WebFormOrderConfirmation.ascx.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
private void ShowOrder(OrganizationServiceContext serviceContext, Enreplacedy order)
{
var orderProducts = serviceContext.CreateQuery("salesorderdetail")
.Where(e => e.GetAttributeValue<EnreplacedyReference>("salesorderid") == order.ToEnreplacedyReference())
.Where(e => e.GetAttributeValue<decimal>("quanreplacedy") > 0)
.ToArray();
var productIds = orderProducts
.Select(e => e.GetAttributeValue<EnreplacedyReference>("productid"))
.Where(product => product != null)
.Select(product => product.Id);
var products = serviceContext.CreateQuery("product")
.WhereIn(e => e.GetAttributeValue<Guid>("productid"), productIds)
.ToDictionary(e => e.Id, e => e);
var items = orderProducts
.Select(e => GetLineItemFromOrderProduct(e, products))
.Where(e => e != null)
.OrderBy(e => e.Number)
.ThenBy(e => e.Name);
OrderItems.DataSource = items;
OrderItems.DataBind();
OrderNumber.Text = order.GetAttributeValue<string>("ordernumber");
var tax = order.GetAttributeValue<Money>("totaltax") ?? new Money(0);
OrderTotalTax.Visible = tax.Value > 0;
OrderTotalTaxAmount.Text = tax.Value.ToString("C2");
var shipping = order.GetAttributeValue<Money>("freightamount") ?? new Money(0);
OrderTotalShipping.Visible = shipping.Value > 0;
OrderTotalShippingAmount.Text = shipping.Value.ToString("C2");
var discount = order.GetAttributeValue<Money>("totaldiscountamount") ?? new Money(0);
OrderTotalDiscount.Visible = discount.Value > 0;
OrderTotalDiscountAmount.Text = discount.Value.ToString("C2");
var total = order.GetAttributeValue<Money>("totalamount") ?? new Money(0);
OrderTotal.Visible = total.Value > 0;
OrderTotalAmount.Text = total.Value.ToString("C2");
GeneralErrorMessage.Visible = false;
Order.Visible = true;
Invoice.Visible = false;
}
19
View Source File : TreeViewExtensions.cs
License : MIT License
Project Creator : Adsito
License : MIT License
Project Creator : Adsito
public static IOrderedEnumerable<T> ThenBy<T, TKey>(this IOrderedEnumerable<T> source, Func<T, TKey> selector, bool ascending)
{
if (ascending)
return source.ThenBy(selector);
else
return source.ThenByDescending(selector);
}
19
View Source File : LinqSample.cs
License : The Unlicense
Project Creator : ahotko
License : The Unlicense
Project Creator : ahotko
private void SumAgeByLastnameAndPlaceGroupingOrderedTwice()
{
var ageLastnameGroups =
(from sample in _sampleList
group sample by new { sample.LastName, sample.Place } into sampleGroup
select
new
{
GroupingKey = sampleGroup.Key,
SumAge = sampleGroup.Sum(x => x.Age),
CountMembers = sampleGroup.Count()
}).OrderBy(x => x.GroupingKey.Place).ThenBy(x => x.CountMembers);
//use result
foreach (var sample in ageLastnameGroups)
{
Console.WriteLine($"Lastname = {sample.GroupingKey.LastName}, Place = {sample.GroupingKey.Place}, {sample.CountMembers} member(s), SumAge = {sample.SumAge}");
}
}
19
View Source File : GroupConversation.cs
License : MIT License
Project Creator : AiursoftWeb
License : MIT License
Project Creator : AiursoftWeb
public override Conversation Build(string userId, OnlineJudger onlineJudger)
{
DisplayName = GetDisplayName(userId);
DisplayImagePath = GetDisplayImagePath(userId);
Users = Users.OrderByDescending(t => t.UserId == OwnerId).ThenBy(t => t.JoinTime);
foreach (var user in Users)
{
user.User.Build(onlineJudger);
}
return this;
}
19
View Source File : FriendshipController.cs
License : MIT License
Project Creator : AiursoftWeb
License : MIT License
Project Creator : AiursoftWeb
[APIProduces(typeof(AiurCollection<FriendDiscovery>))]
public async Task<IActionResult> DiscoverFriends(int take = 15)
{
// Load everything to memory and even functions.
var users = await _dbContext.Users
.AsNoTracking()
.ToListAsync();
var conversations = await _dbContext.PrivateConversations
.AsNoTracking()
.ToListAsync();
var groups = await _dbContext.GroupConversations
.Include(t => t.Users)
.AsNoTracking()
.ToListAsync();
var requests = await _dbContext.Requests
.AsNoTracking()
.ToListAsync();
bool AreFriends(string userId1, string userId2)
{
var relation = conversations.Any(t => t.RequesterId == userId1 && t.TargetId == userId2);
if (relation)
{
return true;
}
var elation = conversations.Any(t => t.RequesterId == userId2 && t.TargetId == userId1);
return elation;
}
List<string> HisPersonalFriendsId(string userId)
{
var personalRelations = conversations
.Where(t => t.RequesterId == userId || t.TargetId == userId)
.Select(t => userId == t.RequesterId ? t.TargetId : t.RequesterId)
.ToList();
return personalRelations;
}
List<int> HisGroups(string userId)
{
return groups
.Where(t => t.Users.Any(p => p.UserId == userId))
.Select(t => t.Id)
.ToList();
}
bool SentRequest(string userId1, string userId2)
{
var relation = requests.Where(t => t.Completed == false).Any(t => t.CreatorId == userId1 && t.TargetId == userId2);
if (relation)
{
return true;
}
var elation = requests.Where(t => t.Completed == false).Any(t => t.TargetId == userId1 && t.CreatorId == userId1);
return elation;
}
var currentUser = await GetKahlaUser();
var myFriends = HisPersonalFriendsId(currentUser.Id);
var myGroups = HisGroups(currentUser.Id);
var calculated = new List<FriendDiscovery>();
foreach (var user in users)
{
if (user.Id == currentUser.Id || AreFriends(user.Id, currentUser.Id))
{
continue;
}
var hisFriends = HisPersonalFriendsId(user.Id);
var hisGroups = HisGroups(user.Id);
var commonFriends = myFriends.Intersect(hisFriends).Count();
var commonGroups = myGroups.Intersect(hisGroups).Count();
if (commonFriends > 0 || commonGroups > 0)
{
calculated.Add(new FriendDiscovery
{
CommonFriends = commonFriends,
CommonGroups = commonGroups,
TargetUser = user,
SentRequest = SentRequest(currentUser.Id, user.Id)
});
}
}
var ordered = calculated
.OrderByDescending(t => t.CommonFriends)
.ThenBy(t => t.CommonGroups)
.Take(take)
.ToList();
return this.Protocol(new AiurCollection<FriendDiscovery>(ordered)
{
Code = ErrorType.Success,
Message = "Successfully get your suggested friends."
});
}
19
View Source File : ScriptableCreatorWindow.cs
License : MIT License
Project Creator : alen-smajic
License : MIT License
Project Creator : alen-smajic
void OnGUI()
{
if (_replacedets == null || _replacedets.Count == 0)
{
var list = replacedetDatabase.Findreplacedets("t:" + _type.Name);
_replacedets = new List<ScriptableObject>();
foreach (var item in list)
{
var ne = replacedetDatabase.GUIDToreplacedetPath(item);
var replacedet = replacedetDatabase.LoadreplacedetAtPath(ne, _type) as ScriptableObject;
_replacedets.Add(replacedet);
}
_replacedets = _replacedets.OrderBy(x => x.GetType().Name).ThenBy(x => x.name).ToList();
}
var st = new GUIStyle();
st.padding = new RectOffset(15, 15, 15, 15);
scrollPos = EditorGUILayout.BeginScrollView(scrollPos, st);
for (int i = 0; i < _replacedets.Count; i++)
{
var replacedet = _replacedets[i];
if (replacedet == null) //yea turns out this can happen
continue;
GUILayout.BeginHorizontal();
var b = Header(string.Format("{0,-40} - {1, -15}", replacedet.GetType().Name, replacedet.name), i == activeIndex);
if (b)
activeIndex = i;
if (GUILayout.Button(new GUIContent("Select"), header, GUILayout.Width(80)))
{
if (_act != null)
{
_act(replacedet);
}
else
{
if (_index == -1)
{
_finalize.arraySize++;
_finalize.GetArrayElementAtIndex(_finalize.arraySize - 1).objectReferenceValue = replacedet;
_finalize.serializedObject.ApplyModifiedProperties();
}
else
{
_finalize.GetArrayElementAtIndex(_index).objectReferenceValue = replacedet;
_finalize.serializedObject.ApplyModifiedProperties();
}
}
MapboxDataProperty mapboxDataProperty = (MapboxDataProperty)EditorHelper.GetTargetObjectOfProperty(_container);
if (mapboxDataProperty != null)
{
mapboxDataProperty.HasChanged = true;
}
this.Close();
}
GUILayout.EndHorizontal();
if (b)
{
EditorGUILayout.Space();
EditorGUI.indentLevel += 4;
GUI.enabled = false;
var ed = UnityEditor.Editor.CreateEditor(replacedet);
ed.hideFlags = HideFlags.NotEditable;
ed.OnInspectorGUI();
GUI.enabled = true;
EditorGUI.indentLevel -= 4;
EditorGUILayout.Space();
}
EditorGUILayout.Space();
}
EditorGUILayout.EndScrollView();
}
19
View Source File : DnsSecRecursiveDnsResolver.cs
License : Apache License 2.0
Project Creator : alexreinert
License : Apache License 2.0
Project Creator : alexreinert
private IEnumerable<IPAddress> GetBestNameservers(DomainName name)
{
Random rnd = new Random();
while (name.LabelCount > 0)
{
List<IPAddress> cachedAddresses;
if (_nameserverCache.TryGetAddresses(name, out cachedAddresses))
{
return cachedAddresses.OrderBy(x => x.AddressFamily == AddressFamily.InterNetworkV6 ? 0 : 1).ThenBy(x => rnd.Next());
}
name = name.GetParentName();
}
return _resolverHintStore.RootServers.OrderBy(x => x.AddressFamily == AddressFamily.InterNetworkV6 ? 0 : 1).ThenBy(x => rnd.Next());
}
19
View Source File : GridifyExtensionsShould.cs
License : MIT License
Project Creator : alirezanet
License : MIT License
Project Creator : alirezanet
[Fact]
public void ApplyOrdering_MultipleOrderBy()
{
var gq = new GridifyQuery { OrderBy = "MyDateTime desc , id , name asc" };
var actual = _fakeRepository.AsQueryable()
.ApplyOrdering(gq)
.ToList();
var expected = _fakeRepository
.OrderByDescending(q => q.MyDateTime)
.ThenBy(q => q.Id)
.ThenBy(q => q.Name)
.ToList();
replacedert.Equal(expected.First().Id, actual.First().Id);
replacedert.Equal(expected.Last().Id, actual.Last().Id);
replacedert.Equal(expected, actual);
}
19
View Source File : TMP_FontAssetCommon.cs
License : MIT License
Project Creator : Alword
License : MIT License
Project Creator : Alword
public void SortKerningPairs()
{
// Sort List of Kerning Info
if (kerningPairs.Count > 0)
kerningPairs = kerningPairs.OrderBy(s => s.firstGlyph).ThenBy(s => s.secondGlyph).ToList();
}
19
View Source File : TMP_FontFeatureTable.cs
License : MIT License
Project Creator : Alword
License : MIT License
Project Creator : Alword
public void SortGlyphPairAdjustmentRecords()
{
// Sort List of Kerning Info
if (m_GlyphPairAdjustmentRecords.Count > 0)
m_GlyphPairAdjustmentRecords = m_GlyphPairAdjustmentRecords.OrderBy(s => s.firstAdjustmentRecord.glyphIndex).ThenBy(s => s.secondAdjustmentRecord.glyphIndex).ToList();
}
19
View Source File : SQLiteClientRepository.cs
License : MIT License
Project Creator : ambleside138
License : MIT License
Project Creator : ambleside138
public Client[] SelectAll()
{
var list = new List<Client>();
RepositoryAction.Query(c =>
{
var listRow = new ClientDao(c, null).SelectAll();
list.AddRange(listRow.Select(r => r.ToDomainObject()));
});
return list.OrderBy(i => i.KanaName)
.ThenBy(i => i.Id.Value)
.ToArray();
}
19
View Source File : SQLiteWorkTaskWithTimesQueryService.cs
License : MIT License
Project Creator : ambleside138
License : MIT License
Project Creator : ambleside138
public WorkTaskWithTimesDto[] SelectByYmd(YmdString ymd, bool containsCompleted)
{
var list = new List<WorkTaskWithTimesDto>();
RepositoryAction.Query(c =>
{
var workTaskDao = new WorkTaskDao(c, null);
var workingTimeDao = new WorkingTimeDao(c, null);
var processes = new WorkProcessDao(c, null).SelectAll();
var products = new ProductDao(c, null).SelectAll();
var clients = new ClientDao(c, null).SelectAll();
var completedDao = new WorkTaskCompletedDao(c, null);
var tasks = workTaskDao.SelectPlaned(ymd, containsCompleted);
var times = workingTimeDao.SelectByTaskIds(tasks.Select(t => t.Id).Distinct().ToArray());
var completed = completedDao.SelectCompleted(tasks.Select(t => t.Id).Distinct().ToArray());
foreach(var task in tasks)
{
var dto = new WorkTaskWithTimesDto
{
TaskId = new Idenreplacedy<Domain.Domain.Tasks.WorkTask>(task.Id),
ClientName = clients.FirstOrDefault(c => c.Id == task.ClientId)?.Name ?? "",
ProcessName = processes.FirstOrDefault(p => p.Id == task.ProcessId)?.replacedle ?? "",
ProductName = products.FirstOrDefault(p => p.Id == task.ProductId)?.Name ?? "",
TaskCategory = task.TaskCategory,
replacedle = task.replacedle,
IsCompleted = completed.Any(c => c == task.Id),
IsScheduled = task.TaskSource == Domain.Domain.Tasks.TaskSource.Schedule,
};
dto.WorkingTimes = times.Where(t => t.TaskId == task.Id)
.Select(t => t.ToDomainObject())
.OrderBy(t => t.TimePeriod.StartDateTime)
.ThenBy(t => t.Id)
.ToArray();
list.Add(dto);
}
});
try
{
return list.OrderBy(i => i.WorkingTimes.Any(t => t.IsDoing) ? 0 : 1)
.ThenByDescending(i => i.WorkingTimes.Where(t => t.TimePeriod.IsFuture == false).Any() ? i.WorkingTimes.Where(t => t.TimePeriod.IsFuture == false).Max(t => t.TimePeriod.StartDateTime) : DateTime.MinValue)
.ThenBy(i => i.WorkingTimes.Where(t => t.TimePeriod.IsFuture).Any() ? i.WorkingTimes.Where(t => t.TimePeriod.IsFuture).Min(t => t.TimePeriod.StartDateTime) : DateTime.MaxValue)
.ThenBy(i => i.TaskId.Value).ToArray();
}
catch(Exception)
{
return list.ToArray();
}
}
19
View Source File : CppFilesTab.cs
License : MIT License
Project Creator : AndresTraks
License : MIT License
Project Creator : AndresTraks
private IOrderedEnumerable<SourceItemDefinition> InputFileOrder(IEnumerable<SourceItemDefinition> item)
{
return item
.OrderBy(i => !i.IsFolder)
.ThenBy(i => i.IsExcluded);
}
19
View Source File : RoomCreationServerHubsListViewController.cs
License : MIT License
Project Creator : andruzzzhka
License : MIT License
Project Creator : andruzzzhka
public void SetServerHubs(List<ServerHubClient> hubs)
{
hubInfosList.Clear();
if (hubs != null)
{
var availableHubs = hubs.OrderByDescending(x => x.serverHubCompatible ? 2 : (x.serverHubAvailable ? 1 : 0)).ThenBy(x => x.ping).ThenBy(x => x.availableRoomsCount).ToList();
foreach (ServerHubClient room in availableHubs)
{
hubInfosList.Add(new ServerHubListObject(room));
}
}
hubsList.tableView.ReloadData();
}
19
View Source File : DefaultTypeMap.cs
License : MIT License
Project Creator : anet-team
License : MIT License
Project Creator : anet-team
public ConstructorInfo FindConstructor(string[] names, Type[] types)
{
var constructors = _type.GetConstructors(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
foreach (ConstructorInfo ctor in constructors.OrderBy(c => c.IsPublic ? 0 : (c.IsPrivate ? 2 : 1)).ThenBy(c => c.GetParameters().Length))
{
ParameterInfo[] ctorParameters = ctor.GetParameters();
if (ctorParameters.Length == 0)
return ctor;
if (ctorParameters.Length != types.Length)
continue;
int i = 0;
for (; i < ctorParameters.Length; i++)
{
if (!string.Equals(ctorParameters[i].Name, names[i], StringComparison.OrdinalIgnoreCase))
break;
if (types[i] == typeof(byte[]) && ctorParameters[i].ParameterType.FullName == SqlMapper.LinqBinary)
continue;
var unboxedType = Nullable.GetUnderlyingType(ctorParameters[i].ParameterType) ?? ctorParameters[i].ParameterType;
if ((unboxedType != types[i] && !SqlMapper.HasTypeHandler(unboxedType))
&& !(unboxedType.IsEnum() && Enum.GetUnderlyingType(unboxedType) == types[i])
&& !(unboxedType == typeof(char) && types[i] == typeof(string))
&& !(unboxedType.IsEnum() && types[i] == typeof(string)))
{
break;
}
}
if (i == ctorParameters.Length)
return ctor;
}
return null;
}
19
View Source File : BrainstormAppService.cs
License : MIT License
Project Creator : anteatergames
License : MIT License
Project Creator : anteatergames
public OperationResultListVo<BrainstormSessionViewModel> GetSessions(Guid userId)
{
try
{
IEnumerable<BrainstormSession> allModels = brainstormDomainService.GetAll();
IEnumerable<BrainstormSessionViewModel> vms = mapper.Map<IEnumerable<BrainstormSession>, IEnumerable<BrainstormSessionViewModel>>(allModels);
vms = vms.OrderBy(x => x.Type).ThenBy(x => x.CreateDate);
return new OperationResultListVo<BrainstormSessionViewModel>(vms);
}
catch (Exception ex)
{
return new OperationResultListVo<BrainstormSessionViewModel>(ex.Message);
}
}
19
View Source File : AIInvestigator.cs
License : GNU Lesser General Public License v3.0
Project Creator : ApexGameTools
License : GNU Lesser General Public License v3.0
Project Creator : ApexGameTools
private string Export()
{
StringBuilder b = new StringBuilder();
if (_aiGrouping == AIGrouping.ScenesAndPrefabs)
{
foreach (var item in _referencers.OrderBy(item => !item.isPrefab).ThenBy(item => item.name))
{
b.AppendFormat("[{0}]", item.name);
b.AppendLine();
b.AppendLine();
b.AppendLine("Direct References:");
foreach (var aiRef in item.directReferences)
{
b.AppendLine(aiRef.name);
}
b.AppendLine();
if (item.indirectReferences.Count > 0)
{
b.AppendLine("Indirect References:");
foreach (var aiRef in item.indirectReferences)
{
b.AppendLine(aiRef.name);
}
b.AppendLine();
}
}
}
else
{
foreach (var ai in _aisList)
{
b.AppendFormat("[{0}]", ai.name);
b.AppendLine();
b.AppendLine();
if (ai.directReferences.Count > 0)
{
b.AppendLine("Direct References:");
foreach (var aiRef in ai.directReferences)
{
b.AppendLine(aiRef.name);
}
b.AppendLine();
}
if (ai.directlyReferencingScenesOrPrefabs.Length > 0)
{
b.AppendLine("Directly referenced by Scene or Prefab:");
foreach (var sof in ai.directlyReferencingScenesOrPrefabs)
{
b.AppendLine(sof.name);
}
b.AppendLine();
}
if (ai.directlyReferencingAIs.Length > 0)
{
b.AppendLine("Directly referenced by AIs:");
foreach (var aiRef in ai.directlyReferencingAIs)
{
b.AppendLine(aiRef.name);
}
b.AppendLine();
}
if (ai.indirectReferences.Count > 0)
{
b.AppendLine("Indirect References:");
foreach (var aiRef in ai.indirectReferences)
{
b.AppendLine(aiRef.name);
}
b.AppendLine();
}
if (ai.indirectlyReferencingScenesOrPrefabs.Length > 0)
{
b.AppendLine("Indirectly referenced by Scene or Prefab:");
foreach (var sof in ai.indirectlyReferencingScenesOrPrefabs)
{
b.AppendLine(sof.name);
}
b.AppendLine();
}
if (ai.indirectlyReferencingAIs.Length > 0)
{
b.AppendLine("Indirectly referenced by AIs:");
foreach (var aiRef in ai.indirectlyReferencingAIs)
{
b.AppendLine(aiRef.name);
}
b.AppendLine();
}
}
}
return b.ToString();
}
19
View Source File : MarkdownReporter.cs
License : MIT License
Project Creator : apexsharp
License : MIT License
Project Creator : apexsharp
public static string GetReport(IEnumerable<ClreplacedReference> clreplacedes, bool notImplementedOnly = false, bool ignoreApexSharp = true)
{
var sb = new StringBuilder();
clreplacedes = clreplacedes.Where(c => c != null)
.OrderBy(c => c.Namespace)
.ThenBy(c => c.Name);
if (notImplementedOnly)
{
clreplacedes = clreplacedes.Where(c => !c.HasImplementation);
}
var lastNamespace = string.Empty;
foreach (var c in clreplacedes)
{
if (ignoreApexSharp && c.Namespace.StartsWith("Apex.ApexSharp"))
{
continue;
}
if (c.Namespace != lastNamespace)
{
sb.AppendLine("## " + c.Namespace + " namespace");
lastNamespace = c.Namespace;
}
var ni = c.HasImplementation ? string.Empty : " (not implemented)";
sb.AppendLine("#### " + c.Name + " clreplaced" + ni);
var constructors = c.Constructors.Values.OrderBy(m => m.Signature);
if (constructors.Any())
{
foreach (var m in constructors)
{
sb.Append("* new ");
sb.AppendLine(m.Signature);
}
}
var methods = c.Methods.Values.OrderBy(m => m.Signature);
if (methods.Any())
{
foreach (var m in methods)
{
sb.Append("* ");
sb.AppendLine(m.Signature);
}
}
var properties = c.Properties.Values.OrderBy(m => m.Name);
if (properties.Any())
{
foreach (var p in properties)
{
sb.Append("* ");
sb.AppendLine(p.Signature);
}
}
}
return sb.ToString();
}
19
View Source File : SimpleReporter.cs
License : MIT License
Project Creator : apexsharp
License : MIT License
Project Creator : apexsharp
public static string GetReport(IEnumerable<ClreplacedReference> clreplacedes, bool notImplementedOnly = false, bool ignoreApexSharp = true)
{
var sb = new StringBuilder();
clreplacedes = clreplacedes.Where(c => c != null)
.OrderBy(c => c.Namespace)
.ThenBy(c => c.Name);
if (notImplementedOnly)
{
clreplacedes = clreplacedes.Where(c => !c.HasImplementation);
}
var lastNamespace = string.Empty;
foreach (var c in clreplacedes)
{
if (ignoreApexSharp && c.Namespace.StartsWith("Apex.ApexSharp"))
{
continue;
}
if (c.Namespace != lastNamespace)
{
sb.AppendLine(c.Namespace);
lastNamespace = c.Namespace;
}
sb.Append(Indent);
sb.AppendLine(c.Name);
var constructors = c.Constructors.Values.OrderBy(m => m.Signature);
foreach (var m in constructors)
{
sb.Append(Indent + Indent + "new ");
sb.AppendLine(m.Signature);
}
var methods = c.Methods.Values.OrderBy(m => m.Signature);
foreach (var m in methods)
{
sb.Append(Indent + Indent);
sb.AppendLine(m.Signature);
}
var properties = c.Properties.Values.OrderBy(m => m.Name);
foreach (var p in properties)
{
sb.Append(Indent + Indent);
sb.AppendLine(p.Signature);
}
}
return sb.ToString();
}
19
View Source File : UploadController.cs
License : MIT License
Project Creator : aprilyush
License : MIT License
Project Creator : aprilyush
[HttpGet("Merge")]
[RequirePermission("#")]
public IActionResult Merge()
{
var result = new ResultAdaptDto();
try
{
string guid = RequestHelper.GetQueryString("guid");
string fileName = RequestHelper.GetQueryString("fileName");
var tempDir = GlobalContext.WebRootPath + "/UploadTemp/" + guid; // 缓存文件夹
var targetDir = GlobalContext.WebRootPath + "/upfiles/videos/" + DateTime.Now.ToString("yyyyMMdd"); // 目标文件夹
//uploadfile,uploadvideo
string action = RequestHelper.GetPostString("action");
if(action== "uploadfile")
{
targetDir = GlobalContext.WebRootPath + "/upfiles/attachments/" + DateTime.Now.ToString("yyyyMMdd"); // 目标文件夹
}
if (!System.IO.Directory.Exists(targetDir))
{
System.IO.Directory.CreateDirectory(targetDir);
}
int index = fileName.LastIndexOf('.');
string extName = fileName.Substring(index);
string guidFileName = IdHelper.ObjectId() + extName;
var finalPath = Path.Combine(targetDir, guidFileName);
var files = System.IO.Directory.GetFiles(tempDir);//获得下面的所有文件
using (FileStream fs = System.IO.File.Create(finalPath))
{
foreach (var part in files.OrderBy(x => x.Length).ThenBy(x => x))//排一下序,保证从0-N Write
{
var bytes = System.IO.File.ReadAllBytes(part);
fs.Write(bytes, 0, bytes.Length);
bytes = null;
System.IO.File.Delete(part);//删除分块
}
fs.Flush();
}
string returnPath = "/upfiles/videos/" + DateTime.Now.ToString("yyyyMMdd") + "/" + guidFileName;
if (action == "uploadfile")
{
returnPath= "/upfiles/attachments/" + DateTime.Now.ToString("yyyyMMdd") + "/"+ guidFileName;
}
result.data.Add("url", returnPath);
//文件合并完成后移除缓存
FileChunkCache.RemoveChunkId(guid);
result.data.Add("fileName", fileName);
}
catch(Exception ex)
{
result.status = false;
result.message = ex.Message;
}
return Content(result.ToJson());
}
19
View Source File : WinFormsTranslator.cs
License : MIT License
Project Creator : architdate
License : MIT License
Project Creator : architdate
public IEnumerable<string> Write(char separator = Separator)
{
return Translation.Select(z => $"{z.Key}{separator}{z.Value}").OrderBy(z => z.Contains(".")).ThenBy(z => z);
}
19
View Source File : StatsContainerEditor.cs
License : MIT License
Project Creator : ashblue
License : MIT License
Project Creator : ashblue
void RebuildDisplay () {
_definitions.Clear();
List<StatDefinition> results;
if (Target.collection == null) {
results = StatDefinitionsCompiled.GetDefinitions(StatsSettings.Current.DefaultStats);
} else {
results = StatDefinitionsCompiled.GetDefinitions(Target.collection);
}
if (results == null) return;
_definitions = results;
_definitions = _definitions
.OrderByDescending(d => d.SortIndex)
.ThenBy(d => d.DisplayName)
.ToList();
Target.overrides.Clean();
serializedObject.ApplyModifiedProperties();
}
19
View Source File : ReactionsModule.cs
License : GNU Affero General Public License v3.0
Project Creator : asmejkal
License : GNU Affero General Public License v3.0
Project Creator : asmejkal
[Command("reactions", "stats", "Shows how many times reactions have been used.")]
[Alias("reaction", "stats", true), Alias("reactions", "top")]
[Parameter("IdOrTrigger", ParameterType.String, ParameterFlags.Remainder | ParameterFlags.Optional, "the reaction trigger or ID; shows all reactions if omitted")]
public async Task ShowReactionStats(ICommand command)
{
var settings = await _settings.Read<ReactionsSettings>(command.GuildId, false);
if (settings == null || !settings.Reactions.Any())
{
await command.Reply("No reactions have been set up on this server.");
return;
}
IEnumerable<Reaction> reactions;
if (command["IdOrTrigger"].HasValue)
reactions = FindReactions(settings, command["IdOrTrigger"]);
else
reactions = settings.Reactions;
var stats = reactions
.GroupBy(x => x.Trigger)
.Select(x => (Trigger: x.Key, TriggerCount: x.Sum(y => y.TriggerCount)))
.OrderByDescending(x => x.TriggerCount)
.ThenBy(x => x.Trigger);
var pages = new PageCollectionBuilder();
var place = 1;
foreach (var reaction in stats.Take(100))
pages.AppendLine($"`#{place++}` **{reaction.Trigger.Truncate(30)}** – triggered **{reaction.TriggerCount}** time{(reaction.TriggerCount != 1 ? "s" : "")}");
var embedFactory = new Func<EmbedBuilder>(() => new EmbedBuilder()
.Withreplacedle("Reaction statistics")
.WithFooter($"{settings.Reactions.Count} reactions in total"));
await command.Reply(pages.BuildEmbedCollection(embedFactory, 10), true);
}
19
View Source File : ReactionsModule.cs
License : GNU Affero General Public License v3.0
Project Creator : asmejkal
License : GNU Affero General Public License v3.0
Project Creator : asmejkal
private static PageCollection BuildReactionList(IEnumerable<Reaction> reactions, string replacedle, string footer = null)
{
var pages = new PageCollection();
int count = 0;
foreach (var reaction in reactions.OrderBy(x => x.Trigger).ThenBy(x => x.Id))
{
if (count++ % 10 == 0)
{
var embed = new EmbedBuilder().Withreplacedle(replacedle);
if (!string.IsNullOrEmpty(footer))
embed.WithFooter(footer);
pages.Add(embed);
}
pages.Last.Embed.AddField(x => x
.WithName($"{reaction.Id}: {reaction.Trigger}".Truncate(EmbedBuilder.MaxreplacedleLength))
.WithValue(reaction.Value.Truncate(500)));
}
return pages;
}
19
View Source File : FIlesViewer.xaml.cs
License : GNU General Public License v3.0
Project Creator : autodotua
License : GNU General Public License v3.0
Project Creator : autodotua
private ObservableCollection<UIFile> GetSortedFiles(SortType type, IEnumerable<UIFile> rawFiles = null)
{
IEnumerable<UIFile> files = null;
switch (type)
{
case SortType.Default:
files = rawFiles
.OrderBy(p => p.File.Dir)
.ThenBy(p => p.File.Name);
break;
case SortType.NameUp:
files = rawFiles
.OrderBy(p => p.File.Name)
.ThenBy(p => p.File.Dir);
break;
case SortType.NameDown:
files = rawFiles
.OrderByDescending(p => p.File.Name)
.ThenByDescending(p => p.File.Dir);
break;
case SortType.LengthUp:
files = rawFiles
.OrderBy(p => GetFileInfoValue(p, nameof(FI.Length)))
.ThenBy(p => p.File.Name)
.ThenBy(p => p.File.Dir);
break;
case SortType.LengthDown:
files = rawFiles
.OrderByDescending(p => GetFileInfoValue(p, nameof(FI.Length)))
.ThenByDescending(p => p.File.Name)
.ThenByDescending(p => p.File.Dir);
break;
case SortType.LastWriteTimeUp:
files = rawFiles
.OrderBy(p => GetFileInfoValue(p, nameof(FI.LastWriteTime)))
.ThenBy(p => p.File.Name)
.ThenBy(p => p.File.Dir);
break;
case SortType.LastWriteTimeDown:
files = rawFiles
.OrderByDescending(p => GetFileInfoValue(p, nameof(FI.LastWriteTime)))
.ThenByDescending(p => p.File.Name)
.ThenByDescending(p => p.File.Dir);
break;
case SortType.CreationTimeUp:
files = rawFiles
.OrderBy(p => GetFileInfoValue(p, nameof(FI.CreationTime)))
.ThenBy(p => p.File.Name)
.ThenBy(p => p.File.Dir);
break;
case SortType.CreationTimeDown:
files = rawFiles
.OrderByDescending(p => GetFileInfoValue(p, nameof(FI.CreationTime)))
.ThenByDescending(p => p.File.Name)
.ThenByDescending(p => p.File.Dir);
break;
}
//在非UI线程里就得把Lazy的全都计算好
return new ObservableCollection<UIFile>(files);
//若文件不存在,直接访问FileInfo属性会报错,因此需要加一层try
static long GetFileInfoValue(UIFile file, string name)
{
if (!file.File.FileInfo.Exists)
{
return 0;
}
try
{
return name switch
{
nameof(FI.Length) => file.File.FileInfo.Length,
nameof(FI.LastWriteTime) => file.File.FileInfo.LastWriteTime.Ticks,
nameof(FI.CreationTime) => file.File.FileInfo.CreationTime.Ticks,
_ => throw new NotImplementedException(),
};
}
catch
{
return 0;
}
}
19
View Source File : LogAggregator.cs
License : MIT License
Project Creator : awaescher
License : MIT License
Project Creator : awaescher
public List<AggregateLogItem> Aggregate(List<LogItem> logs)
{
var result = new List<AggregateLogItem>();
AggregateLogItem aggregate = null;
var orderedLogs = logs
.OrderBy(l => l.DisplayName)
.ThenBy(l => l.TimeStampUtc)
.ToList();
foreach (var log in orderedLogs)
{
if (aggregate?.CanAggregate(log) ?? false)
{
aggregate.AddItem(log);
continue;
}
aggregate = new AggregateLogItem(log);
result.Add(aggregate);
}
return result;
}
19
View Source File : WriterExtensions.cs
License : Apache License 2.0
Project Creator : azizamari
License : Apache License 2.0
Project Creator : azizamari
public static void WriteDiagnostics(this TextWriter writer, IEnumerable<Diagnostic> diagnostics)
{
foreach (var diagnostic in diagnostics.OrderBy(d=>d.Location.Text.FileName).ThenBy(d => d.Location.Span.Start).ThenBy(d=>d.Location.Span.Length))
{
var text = diagnostic.Location.Text;
var fileName = diagnostic.Location.FileName;
var startLine = diagnostic.Location.StartLine + 1;
var startCharacter = diagnostic.Location.StartCharacter + 1;
//var endLine = diagnostic.Location.EndLine + 1;
//var endCharacter = diagnostic.Location.EndCharacter + 1;
var span = diagnostic.Location.Span;
var lineIndex = text.GetLineIndex(span.Start);
var line = text.Lines[lineIndex];
Console.ForegroundColor = ConsoleColor.Red;
Console.Write($"{fileName}(line {startLine}, col {startCharacter}): ");
Console.WriteLine(diagnostic);
Console.ResetColor();
var prefixSpan = TextSpan.FromBounds(line.Start, span.Start);
var suffixSpan = TextSpan.FromBounds(span.End, line.End);
var prefix = text.ToString(prefixSpan);
var error = text.ToString(span);
var suffix = text.ToString(suffixSpan);
Console.Write(" ");
Console.WriteLine(prefix + error + suffix);
var arrows = " " + new string(' ', prefix.Length) + new string('^', error.Length);
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(arrows);
Console.ResetColor();
}
}
19
View Source File : WriterExtensions.cs
License : Apache License 2.0
Project Creator : azizamari
License : Apache License 2.0
Project Creator : azizamari
public static void ReturnDiagnostics(this IEnumerable<Diagnostic> diagnostics, Action<string> send)
{
foreach (var diagnostic in diagnostics.OrderBy(d => d.Location.Text.FileName).ThenBy(d => d.Location.Span.Start).ThenBy(d => d.Location.Span.Length))
{
var text = diagnostic.Location.Text;
var fileName = diagnostic.Location.FileName;
var startLine = diagnostic.Location.StartLine + 1;
var startCharacter = diagnostic.Location.StartCharacter + 1;
send($"{fileName}(line {startLine}, col {startCharacter}): "+ diagnostic.ToString());
}
}
19
View Source File : UniSymbolTreeView.cs
License : MIT License
Project Creator : baba-s
License : MIT License
Project Creator : baba-s
private void Sorreplacedems( MultiColumnHeader header )
{
var index = ( ColumnType ) header.sortedColumnIndex;
var ascending = header.IsSortedAscending( header.sortedColumnIndex );
IOrderedEnumerable<UniSymbolItem> ordered = null;
switch ( index )
{
case ColumnType.NUMBER:
case ColumnType.COPY:
ordered = m_list.OrderBy( c => c.id );
break;
case ColumnType.IS_ENABLE:
ordered = m_list
.OrderBy( c => !c.IsEnable )
.ThenBy( c => c.id )
;
break;
case ColumnType.NAME:
ordered = m_list
.OrderBy( c => c.Name )
.ThenBy( c => c.id )
;
break;
case ColumnType.COMMENT:
ordered = m_list
.OrderBy( c => c.Comment )
.ThenBy( c => c.id )
;
break;
}
var items = ordered.AsEnumerable();
if ( !ascending )
{
items = items.Reverse();
}
rooreplacedem.children = items.Cast<TreeViewItem>().ToList();
BuildRows( rooreplacedem );
}
19
View Source File : UCTRUtils.cs
License : MIT License
Project Creator : baba-s
License : MIT License
Project Creator : baba-s
private static IEnumerable<GameObjectData> OrderByName( this IEnumerable<GameObjectData> self )
{
return self
.OrderBy( c => c.ScenePath )
.ThenBy( c => c.RootPath )
;
}
19
View Source File : AliasesCache.cs
License : MIT License
Project Creator : baking-bad
License : MIT License
Project Creator : baking-bad
public IEnumerable<Alias> Search(string search, int limit)
{
search = search.Trim().ToLower();
if (search.Length < 3)
return SimpleSearch(search, limit);
var candidates = new Dictionary<Alias, int>();
lock (this)
{
foreach (var trigram in GetTrigrams(search))
{
if (Dictionary.TryGetValue(trigram, out var aliases))
{
foreach (var alias in aliases)
{
if (!candidates.TryAdd(alias, 1))
candidates[alias] += 1;
}
}
}
if (Dictionary.TryGetValue($" {search[..2]}", out var aliases2))
{
foreach (var alias in aliases2)
{
if (alias.Name.ToLower() == search)
candidates[alias] += 1000;
}
}
}
return candidates.OrderByDescending(x => x.Value)
.ThenBy(x => x.Key.Name)
.Select(x => x.Key)
.Take(limit);
}
19
View Source File : AliasesCache.cs
License : MIT License
Project Creator : baking-bad
License : MIT License
Project Creator : baking-bad
public IEnumerable<Alias> SimpleSearch(string search, int limit)
{
var res = new List<(Alias alias, int priority)>();
lock (this)
{
foreach (var item in Aliases)
{
var name = item.Name.ToLower();
if (name == search)
res.Add((item, 0));
else if (name.StartsWith(search))
res.Add((item, 1));
else if (name.Contains(search))
res.Add((item, 2));
}
}
return res.OrderBy(x => x.priority)
.ThenBy(x => x.alias.Name)
.Select(x => x.alias)
.Take(limit);
}
19
View Source File : CreatureTextDumper.cs
License : The Unlicense
Project Creator : BAndysc
License : The Unlicense
Project Creator : BAndysc
public async Task<string> Generate()
{
var trans = Queries.BeginTransaction();
if (!asDiff)
trans.Comment("Warning!! This SQL will override current texts");
foreach (var entry in perEntryState)
{
int maxId = -1;
if (asDiff)
{
var existing = await databaseProvider.GetCreatureTextsByEntry(entry.Key);
foreach (var text in existing)
{
if (text.Text == null)
continue;
var databaseEntry = new TextEntry(text);
if (entry.Value.texts.TryGetValue(databaseEntry, out var sniffEntry))
{
entry.Value.texts.Remove(sniffEntry);
databaseEntry.IsInSniffText = true;
}
entry.Value.texts.Add(databaseEntry);
maxId = Math.Max(maxId, text.GroupId);
}
}
foreach (var sniffText in entry.Value.texts.Where(t => t.IsInSniffText && !t.IsInDatabaseText))
{
sniffText.BroadcastTextId =
(await databaseProvider.GetBroadcastTextByTextAsync(sniffText.Text))?.Id ?? 0;
sniffText.GroupId = (byte)(++maxId);
}
var template = databaseProvider.GetCreatureTemplate(entry.Key);
if (template != null)
trans.Comment(template.Name);
trans.Table("creature_text")
.Where(row => row.Column<uint>("CreatureID") == entry.Key)
.Delete();
trans.Table("creature_text")
.BulkInsert(entry.Value.texts
.OrderBy(t => t.GroupId)
.ThenBy(t => t.Id)
.Select(text => new
{
CreatureID = entry.Key,
GroupID = text.GroupId,
ID = text.Id,
Text = text.Text,
Type = (uint)text.Type,
Language = text.Language,
Probability = text.Probability,
Duration = text.Duration,
TextRange = (uint)text.Range,
Emote = text.Emote,
Sound = text.Sound,
BroadcastTextId = text.BroadcastTextId,
comment = text.Comment ?? template?.Name ?? "",
__comment = !text.IsInSniffText ? "not in sniff" : null
}));
trans.BlankLine();
}
return trans.Close().QueryString;
}
19
View Source File : UnzippedDirectory.cs
License : MIT License
Project Creator : bbepis
License : MIT License
Project Creator : bbepis
public IEnumerable<RedirectedResource> GetFiles( string path, params string[] extensions )
{
if( !_cacheNormalFiles )
{
if( Directory.Exists( path ) )
{
var noExtensions = extensions == null || extensions.Length == 0;
var files = Directory.GetFiles( path, "*", SearchOption.TopDirectoryOnly );
foreach( var file in files )
{
if( noExtensions || extensions.Any( x => file.EndsWith( x, StringComparison.OrdinalIgnoreCase ) ) )
{
yield return new RedirectedResource( file );
}
}
}
}
if( _rootDirectory != null )
{
path = path.ToLowerInvariant();
if( !Path.IsPathRooted( path ) )
{
path = Path.Combine( _loweredCurrentDirectory, path );
}
path = path.MakeRelativePath( _root );
var entries = _rootDirectory.GetFiles( path, null, true )
.OrderBy( x => x.IsZipped )
.ThenBy( x => x.ContainerFile )
.ThenBy( x => x.FullPath )
.ToList();
foreach( var entry in entries )
{
if( entry.IsZipped )
{
yield return new RedirectedResource( () => entry.ZipFile.GetInputStream( entry.ZipEntry ), entry.ContainerFile, entry.FullPath );
}
else
{
yield return new RedirectedResource( entry.FileName );
}
}
}
}
19
View Source File : TranslationManager.cs
License : MIT License
Project Creator : bbepis
License : MIT License
Project Creator : bbepis
public void InitializeEndpoints( GameObject go )
{
try
{
var httpSecurity = new HttpSecurity();
var context = new InitializationContext( httpSecurity, Settings.FromLanguage, Settings.Language );
CreateEndpoints( go, context );
AllEndpoints = AllEndpoints
.OrderBy( x => x.Error != null )
.ThenBy( x => x.Endpoint.FriendlyName )
.ToList();
PreplacedthroughEndpoint = AllEndpoints.FirstOrDefault( x => x.Endpoint is PreplacedthroughTranslateEndpoint );
var fallbackEndpoint = AllEndpoints.FirstOrDefault( x => x.Endpoint.Id == Settings.FallbackServiceEndpoint );
if( fallbackEndpoint != null )
{
if( fallbackEndpoint.Error != null )
{
XuaLogger.AutoTranslator.Error( fallbackEndpoint.Error, "Error occurred during the initialization of the fallback translate endpoint." );
}
else
{
FallbackEndpoint = fallbackEndpoint;
}
}
var primaryEndpoint = AllEndpoints.FirstOrDefault( x => x.Endpoint.Id == Settings.ServiceEndpoint );
if( primaryEndpoint != null )
{
if( primaryEndpoint.Error != null )
{
XuaLogger.AutoTranslator.Error( primaryEndpoint.Error, "Error occurred during the initialization of the selected translate endpoint." );
}
else
{
if( fallbackEndpoint == primaryEndpoint )
{
XuaLogger.AutoTranslator.Warn( "Cannot use same fallback endpoint as primary." );
}
CurrentEndpoint = primaryEndpoint;
}
}
else if( !string.IsNullOrEmpty( Settings.ServiceEndpoint ) )
{
XuaLogger.AutoTranslator.Error( $"Could not find the configured endpoint '{Settings.ServiceEndpoint}'." );
}
if( Settings.DisableCertificateValidation )
{
XuaLogger.AutoTranslator.Debug( $"Disabling certificate checks for endpoints because of configuration." );
ServicePointManager.ServerCertificateValidationCallback += ( a1, a2, a3, a4 ) => true;
}
else
{
var callback = httpSecurity.GetCertificateValidationCheck();
if( callback != null && !Features.SupportsNet4x )
{
XuaLogger.AutoTranslator.Debug( $"Disabling certificate checks for endpoints because a .NET 3.x runtime is used." );
ServicePointManager.ServerCertificateValidationCallback += callback;
}
else
{
XuaLogger.AutoTranslator.Debug( $"Not disabling certificate checks for endpoints because a .NET 4.x runtime is used." );
}
}
// save config because the initialization phase of plugins may have changed the config
Settings.Save();
}
catch( Exception e )
{
XuaLogger.AutoTranslator.Error( e, "An error occurred while constructing endpoints. Shutting plugin down." );
Settings.IsShutdown = true;
}
}
19
View Source File : UnzippedDirectory.cs
License : MIT License
Project Creator : bbepis
License : MIT License
Project Creator : bbepis
public IEnumerable<RedirectedResource> GetFile( string path )
{
if( !_cacheNormalFiles )
{
if( File.Exists( path ) )
{
yield return new RedirectedResource( path );
}
}
if( _rootDirectory != null )
{
path = path.ToLowerInvariant();
if( !Path.IsPathRooted( path ) )
{
path = Path.Combine( _loweredCurrentDirectory, path );
}
path = path.MakeRelativePath( _root );
var entries = _rootDirectory.GetFiles( path, null, false )
.OrderBy( x => x.IsZipped )
.ThenBy( x => x.ContainerFile )
.ThenBy( x => x.FullPath );
foreach( var entry in entries )
{
if( entry.IsZipped )
{
yield return new RedirectedResource( () => entry.ZipFile.GetInputStream( entry.ZipEntry ), entry.ContainerFile, entry.FullPath );
}
else
{
yield return new RedirectedResource( entry.FileName );
}
}
}
}
19
View Source File : FunctionEndpoint.cs
License : MIT License
Project Creator : Beffyman
License : MIT License
Project Creator : Beffyman
public IEnumerable<IParameter> GetParametersForHttpMethod(HttpMethod method)
{
return GetChildren().OfType<IParameter>().Union(GetHttpParameters(method)).OrderBy(x => x.DefaultValue == null ? 0 : 1).ThenBy(x => x.SortOrder);
}
19
View Source File : HubEndpoint.cs
License : MIT License
Project Creator : Beffyman
License : MIT License
Project Creator : Beffyman
public IEnumerable<IParameter> GetParameters()
{
return GetChildren()
.OfType<IParameter>()
.Union(new List<IParameter> { new CancellationTokenModifier() })
.OrderBy(x => x.SortOrder)
.ThenBy(x => x.DefaultValue == null ? 0 : 1);
}
See More Examples