Why am I getting an error while running this code? - c#

When I was running a console application, I got this stack overflow error.
As this error seems to be in the Assignlogic part of my code, I have wrote down that part of code and the error which is shown. My question is how to handle this exception, without changing the functionality of code?
//Assign
public class Assignlogic
{
private List<Assign> Assigns { get; set; } = new List<Assign>();//Here exception unhandled was thrown
//System.StackOverflowException: 'Exception of type 'System.StackOverflowException' was thrown.'
readonly Assignlogic logicC = new Assignlogic();
public void AddEmployeetoProject(Assign assign, Employeelogic logicA, Projectlogic logicB)
{
List<Employee> Employes = logicA.Employees;
List<Project> Projcts = logicB.Projects;
List<Assign> Assignss = logicC.Assigns;
var id = assign.EmpId;
var pid = assign.PID;
var emp = Employes.Find(a => a.EmpId == id);
var prjct = Projcts.Find(c => c.PID == pid);
if (emp != null || prjct != null)
{
Assignss.Add(assign);
}
}
//view all assigned projects
public List<Assign> GetAllAssignedProjects()
{
return Assigns;
}
//remove an employee from a project
public void RemoveEmployee(string id)
{
var emp = Assigns.Find(a => a.EmpId == id);
if (emp != null)
{
Assigns.Remove(emp);
}
}
public bool SearchProjectbyMappedId(string id)
{
var employee = Assigns.Find(c => c.EmpId == id);
if (employee != null)
{
return true;
}
else
{
return false;
}
}
}

What happens when you create an instance of Assignlogic? This:
readonly Assignlogic logicC = new Assignlogic();
So creating an instance of Assignlogic creates an instance of Assignlogic, which creates an isntance of Assignlogic, which creates an instance of Assignlogic, etc., etc.
I don't know what your intent is here, but this is clearly not the way to do it. Objects shouldn't recursively create themselves ad infinitum.

you have this member in your class AssignLogic
readonly Assignlogic logicC = new Assignlogic();
So when you create an AssignLogic, it has to go and create an AssignLogic to put there. Creating that AssignLogic requires another AssignLogic,.......

Related

How to implement IConvertible

