I have edited the question. Thanks for the comments below.
It looks like my issue was with a parameterless constructor to declare the class in XAML. However, I can't seem to figure out how to get a parameterless constructor with an observable collection. Please see my code below:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
using System.ComponentModel;
using System.Collections.ObjectModel;
namespace LinkKing.Classes
{
[Serializable()]
public class TheLinks
{
public string linkID;
public string parentID;
public string link;
public DateTime dateAdded;
public int stepAdded;
public string img;
[System.Xml.Serialization.XmlElement("Link")]
public string Link
{
get { return link; }
set { link = value; }
}
[System.Xml.Serialization.XmlElement("DateAdded")]
public DateTime DateAdded
{
get { return dateAdded; }
set { dateAdded = value; }
}
[System.Xml.Serialization.XmlElement("StepAdded")]
public int StepAdded
{
get { return stepAdded; }
set { stepAdded = value; }
}
[System.Xml.Serialization.XmlElement("LinkID")]
public string LinkID
{
get { return linkID; }
set { linkID = value; }
}
[System.Xml.Serialization.XmlElement("ParentID")]
public string ParentID
{
get { return parentID; }
set { parentID = value; }
}
[System.Xml.Serialization.XmlElement("IMG")]
public string IMG
{
get { return img; }
set { img = value; }
}
public TheLinks(string linkID, string parentID, string link, DateTime dateAdded, int stepAdded, string img) : base()
{
this.Link = link;
this.DateAdded = dateAdded;
this.StepAdded = stepAdded;
this.LinkID = linkID;
this.ParentID = parentID;
this.IMG = img;
}
}
public class MyLinks : ObservableCollection<TheLinks>
{
public MyLinks() : base()
{
}
}
}
The error I get is The Type does not include any accessible constructors.
I appreciate everyone's help.
Just based on the code, you have no public parameterless constructor for MyLinks. If you did you would find it on local.
Also usually if it's MVVM, I think having a different namespace for the ViewModel would be better.
Maybe it would also make sense to make your fields (i.e. public string linkID;public string parentID; up to public string img;) private too since you don't access them from outside the class anyway.
Related
Screenshot showing column & column entry
Hey all, I'm getting an error saying my column names are invalid. I know it's not the table that is wrong because it worked perfectly fine an hour ago. I tried different variations of the Id, issue, etc with no luck.
namespace Csis265.DAL
{
public class BugMapper : BaseMapper
{
public BugMapper(SqlDataReader rdr) : base(rdr)
{ }
public override object DoMapping()
{
logger.Debug("INSIDE BugMapper DoMapping() !!!");
int id = GetInteger("ID");
string issue = GetString("ISSUE");
string resolution = GetString("RESOLUTION");
int statusId = GetInteger("STATUS_ID");
int priorityId = GetInteger("PRIORITY_ID");
int softwareappId = GetInteger("SOFTWARE_APP_ID");
DateTime dateCreated = GetDateTime("DATE_CREATED");
DateTime dateResolved = GetDateTime("DATE_RESOLVED");
Bug rtnObj = new Bug(id, issue, resolution,
statusId, priorityId, softwareappId, dateCreated, dateResolved);
logger.Debug($"INSIDE BugMapper DoMapping() {rtnObj.ToString()}");
return rtnObj;
}
}
BUG CLASS - Nothing was touched besides the issue get/set. I originally had it as name instead of issue but have fixed that mistake
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using log4net;
namespace Csis265.Domain
{
public class Bug : BaseObject
{
protected string issue;
protected string resolution;
protected int statusId;
protected int priorityId;
protected int softwareappId;
protected Status status;
protected Priority priority;
protected SoftwareApp softwareapp;
public Status Status
{
get { return status; }
set { status = value; }
}
public Priority Priority
{
get { return priority; }
set { priority = value; }
}
public SoftwareApp SoftwareApp
{
get { return softwareapp; }
set { softwareapp = value; }
}
public int Id
{
get { return id; }
set { id = value; }
}
public string Issue
{
get { return issue; }
set { issue = value; }
}
public string Resolution
{
get { return resolution; }
set { resolution = value; }
}
public string StatusName
{
get { return Status.Name; }
}
public string PriorityName
{
get { return Priority.Name; }
}
public string SoftwareAppName
{
get { return SoftwareApp.Name; }
}
public Bug(int id, string issuse, string resolution,
int statusId, int priorityId, int softwareappId,
DateTime dateCreated, DateTime dateResolved) : base(id, dateCreated)
{
SetIssue(issue);
SetResolution(resolution);
SetStatusId(statusId);
SetPriorityId(priorityId);
SetSoftwareAppId(softwareappId);
}
public void SetIssue(string issue)
{
this.issue = issue;
}
private void SetSoftwareAppId(int softwareappId)
{
this.softwareappId = softwareappId;
}
private void SetPriorityId(int priorityId)
{
this.priorityId = priorityId;
}
private void SetStatusId(int statusId)
{
this.statusId = statusId;
}
private void SetResolution(string resolution)
{
this.resolution = resolution;
}
public string GetIssue()
{
return issue;
}
public override string ToString()
{
return $"BUG ID:{id} ISSUE: {issue} DTC: {dateCreated}";
}
public string GetResolution()
{
return resolution;
}
public int GetStatusId()
{
return statusId;
}
public int GetPriorityId()
{
return priorityId;
}
public int GetSoftwareAppId()
{
return softwareappId;
}
}
}
line 20..
Change
int id = GetInteger("ID'");
to
int id = GetInteger("ID"); // Without the quote
I want to try a .NET deserialization example, but it seems I am not able to get the getters and setters working. This is my code
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml.Serialization;
namespace WindowsFormsApplication3
{
[XmlRoot]
public class TestClass
{
public string classname;
private string name;
private int age;
[XmlAttribute]
public string Classname { get => classname; set => classname = value; }
[XmlElement]
public string Name { get => name; set => name = value; }
[XmlElement]
public int Age { get=>age; set => age = value; }
public override string ToString()
{
return base.ToString();
}
}
class Program
{
static void Main(string[] args)
{
TestClass testClass = new TestClass();
testClass.Classname = "test";
testClass.Name = "william";
testClass.Age = 50;
Console.WriteLine("Hello World!");
MessageBox.Show("Test");
}
}
}
And I get the following error in the get declaration: Not all code paths return a value
As commented by #CodeCaster, you need a minimum of C# 7.0 to work around on Expression-Bodied Members and your visual studio doesn't support it.
So you can upgrade your visual studio to C# 7.0 or use below with current version,
You can use
public string Classname
{
get { return classname; }
set { classname = value; }
}
instead of
public string Classname
{
get => classname;
set => classname = value;
}
And do the same for all other remaining properties in your class those are with expression-bodies.
I followed the article here and the sample code given in it.
What I am trying to implement is pretty straightfoward. I do have a fair understanding about collections and enumerators. However, what I don't understand is that even though there is hardly any difference in the way I have implemented the code as compared to how it is implemented in the given article, why I am getting an error.
Only difference in the implementation is that the sample code uses T (generic) whereas I am using a class named Address while implementing the custom Addresses collection class.
The code is pretty straightfoward. I have the following classes in the project.
Contact class
Addresses class (Implements custom collection and inherits from ICollection)
Address class
AddressEnumerator
What I wish to achieve is the Dataset like functionality where we can use a syntax like:
Dataset ds = new Dataset();
Ds.Tables[0]....blah blah blah.
I get a compile time error in the following method of the AddressEnumerator.cs class.
Error:
cannot apply indexing with [] to an expression of type ConsoleApplication2.Addresses (Addresses class implements an ICollection)
Compile time error occurs in the following statement:
_current = _collection[index];
public bool MoveNext()
{
if(++index >= _collection.Count)
{
return false;
}
else
{
_current = _collection[index];
}
return true;
}
Source code:
//following code snippet does not traverse the collection
foreach (Address a in c.Addresses)
{
Console.WriteLine(a.Street);
}
Program.cs
using System;
using System.Configuration;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
//RenderTimeSheet();
Address ad = new Address();
ad.Street = "Hollywood";
ad.City = "LA";
ad.State = "California";
ad.ZipCode = "93494";
ad.Country = "USA";
using (Contact c = new Contact(ad))
{
c.FirstName = "John";
c.LastName = "Doe";
Console.WriteLine(c.FirstName);
Console.WriteLine(c.LastName);
foreach (Address a in c.Addresses)
{
Console.WriteLine(a.Street);
}
}
Console.ReadKey();
}
}
Contact.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
namespace ConsoleApplication2
{
public class Contact : IDisposable
{
public string FirstName { get; set; }
public string LastName { get; set; }
public Addresses Addresses { get; set; }
public Contact(Address a)
{
Addresses = new Addresses(a);
}
public Contact()
{
}
public void Dispose()
{
Console.Write("Disposing off...");
}
}
}
Addresses.cs
using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication2
{
public class Addresses : ICollection<Address>
{
private IList<Address> _lstAddress;
protected bool _IsReadOnly;
public Addresses(Address _a)
{
_lstAddress = new List<Address>();
}
public void Add(Address item)
{
_lstAddress.Add(item);
}
public void Clear()
{
_lstAddress.Clear();
}
public bool Contains(Address item)
{
foreach(Address a in _lstAddress)
{
if(a.Street == item.Street)
{
return true;
}
}
return false;
}
public void CopyTo(Address[] array, int arrayIndex)
{
throw new Exception("Not valid for this implementation.");
}
public int Count
{
get { return _lstAddress.Count; }
}
public bool IsReadOnly
{
get { return _IsReadOnly; }
}
public bool Remove(Address item)
{
bool result = false;
for (int i = 0; i < _lstAddress.Count; i++)
{
Address obj = (Address)_lstAddress[i];
if(obj.Street == item.Street)
{
_lstAddress.RemoveAt(i);
result = true;
break;
}
}
return result;
}
public IEnumerator<Address> GetEnumerator()
{
return new AddressEnumerator(this);
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
//throw new NotImplementedException();
return this.GetEnumerator();
}
}
}
Address.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication2
{
public class Address
{
public string Street { get; set; }
public string City { get; set; }
public string State { get; set; }
public string ZipCode { get; set; }
public string Country { get; set; }
}
}
AddressEnumerator.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication2
{
public class AddressEnumerator : IEnumerator<Address>
{
protected Addresses _collection;
protected int index;
protected Address _current;
public AddressEnumerator()
{
}
public AddressEnumerator(Addresses collection)
{
_collection = collection;
index = -1;
_current = default(Address);
}
public Address Current
{
get
{
return _current;
}
}
public void Dispose()
{
_collection = null;
_current = default(Address);
index = -1;
}
object System.Collections.IEnumerator.Current
{
get
{
return _current;
}
}
public bool MoveNext()
{
if(++index >= _collection.Count)
{
return false;
}
else
{
_current = _collection[index];
}
return true;
}
public void Reset()
{
throw new NotImplementedException();
}
}
}
this is a direct and short solution to your problem,
but it is not a "complete clean" solution, also the coding style of the complete implementation should be changed. there are more effective ways implementing enumerable interfaces ...
change the line
_current = _collection[index];
to
_current = _collection._lstAddress[index];
but you also need to change the access modifier
private IList<Address> _lstAddress
for example to
internal IList<Address> _lstAddress
The reason that the sample code works and yours doesn't is because the sample code class BusinessObjectCollection includes this:
public virtual T this[int index]
{
get
{
return (T)_innerArray[index];
}
set
{
_innerArray[index] = value;
}
}
which provides the subscript operator [] that your code lacks.
If you add that to your Addresses class (changing _innerArray to _lstAddress) then it should work, I think.
I am starting a new project using C# + Castle ActiveRecord with PostgreSQL. I have this two classes:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Castle.ActiveRecord;
namespace ITELnetERP.Model
{
[ActiveRecord("countries", Table = "countries")]
public class Country : ActiveRecordBase<Country>
{
private string _code;
private string _iso3;
private string _number;
private string _name;
private Continent _continent;
private string _calling_code;
private DateTime _created_at;
private DateTime _updated_at;
[PrimaryKey(PrimaryKeyType.Assigned, Column = "code")]
public string Code
{
get { return _code; }
set { _code = value; }
}
[Property("iso3")]
public string ISO3
{
get { return _iso3; }
set { _iso3 = value; }
}
[Property("number")]
public string Number
{
get { return _number; }
set { _number = value; }
}
[Property("name")]
public string Name
{
get { return _name; }
set { _name = value; }
}
[Property("calling_code")]
public string CallingCode
{
get { return _calling_code; }
set { _calling_code = value; }
}
[BelongsTo("continent_code")]
public Continent Continent
{
get { return _continent; }
set { _continent = value; }
}
[Property("created_at")]
public DateTime CreatedAt
{
get { return _created_at; }
set { _created_at = value; }
}
[Property("updated_at")]
public DateTime UpdatedAt
{
get { return _updated_at; }
set { _updated_at = value; }
}
}
}
and:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Castle.ActiveRecord;
using System.Collections;
namespace ITELnetERP.Model
{
[ActiveRecord("continents")]
public class Continent : ActiveRecordBase<Continent>
{
private string _code;
private string _name;
private DateTime _created_at;
private DateTime _updated_at;
private IList _countries = new ArrayList();
[PrimaryKey(PrimaryKeyType.Assigned, Column = "code")]
public string Code
{
get { return _code; }
set { _code = value; }
}
[Property("name")]
public string Name
{
get { return _name; }
set { _name = value; }
}
[HasMany(typeof(Country), Table = "countries", ColumnKey = "continent_code")]
public IList Countries
{
get { return _countries; }
set { _countries = value; }
}
[Property("created_at")]
public DateTime CreatedAt
{
get { return _created_at; }
set { _created_at = value; }
}
[Property("updated_at")]
public DateTime UpdatedAt
{
get { return _updated_at; }
set { _updated_at = value; }
}
}
}
on my startup file I have this (Note I am using PostgreSQL as DBMS):
static void Main()
{
// Read Configuration for Database
IDictionary<string, string> properties = new Dictionary<string, string>();
properties.Add("connection.driver_class", "NHibernate.Driver.NpgsqlDriver");
properties.Add("dialect", "NHibernate.Dialect.PostgreSQLDialect");
properties.Add("connection.provider", "NHibernate.Connection.DriverConnectionProvider");
properties.Add("connection.connection_string", "Server=localhost;Port=5433;Database=ITELnet_ERP;Uid=itelnet_erp;Pwd=itelnet");
properties.Add("proxyfactory.factory_class", "NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle");
InPlaceConfigurationSource source = new InPlaceConfigurationSource();
source.Add(typeof(ActiveRecordBase), properties);
// Initialize Database
ActiveRecordStarter.Initialize(source, GetActiveRecordTypes());
// Start the Application
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainForm());
}
When I try to select all "Countries" from the database using following statement:
var countries = Country.FindAll();
foreach (Country country in countries)
{
MessageBox.Show("Country Name: " + country.Name);
}
I get this error:
An unhandled exception of type 'Castle.ActiveRecord.Framework.ActiveRecordException' occurred in Castle.ActiveRecord.dll
Additional information: Could not perform FindAll for Country
Image for more details:
What is wrong with my code?
How can I solve that?
Thanks for your attention
Regards
PS
I am trying to map one object to another but I am getting a problem while mapping an empty string to type int or a non integer string to int, so what I want that if I such exceptions occur it must assign some default value to it, let say -1.
for example we have a class A and Class B
Class A
{
public string a{get;set;}
}
Class B
{
public int a{get;set;}
}
Now if we map from class A to B using default rule it will through exception if string is empty or non integer.
Please help me fix this problem.
Thanks in advance.
I think this is what you're after.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AutoMapper;
using NUnit.Framework;
namespace StackOverFlowAnswers
{
public class LineItem
{
public int Id { get; set; }
public string ProductId { get; set; }
public int Amount { get; set; }
}
public class Model
{
public int Id { get; set; }
public string ProductId { get; set; }
public string Amount { get; set; }
}
public class AutoMappingTests
{
[TestFixtureSetUp]
public void TestFixtureSetUp()
{
Mapper.CreateMap<Model, LineItem>()
.ForMember(x => x.Amount, opt => opt.ResolveUsing<StringToInteger>());
}
[Test]
public void TestBadStringToDefaultInteger()
{
// Arrange
var model = new Model() {Id = 1, ProductId = "awesome-product-133-XP", Amount = "EVIL STRING, MWUAHAHAHAH"};
// Act
LineItem mapping1 = Mapper.Map<LineItem>(model);
// Assert
Assert.AreEqual(model.Id, mapping1.Id);
Assert.AreEqual(model.ProductId, mapping1.ProductId);
Assert.AreEqual(0, mapping1.Amount);
// Arrange
model.Amount = null; // now we test null, which we said in options to map from null to -1
// Act
LineItem mapping2 = Mapper.Map<LineItem>(model);
// Assert
Assert.AreEqual(-1, mapping2.Amount);
}
}
public class StringToInteger : ValueResolver<Model, int>
{
protected override int ResolveCore(Model source)
{
if (source.Amount == null)
{
return -1;
}
int value;
if (int.TryParse(source.Amount, out value))
{
return value; // Wahayy!!
}
return 0; // return 0 if it could not parse!
}
}
}
Well the above code works too while i am sharing one code which i made myself as it works too
public class StringToIntTypeConverter : ITypeConverter<string, int>
{
public int Convert(ResolutionContext context)
{
int result;
if (!int.TryParse(context.SourceValue.ToString(), out result))
{
result = -1;
};
return result;
}
}