How to inherit partial class for stored procedure call - c#-4.0

I have this class as parent class:
public partial class GetStuffResult
{
private int _Id;
private string _Name;
public GetStuffResult()
{
}
[Column(Storage="_Id", DbType="INT NOT NULL")]
public int Id
{
get
{
return this._Id;
}
set
{
if ((this._Id != value))
{
this._Id = value;
}
}
}
[Column(Storage="_Name", DbType="NVarChar(100)")]
public string Name
{
get
{
return this._Name;
}
set
{
if ((this._Name != value))
{
this._Name = value;
}
}
}
}
This is base class which has same methods with exception of an extra method:
public partial class GetStuffResult1
{
private int _Score;
private int _Id;
private string _Name;
public GetStuffResult1()
{
}
[Column(Storage="_Score", DbType="INT NOT NULL")]
public int Id
{
get
{
return this._Score;
}
set
{
if ((this._Score != value))
{
this._Score = value;
}
}
}
[Column(Storage="_Id", DbType="INT NOT NULL")]
public int Id
{
get
{
return this._Id;
}
set
{
if ((this._Id != value))
{
this._Id = value;
}
}
}
[Column(Storage="_Name", DbType="NVarChar(100)")]
public string Name
{
get
{
return this._Name;
}
set
{
if ((this._Name != value))
{
this._Name = value;
}
}
}
}
I have done inheritance before but i am totally confused how it will work in this scenario? How can i inherit GetStuffResult so that i can use its 2 methods and dont have to copy paste same code twice in GetStuffResult1.
Will appreciate if someone can give example with code as i am new to .net 3.5 and still trying to learn it.