I have some test code to check if 2 sides are equal.
public void GetCompanies_WithCorrectCompanyRequest_ReturnCompanyDtos()
{
// Arrange
var companyRequset = new CompanyRequest();
// Act
var companyDtos = _datlinqServiceMock.GetCompanies(companyRequset);
// Assert
Assert.IsTrue(companyDtos != null && companyDtos.Any());
Assert.AreEqual(DatlinqServiceMock.CompanyName, companyDtos.FirstOrDefault().Name);
}
That calls this.
public class DatlinqServiceMock: DatlinqService
{
public static string CompanyName = "Company_Test";
public override T GetApi<Q,T>(string apiMethod, Q request)
{
var companyList = new List<Company>()
{
new Company(){ Name = CompanyName}
};
return (T)Convert.ChangeType(companyList, typeof(T));
}
}
GetCompanies:
public List<Company> GetCompanies(CompanyRequest request)
{
if (request == null)
{
return new List<Company>();
}
var searchCompany = new SearchCompanyRequest();
searchCompany.Query = request.Name;
searchCompany.DatlinqKey = ConfigurationManager.AppSettings["Datlinq_Key"];
var searchCompanyResponse = GetApi<SearchCompanyRequest,SearchCompanyResponse>(DatlinqApiMethod.SearchCompany, searchCompany);
var companies = searchCompanyResponse.Result
.Select(c => new Company { Id = c.Id, Name = c.Name })
.ToList();
return companies;
}
GetApi:
public virtual T GetApi<Q,T>(string apiMethod, Q request)
{
var result = default(T);
try
{
var url = String.Format("{0}{1}", _apiUrl, apiMethod);
if (request != null)
{
url = QueryHelpers.AddQueryString(url, request.ToDictionary());
}
var apiResponse = _httpClient.GetAsync(url).Result;
if (apiResponse.IsSuccessStatusCode)
{
string apiResponseString = apiResponse.Content.ReadAsStringAsync().Result;
if (!string.IsNullOrEmpty(apiResponseString))
{
result = JsonConvert.DeserializeObject<T>(apiResponseString);
}
}
}
catch (Exception)
{
// do something
}
return result;
}
And I get an error when I execute the first test
Message: 
Test method Lavazza.ContractTool.Datlinq.Tests.Services.DatlinqServiceTests.GetCompanies_WithCorrectCompanyRequest_ReturnCompanyDtos threw exception:
System.InvalidCastException: Object must implement IConvertible.
Stack Trace: 
Convert.ChangeType(Object value, Type conversionType, IFormatProvider provider)
Convert.ChangeType(Object value, Type conversionType)
DatlinqServiceMock.GetApi[Q,T](String apiMethod, Q request) line 79
DatlinqService.GetCompanies(CompanyRequest request) line 23
DatlinqServiceTests.GetCompanies_WithCorrectCompanyRequest_ReturnCompanyDtos() line 32
I hope this is enough code to know what the problem/solution is if not let me know what you need.
To answer some question asked below.
Dai: I am trying to find what this is and why I need it because it came up in the error but the microsoft docs don't make it clear for me.
Jeroen: It is kind of a legacy project so I can't/won't add extra dependencies.
The "issue" here is that your GetApi method is designed to return a sort of generic response - in this specific case SearchCompanyResponse - but you're trying to override it to return a List<Company> which is wrong because that is what your GetCompanies method does (ie turn a SearchCompanyResponse to a List<Company>).
Suffice it to say this has nothing to do with implementing IConvertable.
What you would be better off doing is serializing a SearchCommpanyResponse that you wish to use for testing to a file, and using that file-based response for your testing.
That way your overridden "Mock" would be
public override T GetApi<Q,T>(string apiMethod, Q request)
{
return JsonConvert.DeserializeObject<T>(File.ReadAllText("mytestfile.json"));
}

Using Function from a class in API Class

