ToDictionary error "Cannot apply indexing with [] to an expression of type 'method group'" - c#

I have the following code inside my asp.net mvc web application :-
public void syncWithEX()
{
var EXresource = entities.Resources.Select(g => new
{
EXID = g.RESOURCEID,
CurrentEXSiteID = g.ResourceLocation.SITEID
}).ToDictionary(a => a.EXID, a => a.CurrentEXSiteID);
var technology = ITSys.Technologies.Select(g => new
{
ID = g.TechnologyID,
EXID = g.EXID
}).ToDictionary(a => a.ID, a => a.EXID);
var server = ITSys.ITSYSServers.Where(a => !a.Technology.IsDeleted && a.Technology.IsCompleted);
foreach (var s in server)
{
long? EXid = technology[s.ITSYSServerID];
if (EXresource.ContainsKey[EXid.Value] )
{
long? CurrentEXsiteid = EXresource[EXid.Value];
if (CurrentEXsiteid != s.EXSiteID)
{
s.EXSiteID = CurrentEXsiteid.Value;
ITSys.Entry(s).State = EntityState.Modified;
}
}
}
But i am getting the following error :
Cannot apply indexing with [] to an expression of type 'method group
on the following code:
if (EXresource.ContainsKey[EXid.Value] )

change to:
if (EXresource.ContainsKey(EXid.Value))
Dictionary.ContainsKey()

Related

Cannot implicitly convert type 'string' to 'System.Collections.Generic.IEnumerable<string>when using Nest to search a text

I am having a code error "Cannot implicitly convert type 'string' to 'System.Collections.Generic.IEnumerable" when trying to use Nest to search a text
class Program
{
static void Main(string[] args)
{
var settings = new ConnectionSettings(new Uri("http://localhost:9200"))
.DefaultIndex("my_index");
var client = new ElasticClient(settings);
var text = "testinsg, test, my testing";
var analyzeResponse = client.Indices.Analyze(new AnalyzeRequest
{
// error occurred here when trying to pass the value of the variable text
Text = text,
Analyzer = "standard",
Tokenizer = "standard"
});
var stemmedWords = analyzeResponse.Tokens.Select(t => t.Token);
var stemCounts = stemmedWords
.GroupBy(w => new Stemmer().Stem(w))
.Select(g => new { Stem = g.Key, Count = g.Count() })
foreach (var stemCount in stemCounts)
{
Console.WriteLine($"Stem: {stemCount.Stem}, Count: {stemCount.Count}");
}
}
}
Seems that Text is IEnumerable<string> so just wrap the string into collection, for example array:
new AnalyzeRequest
{
Text = new [] {text},
// ...
}

Unification of the 2 methods

I need some help. I need to combine these two methods into one and I can't figure out how.
I tried with an IF statement (we checked if employeeMark is NullOrEmpty, we use the first logic and if it's not, the second logic) but it's just duplicated code in one method instead of two.
This is the first method :
private async Task<ProcessedContractsIdentifiers> GetContractsIdentifiersByContractsCodes(List<ImportableContractIdentifier> importableContractsIdentifiers)
{
var errors = new List<ContractImportValidationErrorDto>();
foreach (var contract in importableContractsIdentifiers.Where(contract => string.IsNullOrWhiteSpace(contract.ContractCode)))
{
errors.Add(new ContractImportValidationErrorDto
{
ValidatedCode = string.Empty,
Line = contract.RowNumber,
ErrorCode = ContractImportValidationErrorCode.ContractCodeIsRequired
});
}
var contractsCodes = importableContractsIdentifiers.ConvertAll(x => x.ContractCode);
contractsCodes = contractsCodes.Where(x => !string.IsNullOrWhiteSpace(x)).ToList();
var contractsSignatures = await GetContractsSignaturesByContractsCodes(contractsCodes);
var unresolvedContracts = contractsCodes.Except(contractsSignatures.Select(cs => cs.Code)).ToHashSet();
foreach (var c in unresolvedContracts)
{
errors.Add(new ContractImportValidationErrorDto
{
ValidatedCode = c,
ErrorCode = ContractImportValidationErrorCode.InvalidContractCode
});
}
return new ProcessedContractsIdentifiers
{
IdentificationMethod = ContractIdentificationMethod.ByContractCode,
IdentifiedContractsSignatures = contractsSignatures,
NonIdentifiableContracts = errors
};
}
And this is the second method :
private async Task<ProcessedContractsIdentifiers> GetContractsIdentifiersByEmployeesMarks(List<ImportableContractIdentifier> importableContractsIdentifiers)
{
const int withSingleContract = 1;
var errors = new List<ContractImportValidationErrorDto>();
foreach (var contract in importableContractsIdentifiers.Where(contract => string.IsNullOrWhiteSpace(contract.EmployeeMark)))
{
errors.Add(new ContractImportValidationErrorDto
{
ValidatedCode = string.Empty,
Line = contract.RowNumber,
ErrorCode = ContractImportValidationErrorCode.EmployeeMarkIsRequired
});
}
var employeesMarks = importableContractsIdentifiers.Select(x => x.EmployeeMark).Where(x => !string.IsNullOrWhiteSpace(x)).ToHashSet();
var contractsSignatures = await GetContractsSignaturesByEmployeeMark(employeesMarks);
var contractsGroupedByEmployeeMark = contractsSignatures.GroupBy(x => x.EmployeeMark);
foreach (var contracts in contractsGroupedByEmployeeMark.Where(x => x.ToList().Count != withSingleContract))
{
errors.Add(new ContractImportValidationErrorDto
{
ValidatedCode = contracts.Key,
ErrorCode = ContractImportValidationErrorCode.EmployeeMarkWithMultipleContracts
});
}
var unresolvedMarks = employeesMarks.Except(contractsSignatures.Select(cs => cs.EmployeeMark)).ToHashSet();
foreach (var eMark in unresolvedMarks)
{
errors.Add(new ContractImportValidationErrorDto
{
ValidatedCode = eMark,
ErrorCode = ContractImportValidationErrorCode.InvalidEmployeeMark
});
}
return new ProcessedContractsIdentifiers
{
IdentificationMethod = ContractIdentificationMethod.ByEmployeeMark,
IdentifiedContractsSignatures = contractsSignatures,
NonIdentifiableContracts = errors
};
}
Use Enum as parameter, so according to its value you can write code blocks.
public Enum IOMode
{
In=0,
Out=1
}
public void CalculateAttendance(List<Log> lstLog, IOMode eIOMode)
{
if(eIOMode==IOMode.In)
{}
else
{ }
}
call CalculateAttendance(lstLog, IOMode.In) etc

Using EF to return specific formatted JSON from ASP.NET MVC

I have a model like below where PermissionGroup has 1-Many relationship with Permission and Permission and Roles have Many-Many relationship.
PermissionGroup 1-----* Permission *--------* Role
I have to be able to return JSON in the following format:
PermissionGroupId : 1,
PermissionGroupName : "Market",
Permissions : [
{PermissionId : 1, PermissionName : "Create"},
{PermissionId : 2, PermissionName : "Update"}
]
That will be asked for a specific RoleId.
Problem:
Since, PermissionGroup has no relation directly with Role so I cannot do a Where linq query. I could do the following but it is not returning desired result like above.
public JsonResult GetRolePermission(int roleid)
{
var list = con.PermissionGroups.Select(pg => new
{
PermissionGroupId = pg.PermissionGroupId,
PermissionGroupName = pg.PermissionGroupName,
Permissions = pg.Permissons.Select(pe => new
{
PermissionId = pe.PermissionId,
PermissionName = pe.PermissionName
})
})//Maybe do the where query here somehow like where(f => f.RoleId == roleid);
return Json(list);
}
Any suggestion is appreciated.
You can use Any method in Where? Like this:
var list = con.PermissionGroups
.Where(pg => pg.Permissons.Any(p => p.Roles.Any(r => r.RoleId == roleId)))
.Select(pg => new
{
PermissionGroupId = pg.PermissionGroupId,
PermissionGroupName = pg.PermissionGroupName,
Permissions = pg.Permissons.Select(pe => new
{
PermissionId = pe.PermissionId,
PermissionName = pe.PermissionName
})
});
I found a way to do this but highly doubt that it is efficient.
var getPermissionsForRole = context.Roles.Where(roleid => roleid.RoleId == 1).Select(p => p.Permissions).ToList();
var getAllPermissionGroup = context.PermissionGroups.ToList();
List<PermissionGroup> jsonPg = new List<PermissionGroup>();
foreach (var pg in getAllPermissionGroup)
{
PermissionGroup newPg = new PermissionGroup();
newPg.PermissionGroupId = pg.PermissionGroupId;
newPg.PermissionGroupName = pg.PermissionGroupName;
newPg.Permissons = new List<Permission>();
foreach (var pers in getPermissionsForRole[0])
{
if (pers.PermissionGroup.PermissionGroupId == pg.PermissionGroupId)
{
Permission newPe = new Permission();
newPe.PermissionId = pers.PermissionId;
newPe.PermissionName = pers.PermissionName;
newPg.Permissons.Add(newPe);
}
}
if (newPg.Permissons.Count > 0)
{
jsonPg.Add(newPg);
}
}
var json = JsonConvert.SerializeObject(jsonPg);
Still open to better code.

How do I use Linq to query nested dynamic BsonDocuments?

public class Foo
{
public ObjectId _id { get; set; }
public BsonDocument properties { get; set; }
}
public void FindFoos()
{
var client = new MongoClient(ConfigurationManager.ConnectionStrings["MongoDB"].ConnectionString);
var server = client.GetServer();
var db = server.GetDatabase("FooBar");
//var collection = db.GetCollection<GeoJsonFeature<GeoJson2DGeographicCoordinates>>("Sections");
var collection = db.GetCollection<Foo>("Foos");
collection.Insert(new Foo
{
properties = new BsonDocument{
{"Foo" , "foo1"},
{"Bar" , "bar1"}
}
});
collection.Insert(new Foo
{
properties = new BsonDocument{
{"Foo" , "foo2"},
{"Bar" , "bar2"}
}
});
var query = Query<Foo>.Where(foo => foo.properties.AsQueryable().Any(property => property.Name == "Foo" && property.Value.AsString == "foo1"));
var result = collection.Find(query).First();
}
calling FindFoos results in the following exception:
Unsupported where clause: Queryable.Any(Queryable.AsQueryable(foo.properties), (BsonElement property) => ((property.Name == "Foo") && (property.Value.AsString == "foo1"))).
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.ArgumentException: Unsupported where clause: Queryable.Any(Queryable.AsQueryable(foo.properties), (BsonElement property) => ((property.Name == "Foo") && (property.Value.AsString == "foo1"))).
at the line:
var query = Query<Foo>.Where(foo => foo.properties.AsQueryable().Any(property => property.Name == "Foo" && property.Value.AsString == "foo1"));
I can do this query easily in the mongodb shell as:
db.Foos.find( {'properties.Foo' : 'foo1'} );
What is the correct way to do this query with Linq?
Try LINQ's SelectMany() method. It is used to flatten nested collections. Instead of using nested for loops, we can do the task in a more 'LINQ' way.
Ex given below -
Master m1 = new Master() { name = "A", lstObj = new List<obj> { new obj { i = 1, s = "C++" }, new obj { i = 1, s = "C#" }, new obj { i = 1, s = "Java" } } };
Master m2 = new Master() { name = "A", lstObj = new List<obj> { new obj { i = 4, s = "PHP" }, new obj { i = 5, s = "Ruby" }, new obj { i = 6, s = "Perl" } } };
List<Master> lstMasters = new List<Master> { m1, m2 };
var result = lstMasters.SelectMany(m => m.lstObj).Where(o => o.s == "PHP");
Just replace the Master class with your BsonDocument.

Error on result of linq expression (and anounymous type)

I have a linq query in my class. When I try to return one or another result the compiler throw a conversion type error related a "Anonymous Type" and I found no solution for it.
This is my code:
public static string VerificaExame(string desc)
{
var model = new ExameContext();
var res = model.DbExame.Where(exame => exame.Descricao.Trim() == desc.Trim()).Select(exame => new { Id = exame.Id, Codigo = exame.Codigo });
if (res == null)
res = model.DbExame.Where(exame => exame.Codigo.Trim() == desc.Trim()).Select(exame => new { Id = exame.Id, Descricao = exame.Descricao });
var ret = res.FirstOrDefault();
return JsonConvert.SerializeObject(ret);
}
And the error message:
Invalid anonymous type member declarator. Anonymous type members must be declared with a member assignment, simple name or member access.
This error is referent to:
res = model.DbExame.Where(exame => exame.Codigo.Trim() == desc.Trim()).Select(exame => new { Id = exame.Id, Descricao = exame.Descricao });
Use a different variable (do not use res)
var res = model.DbExame.Where(exame => exame.Descricao.Trim() == desc.Trim()).Select(exame => new { Id = exame.Id, Codigo = exame.Codigo });
//^ Now res is of a specific type (ie: IEnumerable<Anonymous1>)
if (res == null)
var res2 = model.DbExame.Where(exame => exame.Codigo.Trim() == desc.Trim()).Select(exame => new { Id = exame.Id, Descricao = exame.Descricao });
//^ you cant affect res2 to res because they are of different type
if (res == null) res will never be null, may be you want if (!res.Any()) to see if res has items.
This is what you should do:
public static string VerificaExame(string desc)
{
var model = new ExameContext();
object res = (object)model.DbExame.Where(exame => exame.Descricao.Trim() == desc.Trim())
.Select(exame => new { Id = exame.Id, Codigo = exame.Codigo })
.FirstOrDefault()
??
(object)model.DbExame.Where(exame => exame.Codigo.Trim() == desc.Trim())
.Select(exame => new { Id = exame.Id, Descricao = exame.Descricao })
.FirstOrDefault();
if (res != null)
return JsonConvert.SerializeObject(res);
return JsonConvert.SerializeObject("");//Or throw an exception
}

Categories