I am not sure if I correctly understood your question. (Your current code for GetStuffResult1 shouldn't compile as you have define Id property twice.) If you are looking to inherit from GetStuffResult then this would do (See Inheritance):
public partial class GetStuffResult1 : GetStuffResult
{
private int _Score;
public GetStuffResult1()
{
}
[Column(Storage = "_Score", DbType = "INT NOT NULL")]
public int Id
{
get
{
return this._Score;
}
set
{
if ((this._Score != value))
{
this._Score = value;
}
}
}
}
Notice that I have removed _Id and _Name from the child class. This however will give you warning that:
GetStuffResult1.Id' hides inherited member
'ThreadConsoleApp.GetStuffResult.Id'. Use the new keyword if hiding
was intended.
The second thing I am thinking about your question if you are confused about using partial classes and you may need a single class in multiple source file. In that case you may use partial keyword. If that is the case and you don't need inheritance then you need to use a single name for the class. e.g. GetStuffResult. In that particular case your GetStuffResult1 will become:
public partial class GetStuffResult
{
private int _Score;
public GetStuffResult1()
{
}
[Column(Storage = "_Score", DbType = "INT NOT NULL")]
public int Id
{
get
{
return this._Score;
}
set
{
if ((this._Score != value))
{
this._Score = value;
}
}
}
}
This will be similar to having a single class with all the combined properties.
Edit:
To access the base class properties in the child class, you may use base keyword.
base.Id = 0;
base.Name = "SomeName";
To access the base class properties from the object of GetStuffResult1, see the following example.
GetStuffResult1 gsr1 = new GetStuffResult1();
gsr1.Id = 0;
gsr1.Name = "SomeName";
Here gsr1.Name is from the base class, you may use different name for Id in either base or child class so that it can be more clearer.

Related

Vala files import

I have a problem when work with properties in separated files in Vala Language
The Main.vala file is
using Teste;
using Cagado;
static int main(string[] args)
{
GUI gui = new GUI();
stdout.printf("%d\n", gui.idade);
return 0;
}
The HelloVala.vala is:
namespace Teste
{
public class Person : Object
{
private int _age = 32;
public int age
{
get { return _age; }
set { _age = value; }
}
}
}
The Cagado.vala is:
using Teste;
namespace Cagado
{
public class GUI : Object
{
Person _person = new Person();
_person.age = 35;
private int _idade;
public int idade
{
get { return _idade; }
set { _idade = value; }
}
}
}
When i compile this code, the compile gives me the message error:
Cagado.vala:9.15-9.15: error: syntax error, expected identifier
_person.age = 35;
^
I program in C# and this not happened in C# oriented object system.
Someone could explain this?
The problem is this:
public class GUI : Object
{
Person _person = new Person();
_person.age = 35; // <--
...
You can't put arbitrary code inside of the class itself, only declarations. What you need to do is something like
public class GUI : Objects
{
Person _person = new Person();
construct {
_person.age = 35;
}
You could also modify add a constructor to the Person class:
namespace Teste
{
public class Person : Object
{
private int _age = 32;
public int age
{
get { return _age; }
set { _age = value; }
}
public Person(int age) {
GLib.Object (age: age);
}
}
}
Then do
public class GUI : Object
{
Person _person = new Person(35);

Ignore member of base class in YamlDotNet

I have a class which I want to serialize with YamlDotNet:
public class AwesomeClass : PropertyChangedBase
{
private bool _element1;
private bool _enabled;
public bool Element1
{
get { return _element1; }
set
{
_element1 = value;
NotifyOfPropertyChange(() => Element1);
}
}
public bool Enabled
{
get { return _enabled; }
set
{
_enabled = value;
NotifyOfPropertyChange(() => Enabled);
}
}
}
My problem is, in the base class is an element named: IsNotifying
Is there a way to exclude this element from serialization, without the change of the base class?
You could override the property in the derived class and apply the YamlIgnore attribute there. While the sample below works, I suspect for more complicated class hierarchies you would really need to ensure no behavior changes.
public class AwesomeClass : PropertyChangedBase
{
[YamlIgnore]
public new bool IsNotifying
{
get { return base.IsNotifying; }
set { base.IsNotifying = value; }
}
[YamlIgnore]
public override bool Blah
{
get { return base.Blah; }
set { base.Blah = value; }
}
}
public class PropertyChangedBase
{
public bool IsNotifying
{
get;
set;
}
public virtual bool Blah
{
get;
set;
}
}
I had a similar problem (needed to filter properties of a particular type from classes I couldn't change, so using the attribute was not an option) and is what I came up with:
Create a custom type inspector:
public class MyTypeInspector : TypeInspectorSkeleton
{
private readonly ITypeInspector _innerTypeDescriptor;
public MyTypeInspector(ITypeInspector innerTypeDescriptor)
{
_innerTypeDescriptor = innerTypeDescriptor;
}
public override IEnumerable<IPropertyDescriptor> GetProperties(Type type, object container)
{
var props = _innerTypeDescriptor.GetProperties(type, container);
props = props.Where(p => !(p.Type == typeof(Dictionary<string, object>) && p.Name == "extensions"));
props = props.Where(p => p.Name != "operation-id");
return props;
}
}
Create the serializer as follows:
var builder = new SerializerBuilder();
builder.WithTypeInspector(inspector => new MyTypeInspector(inspector));
var serializer = builder.Build();

How to assign values to the class attributes in C#?

I'm new to C# programming and trying to write the following program using "Vihicle" interface properties that are inherited in 'Car', 'Truck' classes. The problem I'm facing is this error:
An unhandled exception of type 'System.StackOverflowException' occurred"
I get this while assigning the values to the Car properties. Here is my code:
namespace Inheritance_Assignment_2
{
interface Vihicle
{
string Make
{
get;
set;
}
String Model
{
get;
set;
}
int Year
{
get;
set;
}
void DisplayInfo();
float calculateMileage();
}
class Car : Vihicle
{
private string make;
public string Make // read-write instance property
{
get
{
return Make;
}
set
{
Make = value;
}
}
private string model;
public string Model // read-write instance property
{
get
{
return Model;
}
set
{
Model = value;
}
}
private int year;
public int Year // read-write instance property
{
get
{
return Year;
}
set
{
Year = value;
}
}
public void DisplayInfo()
{
Console.WriteLine(Make);
Console.WriteLine(Model);
Console.WriteLine(Year);
}
public float calculateMileage()
{
Random random = new Random();
float value = random.Next(10, 20);
return value;
}
}
class Truck : Vihicle
{
private string make;
public string Make // read-write instance property
{
get
{
return Make;
}
set
{
Make = value;
}
}
private string model;
public string Model // read-write instance property
{
get
{
return Model;
}
set
{
Model = value;
}
}
private int year;
public int Year // read-write instance property
{
get
{
return Year;
}
set
{
Year = value;
}
}
public void DisplayInfo()
{
Console.WriteLine(Make);
Console.WriteLine(Model);
Console.WriteLine(Year);
}
public float calculateMileage()
{
throw new NotImplementedException();
}
}
class TowingTruck : Truck
{
public string TowingCapacity // read-write instance property
{
get
{
return TowingCapacity;
}
set
{
TowingCapacity = value;
}
}
public void DisplayInfo() // Overrided function of class truck because this function doing some extra printing of
{ //TowingCapacity that is present in this TowingTruck Child of Truck Class
Console.WriteLine(Make);
Console.WriteLine(Model);
Console.WriteLine(Year);
Console.WriteLine(TowingCapacity);
}
public float calculateMileage()
{
throw new NotImplementedException();
}
}
class DeliveryTruck : Truck
{
public string Make // read-write instance property
{
get
{
return Make;
}
set
{
Make = value;
}
}
public string Model // read-write instance property
{
get
{
return Model;
}
set
{
Model = value;
}
}
public int Year // read-write instance property
{
get
{
return Year;
}
set
{
Year = value;
}
}
/*
public void DisplayInfo()
{
Console.WriteLine(Make);
Console.WriteLine(Model);
Console.WriteLine(Year);
}
public float calculateMileage()
{
// throw new NotImplementedException();
return 0;
}
*/
}
class Program
{
static void Main(string[] args)
{
//while (true) // Loop indefinitely
//{
// string name;
// int age;
// double height;
// Console.Write("Enter your name: ");
// name = Console.ReadLine();
// Console.Write("Enter your age: ");
// age = Convert.ToInt32(Console.ReadLine());
// Console.Write("Enter your height: ");
// height = Convert.ToDouble(Console.ReadLine());
// //Print a blank line
// Console.WriteLine();
// //Show the details you typed
// Console.WriteLine( name);
// Console.WriteLine( age);
// Console.WriteLine("Height is ", height);
// Console.WriteLine('\n');
//}
Car C = new Car();
float rnum = C.calculateMileage();
Console.WriteLine("Here is the Milage : " + rnum);
C.Make = System.Console.ReadLine();
System.Console.WriteLine("The employee information:");
System.Console.WriteLine("Employee name: {0}", C.Make);
//Console.Write("Enter your Model : ");
//C.Model = Console.ReadLine();
//Console.WriteLine(C.Model);
//Console.ReadLine();
}
}
}
Look at your properties:
private string make;
public string Make // read-write instance property
{
get
{
return Make;
}
set
{
Make = value;
}
}
When you read a value from Make, it internally reads a value from Make (same with writing a value), which results in an infinite recursion. You need to read/write from the variable which holds the value:
private string make;
public string Make // read-write instance property
{
get
{
return make;
}
set
{
make = value;
}
}
A property's internal logic can't reference itself. Something actually has to store the value.
Edit: Unless there's any particular reason to use properties like this (such as requiring more logic in the getters/setters), you can just use auto-generated properties to simplify the code. So instead of this:
private string make;
public string Make // read-write instance property
{
get
{
return make;
}
set
{
make = value;
}
}
You can just use this:
public string Make { get; set; }
The compiler automatically converts the latter into something very similar to the former (maybe with just a different backing variable name).

AutoMapper.."CreateMapExpression" doesn't support to create map for Linq.Expression for "Enum" type which from different namespace

Based on my test for mapping Linq.Expression using Automapper, it's not support to use "Enum" which in different namespaces.
Please see my sample below,
namespace TestNamespace1
{
public enum EnumTypes
{
EnumType01,
EnumType02
}
}
namespace TestNamespace2
{
public enum EnumTypes
{
EnumType01,
EnumType02
}
}
namespace MappingTest
{
class A
{
public TestNamespace1.EnumTypes EnumType { get; set; }
}
class B
{
public TestNamespace2.EnumTypes EnumType { get; set; }
}
class TestMapping
{
static void Main()
{
var bDataSource = new List<B> { new B { EnumType = **TestNamespace2**.EnumTypes.EnumType01 } };
Mapper.CreateMap<A, B>();
Mapper.CreateMap<B, A>();
Expression<Func<A, bool>> expressionA = x => x.EnumType == TestNamespace1.EnumTypes.EnumType01;
var expressionB = GetMappedSelectorForAB(expressionA);
var result = bDataSource.AsQueryable().Where(expressionB);
foreach (B b in result)
{
Console.WriteLine("Matching B: {0}", b.EnumType.ToString());
}
}
static Expression<Func<B, bool>> GetMappedSelectorForAB(Expression<Func<A, bool>> selector)
{
Expression<Func<B, A>> mapper = AutoMapper.QueryableExtensions.Extensions.CreateMapExpression<B, A>(Mapper.Engine);
Expression<Func<B, bool>> mappedSelector = selector.Compose(mapper);
return mappedSelector;
}
}
public static class FunctionCompositionExtensions
{
public static Expression<Func<X, Y>> Compose<X, Y, Z>(this Expression<Func<Z, Y>> outer, Expression<Func<X, Z>> inner)
{
return Expression.Lambda<Func<X, Y>>(
ParameterReplacer.Replace(outer.Body, outer.Parameters[0], inner.Body),
inner.Parameters[0]);
}
}
class ParameterReplacer : ExpressionVisitor
{
private ParameterExpression _parameter;
private Expression _replacement;
private ParameterReplacer(ParameterExpression parameter, Expression replacement)
{
_parameter = parameter;
_replacement = replacement;
}
public static Expression Replace(Expression expression, ParameterExpression parameter, Expression replacement)
{
return new ParameterReplacer(parameter, replacement).Visit(expression);
}
protected override Expression VisitParameter(ParameterExpression parameter)
{
if (parameter == _parameter)
{
return _replacement;
}
return base.VisitParameter(parameter);
}
}
}
AutoMapper.QueryableExtensions.Extensions.CreateMapExpression
I have saw the source code of Automapper, and debuged it I will got this error "Unable to create a map expression from ..."
If both of the Class A and B use the same Enum from same namespace, then it works fine like this
class A
{
public TestNamespace1.EnumTypes EnumType { get; set; }
}
class B
{
public TestNamespace1.EnumTypes EnumType { get; set; }
}
Is there a way to implement it? we know the target and source object may have themselft namespace [DTO].

Trying to simplify the code

Does anybody suggest me how can I simplify the follow code
private bool isMethodCalled;
private void CallMethod()
{
if (!isMethodCalled)
{
this.CallCertainMethod();
isMethodCalled = true;
}
}
private int field1;
public int Property1
{
get
{
CallMethod();
return this.field1;
}
set { this.field1 = value; }
}
private int field2;
public int Property2
{
get
{
CallMethod();
return this.field2;
}
set { this.field2 = value; }
}
private int field3;
public int Property3
{
get
{
CallMethod();
return this.field3;
}
set { this.field3 = value; }
}
You could use an AOP framework like PostSharp to create an attribute which would call CallMethod and just use automatic properties for Property1, Property2 and Property3. Although it wouldn't save much in the number of lines of code unless there are a lot of other properties.
Something you can simplify is the following:
private void CallMethod()
{
if (!isMethodCalled)
{
this.CallCertainMethod();
isMethodCalled = true;
}
}
to:
private void CallMethod()
{
if (!isMethodCalled) this.CallCertainMethod();
isMethodCalled = true;
}
As a side note:
I don't know what CallCertainMethod() does. Just in case, it is not recommended to query data and mutate state at the same time. See Command Query-Separation, which states that every method should either be a command that performs an action, or a query that returns data to the caller, but not both. In other words, asking a question should not change the answer.

Resources