I want to set some data in an API class by calling a function from another class.
Why the 'main' has error while 'Classes' works? How and where I should define it?
Error: a field initializer cannot reference the nonstatic field
How do I can get the ID which has passed in URL to use in my class?
This is my code:
public class InformationController : ApiController
{
Classes main = new Classes();
Information[] Information = new Information[]
{
new Information { Info_ID = 2, fullName = main.getFullname("2"), },
};
public IEnumerable<Information> GetAllInformation()
{
return Information;
}
public Information GetInformationById(int id)
{
var information = Information.FirstOrDefault((p) => p.Info_ID == id);
if (information == null)
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
return information;
}
public IEnumerable<Information> GetInformationByCategory(string category)
{
return Information.Where(
(p) => string.Equals(p.std_nextClass, category,
StringComparison.OrdinalIgnoreCase));
}
}
You can try initialize the array in the constructor:
public class InformationController : ApiController
{
private Classes main = new Classes();
private Information[] Information;
public InformationController()
{
Information = new Information[]
{
new Information { Info_ID = 2, fullName = main.getFullname("2"), },
};
}
/// the rest of your code...

Objects cannot be defined because they are attached to different ObjectContext objects(When using different services)

I read a lot on this topic but I still do not understand how to use different services with own contexts. I know that if I use something like "Unit Of Work", this approach will solve my problem, but I am looking for another solution. Any help will be appreciated!
public class SportCategoryService : ISportCategoryService
{
private IDeletableEntityRepository<SportCategory> sportCategoriesDb;
private IDeletableEntityRepository<User> usersDb;
public SportCategoryService(IDeletableEntityRepository<SportCategory> sportCategoriesDb, IDeletableEntityRepository<User> usersDb)
{
this.sportCategoriesDb = sportCategoriesDb;
this.usersDb = usersDb;
}
public void AddCategoriesForUser(string[] categories, string userId)
{
var user = usersDb.All().FirstOrDefault(x => x.Id == userId);
foreach (var name in categories)
{
var currentCategory = this.sportCategoriesDb.All().FirstOrDefault(x => x.Name == name);
if (currentCategory != null)
{
currentCategory.Users.Add(user);
}
else
{
sportCategoriesDb.Add(new SportCategory() { Name = name, Users = new List<User>() { user } });
}
}
sportCategoriesDb.SaveChanges();
}
}

The query contains references to items defined on a different data context?

This throws an error saying The query contains references to items defined on a different data context. when i try to assign catName at the bottom.
this.CustomSettings = (
from xx in DBContext.ProductCustomizationMasters
where xx.ProductID == this._ProductID
select new ProductCustomization()
{
ProductID = (int)xx.ProductID,
CategoryID = (int)xx.CustomCategoryID,
CustomID = xx.CustomID,
CustomizationType = (CategoryType)xx.CustomType,
DefaultFreeCount = (short)xx.DefaultFreeCount,
IsDefaultLimit = (bool)xx.IsDefault,
HasItems = ((xx.DefaultFreeCount == 0) ? (false) : (true)),
CatName= (from yy in DBContext.CustomCategoryTbls where yy.CatID == xx.CustomCategoryID select yy.CatName).FirstOrDefault()
}
).ToList();
i am makng datacontext like this
private libDBDataContext _DB = null;
public libDBDataContext DBContext { get { return (_DB == null) ? new libDBDataContext() : _DB; } set { _DB = value; } }
how it says it has two different datacontext, while things are being performed on the same datacontext.
Every time you access your DBContext property you are creating a new libDBDataContext because you never assign it to _DB.
Try changing your code to this
private libDBDataContext _DB = null;
public libDBDataContext DBContext
{
get
{
if (_DB == null)
{
_DB = new libDBDataContext();
}
return _DB;
}
set { _DB = value; }
}
This is not thread safe, but it should help you get through your current issue.
EDIT
As #Servy pointed out there is a cleaner and thread safe implementation using Lazy.
private Lazy<libDBDataContext> _DB = new Lazy<libDBDataContext>(
() => new libDBDataContext()
);
public libDBDataContext DBContext
{
get { return _DB.Value; }
}

An object with a key that matches the key of the supplied object could not be found in the ObjectStateManager

I want to update record from FormView with ObjectDataSource and lose my day to solve this error.
An object with a key that matches the key of the supplied object could
not be found in the ObjectStateManager. Verify that the key values of
the supplied object match the key values of the object to which
changes must be applied.
My code is below
private static Entities1 _db = null;
public static Entities1 CreateDataContext()
{
if (_db == null)
{
_db = new Entities1(System.Configuration.ConfigurationManager.ConnectionStrings["Entities1"].ConnectionString);
_db.games.MergeOption = MergeOption.NoTracking;
_db.my_aspnet_users.MergeOption = MergeOption.NoTracking;
_db.platforms.MergeOption = MergeOption.NoTracking;
}
return _db;
}
public void Update(game item)
{
Entities1 DB = CreateDataContext();
item.modified = DateTime.Now;
var obj = (from u in DB.games
where u.idgames == item.idgames
select u).First();
DB.games.ApplyCurrentValues(item);//Error Here
DB.SaveChanges();
}
In your method:
public void Update(game item)
{
Entities1 DB = CreateDataContext();
item.modified = DateTime.Now;
var obj = (from u in DB.games
where u.idgames == item.idgames
select u).First();
DB.games.ApplyCurrentValues(item);//Error Here
DB.SaveChanges();
}
item is not attached so it can't be updated. That's pretty much what the error message is telling you, too.
It looks like you'd want to use obj which is retrieved from your context. Then set the values of obj to those in item, and use obj to make the updates.
EDIT for sample...
If you just want to set the modified date and time you'd do this:
public void Update(game item) {
Entities1 DB = CreateDataContext();
var obj = (from u in DB.games
where u.idgames == item.idgames
select u).SingleOrDefault();
if (obj == null) {
// handle the case where obj isn't found
// probably by throwing an exception
}
obj.modified = DateTime.Now;
DB.games.ApplyCurrentValues(obj);
DB.SaveChanges();
}

Categories

Resources