Here are the examples of the csharp api System.Collections.Generic.IEnumerable.ToDictionary(System.Func, System.Func, System.Collections.Generic.IEqualityComparer) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
781 Examples
19
View Source File : ZooKeeperServiceDiscovery.cs
License : MIT License
Project Creator : 1100100
License : MIT License
Project Creator : 1100100
public IReadOnlyDictionary<string, IReadOnlyList<ServiceNodeInfo>> GetAllService()
{
return ServiceNodes.ToDictionary(k => k.Key, v => (IReadOnlyList<ServiceNodeInfo>)v.Value);
}
19
View Source File : DiscInfoConverter.cs
License : MIT License
Project Creator : 13xforever
License : MIT License
Project Creator : 13xforever
public static DiscInfo ToDiscInfo(this Ird ird)
{
List<FileRecord> fsInfo;
var sectorSize = 2048L;
using (var stream = new MemoryStream())
{
using (var headerStream = new MemoryStream(ird.Header))
using (var gzipStream = new GZipStream(headerStream, CompressionMode.Decompress))
gzipStream.CopyTo(stream);
stream.Seek(0, SeekOrigin.Begin);
var reader = new CDReader(stream, true, true);
(fsInfo, _) = reader.GetFilesystemStructure();
sectorSize = reader.ClusterSize;
}
var checksums = ird.Files.ToDictionary(f => f.Offset, f => f.Md5Checksum.ToHexString());
return new DiscInfo
{
ProductCode = ird.ProductCode,
DiscVersion = ird.GameVersion,
DiscKeyRawData = ird.Data1.ToHexString(),
DiscKey = Decrypter.DecryptDiscKey(ird.Data1).ToHexString(),
Files = fsInfo.ToDictionary(
f => f.Filename,
f => new FileInfo
{
Offset = f.StartSector * sectorSize,
Size = f.Length,
Hashes = new Dictionary<string, string>
{
["MD5"] = checksums[f.StartSector],
}
})
};
}
19
View Source File : Admin.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
async public static Task<bool> Use(HttpContext context, IFreeSql fsql, string requestPathBase, Dictionary<string, Type> dicEnreplacedyTypes) {
HttpRequest req = context.Request;
HttpResponse res = context.Response;
var remUrl = req.Path.ToString().Substring(requestPathBase.Length).Trim(' ', '/').Split('/');
var enreplacedyName = remUrl.FirstOrDefault();
if (!string.IsNullOrEmpty(enreplacedyName)) {
if (dicEnreplacedyTypes.TryGetValue(enreplacedyName, out var enreplacedyType) == false) throw new Exception($"UseFreeAdminLtePreview 错误,找不到实体类型:{enreplacedyName}");
var tb = fsql.CodeFirst.GetTableByEnreplacedy(enreplacedyType);
if (tb == null) throw new Exception($"UseFreeAdminLtePreview 错误,实体类型无法映射:{enreplacedyType.FullName}");
var tpl = _tpl.Value;
switch (remUrl.ElementAtOrDefault(1)?.ToLower()) {
case null:
//首页
if (true) {
MakeTemplateFile($"{enreplacedyName}-list.html", Views.List);
//ManyToOne/OneToOne
var getlistFilter = new List<(TableRef, string, string, Dictionary<string, object>, List<Dictionary<string, object>>)>();
foreach (var prop in tb.Properties) {
if (tb.ColumnsByCs.ContainsKey(prop.Key)) continue;
var tbref = tb.GetTableRef(prop.Key, false);
if (tbref == null) continue;
switch (tbref.RefType) {
case TableRefType.OneToMany: continue;
case TableRefType.ManyToOne:
getlistFilter.Add(await Utils.GetTableRefData(fsql, tbref));
continue;
case TableRefType.OneToOne:
continue;
case TableRefType.ManyToMany:
getlistFilter.Add(await Utils.GetTableRefData(fsql, tbref));
continue;
}
}
int.TryParse(req.Query["page"].FirstOrDefault(), out var getpage);
int.TryParse(req.Query["limit"].FirstOrDefault(), out var getlimit);
if (getpage <= 0) getpage = 1;
if (getlimit <= 0) getlimit = 20;
var getselect = fsql.Select<object>().AsType(enreplacedyType);
foreach (var getlistF in getlistFilter) {
var qv = req.Query[getlistF.Item3].ToArray();
if (qv.Any()) {
switch (getlistF.Item1.RefType) {
case TableRefType.OneToMany: continue;
case TableRefType.ManyToOne:
getselect.Where(Utils.GetObjectWhereExpressionContains(tb, enreplacedyType, getlistF.Item1.Columns[0].CsName, qv));
continue;
case TableRefType.OneToOne:
continue;
case TableRefType.ManyToMany:
if (true) {
var midType = getlistF.Item1.RefMiddleEnreplacedyType;
var midTb = fsql.CodeFirst.GetTableByEnreplacedy(midType);
var midISelect = typeof(ISelect<>).MakeGenericType(midType);
var funcType = typeof(Func<,>).MakeGenericType(typeof(object), typeof(bool));
var expParam = Expression.Parameter(typeof(object), "a");
var midParam = Expression.Parameter(midType, "mdtp");
var anyMethod = midISelect.GetMethod("Any");
var selectExp = qv.Select(c => Expression.Convert(Expression.Constant(FreeSql.Internal.Utils.GetDataReaderValue(getlistF.Item1.MiddleColumns[1].CsType, c)), getlistF.Item1.MiddleColumns[1].CsType)).ToArray();
var expLambad = Expression.Lambda<Func<object, bool>>(
Expression.Call(
Expression.Call(
Expression.Call(
Expression.Constant(fsql),
typeof(IFreeSql).GetMethod("Select", new Type[0]).MakeGenericMethod(midType)
),
midISelect.GetMethod("Where", new[] { typeof(Expression<>).MakeGenericType(typeof(Func<,>).MakeGenericType(midType, typeof(bool))) }),
Expression.Lambda(
typeof(Func<,>).MakeGenericType(midType, typeof(bool)),
Expression.AndAlso(
Expression.Equal(
Expression.MakeMemberAccess(Expression.TypeAs(expParam, enreplacedyType), tb.Properties[getlistF.Item1.Columns[0].CsName]),
Expression.MakeMemberAccess(midParam, midTb.Properties[getlistF.Item1.MiddleColumns[0].CsName])
),
Expression.Call(
Utils.GetLinqContains(getlistF.Item1.MiddleColumns[1].CsType),
Expression.NewArrayInit(
getlistF.Item1.MiddleColumns[1].CsType,
selectExp
),
Expression.MakeMemberAccess(midParam, midTb.Properties[getlistF.Item1.MiddleColumns[1].CsName])
)
),
midParam
)
),
anyMethod,
Expression.Default(anyMethod.GetParameters().FirstOrDefault().ParameterType)
),
expParam);
getselect.Where(expLambad);
}
continue;
}
}
}
var getlistTotal = await getselect.CountAsync();
var getlist = await getselect.Page(getpage, getlimit).ToListAsync();
var gethashlists = new Dictionary<string, object>[getlist.Count];
var gethashlistsIndex = 0;
foreach (var getlisreplacedem in getlist) {
var gethashlist = new Dictionary<string, object>();
foreach (var getcol in tb.ColumnsByCs) {
gethashlist.Add(getcol.Key, tb.Properties[getcol.Key].GetValue(getlisreplacedem));
}
gethashlists[gethashlistsIndex++] = gethashlist;
}
var options = new Dictionary<string, object>();
options["tb"] = tb;
options["getlist"] = gethashlists;
options["getlistTotal"] = getlistTotal;
options["getlistFilter"] = getlistFilter;
var str = _tpl.Value.RenderFile($"{enreplacedyName}-list.html", options);
await res.WriteAsync(str);
}
return true;
case "add":
case "edit":
//编辑页
object gereplacedem = null;
Dictionary<string, object> gethash = null;
if (req.Query.Any()) {
gereplacedem = Activator.CreateInstance(enreplacedyType);
foreach (var getpk in tb.Primarys) {
var reqv = req.Query[getpk.CsName].ToArray();
if (reqv.Any())
fsql.SetEnreplacedyValueWithPropertyName(enreplacedyType, gereplacedem, getpk.CsName, reqv.Length == 1 ? (object)reqv.FirstOrDefault() : reqv);
}
gereplacedem = await fsql.Select<object>().AsType(enreplacedyType).WhereDynamic(gereplacedem).FirstAsync();
if (gereplacedem != null) {
gethash = new Dictionary<string, object>();
foreach (var getcol in tb.ColumnsByCs) {
gethash.Add(getcol.Key, tb.Properties[getcol.Key].GetValue(gereplacedem));
}
}
}
if (req.Method.ToLower() == "get") {
MakeTemplateFile($"{enreplacedyName}-edit.html", Views.Edit);
//ManyToOne/OneToOne
var getlistFilter = new Dictionary<string, (TableRef, string, string, Dictionary<string, object>, List<Dictionary<string, object>>)>();
var getlistManyed = new Dictionary<string, IEnumerable<string>>();
foreach (var prop in tb.Properties) {
if (tb.ColumnsByCs.ContainsKey(prop.Key)) continue;
var tbref = tb.GetTableRef(prop.Key, false);
if (tbref == null) continue;
switch (tbref.RefType) {
case TableRefType.OneToMany: continue;
case TableRefType.ManyToOne:
getlistFilter.Add(prop.Key, await Utils.GetTableRefData(fsql, tbref));
continue;
case TableRefType.OneToOne:
continue;
case TableRefType.ManyToMany:
getlistFilter.Add(prop.Key, await Utils.GetTableRefData(fsql, tbref));
if (gereplacedem != null) {
var midType = tbref.RefMiddleEnreplacedyType;
var midTb = fsql.CodeFirst.GetTableByEnreplacedy(midType);
var manyed = await fsql.Select<object>().AsType(midType)
.Where(Utils.GetObjectWhereExpression(midTb, midType, tbref.MiddleColumns[0].CsName, fsql.GetEnreplacedyKeyValues(enreplacedyType, gereplacedem)[0]))
.ToListAsync();
getlistManyed.Add(prop.Key, manyed.Select(a => fsql.GetEnreplacedyValueWithPropertyName(midType, a, tbref.MiddleColumns[1].CsName).ToString()));
}
continue;
}
}
var options = new Dictionary<string, object>();
options["tb"] = tb;
options["gethash"] = gethash;
options["getlistFilter"] = getlistFilter;
options["getlistManyed"] = getlistManyed;
options["postaction"] = $"{requestPathBase}restful-api/{enreplacedyName}";
var str = _tpl.Value.RenderFile($"{enreplacedyName}-edit.html", options);
await res.WriteAsync(str);
} else {
if (gereplacedem == null) {
gereplacedem = Activator.CreateInstance(enreplacedyType);
foreach(var getcol in tb.Columns.Values) {
if (new[] { typeof(DateTime), typeof(DateTime?) }.Contains(getcol.CsType) && new[] { "create_time", "createtime" }.Contains(getcol.CsName.ToLower()))
fsql.SetEnreplacedyValueWithPropertyName(enreplacedyType, gereplacedem, getcol.CsName, DateTime.Now);
}
}
var manySave = new List<(TableRef, object[], List<object>)>();
if (req.Form.Any()) {
foreach(var getcol in tb.Columns.Values) {
if (new[] { typeof(DateTime), typeof(DateTime?) }.Contains(getcol.CsType) && new[] { "update_time", "updatetime" }.Contains(getcol.CsName.ToLower()))
fsql.SetEnreplacedyValueWithPropertyName(enreplacedyType, gereplacedem, getcol.CsName, DateTime.Now);
var reqv = req.Form[getcol.CsName].ToArray();
if (reqv.Any())
fsql.SetEnreplacedyValueWithPropertyName(enreplacedyType, gereplacedem, getcol.CsName, reqv.Length == 1 ? (object)reqv.FirstOrDefault() : reqv);
}
//ManyToMany
foreach (var prop in tb.Properties) {
if (tb.ColumnsByCs.ContainsKey(prop.Key)) continue;
var tbref = tb.GetTableRef(prop.Key, false);
if (tbref == null) continue;
switch (tbref.RefType) {
case TableRefType.OneToMany: continue;
case TableRefType.ManyToOne:
continue;
case TableRefType.OneToOne:
continue;
case TableRefType.ManyToMany:
var midType = tbref.RefMiddleEnreplacedyType;
var mtb = fsql.CodeFirst.GetTableByEnreplacedy(midType);
var reqv = req.Form[$"mn_{prop.Key}"].ToArray();
var reqvIndex = 0;
var manyVals = new object[reqv.Length];
foreach (var rv in reqv) {
var miditem = Activator.CreateInstance(midType);
foreach (var getcol in tb.Columns.Values) {
if (new[] { typeof(DateTime), typeof(DateTime?) }.Contains(getcol.CsType) && new[] { "create_time", "createtime" }.Contains(getcol.CsName.ToLower()))
fsql.SetEnreplacedyValueWithPropertyName(midType, miditem, getcol.CsName, DateTime.Now);
if (new[] { typeof(DateTime), typeof(DateTime?) }.Contains(getcol.CsType) && new[] { "update_time", "updatetime" }.Contains(getcol.CsName.ToLower()))
fsql.SetEnreplacedyValueWithPropertyName(midType, miditem, getcol.CsName, DateTime.Now);
}
//fsql.SetEnreplacedyValueWithPropertyName(midType, miditem, tbref.MiddleColumns[0].CsName, fsql.GetEnreplacedyKeyValues(enreplacedyType, gereplacedem)[0]);
fsql.SetEnreplacedyValueWithPropertyName(midType, miditem, tbref.MiddleColumns[1].CsName, rv);
manyVals[reqvIndex++] = miditem;
}
var molds = await fsql.Select<object>().AsType(midType).Where(Utils.GetObjectWhereExpression(mtb, midType, tbref.MiddleColumns[0].CsName, fsql.GetEnreplacedyKeyValues(enreplacedyType, gereplacedem)[0])).ToListAsync();
manySave.Add((tbref, manyVals, molds));
continue;
}
}
}
using (var db = fsql.CreateDbContext()) {
var dbset = db.Set<object>();
dbset.AsType(enreplacedyType);
await dbset.AddOrUpdateAsync(gereplacedem);
foreach (var ms in manySave) {
var midType = ms.Item1.RefMiddleEnreplacedyType;
var moldsDic = ms.Item3.ToDictionary(a => fsql.GetEnreplacedyKeyString(midType, a, true));
var manyset = db.Set<object>();
manyset.AsType(midType);
foreach (var msVal in ms.Item2) {
fsql.SetEnreplacedyValueWithPropertyName(midType, msVal, ms.Item1.MiddleColumns[0].CsName, fsql.GetEnreplacedyKeyValues(enreplacedyType, gereplacedem)[0]);
await manyset.AddOrUpdateAsync(msVal);
moldsDic.Remove(fsql.GetEnreplacedyKeyString(midType, msVal, true));
}
manyset.RemoveRange(moldsDic.Values);
}
await db.SaveChangesAsync();
}
gethash = new Dictionary<string, object>();
foreach (var getcol in tb.ColumnsByCs) {
gethash.Add(getcol.Key, tb.Properties[getcol.Key].GetValue(gereplacedem));
}
await Utils.Jsonp(context, new { code = 0, success = true, message = "Success", data = gethash });
}
return true;
case "del":
if (req.Method.ToLower() == "post") {
var delitems = new List<object>();
var reqv = new List<string[]>();
foreach(var delpk in tb.Primarys) {
var reqvs = req.Form[delpk.CsName].ToArray();
if (reqv.Count > 0 && reqvs.Length != reqv[0].Length) throw new Exception("删除失败,联合主键参数传递不对等");
reqv.Add(reqvs);
}
if (reqv[0].Length == 0) return true;
using (var ctx = fsql.CreateDbContext()) {
var dbset = ctx.Set<object>();
dbset.AsType(enreplacedyType);
for (var a = 0; a < reqv[0].Length; a++) {
object delitem = Activator.CreateInstance(enreplacedyType);
var delpkindex = 0;
foreach (var delpk in tb.Primarys)
fsql.SetEnreplacedyValueWithPropertyName(enreplacedyType, delitem, delpk.CsName, reqv[delpkindex++][a]);
dbset.Remove(delitem);
}
await ctx.SaveChangesAsync();
}
await Utils.Jsonp(context, new { code = 0, success = true, message = "Success" });
return true;
}
break;
}
}
return false;
}
19
View Source File : WorkFlowManagementDomainAutoMapperProfile.cs
License : Apache License 2.0
Project Creator : AbpApp
License : Apache License 2.0
Project Creator : AbpApp
public IDictionary<string, global::Elsa.Models.ActivityInstance> Convert(ICollection<ActivityInstance> sourceMember, ResolutionContext context)
{
return sourceMember.ToDictionary(x => x.ActivityId, x => context.Mapper.Map<global::Elsa.Models.ActivityInstance>(x));
}
19
View Source File : SurfaceMeshSelectionModifier.cs
License : MIT License
Project Creator : ABTSoftware
License : MIT License
Project Creator : ABTSoftware
public override void OnModifierMouseUp(ModifierMouseArgs e)
{
base.OnModifierMouseUp(e);
ClearAll();
if (!IsDragging || Viewport3D == null || Viewport3D.RootEnreplacedy == null) return;
var endPoint = e.MousePoint;
var distanceDragged = PointUtil.Distance(StartPoint, endPoint);
var isAreaSelection = distanceDragged > MinDragSensitivity;
IList<EnreplacedyVertexId> hitEnreplacedyVertexIds;
if (isAreaSelection)
{
// Drag select
hitEnreplacedyVertexIds = Viewport3D.PickScene(new Rect(StartPoint, e.MousePoint));
}
else
{
// Point select
var vertexId = Viewport3D.PickScene(e.MousePoint);
hitEnreplacedyVertexIds = vertexId.HasValue ? new[] { vertexId.Value } : new EnreplacedyVertexId[0];
}
if (!hitEnreplacedyVertexIds.IsNullOrEmpty())
{
var hitEnreplacedyGroups = hitEnreplacedyVertexIds
.GroupBy(x => x.EnreplacedyId)
.ToDictionary(x => x.Key, x => x.Select(i => new VertexId { Id = i.VertexId }).ToList());
var xSize = BoundedPaletteProvider.XSize - 1;
//Visit enreplacedies to perform selection or deselection
Viewport3D.RootEnreplacedy.VisitEnreplacedies(enreplacedy =>
{
var enreplacedyId = enreplacedy.EnreplacedyId;
var hitVertexIds = new List<VertexId>();
if (hitEnreplacedyGroups.ContainsKey(enreplacedyId))
{
hitVertexIds = hitEnreplacedyGroups[enreplacedyId];
}
if (hitVertexIds.Any())
{
if (!_selectedVertices.ContainsKey(enreplacedyId))
_selectedVertices.Add(enreplacedyId, new HashSet<ulong>());
var selectedVertices = _selectedVertices[enreplacedyId];
hitVertexIds.ForEach(x => selectedVertices.Add(x.Id));
BoundedPaletteProvider.SelectedIndexes.Clear();
foreach (var hitEnreplacedyVertexId in hitEnreplacedyVertexIds)
{
var id = Convert.ToInt32(hitEnreplacedyVertexId.VertexId) - 1;
var vertexIndexInfo = new SurfaceMeshVertexInfo();
if (id < xSize)
{
vertexIndexInfo.XIndex = id;
}
else
{
vertexIndexInfo.ZIndex = id / xSize;
vertexIndexInfo.XIndex = id - (vertexIndexInfo.ZIndex * xSize);
}
BoundedPaletteProvider.SelectedIndexes.Add(vertexIndexInfo);
}
}
else
{
_selectedVertices.Remove(enreplacedyId);
BoundedPaletteProvider.SelectedIndexes.Clear();
}
});
}
IsDragging = false;
ReleaseMouseCapture();
BoundedPaletteProvider.DataSeries.IsDirty = true;
BoundedPaletteProvider.DataSeries.OnDataSeriesChanged(DataSeriesUpdate.SelectionChanged,
DataSeriesAction.None);
}
19
View Source File : Profile.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
public object Clone()
{
Profile newProfile = MemberwiseClone() as Profile;
// Since core attributes are cloned on read, we can get away with a shallow copy
newProfile.CoreAttributes = CoreAttributes != null ? CoreAttributes.ToDictionary(x => x.Key, x => (CoreProfileAttribute) x.Value.Clone()) : null;
newProfile.ApplicationContainer = ApplicationContainer != null ? (AttributesContainer)ApplicationContainer.Clone() : null;
return newProfile;
}
19
View Source File : ResourceProperties.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
internal IDictionary<String, Object> ToStringDictionary()
{
return this.Items.ToDictionary(x => x.Key, x => ToObject(x.Value), StringComparer.OrdinalIgnoreCase);
}
19
View Source File : AttributesContainer.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
public object Clone()
{
AttributesContainer newContainer = (AttributesContainer)MemberwiseClone();
// Deep copy of attributes dictionary
newContainer.Attributes = Attributes != null ? Attributes.ToDictionary(x => x.Key, x => (ProfileAttribute)x.Value.Clone()) : null;
return newContainer;
}
19
View Source File : PerformanceProfiler.cs
License : MIT License
Project Creator : adainrivers
License : MIT License
Project Creator : adainrivers
public Dictionary<string, PerformanceValue> GetProfiles()
{
return _profiles.ToDictionary(p =>
p.Key,
p => new PerformanceValue(
p.Value.MaxMilliseconds,
p.Value.TotalMilliseconds,
p.Value.ExecutionCount));
}
19
View Source File : MinVerCli.cs
License : Apache License 2.0
Project Creator : adamralph
License : Apache License 2.0
Project Creator : adamralph
public static async Task<Result> ReadAsync(string workingDirectory, string configuration = Configuration.Current, params (string, string)[] envVars)
{
var environmentVariables = envVars.ToDictionary(envVar => envVar.Item1, envVar => envVar.Item2, StringComparer.OrdinalIgnoreCase);
_ = environmentVariables.TryAdd("MinVerVerbosity".ToAltCase(), "trace");
return await CommandEx.ReadLoggedAsync("dotnet", $"exec {GetPath(configuration)}", workingDirectory, environmentVariables).ConfigureAwait(false);
}
19
View Source File : DefaultTranslationsProvider.cs
License : MIT License
Project Creator : adams85
License : MIT License
Project Creator : adams85
private Dictionary<(string Location, string Culture), POCatalog> LoadFiles()
{
return Directory.GetFiles(_translationsBasePath, FileNamePattern, SearchOption.AllDirectories)
.Select(LoadFile)
.Where(item => item != null)
.ToDictionary(item => (item!.Value.Location, item.Value.Culture), item => item!.Value.Catalog);
}
19
View Source File : OrganizationServiceContextExtensions.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
public static IDictionary<Guid, Tuple<string, string, BlogCommentPolicy, string[], IRatingInfo>> FetchBlogPostExtendedData(this OrganizationServiceContext serviceContext, IEnumerable<Guid> postIds, BlogCommentPolicy defaultCommentPolicy, Guid websiteId)
{
if (!postIds.Any())
{
return new Dictionary<Guid, Tuple<string, string, BlogCommentPolicy, string[], IRatingInfo>>();
}
var ids = postIds.ToArray();
var fetchXml = XDoreplacedent.Parse(@"
<fetch mapping=""logical"">
<enreplacedy name=""adx_blogpost"">
<attribute name=""adx_commentpolicy"" />
<filter type=""and"">
</filter>
<link-enreplacedy name=""adx_blog"" from=""adx_blogid"" to=""adx_blogid"" alias=""blog"">
<attribute name=""adx_commentpolicy"" />
</link-enreplacedy>
<link-enreplacedy link-type=""outer"" name=""contact"" from=""contactid"" to=""adx_authorid"" alias=""author"">
<attribute name=""contactid"" />
<attribute name=""fullname"" />
<attribute name=""firstname"" />
<attribute name=""lastname"" />
<attribute name=""emailaddress1"" />
</link-enreplacedy>
<link-enreplacedy link-type=""outer"" name=""adx_blogpost_tag"" from=""adx_blogpostid"" to=""adx_blogpostid"">
<link-enreplacedy link-type=""outer"" name=""adx_tag"" from=""adx_tagid"" to=""adx_tagid"" alias=""tag"">
<attribute name=""adx_name"" />
<filter type=""and"">
<condition attribute=""adx_websiteid"" operator=""eq"" />
</filter>
</link-enreplacedy>
</link-enreplacedy>
</enreplacedy>
</fetch>");
var postFilter = fetchXml.XPathSelectElement("//enreplacedy[@name='adx_blogpost']/filter");
if (postFilter == null)
{
throw new InvalidOperationException(string.Format("Unable to select {0} element.", "adx_blogpostid filter condition"));
}
postFilter.AddFetchXmlFilterInCondition("adx_blogpostid", ids.Select(id => id.ToString()));
var websiteConditions = fetchXml.XPathSelectElements("//filter/condition[@attribute='adx_websiteid']");
foreach (var websiteCondition in websiteConditions)
{
websiteCondition.SetAttributeValue("value", websiteId.ToString());
}
var fetch = Fetch.Parse(fetchXml.ToString());
var contactLink = fetch.Enreplacedy.Links.FirstOrDefault(l => l.Name.Equals("contact"));
if (contactLink != null)
{
contactLink.IsUnique = true;
}
var response = (serviceContext as IOrganizationService).RetrieveMultiple(fetch);
var aggregateFilter = fetchXml.Descendants("filter").First();
aggregateFilter.AddFetchXmlFilterInCondition("adx_blogpostid", ids.Select(id => id.ToString()));
EnreplacedyCollection aggregateResponse = null;
if (FeatureCheckHelper.IsFeatureEnabled(FeatureNames.Feedback))
{
XDoreplacedent aggregateFetchXml = XDoreplacedent.Parse(@"
<fetch mapping=""logical"" aggregate=""true"">
<enreplacedy name=""feedback"">
<attribute name=""regardingobjectid"" alias=""ratingcount"" aggregate=""countcolumn""/>
<attribute name=""rating"" alias=""ratingsum"" aggregate=""sum"" />
<attribute name=""rating"" alias=""value"" groupby=""true"" />
<filter type=""and"">
<condition attribute=""statecode"" operator=""eq"" value=""0"" />
<condition attribute=""rating"" operator=""not-null"" />
</filter>
<link-enreplacedy name=""adx_blogpost"" from=""adx_blogpostid"" to=""regardingobjectid"">
<attribute name=""adx_blogpostid"" alias=""postid"" groupby=""true"" />
<filter type=""and"" />
</link-enreplacedy>
</enreplacedy>
</fetch>");
aggregateResponse = (serviceContext as IOrganizationService).RetrieveMultiple(Fetch.Parse(aggregateFetchXml.ToString()));
}
return ids.ToDictionary(id => id, id =>
{
var enreplacedies = response.Enreplacedies.Where(e => e.Id == id).ToArray();
if (!enreplacedies.Any())
{
return new Tuple<string, string, BlogCommentPolicy, string[], IRatingInfo>(null, null, defaultCommentPolicy, new string[] { }, null);
}
var enreplacedy = enreplacedies.First();
var authorName = Localization.LocalizeFullName(enreplacedy.GetAttributeAliasedValue<string>("author.firstname"), enreplacedy.GetAttributeAliasedValue<string>("author.lastname"));
var autreplacedmail = enreplacedy.GetAttributeAliasedValue<string>("author.emailaddress1");
object postCommentPolicyAttributeValue;
var postCommentPolicy = enreplacedy.Attributes.TryGetValue("adx_commentpolicy", out postCommentPolicyAttributeValue) && (postCommentPolicyAttributeValue is OptionSetValue)
? (BlogPostCommentPolicy)Enum.ToObject(typeof(BlogPostCommentPolicy), ((OptionSetValue)postCommentPolicyAttributeValue).Value)
: BlogPostCommentPolicy.Inherit;
var blogCommentPolicyOption = enreplacedy.GetAttributeAliasedValue<OptionSetValue>("blog.adx_commentpolicy");
var blogCommentPolicy = blogCommentPolicyOption == null
? defaultCommentPolicy
: (BlogCommentPolicy)Enum.ToObject(typeof(BlogCommentPolicy), blogCommentPolicyOption.Value);
var commentPolicy = postCommentPolicy == BlogPostCommentPolicy.Inherit
? blogCommentPolicy
: (BlogCommentPolicy)Enum.ToObject(typeof(BlogCommentPolicy), (int)postCommentPolicy);
var tags = enreplacedies
.Select(e => e.GetAttributeAliasedValue<string>("tag.adx_name"))
.Where(tagName => !string.IsNullOrWhiteSpace(tagName))
.ToArray();
int ratingCount = 0;
int ratingSum = 0;
double averageRating = 0;
int yesCount = 0;
int noCount = 0;
if (aggregateResponse != null)
{
var aggregateResults = aggregateResponse.Enreplacedies
.Where(e => e.GetAttributeAliasedValue<Guid?>("postid") == id);
var aggregateYesResult = aggregateResponse.Enreplacedies
.Where(e => e.GetAttributeAliasedValue<Guid?>("postid") == id)
.FirstOrDefault(e => e.GetAttributeAliasedValue<int?>("value") == 1);
var aggregateNoResult = aggregateResponse.Enreplacedies
.Where(e => e.GetAttributeAliasedValue<Guid?>("postid") == id)
.FirstOrDefault(e => e.GetAttributeAliasedValue<int?>("value") == 0);
yesCount = (aggregateYesResult != null) ? aggregateYesResult.GetAttributeAliasedValue<int?>("ratingcount") ?? 0 : 0;
noCount = (aggregateNoResult != null) ? aggregateNoResult.GetAttributeAliasedValue<int?>("ratingcount") ?? 0 : 0;
foreach (var aggregateResult in aggregateResults)
{
ratingCount = ratingCount + aggregateResult.GetAttributeAliasedValue<int?>("ratingcount") ?? 0;
ratingSum = ratingSum + aggregateResult.GetAttributeAliasedValue<int?>("ratingsum") ?? 0;
}
if (ratingCount == 0)
{
averageRating = 0;
}
else
{
averageRating = ratingSum / (double)ratingCount;
}
}
var ratingInfo = new RatingInfo(yesCount, noCount, averageRating, ratingCount, ratingSum);
return new Tuple<string, string, BlogCommentPolicy, string[], IRatingInfo>(authorName, autreplacedmail, commentPolicy, tags, ratingInfo);
});
}
19
View Source File : OrganizationServiceContextExtensions.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
public static IDictionary<Guid, Tuple<string, string, string, IRatingInfo>> FetchBlogPostCommentExtendedData(this OrganizationServiceContext serviceContext, IEnumerable<Guid> commentIds)
{
if (!FeatureCheckHelper.IsFeatureEnabled(FeatureNames.Feedback))
{
return new Dictionary<Guid, Tuple<string, string, string, IRatingInfo>>();
}
if (!commentIds.Any())
{
return new Dictionary<Guid, Tuple<string, string, string, IRatingInfo>>();
}
var ids = commentIds.ToArray();
XDoreplacedent fetchXml = XDoreplacedent.Parse(@"
<fetch mapping=""logical"">
<enreplacedy name=""feedback"">
<filter type=""and"">
</filter>
<link-enreplacedy name=""contact"" from=""contactid"" to=""createdbycontact"" alias=""author"">
<attribute name=""contactid"" />
<attribute name=""fullname"" />
<attribute name=""firstname"" />
<attribute name=""lastname"" />
<attribute name=""emailaddress1"" />
<attribute name=""websiteurl"" />
</link-enreplacedy>
</enreplacedy>
</fetch>");
var filter = fetchXml.Descendants("filter").First();
filter.AddFetchXmlFilterInCondition("feedbackid", ids.Select(id => id.ToString()));
var response = (serviceContext as IOrganizationService).RetrieveMultiple(Fetch.Parse(fetchXml.ToString()));
XDoreplacedent aggregateFetchXml = XDoreplacedent.Parse(@"
<fetch mapping=""logical"" aggregate=""true"">
<enreplacedy name=""feedback"">
<attribute name=""regardingobjectid"" alias=""ratingcount"" aggregate=""countcolumn""/>
<attribute name=""rating"" alias=""ratingsum"" aggregate=""sum"" />
<attribute name=""rating"" alias=""value"" groupby=""true"" />
<link-enreplacedy name=""feedback"" from=""feedbackid"" to=""regardingobjectid"">
<attribute name=""feedbackid"" alias=""commentid"" groupby=""true"" />
<filter type=""and"" />
</link-enreplacedy>
</enreplacedy>
</fetch>");
var aggregateFilter = fetchXml.Descendants("filter").First();
aggregateFilter.AddFetchXmlFilterInCondition("feedbackid", ids.Select(id => id.ToString()));
var aggregateResponse = (serviceContext as IOrganizationService).RetrieveMultiple(Fetch.Parse(aggregateFetchXml.ToString()));
return ids.ToDictionary(id => id, id =>
{
var enreplacedy = response.Enreplacedies.FirstOrDefault(e => e.Id == id);
if (enreplacedy == null)
{
return new Tuple<string, string, string, IRatingInfo>(null, null, null, null);
}
var authorName = Localization.LocalizeFullName(enreplacedy.GetAttributeAliasedValue<string>("author.firstname"), enreplacedy.GetAttributeAliasedValue<string>("author.lastname"));
var authorUrl = enreplacedy.GetAttributeAliasedValue<string>("author.websiteurl");
var autreplacedmail = enreplacedy.GetAttributeAliasedValue<string>("author.emailaddress1");
var aggregateResults = aggregateResponse.Enreplacedies
.Where(e => e.GetAttributeAliasedValue<Guid?>("commentid") == id);
var aggregateYesResult = aggregateResponse.Enreplacedies
.Where(e => e.GetAttributeAliasedValue<Guid?>("commentid") == id)
.FirstOrDefault(e => e.GetAttributeAliasedValue<int?>("value") == 1);
var aggregateNoResult = aggregateResponse.Enreplacedies
.Where(e => e.GetAttributeAliasedValue<Guid?>("commentid") == id)
.FirstOrDefault(e => e.GetAttributeAliasedValue<int?>("value") == 0);
var yesCount = (aggregateYesResult != null) ? aggregateYesResult.GetAttributeAliasedValue<int?>("ratingcount") ?? 0 : 0;
var noCount = (aggregateNoResult != null) ? aggregateNoResult.GetAttributeAliasedValue<int?>("ratingcount") ?? 0 : 0;
var ratingCount = 0;
var ratingSum = 0;
foreach (var aggregateResult in aggregateResults)
{
ratingCount = ratingCount + aggregateResult.GetAttributeAliasedValue<int?>("ratingcount") ?? 0;
ratingSum = ratingSum + aggregateResult.GetAttributeAliasedValue<int?>("ratingsum") ?? 0;
}
double averageRating;
if (ratingCount == 0)
{
averageRating = 0;
}
else
{
averageRating = ratingSum / (double)ratingCount;
}
var ratingInfo = new RatingInfo(yesCount, noCount, averageRating, ratingCount, ratingSum);
return new Tuple<string, string, string, IRatingInfo>(authorName, authorUrl, autreplacedmail, ratingInfo);
});
}
19
View Source File : OrganizationServiceContextExtensions.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
public static IDictionary<Guid, Tuple<string, string, string, IRatingInfo>> FetchPageCommentExtendedData(this OrganizationServiceContext serviceContext, IEnumerable<Guid> commentIds)
{
return FetchPageCommentExtendedData(serviceContext, commentIds.ToArray())
.ToDictionary(data => data.Item1, data => new Tuple<string, string, string, IRatingInfo>(data.Item2, data.Item3, data.Item4, data.Item5));
}
19
View Source File : DataAdapterOrganizationServiceContextExtensions.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
public static IDictionary<Guid, IForumThreadInfo> FetchForumThreadInfos(this OrganizationServiceContext serviceContext, IEnumerable<Guid> forumThreadIds, Guid websiteId)
{
if (!forumThreadIds.Any())
{
return new Dictionary<Guid, IForumThreadInfo>();
}
var ids = forumThreadIds.ToArray();
var fetchXml = XDoreplacedent.Parse(@"
<fetch mapping=""logical"">
<enreplacedy name=""adx_communityforumthread"">
<filter type=""and"">
</filter>
<link-enreplacedy name=""adx_communityforumpost"" from=""adx_communityforumpostid"" to=""adx_firstpostid"" alias=""firstpost"">
<attribute name=""adx_communityforumpostid"" />
<attribute name=""adx_date"" />
<link-enreplacedy link-type=""outer"" name=""contact"" from=""contactid"" to=""adx_authorid"" alias=""firstpostauthor"">
<attribute name=""contactid"" />
<attribute name=""fullname"" />
<attribute name=""emailaddress1"" />
</link-enreplacedy>
</link-enreplacedy>
<link-enreplacedy name=""adx_communityforumpost"" from=""adx_communityforumpostid"" to=""adx_lastpostid"" alias=""lastpost"">
<attribute name=""adx_communityforumpostid"" />
<attribute name=""adx_date"" />
<link-enreplacedy link-type=""outer"" name=""contact"" from=""contactid"" to=""adx_authorid"" alias=""lastpostauthor"">
<attribute name=""contactid"" />
<attribute name=""fullname"" />
<attribute name=""emailaddress1"" />
</link-enreplacedy>
</link-enreplacedy>
<link-enreplacedy link-type=""outer"" name=""adx_forumthreadtype"" from=""adx_forumthreadtypeid"" to=""adx_typeid"" alias=""threadtype"">
<attribute name=""adx_forumthreadtypeid"" />
<attribute name=""adx_name"" />
<attribute name=""adx_allowsvoting"" />
<attribute name=""adx_displayorder"" />
<attribute name=""adx_isdefault"" />
<attribute name=""adx_requiresanswer"" />
</link-enreplacedy>
<link-enreplacedy link-type=""outer"" name=""adx_communityforumthread_tag"" from=""adx_communityforumthreadid"" to=""adx_communityforumthreadid"">
<link-enreplacedy link-type=""outer"" name=""adx_tag"" from=""adx_tagid"" to=""adx_tagid"" alias=""tag"">
<attribute name=""adx_name"" />
<filter type=""and"">
<condition attribute=""adx_websiteid"" operator=""eq"" />
</filter>
</link-enreplacedy>
</link-enreplacedy>
</enreplacedy>
</fetch>");
var threadFilter = fetchXml.XPathSelectElement("//enreplacedy[@name='adx_communityforumthread']/filter");
if (threadFilter == null)
{
throw new InvalidOperationException(string.Format("Unable to select {0} element.", "adx_communityforumthreadid filter condition"));
}
threadFilter.AddFetchXmlFilterInCondition("adx_communityforumthreadid", ids.Select(id => id.ToString()));
var websiteConditions = fetchXml.XPathSelectElements("//filter/condition[@attribute='adx_websiteid']");
foreach (var websiteCondition in websiteConditions)
{
websiteCondition.SetAttributeValue("value", websiteId.ToString());
}
var fetch = Fetch.Parse(fetchXml.ToString());
var threadTypeLink = fetch.Enreplacedy.Links.FirstOrDefault(l => l.Name.Equals("adx_forumthreadtype"));
if (threadTypeLink != null)
{
threadTypeLink.IsUnique = true;
}
var response = (serviceContext as IOrganizationService).RetrieveMultiple(fetch);
return ids.ToDictionary(id => id, id =>
{
IForumThreadInfo unknownInfo = new UnknownForumThreadInfo();
var enreplacedies = response.Enreplacedies.Where(e => e.Id == id).ToArray();
if (!enreplacedies.Any())
{
return unknownInfo;
}
var enreplacedy = enreplacedies.First();
var author = GetForumAuthor("firstpostauthor", enreplacedy);
var postedOn = enreplacedy.GetAttributeAliasedValue<DateTime?>("firstpost.adx_date").GetValueOrDefault(unknownInfo.PostedOn);
var threadType = GetForumThreadType("threadtype", enreplacedy);
var latestPostAuthor = GetForumAuthor("lastpostauthor", enreplacedy);
var latestPostInfo = GetForumPostInfo("lastpost", enreplacedy, latestPostAuthor);
var tags = GetForumThreadTags("tag", enreplacedies);
return new ForumThreadInfo(author, postedOn, threadType, tags, latestPostInfo);
});
}
19
View Source File : DataAdapterOrganizationServiceContextExtensions.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
public static IDictionary<Guid, ForumCounts> FetchForumCounts(this OrganizationServiceContext serviceContext, IEnumerable<Guid> forumIds)
{
if (!forumIds.Any())
{
return new Dictionary<Guid, ForumCounts>();
}
var ids = forumIds.ToArray();
var fetchXml = XDoreplacedent.Parse(@"
<fetch mapping=""logical"" aggregate=""true"">
<enreplacedy name=""adx_communityforum"">
<attribute name=""adx_communityforumid"" alias=""id"" groupby=""true""/>
<filter type=""and""/>
<link-enreplacedy name=""adx_communityforumthread"" from=""adx_forumid"" to=""adx_communityforumid"">
<attribute name=""adx_communityforumthreadid"" alias=""threadid"" groupby=""true""/>
<link-enreplacedy name=""adx_communityforumpost"" from=""adx_forumthreadid"" to=""adx_communityforumthreadid"">
<attribute name=""adx_communityforumpostid"" alias=""postcount"" aggregate=""count""/>
</link-enreplacedy>
</link-enreplacedy>
</enreplacedy>
</fetch>");
var filter = fetchXml.XPathSelectElement("//enreplacedy[@name='adx_communityforum']/filter");
if (filter == null)
{
throw new InvalidOperationException(string.Format("Unable to select {0} element.", "adx_communityforum filter"));
}
filter.AddFetchXmlFilterInCondition("adx_communityforumid", ids.Select(id => id.ToString()));
var fetch = Fetch.Parse(fetchXml.ToString());
var response = (serviceContext as IOrganizationService).RetrieveMultiple(fetch);
var results = response.Enreplacedies
.GroupBy(e => (Guid)e.GetAttributeValue<AliasedValue>("id").Value, e => e)
.Select(forumThreadGrouping => new KeyValuePair<Guid, ForumCounts>(
forumThreadGrouping.Key,
new ForumCounts(
forumThreadGrouping.Count(),
forumThreadGrouping.Sum(postCounts => postCounts.GetAttributeAliasedValue<int?>("postcount").GetValueOrDefault()))));
var counts = ids.ToDictionary(id => id, id => new ForumCounts(0, 0));
foreach (var result in results)
{
counts[result.Key] = result.Value;
}
return counts;
}
19
View Source File : DataAdapterOrganizationServiceContextExtensions.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
public static IDictionary<Guid, IForumInfo> FetchForumInfos(this OrganizationServiceContext serviceContext, IEnumerable<Guid> forumIds)
{
if (!forumIds.Any())
{
return new Dictionary<Guid, IForumInfo>();
}
var ids = forumIds.ToArray();
var fetchXml = XDoreplacedent.Parse(@"
<fetch mapping=""logical"">
<enreplacedy name=""adx_communityforum"">
<filter type=""and"">
</filter>
<link-enreplacedy name=""adx_communityforumpost"" from=""adx_communityforumpostid"" to=""adx_lastpostid"" alias=""lastpost"">
<attribute name=""adx_communityforumpostid"" />
<attribute name=""adx_date"" />
<link-enreplacedy link-type=""outer"" name=""contact"" from=""contactid"" to=""adx_authorid"" alias=""lastpostauthor"">
<attribute name=""contactid"" />
<attribute name=""fullname"" />
<attribute name=""emailaddress1"" />
</link-enreplacedy>
</link-enreplacedy>
</enreplacedy>
</fetch>");
var filter = fetchXml.XPathSelectElement("//enreplacedy[@name='adx_communityforum']/filter");
if (filter == null)
{
throw new InvalidOperationException(string.Format("Unable to select {0} element.", "adx_communityforum filter"));
}
filter.AddFetchXmlFilterInCondition("adx_communityforumid", ids.Select(id => id.ToString()));
var fetch = Fetch.Parse(fetchXml.ToString());
var forumpostLink = fetch.Enreplacedy.Links.FirstOrDefault(l => l.Name.Equals("adx_communityforumpost"));
if (forumpostLink != null)
{
forumpostLink.IsUnique = true;
var contactLink = forumpostLink.Links.FirstOrDefault(l => l.Name.Equals("contact"));
if (contactLink != null)
{
contactLink.IsUnique = true;
}
}
var response = (serviceContext as IOrganizationService).RetrieveMultiple(fetch);
return ids.ToDictionary(id => id, id =>
{
IForumInfo unknownInfo = new UnknownForumInfo();
var enreplacedy = response.Enreplacedies.FirstOrDefault(e => e.Id == id);
if (enreplacedy == null)
{
return unknownInfo;
}
var latestPostAuthor = GetForumAuthor("lastpostauthor", enreplacedy);
var latestPostInfo = GetForumPostInfo("lastpost", enreplacedy, latestPostAuthor);
return new ForumInfo(latestPostInfo);
});
}
19
View Source File : DataAdapterOrganizationServiceContextExtensions.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
public static IDictionary<Guid, IForumPostInfo> FetchForumPostInfos(this OrganizationServiceContext serviceContext, IEnumerable<Guid> forumPostIds, Guid websiteId, CloudBlobContainer cloudStorageContainer = null)
{
if (!forumPostIds.Any())
{
return new Dictionary<Guid, IForumPostInfo>();
}
var ids = forumPostIds.ToArray();
var fetchXml = XDoreplacedent.Parse(@"
<fetch mapping=""logical"">
<enreplacedy name=""adx_communityforumpost"">
<filter type=""and"">
</filter>
<attribute name=""adx_date"" />
<link-enreplacedy link-type=""outer"" name=""contact"" from=""contactid"" to=""adx_authorid"" alias=""author"">
<attribute name=""contactid"" />
<attribute name=""fullname"" />
<attribute name=""emailaddress1"" />
</link-enreplacedy>
<link-enreplacedy link-type=""outer"" name=""annotation"" from=""objectid"" to=""adx_communityforumpostid"" alias=""attachment"">
<attribute name=""annotationid"" />
<attribute name=""mimetype"" />
<attribute name=""filename"" />
<attribute name=""filesize"" />
</link-enreplacedy>
<link-enreplacedy link-type=""outer"" name=""adx_communityforumthread"" from=""adx_communityforumthreadid"" to=""adx_forumthreadid"" alias=""thread"">
<attribute name=""adx_communityforumthreadid"" />
</link-enreplacedy>
</enreplacedy>
</fetch>");
var filter = fetchXml.Descendants("filter").First();
filter.AddFetchXmlFilterInCondition("adx_communityforumpostid", ids.Select(id => id.ToString()));
var fetch = Fetch.Parse(fetchXml.ToString());
var contactLink = fetch.Enreplacedy.Links.FirstOrDefault(l => l.Name.Equals("contact"));
if (contactLink != null)
{
contactLink.IsUnique = true;
}
var response = (serviceContext as IOrganizationService).RetrieveMultiple(fetch);
return ids.ToDictionary(id => id, id =>
{
IForumPostInfo unknownInfo = new UnknownForumPostInfo();
var enreplacedies = response.Enreplacedies.Where(e => e.Id == id).ToArray();
if (!enreplacedies.Any())
{
return unknownInfo;
}
var attachmentInfo = enreplacedies.Select(e =>
{
var annotationId = e.GetAttributeAliasedValue<Guid?>("attachment.annotationid");
var filename = e.GetAttributeAliasedValue<string>("attachment.filename");
var mimetype = e.GetAttributeAliasedValue<string>("attachment.mimetype");
var filesize = e.GetAttributeAliasedValue<int?>("attachment.filesize").GetValueOrDefault();
if (annotationId == null || string.IsNullOrEmpty(filename))
{
return null;
}
return new NoteAttachmentInfo(new EnreplacedyReference("annotation", annotationId.Value), filename, mimetype, filesize, websiteId, cloudStorageContainer);
}).Where(info => info != null);
var enreplacedy = enreplacedies.First();
var author = GetForumAuthor("author", enreplacedy);
var thread = new EnreplacedyReference(("adx_communityforumthread"),
enreplacedy.GetAttributeAliasedValue<Guid>("thread.adx_communityforumthreadid"));
return new ForumPostInfo(
new EnreplacedyReference("adx_communityforumpost", enreplacedy.Id),
author,
enreplacedy.GetAttributeAliasedValue<DateTime?>("adx_date").GetValueOrDefault(unknownInfo.PostedOn),
attachmentInfo,
thread);
});
}
19
View Source File : OrganizationServiceContextExtensions.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
public static Dictionary<Guid, int> FetchIdeaForumActiveVoteCountsForUser(this OrganizationServiceContext serviceContext, IEnumerable<Guid> ideaForumIds, HttpContextBase httpContext, EnreplacedyReference portalUser)
{
if (!FeatureCheckHelper.IsFeatureEnabled(FeatureNames.Feedback))
{
return new Dictionary<Guid, int>();
}
var ids = ideaForumIds.ToArray();
var fetchXml = XDoreplacedent.Parse(@"
<fetch mapping=""logical"" aggregate=""true"">
<enreplacedy name=""feedback"">
<attribute name=""rating"" alias=""votesum"" aggregate=""sum"" />
<attribute name=""rating"" alias=""value"" groupby=""true"" />
<filter type=""or"" />
<filter type=""and"">
<condition attribute=""statecode"" operator=""eq"" value=""0"" />
<condition attribute=""rating"" operator=""not-null"" />
</filter>
<link-enreplacedy name=""adx_idea"" from=""adx_ideaid"" to=""regardingobjectid"">
<attribute name=""adx_ideaforumid"" alias=""ideaforumid"" groupby=""true"" />
<filter type=""or"" />
<filter type=""and"">
<condition attribute=""statuscode"" operator=""eq"" value=""1"" />
</filter>
</link-enreplacedy>
</enreplacedy>
</fetch>");
var enreplacedy = fetchXml.Descendants("enreplacedy").First();
var orFilter = enreplacedy.Descendants("filter").First();
if (!string.IsNullOrEmpty(httpContext.Request.AnonymousID))
{
orFilter.AddFetchXmlFilterCondition("createdbycontact", "eq", httpContext.Request.AnonymousID);
}
if (portalUser != null)
{
orFilter.AddFetchXmlFilterCondition("createdbycontact", "eq", portalUser.Id.ToString());
}
else
{
//author url?
//orFilter.AddFetchXmlFilterCondition("adx_createdbyipaddress", "eq", httpContext.Request.UserHostAddress);
}
var ideaForumFilter = enreplacedy.Descendants("link-enreplacedy").First().Descendants("filter").First();
foreach (var id in ids)
{
ideaForumFilter.AddFetchXmlFilterCondition("adx_ideaforumid", "eq", id.ToString());
}
var response = (serviceContext as IOrganizationService).RetrieveMultiple(Fetch.Parse(fetchXml.ToString()));
var results = ids.ToDictionary(
id => id,
id =>
{
var totalVotes = response.Enreplacedies
.Where(result => result.GetAttributeAliasedValue<Guid>("ideaforumid") == id)
.Sum(result => Math.Abs(result.GetAttributeAliasedValue<int>("votesum")));
return totalVotes;
});
return results;
}
19
View Source File : OrganizationServiceContextExtensions.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
public static IDictionary<Guid, Tuple<string, string>> FetchArticleCommentExtendedData(
this OrganizationServiceContext serviceContext, IEnumerable<Guid> commentIds)
{
var ids = commentIds.ToArray();
var fetchXml = XDoreplacedent.Parse(@"
<fetch mapping=""logical"">
<enreplacedy name=""feedback"">
<attribute name=""feedbackid"" />
<filter type=""or"" />
<link-enreplacedy name=""contact"" from=""contactid"" to=""createdbycontact"" alias=""author"">
<attribute name=""fullname"" />
<attribute name=""emailaddress1"" />
</link-enreplacedy>
</enreplacedy>
</fetch>");
var filter = fetchXml.Descendants("filter").First();
foreach (var id in ids)
{
filter.AddFetchXmlFilterCondition("feedbackid", "eq", id.ToString());
}
var response = (serviceContext as IOrganizationService).RetrieveMultiple(Fetch.Parse(fetchXml.ToString()));
return ids.ToDictionary(id => id, id =>
{
var data = response.Enreplacedies.FirstOrDefault(e => e.GetAttributeValue<Guid>("feedbackid") == id);
if (data == null)
{
return new Tuple<string, string>(null, null);
}
var authorName = data.GetAttributeAliasedValue<string>("fullname", "author");
var autreplacedmail = data.GetAttributeAliasedValue<string>("emailaddress1", "author");
return new Tuple<string, string>(authorName, autreplacedmail);
});
}
19
View Source File : SharePointConfigurationManager.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
public static IDictionary<string, string> CreateConnectionDictionary(ConnectionStringSettings connectionString)
{
connectionString.ThrowOnNull("connectionString");
var name = connectionString.Name;
if (!_connectionLookup.ContainsKey(name))
{
var connection = connectionString.ConnectionString.ToDictionary();
if (name == "Xrm")
{
// if using the CRM connection, replace the Url with the SharePoint one
var context = PortalCrmConfigurationManager.CreateServiceContext();
var sharePointUrl = context.GetSettingValueByName("SharePoint/URL");
if (string.IsNullOrWhiteSpace(sharePointUrl))
{
var sharePointSites = context.CreateQuery("sharepointsite").Where(site => site.GetAttributeValue<int?>("statecode") == 0).ToArray(); // all active SP sites
var defaultSharePointSite = sharePointSites.FirstOrDefault(site => site.GetAttributeValue<bool>("isdefault"));
if (defaultSharePointSite == null) throw new Exception("A SharePoint/URL site setting couldn't be found, and no default SharePoint site exists. Specify a SharePoint/URL site setting or make a default SharePoint site.");
sharePointUrl = defaultSharePointSite.GetAttributeValue<string>("absoluteurl") ?? string.Empty;
var parentSiteReference = defaultSharePointSite.GetAttributeValue<EnreplacedyReference>("parentsite");
if (parentSiteReference != null)
{
var parentSite = sharePointSites.FirstOrDefault(site => site.Id == parentSiteReference.Id);
if (parentSite != null)
{
sharePointUrl = "{0}/{1}".FormatWith(parentSite.GetAttributeValue<string>("absoluteurl").TrimEnd('/'), defaultSharePointSite.GetAttributeValue<string>("relativeurl"));
}
}
}
connection["Url"] = sharePointUrl;
}
// cache ths mapping for performance
_connectionLookup[name] = connection;
}
return _connectionLookup[name];
}
19
View Source File : OrganizationServiceContextExtensions.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
public static IDictionary<Guid, Tuple<string, string>> FetchIdeaCommentExtendedData(this OrganizationServiceContext serviceContext, IEnumerable<Guid> commentIds)
{
if (FeatureCheckHelper.IsFeatureEnabled(FeatureNames.Feedback))
{
var ids = commentIds.ToArray();
var fetchXml = XDoreplacedent.Parse(@"
<fetch mapping=""logical"">
<enreplacedy name=""feedback"">
<attribute name=""feedbackid"" />
<filter type=""or"" />
<link-enreplacedy name=""contact"" from=""contactid"" to=""createdbycontact"" alias=""author"">
<attribute name=""fullname"" />
<attribute name=""firstname"" />
<attribute name=""lastname"" />
<attribute name=""emailaddress1"" />
</link-enreplacedy>
</enreplacedy>
</fetch>");
var filter = fetchXml.Descendants("filter").First();
foreach (var id in ids)
{
filter.AddFetchXmlFilterCondition("feedbackid", "eq", id.ToString());
}
var response = (serviceContext as IOrganizationService).RetrieveMultiple(Fetch.Parse(fetchXml.ToString()));
return ids.ToDictionary(id => id, id =>
{
var data = response.Enreplacedies.FirstOrDefault(e => e.GetAttributeValue<Guid>("feedbackid") == id);
if (data == null)
{
return new Tuple<string, string>(null, null);
}
var authorName = Localization.LocalizeFullName(data.GetAttributeAliasedValue<string>("author.firstname"), data.GetAttributeAliasedValue<string>("author.lastname"));
var autreplacedmail = data.GetAttributeAliasedValue<string>("emailaddress1", "author");
return new Tuple<string, string>(authorName, autreplacedmail);
});
}
return new Dictionary<Guid, Tuple<string, string>>();
}
19
View Source File : OrganizationServiceContextExtensions.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
public static IDictionary<Guid, IdeaExtendedData> FetchIdeaExtendedData(this OrganizationServiceContext serviceContext, IEnumerable<Guid> ideaIds)
{
var ids = ideaIds.ToArray();
var fetchXml = XDoreplacedent.Parse(@"
<fetch mapping=""logical"">
<enreplacedy name=""adx_idea"">
<attribute name=""adx_ideaid"" />
<filter type=""or"" />
<link-enreplacedy name=""adx_ideaforum"" from=""adx_ideaforumid"" to=""adx_ideaforumid"" alias=""ideaforum"">
<attribute name=""adx_name"" />
<attribute name=""adx_partialurl"" />
<attribute name=""adx_commentpolicy"" />
<attribute name=""adx_votingpolicy"" />
<attribute name=""adx_votingtype"" />
<attribute name=""adx_votesperidea"" />
<attribute name=""adx_votesperuser"" />
</link-enreplacedy>
<link-enreplacedy link-type=""outer"" name=""contact"" from=""contactid"" to=""adx_authorid"" alias=""author"">
<attribute name=""fullname"" />
<attribute name=""firstname"" />
<attribute name=""lastname"" />
<attribute name=""emailaddress1"" />
</link-enreplacedy>
</enreplacedy>
</fetch>");
var filter = fetchXml.Descendants("filter").First();
foreach (var id in ids)
{
filter.AddFetchXmlFilterCondition("adx_ideaid", "eq", id.ToString());
}
var response = (serviceContext as IOrganizationService).RetrieveMultiple(Fetch.Parse(fetchXml.ToString()));
return ids.ToDictionary(id => id, id =>
{
var data = response.Enreplacedies.FirstOrDefault(e => e.GetAttributeValue<Guid>("adx_ideaid") == id);
if (data == null)
{
return IdeaExtendedData.Default;
}
var authorName = Localization.LocalizeFullName(data.GetAttributeAliasedValue<string>("author.firstname"), data.GetAttributeAliasedValue<string>("author.lastname"));
var autreplacedmail = data.GetAttributeAliasedValue<string>("emailaddress1", "author");
var ideaForumreplacedle = data.GetAttributeAliasedValue<string>("adx_name", "ideaforum");
var ideaForumPartialUrl = data.GetAttributeAliasedValue<string>("adx_partialurl", "ideaforum");
var ideaForumCommentPolicyValue = data.GetAttributeAliasedValue<int?>("adx_commentpolicy", "ideaforum");
var ideaForumCommentPolicy = ideaForumCommentPolicyValue.HasValue
? (IdeaForumCommentPolicy)Enum.ToObject(typeof(IdeaForumCommentPolicy), ideaForumCommentPolicyValue)
: IdeaExtendedData.Default.IdeaForumCommentPolicy;
var ideaForumVotingPolicyValue = data.GetAttributeAliasedValue<int?>("adx_votingpolicy", "ideaforum");
var ideaForumVotingPolicy = ideaForumVotingPolicyValue.HasValue
? (IdeaForumVotingPolicy)Enum.ToObject(typeof(IdeaForumVotingPolicy), ideaForumVotingPolicyValue)
: IdeaExtendedData.Default.IdeaForumVotingPolicy;
var ideaForumVotingTypeValue = data.GetAttributeAliasedValue<int?>("adx_votingtype", "ideaforum");
var ideaForumVotingType = ideaForumVotingTypeValue.HasValue
? (IdeaForumVotingType)Enum.ToObject(typeof(IdeaForumVotingType), ideaForumVotingTypeValue)
: IdeaExtendedData.Default.IdeaForumVotingType;
var ideaForumVotesPerIdeaValue = data.GetAttributeAliasedValue<int?>("adx_votesperidea", "ideaforum");
var ideaForumVotesPerIdea = ideaForumVotesPerIdeaValue.HasValue
? ideaForumVotesPerIdeaValue.Value
: IdeaExtendedData.Default.IdeaForumVotesPerIdea;
var ideaForumVotesPerUser = data.GetAttributeAliasedValue<int?>("adx_votesperuser", "ideaforum");
return new IdeaExtendedData(authorName, autreplacedmail, ideaForumreplacedle, ideaForumPartialUrl, ideaForumCommentPolicy, ideaForumVotingPolicy, ideaForumVotingType, ideaForumVotesPerIdea, ideaForumVotesPerUser);
});
}
19
View Source File : OrganizationServiceContextExtensions.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
public static Dictionary<Guid, Tuple<int, int>> FetchIdeaVoteCountsForUser(this OrganizationServiceContext serviceContext, IEnumerable<Enreplacedy> ideaEnreplacedies, HttpContextBase httpContext, EnreplacedyReference portalUser)
{
if (!FeatureCheckHelper.IsFeatureEnabled(FeatureNames.Feedback))
{
return new Dictionary<Guid, Tuple<int, int>>();
}
var ideas = ideaEnreplacedies.ToArray();
var fetchXml = XDoreplacedent.Parse(@"
<fetch mapping=""logical"" aggregate=""true"">
<enreplacedy name=""feedback"">
<attribute name=""rating"" alias=""votesum"" aggregate=""sum"" />
<attribute name=""rating"" alias=""value"" groupby=""true"" />
<filter type=""or"" />
<filter type=""and"">
<condition attribute=""statecode"" operator=""eq"" value=""0"" />
<condition attribute=""rating"" operator=""not-null"" />
</filter>
<link-enreplacedy name=""adx_idea"" from=""adx_ideaid"" to=""regardingobjectid"">
<attribute name=""adx_ideaforumid"" alias=""ideaforumid"" groupby=""true"" />
<attribute name=""adx_ideaid"" alias=""ideaid"" groupby=""true"" />
<attribute name=""statuscode"" alias=""statuscode"" groupby=""true"" />
<filter type=""or"" />
<filter type=""and"">
<condition attribute=""statecode"" operator=""eq"" value=""0"" />
</filter>
</link-enreplacedy>
</enreplacedy>
</fetch>");
var enreplacedy = fetchXml.Descendants("enreplacedy").First();
var orFilter = enreplacedy.Descendants("filter").First();
if (!string.IsNullOrEmpty(httpContext.Request.AnonymousID))
{
orFilter.AddFetchXmlFilterCondition("createdbycontact", "eq", httpContext.Request.AnonymousID);
}
if (portalUser != null)
{
orFilter.AddFetchXmlFilterCondition("createdbycontact", "eq", portalUser.Id.ToString());
}
else
{
// author_url?
//orFilter.AddFetchXmlFilterCondition("adx_createdbyipaddress", "eq", httpContext.Request.UserHostAddress);
}
var ideaForumFilter = enreplacedy.Descendants("link-enreplacedy").First().Descendants("filter").First();
foreach (var id in ideas.Where(idea => idea.GetAttributeValue<EnreplacedyReference>("adx_ideaforumid") != null).Select(idea => idea.GetAttributeValue<EnreplacedyReference>("adx_ideaforumid").Id).Distinct())
{
ideaForumFilter.AddFetchXmlFilterCondition("adx_ideaforumid", "eq", id.ToString());
}
var response = (serviceContext as IOrganizationService).RetrieveMultiple(Fetch.Parse(fetchXml.ToString()));
var ideaForumActiveVoteCounts = response.Enreplacedies
.Where(result => result.GetAttributeAliasedValue<int>("statuscode") == 1)
.GroupBy(
result => result.GetAttributeAliasedValue<Guid>("ideaforumid"),
result => Math.Abs(result.GetAttributeAliasedValue<int>("votesum")))
.ToDictionary(g => g.Key, ints => ints.Sum());
var results = ideas.ToDictionary(
idea => idea.Id,
idea =>
{
int ideaForumActiveVoteCountValue;
var ideaForumActiveVoteCount = idea.GetAttributeValue<EnreplacedyReference>("adx_ideaforumid") == null ? 0 : ideaForumActiveVoteCounts.TryGetValue(idea.GetAttributeValue<EnreplacedyReference>("adx_ideaforumid").Id, out ideaForumActiveVoteCountValue)
? ideaForumActiveVoteCountValue
: 0;
var ideaVoteCount = response.Enreplacedies
.Where(result => result.GetAttributeAliasedValue<Guid>("ideaid") == idea.Id)
.Sum(result => Math.Abs(result.GetAttributeAliasedValue<int>("votesum")));
return new Tuple<int, int>(ideaForumActiveVoteCount, ideaVoteCount);
});
return results;
}
19
View Source File : OrganizationServiceContextExtensions.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
public static Dictionary<Guid, Tuple<int, int, int>> FetchIdeaVoteCounts(this OrganizationServiceContext serviceContext, IEnumerable<Guid> ideaIds)
{
if (!FeatureCheckHelper.IsFeatureEnabled(FeatureNames.Feedback))
{
return new Dictionary<Guid, Tuple<int, int, int>>();
}
var ids = ideaIds.ToArray();
var fetchXml = XDoreplacedent.Parse(@"
<fetch mapping=""logical"" aggregate=""true"">
<enreplacedy name=""feedback"">
<attribute name=""feedbackid"" alias=""totalvoters"" aggregate=""countcolumn"" />
<attribute name=""rating"" alias=""votesum"" aggregate=""sum"" />
<attribute name=""rating"" alias=""value"" groupby=""true"" />
<filter type=""and"">
<condition attribute=""statecode"" operator=""eq"" value=""0"" />
<condition attribute=""rating"" operator=""not-null"" />
</filter>
<link-enreplacedy name=""adx_idea"" from=""adx_ideaid"" to=""regardingobjectid"">
<attribute name=""adx_ideaid"" alias=""ideaid"" groupby=""true"" />
<filter type=""or"" />
<filter type=""and"">
<condition attribute=""statecode"" operator=""eq"" value=""0"" />
</filter>
</link-enreplacedy>
</enreplacedy>
</fetch>");
var enreplacedy = fetchXml.Descendants("enreplacedy").First();
var linkEnreplacedy = enreplacedy.Descendants("link-enreplacedy").First();
var linkEnreplacedyFilter = linkEnreplacedy.Descendants("filter").First();
foreach (var id in ids)
{
linkEnreplacedyFilter.AddFetchXmlFilterCondition("adx_ideaid", "eq", id.ToString());
}
var response = (serviceContext as IOrganizationService).RetrieveMultiple(Fetch.Parse(fetchXml.ToString()));
var results = ids.ToDictionary(
id => id,
id =>
{
var aggregates = response.Enreplacedies
.Where(result => result.GetAttributeAliasedValue<Guid>("ideaid") == id);
var upVoteSum = aggregates.Where(result => result.GetAttributeAliasedValue<int>("votesum") > 0)
.Sum(result => result.GetAttributeAliasedValue<int>("votesum"));
var downVoteSum = Math.Abs(aggregates.Where(result => result.GetAttributeAliasedValue<int>("votesum") < 0)
.Sum(result => result.GetAttributeAliasedValue<int>("votesum")));
var totalVoters = aggregates.Sum(result => result.GetAttributeAliasedValue<int>("totalvoters"));
return new Tuple<int, int, int>(upVoteSum, downVoteSum, totalVoters);
});
return results;
}
19
View Source File : OrganizationServiceContextExtensions.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
public static IDictionary<Guid, Tuple<string, string>> FetchIssueCommentExtendedData(this OrganizationServiceContext serviceContext, IEnumerable<Guid> commentIds)
{
if (FeatureCheckHelper.IsFeatureEnabled(FeatureNames.Feedback))
{
var ids = commentIds.ToArray();
var fetchXml = XDoreplacedent.Parse(@"
<fetch mapping=""logical"">
<enreplacedy name=""feedback"">
<attribute name=""feedbackid"" />
<filter type=""or"" />
<link-enreplacedy name=""contact"" from=""contactid"" to=""createdbycontact"" alias=""author"">
<attribute name=""fullname"" />
<attribute name=""emailaddress1"" />
</link-enreplacedy>
</enreplacedy>
</fetch>");
var filter = fetchXml.Descendants("filter").First();
foreach (var id in ids)
{
filter.AddFetchXmlFilterCondition("feedbackid", "eq", id.ToString());
}
var response = (RetrieveMultipleResponse)serviceContext.Execute(new RetrieveMultipleRequest
{
Query = new FetchExpression(fetchXml.ToString())
});
return ids.ToDictionary(id => id, id =>
{
var data = response.EnreplacedyCollection.Enreplacedies.FirstOrDefault(e => e.GetAttributeValue<Guid>("feedbackid") == id);
if (data == null)
{
return new Tuple<string, string>(null, null);
}
var authorName = data.GetAttributeAliasedValue<string>("fullname", "author");
var autreplacedmail = data.GetAttributeAliasedValue<string>("emailaddress1", "author");
return new Tuple<string, string>(authorName, autreplacedmail);
});
}
return new Dictionary<Guid, Tuple<string, string>>();
}
19
View Source File : OrganizationServiceContextExtensions.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
public static IDictionary<Guid, IssueExtendedData> FetchIssueExtendedData(this OrganizationServiceContext serviceContext, IEnumerable<Guid> issueIds)
{
var ids = issueIds.ToArray();
var fetchXml = XDoreplacedent.Parse(@"
<fetch mapping=""logical"">
<enreplacedy name=""adx_issue"">
<attribute name=""adx_issueid"" />
<filter type=""or"" />
<link-enreplacedy name=""adx_issueforum"" from=""adx_issueforumid"" to=""adx_issueforumid"" alias=""issueforum"">
<attribute name=""adx_name"" />
<attribute name=""adx_partialurl"" />
<attribute name=""adx_commentpolicy"" />
</link-enreplacedy>
<link-enreplacedy link-type=""outer"" name=""contact"" from=""contactid"" to=""adx_authorid"" alias=""author"">
<attribute name=""fullname"" />
<attribute name=""firstname"" />
<attribute name=""lastname"" />
<attribute name=""emailaddress1"" />
</link-enreplacedy>
</enreplacedy>
</fetch>");
var filter = fetchXml.Descendants("filter").First();
foreach (var id in ids)
{
filter.AddFetchXmlFilterCondition("adx_issueid", "eq", id.ToString());
}
var response = (RetrieveMultipleResponse)serviceContext.Execute(new RetrieveMultipleRequest
{
Query = new FetchExpression(fetchXml.ToString())
});
return ids.ToDictionary(id => id, id =>
{
var data = response.EnreplacedyCollection.Enreplacedies.FirstOrDefault(e => e.GetAttributeValue<Guid>("adx_issueid") == id);
if (data == null)
{
return IssueExtendedData.Default;
}
var authorName = Localization.LocalizeFullName(data.GetAttributeAliasedValue<string>("author.firstname"), data.GetAttributeAliasedValue<string>("author.lastname"));
var autreplacedmail = data.GetAttributeAliasedValue<string>("emailaddress1", "author");
var issueForumreplacedle = data.GetAttributeAliasedValue<string>("adx_name", "issueforum");
var issueForumPartialUrl = data.GetAttributeAliasedValue<string>("adx_partialurl", "issueforum");
var issueForumCommentPolicyValue = data.GetAttributeAliasedValue<int?>("adx_commentpolicy", "issueforum");
var issueForumCommentPolicy = issueForumCommentPolicyValue.HasValue
? (IssueForumCommentPolicy)Enum.ToObject(typeof(IssueForumCommentPolicy), issueForumCommentPolicyValue)
: IssueExtendedData.Default.IssueForumCommentPolicy;
return new IssueExtendedData(authorName, autreplacedmail, issueForumreplacedle, issueForumPartialUrl, issueForumCommentPolicy);
});
}
19
View Source File : AdxCmsDataServiceCrmEntityEditingMetadataProvider.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
protected static bool TryGetPicklistOptions(OrganizationServiceContext serviceContext, string enreplacedyName, string propertyName, out Dictionary<int, string> options)
{
options = null;
try
{
var response = (RetrieveEnreplacedyResponse)serviceContext.Execute(new RetrieveEnreplacedyRequest
{
LogicalName = enreplacedyName, EnreplacedyFilters = EnreplacedyFilters.Attributes
});
var attribute = response.EnreplacedyMetadata.Attributes.FirstOrDefault(a => a.LogicalName == propertyName) as PicklistAttributeMetadata;
if (attribute == null)
{
return false;
}
options = attribute.OptionSet.Options
.Where(o => o.Value.HasValue)
.ToDictionary(o => o.Value.Value, o => o.Label.GetLocalizedLabelString());
return true;
}
catch
{
return false;
}
}
19
View Source File : CmsEntityEditingMetadataProvider.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
protected static bool TryGetPicklistOptions(OrganizationServiceContext serviceContext, string enreplacedyLogicalName, string attributeLogicalName, out Dictionary<int, string> options)
{
options = null;
try
{
var enreplacedyFilter = new MetadataFilterExpression(LogicalOperator.And);
enreplacedyFilter.Conditions.Add(new MetadataConditionExpression("LogicalName", MetadataConditionOperator.Equals, enreplacedyLogicalName));
var attributeFilter = new MetadataFilterExpression(LogicalOperator.And);
attributeFilter.Conditions.Add(new MetadataConditionExpression("LogicalName", MetadataConditionOperator.Equals, attributeLogicalName));
var response = (RetrieveMetadataChangesResponse)serviceContext.Execute(new RetrieveMetadataChangesRequest
{
Query = new EnreplacedyQueryExpression
{
Criteria = enreplacedyFilter,
Properties = new MetadataPropertiesExpression("LogicalName", "Attributes"),
AttributeQuery = new AttributeQueryExpression
{
Criteria = attributeFilter,
Properties = new MetadataPropertiesExpression("LogicalName", "OptionSet")
}
}
});
var enreplacedy = response.EnreplacedyMetadata.FirstOrDefault(e => e.LogicalName == enreplacedyLogicalName);
if (enreplacedy == null)
{
return false;
}
var attribute = enreplacedy.Attributes.FirstOrDefault(a => a.LogicalName == attributeLogicalName) as PicklistAttributeMetadata;
if (attribute == null)
{
return false;
}
options = attribute.OptionSet.Options
.Where(o => o.Value.HasValue)
.ToDictionary(o => o.Value.Value, o => o.Label.GetLocalizedLabelString());
return true;
}
catch
{
return false;
}
}
19
View Source File : WSFederationAuthenticationModuleExtensions.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
public static IDictionary<string, string> GetSignInResponseMessageContext(
this WSFederationAuthenticationModule fam,
HttpContext context)
{
var message = fam.GetSignInResponseMessage(context.Request);
var ctx = message.Context.ToDictionary();
return ctx;
}
19
View Source File : AEDPoSExtensionTestBase.cs
License : MIT License
Project Creator : AElfProject
License : MIT License
Project Creator : AElfProject
protected async Task<Dictionary<Hash, Address>> DeploySystemSmartContracts(
IEnumerable<Hash> systemContractNames)
{
return await BlockMiningService.DeploySystemContractsAsync(systemContractNames.ToDictionary(n => n,
n => Codes.Single(c => c.Key.Contains(_systemContractKeyWords[n])).Value));
}
19
View Source File : IChainManager.cs
License : MIT License
Project Creator : AElfProject
License : MIT License
Project Creator : AElfProject
private async Task SetChainBlockIndexesAsync(IDictionary<long,Hash> blockIndexes)
{
var prefix = ChainId.ToStorageKey() + KernelConstants.StorageKeySeparator;
await _chainBlockIndexes.SetAllAsync(blockIndexes.ToDictionary(d => prefix + d.Key.ToStorageKey(),
d => new ChainBlockIndex {BlockHash = d.Value}));
}
19
View Source File : ITransactionResultManager.cs
License : MIT License
Project Creator : AElfProject
License : MIT License
Project Creator : AElfProject
public async Task AddTransactionResultsAsync(IList<TransactionResult> transactionResults,
Hash disambiguationHash)
{
await _transactionResultStore.SetAllAsync(
transactionResults.ToDictionary(t => HashHelper.XorAndCompute(t.TransactionId, disambiguationHash).ToStorageKey(), t => t));
}
19
View Source File : BlockchainExecutedDataServiceExtensions.cs
License : MIT License
Project Creator : AElfProject
License : MIT License
Project Creator : AElfProject
public static async Task AddBlockExecutedDataAsync<T>(
this IBlockchainExecutedDataService blockchainExecutedDataService,
Hash blockHash, IDictionary<string, T> blockExecutedData)
{
var dic = blockExecutedData.ToDictionary(
keyPair => keyPair.Key,
keyPair => ByteString.CopyFrom(SerializationHelper.Serialize(keyPair.Value)));
await blockchainExecutedDataService.AddBlockExecutedDataAsync(blockHash, dic);
}
19
View Source File : DbResourceManager.cs
License : Apache License 2.0
Project Creator : agoda-com
License : Apache License 2.0
Project Creator : agoda-com
public static IDbResourceManager Create(
IReadOnlyDictionary<string, string[]> dbNameAndConnectionStrings)
{
var dict = dbNameAndConnectionStrings
.ToDictionary(x => x.Key, x => ResourceManager.Create(x.Value));
return new DbResourceManager(dict);
}
19
View Source File : GrpcChannelManager.cs
License : Apache License 2.0
Project Creator : agoda-com
License : Apache License 2.0
Project Creator : agoda-com
public void UpdateResources(string[] urls)
{
var resources = urls.ToDictionary(x => x, x => Weighreplacedem.CreateDefaulreplacedem());
UpdateResources(resources);
}
19
View Source File : RandomUrlHttpClient.cs
License : Apache License 2.0
Project Creator : agoda-com
License : Apache License 2.0
Project Creator : agoda-com
public void UpdateBaseUrls(string[] baseUrls)
{
var dict = baseUrls
.Distinct()
.ToDictionary(x => x, _ => Weighreplacedem.CreateDefaulreplacedem());
UrlResourceManager.UpdateResources(dict);
}
19
View Source File : RandomUrlHttpClient.cs
License : Apache License 2.0
Project Creator : agoda-com
License : Apache License 2.0
Project Creator : agoda-com
private static IResourceManager<string> CreateResourceManager(string[] baseUrls)
{
var dict = baseUrls
.Distinct()
.ToDictionary(x => x, x => Weighreplacedem.CreateDefaulreplacedem());
var mgr = new ResourceManager<string>(dict, new AgodaWeightManipulationStrategy());
return mgr;
}
19
View Source File : ResourceManager.cs
License : Apache License 2.0
Project Creator : agoda-com
License : Apache License 2.0
Project Creator : agoda-com
public static void UpdateResources<TSource>(
this IResourceManager<TSource> mgr,
IEnumerable<TSource> collection)
{
mgr.UpdateResources(
collection
.Distinct()
.ToDictionary(x => x, _ => Weighreplacedem.CreateDefaulreplacedem()));
}
19
View Source File : TestPriorityOrderer.cs
License : MIT License
Project Creator : aliyun
License : MIT License
Project Creator : aliyun
public IEnumerable<TTestCase> OrderTestCases<TTestCase>(IEnumerable<TTestCase> testCases)
where TTestCase : ITestCase
{
var cases = testCases.ToArray();
var caseDepends = cases.ToDictionary(
x => x.TestMethod.Method.Name,
x =>
(
depends: x.TestMethod.Method
.GetCustomAttributes(typeof(TestPriorityAttribute).replacedemblyQualifiedName)
.SingleOrDefault()?
.GetNamedArgument<String[]>("DependsOn") ?? EmptyDepends,
// Use Int64 to prevent the after-last case.
priority: (Int64) (x.TestMethod.Method
.GetCustomAttributes(typeof(TestPriorityAttribute).replacedemblyQualifiedName)
.SingleOrDefault()?
.GetNamedArgument<Int32>("Priority") ?? 0)
));
var allCases = caseDepends
.ToDictionary(x => x.Key, x => new DependNode(x.Key));
// Construct hierarchy
foreach (var (current, (depends, _)) in caseDepends)
{
foreach (var depend in depends)
{
if (allCases.TryGetValue(depend, out var @case))
{
@case.TryAdd(allCases[current]);
}
}
}
var prioritizedCases = allCases.ToDictionary(
x => x.Key,
x => caseDepends[x.Key].depends.IsEmpty()
? caseDepends[x.Key].priority // Root nodes use defined priority.
: (Int64?)null); // Child nodes use hierarchy related priority.
// Process all roots.
var rootNodes = allCases
// No depends
.Where(x => caseDepends[x.Key].depends.IsEmpty())
// Contain children
.Where(x => allCases[x.Key].Children.IsNotEmpty())
.ToArray(); // Freeze for debugging.
foreach (var (rootName, rootNode) in rootNodes)
{
// Circular validation context.
var path = new Stack<String>();
void DfsProcessHierarchy(IEnumerable<KeyValuePair<String, DependNode>> nodes, Int64 priority)
{
foreach (var (currentName, currentNode) in nodes)
{
// Check cirular reference.
if (path.Contains(currentName))
{
throw new ArgumentException($"Circular reference detect: [{String.Join("->", path.Append(currentName))}]");
}
path.Push(currentName);
prioritizedCases[currentName] = Math.Max(prioritizedCases[currentName] ?? priority, priority);
// Deep-First traverse
DfsProcessHierarchy(currentNode.Children, priority + 1);
path.Pop();
}
}
path.Push(rootName);
var rootPriority = prioritizedCases[rootName] ?? 0;
DfsProcessHierarchy(rootNode.Children, rootPriority + 1);
path.Pop();
}
var orderedCases = cases
.OrderBy(x => prioritizedCases[x.TestMethod.Method.Name] ?? 0)
.ToArray();
return orderedCases;
}
19
View Source File : DataColumnsToRowsConverter.cs
License : MIT License
Project Creator : aloneguid
License : MIT License
Project Creator : aloneguid
private bool TryBuildListCell(ListField lf, Dictionary<string, LazyColumnEnumerator> pathToColumn, out object cell)
{
//As this is the list, all sub-columns of this list have to be cut into. This is essentially a more complicated version of
//the TryBuildMapCell method
var nestedPathTicks = pathToColumn
.Where(ptc => ptc.Key.StartsWith(lf.Path))
.Select(ptc => new { path = ptc.Key, collection = ptc.Value, moved = ptc.Value.MoveNext() })
.ToList();
if(nestedPathTicks.Any(t => !t.moved))
{
cell = new Row[0];
return true;
}
var nestedPathToColumn = nestedPathTicks
.ToDictionary(ptc => ptc.path, ptc => (LazyColumnEnumerator)ptc.collection.Current);
IReadOnlyList<Row> rows = BuildRows(new[] { lf.Item }, nestedPathToColumn);
cell = rows.Select(r => r[0]).ToArray();
return true;
}
19
View Source File : Player.Weapons.cs
License : MIT License
Project Creator : AlternateLife
License : MIT License
Project Creator : AlternateLife
public void GiveWeapons(IDictionary<uint, uint> weapons)
{
GiveWeapons(weapons.ToDictionary(x => (WeaponHash) x.Key, x => x.Value));
}
19
View Source File : Player.Weapons.cs
License : MIT License
Project Creator : AlternateLife
License : MIT License
Project Creator : AlternateLife
public Task GiveWeaponsAsync(IDictionary<uint, uint> weapons)
{
return GiveWeaponsAsync(weapons.ToDictionary(x => (WeaponHash) x.Key, x => x.Value));
}
19
View Source File : Player.Weapons.cs
License : MIT License
Project Creator : AlternateLife
License : MIT License
Project Creator : AlternateLife
public void GiveWeapons(IDictionary<int, int> weapons)
{
GiveWeapons(weapons.ToDictionary(x => (WeaponHash) x.Key, x => (uint) x.Value));
}
19
View Source File : Player.Weapons.cs
License : MIT License
Project Creator : AlternateLife
License : MIT License
Project Creator : AlternateLife
public Task GiveWeaponsAsync(IDictionary<int, int> weapons)
{
return GiveWeaponsAsync(weapons.ToDictionary(x => (WeaponHash) x.Key, x => (uint) x.Value));
}
19
View Source File : PollRepository.cs
License : Apache License 2.0
Project Creator : Anapher
License : Apache License 2.0
Project Creator : Anapher
public async ValueTask<IReadOnlyDictionary<string, PollAnswerWithKey>> GetPollAnswersOfParticipant(
Participant participant, IEnumerable<string> pollIds)
{
using var transaction = _database.CreateTransaction();
var values = pollIds.ToDictionary(pollId => pollId,
pollId => transaction.HashGetAsync<PollAnswerWithKey>(
GetPollAnswersKey(participant.ConferenceId, pollId), participant.Id));
await transaction.ExecuteAsync();
var result = new Dictionary<string, PollAnswerWithKey>();
foreach (var (pollId, valueTask) in values)
{
var answer = await valueTask;
if (answer == null) continue;
result.Add(pollId, answer);
}
return result;
}
19
View Source File : NgProxyMiddleware.cs
License : MIT License
Project Creator : andfomin
License : MIT License
Project Creator : andfomin
private static Dictionary<string, NgProxy> CreateProxiesAfterNgStarted(Dictionary<string, NgProxyOptions> pathPrefixToProxyOptionsMap)
{
// Do not replacedign an NgProxy until the Ng server is available.
var pathPrefixToProxyMap = pathPrefixToProxyOptionsMap.Keys.ToDictionary(i => i, i => (NgProxy)null);
// Create a proxy for each Ng app
foreach (var item in pathPrefixToProxyOptionsMap)
{
var pathPrefix = item.Key;
var proxyOptions = item.Value;
// Wait until the Ng server has started.
Task.Factory.StartNew(async () =>
{
do
{
await Task.Delay(TimeSpan.FromSeconds(2));
}
while (IsPortAvailable(proxyOptions.Port));
var proxy = new NgProxy(proxyOptions);
// From now on we can proxy requests.
pathPrefixToProxyMap[pathPrefix] = proxy;
}
);
}
return pathPrefixToProxyMap;
}
19
View Source File : Program.cs
License : MIT License
Project Creator : andyalm
License : MIT License
Project Creator : andyalm
private static IDictionary<string,object> ParseProperties(IEnumerable<string> args)
{
return args.Select(a =>
{
var equalsIndex = a.IndexOf('=');
if (equalsIndex <= 0)
{
throw new FormatException("Expected the property argument to be of the format name=value");
}
return new KeyValuePair<string, object>(a.Substring(0, equalsIndex), a.Substring(equalsIndex + 1));
})
.ToDictionary(p => p.Key, p => p.Value, StringComparer.OrdinalIgnoreCase);
}
19
View Source File : IconLoader.cs
License : MIT License
Project Creator : AnnoDesigner
License : MIT License
Project Creator : AnnoDesigner
public Dictionary<string, IconImage> Load(string pathToIconFolder, IconMappingPresets iconNameMapping)
{
Dictionary<string, IconImage> result = null;
try
{
result = new Dictionary<string, IconImage>();
foreach (var path in Directory.EnumerateFiles(pathToIconFolder, CoreConstants.IconFolderFilter))
{
var filenameWithoutExt = Path.GetFileNameWithoutExtension(path);
if (string.IsNullOrWhiteSpace(filenameWithoutExt))
{
continue;
}
var filenameWithExt = Path.GetFileName(path);
// try mapping to the icon translations
Dictionary<string, string> localizations = null;
if (iconNameMapping?.IconNameMappings != null)
{
var map = iconNameMapping.IconNameMappings.Find(x => string.Equals(x.IconFilename, filenameWithExt, StringComparison.OrdinalIgnoreCase));
if (map != null)
{
localizations = map.Localizations.Dict;
}
}
// add the current icon
result.Add(filenameWithoutExt, new IconImage(filenameWithoutExt, localizations, path));
}
// sort icons by their DisplayName
result = result.OrderBy(x => x.Value.DisplayName).ToDictionary(x => x.Key, x => x.Value, StringComparer.OrdinalIgnoreCase);//make sure ContainsKey is caseInSensitive
}
catch (Exception ex)
{
logger.Error(ex, "Error loading the icons.");
throw;
}
return result;
}
19
View Source File : Effect.cs
License : MIT License
Project Creator : ansel86castro
License : MIT License
Project Creator : ansel86castro
public EffectDto ToDto()
{
return new EffectDto
{
Name = Name,
Programs = Programs.ToDictionary(x => x.Key, y => y.Value.Name),
Predicates = Predicates.ToDictionary(x => x.Key, y => new PredicateProgramList { Items = y.Value.Select(y => y.ToDto()).ToList() })
};
}
See More Examples