the sequence does not have elements executing linq query - c#

Having this model class
public class Usuario
{
#region Atributos
private int _intID = 0;
private Perfil _Perfil_FK = null;
private String _strNombre = "";
private String _strPassword = "";
#endregion
#region Propiedades
public int ID
{
get { return _intID; }
set { _intID = value; }
}
public virtual Perfil Perfil_FK
{
get { return _Perfil_FK; }
set { _Perfil_FK = value; }
}
public int PerfilID { get; set; }
public String Nombre
{
get { return _strNombre; }
set { _strNombre = value; }
}
public String Password
{
get { return _strPassword; }
set { _strPassword = value; }
}
#endregion
}
I'm trying to use this query, the data base table have data, so i can't see the problem?
Usuario user = (from U in _db.Usuario
where ((U.Nombre == model.UserName) && (U.Password == encripPassword))
select U).First();
If you need more info about the data base let me know to update my question

Does the table actually have a row with that name and password?
When you run the generated SQL statement in SQL Management Studio, do you get a result?
Suggest checking your two values in UserName and encripPassword for valid values.
Usuario user = _db.Usuario
.FirstOrDefault(x=>x.Nombre == model.UserName
&& x.Password == encripPassword);
string sql = (user as ObjectQuery).ToTraceString(); //the SQL query generated.
if(user==null)
{
//doesn't exist.
}

Obviously you're not pointing to the right database, or your don't have a user name with that password (I'm guessing the encrypted password doesn't match what's in the DB. Try using FirstOrDefault(), then you can check for Null if the password is wrong...

Check if your class has the proper attributes that tell Linq to SQL how to match it against a database table.
Your class should have
[Table(Name="Nombres")]
attribute, and properties should have
[Column]
attributes, some should also be primary keys etc.
If you don't already have this, I suggest you generate the class using the Entity Class Generation tool: http://msdn.microsoft.com/en-us/library/bb425822.aspx#linqtosql_topic32

Related

Custom Selector Attribute - 'Customer' Cannot be found in the system

I made a custom selector that only displays the customers of the current user but when I select a customer I get the error: 'Customer' Cannot be found in the system.
The code for the Custom selector and how I implemented it on the DAC:
[PXNonInstantiatedExtension]
public class SO_SOOrder_ExistingColumn : PXCacheExtension<PX.Objects.SO.SOOrder>
{
#region CustomerID
[PXMergeAttributes(Method = MergeMethod.Merge)]
[PXForeignReference(typeof(Field<SOOrder.customerID>.IsRelatedTo<BAccount.bAccountID>))]
[SalesRepCustomer]
public int? CustomerID { get; set; }
#endregion
}
public class SalesRepCustomer : PXCustomSelectorAttribute
{
public SalesRepCustomer() : base(typeof(Customer.acctCD))
{
this.DescriptionField = typeof(Customer.acctCD);
}
protected virtual IEnumerable GetRecords()
{
foreach (Customer pc in PXSelect<Customer>.Select(this._Graph))
{
//Getting Current UserID
var cache1 = _Graph.Caches[BqlCommand.GetItemType(typeof(AccessInfo.userName))];
AccessInfo currentCacheObjecta = (AccessInfo)cache1.Current;
var userName = currentCacheObjecta.UserName;
SalesPerson person = PXSelect<SalesPerson, Where<SalesPerson.descr, Equal<Required<AccessInfo.userName>>>>.Select(_Graph, userName);
if (person != null)
{
CustSalesPeople custSalesPeople = PXSelect<CustSalesPeople, Where<CustSalesPeople.salesPersonID, Equal<Required<SalesPerson.salesPersonID>>, And<CustSalesPeople.bAccountID, Equal<Required<CustSalesPeople.bAccountID>>>>>.Select(_Graph, person.SalesPersonID, pc.BAccountID);
//return all customers related to this SalesPersonID in the CustSalesPeople table
if (!(custSalesPeople is null))
{
yield return pc;
}
}
else
{
//current user is not a sales person
//return all of the customers
yield return pc;
}
}
}
}
Screenshot of the selector on the Sales Order Screen:
Any help on this will be appreciated
You should have the constructor look something like
public SalesRepCustomer() : base(typeof(Customer.bAccountID))
{
this.DescriptionField = typeof(Customer.acctName);
this.SubstituteKey = typeof(Customer.acctCD);
}
The first type that you pass to the base constructor is the type of the value that will be used for the field.
In this case you want the customer id(an int) and you are currently using the AcctCD(a string) field. The description field would typically be the name of the customer account and the substitute key will make it so that the users see the AcctCD instead of the the customer ID(the actual value) which is just an integer.

c# GroupPrincipal.FindByIdentity finds the group, but when using GetMembers getting error - there is no such object on the server

this code used to work fine for the past year,
now it is still working, but i have only 4 groups that generate this error...
the code is simple:
using (var context = new PrincipalContext(ContextType.Domain, domName))
{
foreach (string grp in myGroups)
{
using (var group = GroupPrincipal.FindByIdentity(context, IdentityType.Name, grp))
{
PrincipalSearchResult<Principal> usersList;
usersList = group.GetMembers(true);
int usersListCount = usersList.Count();
}}}
when these specific groups come to search , i get the group and can see its description in the group object variable, but when getting its members i get an error massage :
base: "There is no such object on the server.\r\n"
ErrorCode: -2147016656
again,this happens only with 4 specific groups from the same domain, and same OU.
this just started a few days ago without me changing anything, not permissions, nothing in the code, very strange...
any ideas ?
When I encountered this problem I could not have an empty group. I had to produce "best possible" results while the network people were working to resolve the "foreign SID" issue.
I know it is a lot extra but it satisfied the auditors so maybe it will help you. This is what I did:
Precursor: I had already built a class that held all the properties of the AD Entity.
Got a list of users and all their group memberships.
Wrapped the call to get members in a try... catch and when this error occurred I inserted a "Group Membership" property of "Error Retrieving members"
When I had iterated through all the Groups I grabbed a list of all groups that had the error message as a group member then queried the Users list to get a list of all the users who were members of that group.
Then inserted Property records with the found users names.
Since this answer is more about solution structure I will only give a very brief outline of the classes used. While far from elegant it gave me a reusable container that was easy to understand and share and provided a solution that was durable across several networks. It probably lacks in many ways but it passes test #1 - it worked.
public class ADPropEntry : IComparable<ADPropEntry>
{
#region Properties
public string Name { get { return _name; } set { _adName = value; SetPropVals(_adName); } }
public string Value { get { return _v; } set { _v = value; DoValConversion(); } }
public bool IsVisible { get { return _isVis; } set { _isVis = value; } }
public string ConvertTo { get { return _convertVal; } set { _convertVal = value; } }
public int ID { get { return _id; } set { _id = value; } }
#endregion
private void SetPropVals(string s)
{
switch (s)
{
case "accountexpires": _name = "Account Expires"; _isVis = false; _convertVal = "FromFileTime"; break;
... more handles each property conversion
}
}
}
public class ADEntity : IComparable<ADEntity>
{
#region Properties
public string Name { get { return _name; } set { _name = value; } }
public List<ADPropEntry> MyProperty { get { return _ade; } set { _ade = value; } }
public string EntityType { get { return _entT; } set { _entT = value; } }
public string ADName { get { return GetProperty("SAM Account Name"); } }
#endregion
}
This formed provided me a durable data container and then I used another class to query AD in whatever method makes sense. This was packaged in a DLL that the client application could use.
class ADAccess
{
#region Properties
public bool HasErrors { get { return (bool)(_errMsg.Length > 10); } }
public string ErrorMsg { get { return _errMsg; } }
public List<ADEntity> GroupEntries { get { return _lstGrps; } }
public List<ADEntity> UserEntries { get { return _lstUsrs; } }
public List<ADEntity> PrinterEntries { get { return _lstPrts; } }
public List<ADEntity> ComputerEntries { get { return _lstCmps; } }
#endregion
public List<ADEntity> GetADListByMSO(string groupType)
{
if (groupType == "")
{
// get them all return an empty list populating properties
}
else
{
// set the context and fetch return populated list
}
}
Used the same structure to report on SQL server permissions as well.
i found out the issue,
the problematic groups contained users from different domains,
once removed these users from the groups , everything went back to work.
thanks.

Guarantee a duplicate record is not inserted?

I have some code that inserts a record, and I want to first delete any existing records with matching tuples. This code is called rapidly from a number of executables:
public void AddMemberEligibility(long memberId, string internalContractKey, int planSponsorId, int vendorId, string vendorContractKey) {
using (IDocumentSession session = Global.DocumentStore.OpenSession()) {
var existingMember = session.Query<MemberEligibility>().FirstOrDefault(x => x.VendorId == vendorId
&& x.MemberId == memberId && x.PlanSponsorId == planSponsorId);
if (existingMember != null) {
session.Delete<MemberEligibility>(existingMember);
session.SaveChanges();
}
Eligibility elig = new Eligibility() {
InternalContractKey = internalContractKey,
MemberId = memberId,
PlanSponsorId = planSponsorId,
VendorId = vendorId
};
session.Store(elig);
session.SaveChanges();
}
}
This doesn't seem to be enough to protect against duplicates. Any suggestions?
A Hash collection would fix this problem this nicely enough.
It calls hashCode() on input and contains functions to keep the collection somewhat organized then equals() to test the overlapping hash codes. This combination makes it put and contains functions typically 0(1); though if say all the hash codes are the same then it increases contains to 0(logn).
Most likely a concurrent hash collection would be preferable. If you are in java (which it looks like), you can use a CurrentHashSet
What I ended up doing, after taking Oren Eini's advice on the Raven Google group, was to use the Unique Constraints Bundle.
My DTO now looks something like this:
using Raven.Client.UniqueConstraints;
public class MemberEligibility {
[UniqueConstraint]
public string EligibilityKey { get { return $"{MemberId}_{VendorId}_{PlanSponsorId}_{VendorContractKey}"; } }
public long MemberId { get; set; }
public int VendorId { get; set; }
public int PlanSponsorId { get; set; }
public string VendorContractKey { get; set; }
// other fields
}
and my add/update looks like this:
public void AddMemberEligibility(long memberId, int planSponsorId, int vendorId, string vendorContractKey, ...) {
using (IDocumentSession session = Global.DocumentStore.OpenSession()) {
MemberEligibility elig = new MemberEligibility() {
MemberId = memberId,
PlanSponsorId = planSponsorId,
VendorId = vendorId,
VendorContractKey = vendorContractKey,
//other stuff
};
var existing = session.LoadByUniqueConstraint<MemberEligibility>(x => x.EligibilityKey, elig.EligibilityKey);
if (existing != null) {
// set some fields
} else {
session.Store(elig);
}
session.SaveChanges();
}
}
At this point I'm not 100% certain this is the solution I'll push to production, but it works. Keep in mind session.SaveChanges() will throw an exception if there's already a document with the same [UniqueConstraint] property in the store. Also I started with this property typed as a Tuple<...>, but Raven's serializer couldn't figure out how to work with it, so I settled on a string for now.

{"Cannot insert explicit value for identity column in table 'Cantact' when IDENTITY_INSERT is set to OFF."}

I'm trying to save a contact in my program which is a simple phone book in C# and I'm using linq & Entity Framework & when I want to add or change any data I get a run time error
Cannot insert explicit value for identity column in table 'Contact' when IDENTITY_INSERT is set to OFF.
Here's my insert (add) code, on the other hand I don't want to add any data in my primary key which is ID and I want to leave it to my SQL Server.
Thank you all for helping me
public void Save()
{
using (var Contex = new Phone_BookEntities1())
{
var p = from c in Contex.Cantacts
where c.Cantact1 == Name
select new { c.Cantact1, c.Number };
if (!p.Any())
{
Ref_Cantact = new Cantact();
Ref_Cantact.Cantact1 = Name;
Ref_Cantact.Number = Num;
Contex.Cantacts.Add(Ref_Cantact);
Contex.SaveChanges();
}
}
}
EDIT
public partial class Cantact
{
public string Cantact1 { get; set; }
public string Number { get; set; }
public int ID { get; set; }
}
You may do this;
public void Save(string Name, string Num)
{
using(var context = new Phone_BookEntities1())
{
var existingContacts = Context.Cantacts.Where( c=>c.Cantact1 == Name); //there can be many contacts with the same name. Use FirstOrDefault and also improve the filtering criteria
if(existingContacts.Any())
{
foreach(var contact in existingContacts)
{
contact.Number = Num;
}
}else
{
var Ref_Cantact = new Cantact(){Cantact1 = Name, Number = Num};
context.Cantacts.Add(Ref_Cantact);
}
Contex.SaveChanges();
}
}
you can try this: this will wrap all calls in a transaction, therefore setting identity insert on for the insert statement (Created by EF when calling Add+SaveChanges).
if (!p.Any())
{
Ref_Cantact = new Cantact();
Ref_Cantact.Cantact1 = Name;
Ref_Cantact.Number = Num;
using(var trans=Contex.Database.BeginTransaction())
{
Contex.Database.ExecuteSqlStatement("SET IDENTITY_INSERT Contact ON;");
Contex.Cantacts.Add(Ref_Cantact);
Contex.SaveChanges();
trans.Commit();
}
}
EDIT: Another possibility would be setting AutoIncrement (DatabaseGeneratedOption.Identity) off, using (in your modelbuilder in context class (or whereever)):
modelBuilder.Entity<Cantacts>().Property(x=>x.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
I needed to update my .edmx class in my model

Need a refresher course on property access

I need help with accessing class properties within a given class.
For example, take the below class:
public partial class Account
{
private Profile _profile;
private Email _email;
private HostInfo _hostInfo;
public Profile Profile
{
get { return _profile; }
set { _profile = value; }
}
public Email Email
{
get { return _email; }
set { _email = value; }
}
public HostInfo HostInfo
{
get { return _hostInfo; }
set { _hostInfo = value; }
}
In the class "Account" exists a bunch of class properties such as Email or Profile.
Now, when I want to access those properties at run-time, I do something like this
(for Email):
_accountRepository = ObjectFactory.GetInstance<IAccountRepository>();
string username = Cryptography.Decrypt(_webContext.UserNameToVerify, "verify");
Account account = _accountRepository.GetAccountByUserName(username);
if(account != null)
{
account.Email.IsConfirmed = true;
But, I get "Object reference not set..." for account.Email... Why is that?
How do I access Account such that account.Email, account.Profile, and so on
returns the correct data for a given AccountId or UserName.
Here is a method that returns Account:
public Account GetAccountByUserName(string userName)
{
Account account = null;
using (MyDataContext dc = _conn.GetContext())
{
try
{
account = (from a in dc.Accounts
where a.UserName == userName
select a).FirstOrDefault();
}
catch
{
//oops
}
}
return account;
}
The above works but when I try:
account = (from a in dc.Accounts
join em in dc.Emails on a.AccountId equals em.AccountId
join p in dc.Profiles on em.AccountId equals p.AccountId
where a.UserName == userName
select a).FirstOrDefault();
I am still getting object reference exceptions for my Email and Profile
properties. Is this simply a SQL problem or is there something else I need to be
doing to be able to fully access all the properties within my Account class?
Thanks!
Your getting this because Email is another class which has not been assigned yet. What you can do is in your constructor default the properties that link to other classes as new items. For example in your ctor:
public Account()
{
// Set Defaults
Email = new Email();
Profile = new Profile();
HostInfo = new HostInfo();
}
Then you can set their values as desired.
This looks like a case of handling null values on your properties. You should initialize the Email property to something other than null if you expect to store or query against it, or alter the queries so that they can expect to deal with null values. Also if you get a null value from the database, and your property cannot be set to null, the reverse problem occurs.
Are you declaring these properties yourself, or are you trying to indicate something like auto-generated code from like Linq-to-SQL?
If this is auto-generated where the Account table references the Email table, etc., then you probably just need to specify that you want those objects to load as well in the load options:
using (MyDataContext dc = _conn.GetContext())
{
var options = new DataLoadOptions();
options.LoadWith<Account>(a => a.Email);
options.LoadWith<Account>(a => a.Profile);
options.LoadWith<Account>(a => a.HostInfo);
dc.LoadOptions = options;
try
{
account = (from a in dc.Accounts
where a.UserName == userName
select a).FirstOrDefault();
}
catch
{
//oops
}
}
Just wanted to add: there is now a shorter form for declaring trivial properties:
public Profile Profile { get; set; }
public Email Email { get; set; }
public HostInfo HostInfo { get; set; }

Categories