why is IsPresentItem giving me error in linklist? - c#

class LinkListGen<T> where T : IComparable
{
private LinkGen<T> list;
public LinkListGen()
{
}
public string DisplayList()
{
Console.WriteLine(test);
foreach (string word in words)
{
Console.Write(word + " ");
}
Console.WriteLine();
Console.WriteLine();
}
public void AddItem(T item)
{
list = new LinkGen<T>(item);
}
public int NumberOfItems()
{
public int Count { get; }
}
public bool IsPresentItem(T item)
{
Link temp = list;
bool result = false;
while (temp != null)
{
if (temp.Data == item)
{
result = true;
break;
}
else
{
temp = temp.Next;
}
}
return result;
}
}
I have been trying to make a generic link list but I am not sure why it is giving me an error. The error is coming from the IsPresentItem. Also I'm not sure when I need to add to the linkListGen. thank you for your time

You've got missing closing brace on the NumberOfItems method because you've declared the Count property within it:
public int NumberOfItems()
{
public int Count { get; }
}
It should be:
public int NumberOfItems()
{
//Do Something
}
public int Count { get; }
The whole class should then look like this:
class LinkListGen<T> where T : IComparable
{
private LinkGen<T> list;
public LinkListGen()
{
}
public string DisplayList()
{
Console.WriteLine(test);
foreach (string word in words)
{
Console.Write(word + " ");
}
Console.WriteLine();
Console.WriteLine();
}
public void AddItem(T item)
{
list = new LinkGen<T>(item);
}
public int NumberOfItems()
{
//Do Something
}
public int Count { get; }
public bool IsPresentItem(T item)
{
Link temp = list;
bool result = false;
while (temp != null)
{
if (temp.Data == item)
{
result = true;
break;
}
else
{
temp = temp.Next;
}
}
return result;
}
}

Related

c# using other class method

Thanks to NHMountainGoat for an answer!
Implementing Interface looks a good choice so we have only the 'needed' method instanciated.
It looks like this now:
EDIT
class Machine
{
//REM: MachineConnexion is a link to the main server where asking the data
internal linkToPLC LinkToPLC;
public IlinkToPLC ILinkPLC;
public interface IlinkToPLC//Interface to linkPLC
{
Int16 MachineNumIS { get; set; }
}
internal class linkToPLC : IlinkToPLC
{
private Int16 Act_MachineNum;
private List<string> genlnkPLCCanvas;
private List<string> genlnkPLCworkingwith;
static private List<string> ListSymbolNoExist;
private string[] ListToPLClnk = {
"GlobalFolder.PMachine[{0}].",
"GlobalFolder.PMachine[{0}].STATE.",
"GlobalFolder.Machine[{0}].",
"GlobalFolder.Machine[{0}].STATE.",
};
public linkToPLC()//ctor
{
genlnkPLCCanvas = new List<string>(ListToPLClnk);
genlnkPLCworkingwith = new List<string>(ListToPLClnk);
ListSymbolNoExist = new List<string>();
Act_MachineNum = MachineNumIS;
}
public Int16 MachineNumIS { get { return (Int16)ReadWriteMachine("data"); } set { ReadWriteMachine("data", value); } }
public string ValueExist(string ValueToreach, bool WorkingDATA = false)
{
if (!WorkingDATA)
{
for (int inc = 0; inc < genlnkPLCworkingwith.Count; inc++)
{
string StrValueToReach = genlnkPLCworkingwith[inc] + ValueToreach;
if (MachineConnexion.SymbolExists(StrValueToReach))
{
ListSymbolNoExist.Clear();
return StrValueToReach;
}
else ListSymbolNoExist.Add(genlnkPLCworkingwith[inc] + ValueToreach);
}
}
else if (WorkingDATA)
{
string StrValueToReach = genlnkPLCworkingwith[10] + ValueToreach;
if (MachineConnexion.SymbolExists(StrValueToReach))
{
ListSymbolNoExist.Clear();
return StrValueToReach;
}
else ListSymbolNoExist.Add(genlnkPLCworkingwith[10] + ValueToreach);
}
if (ListSymbolNoExist.Count != 0)
{
string ErrorList = "";
for (int inc = 0; inc < ListSymbolNoExist.Count; inc++)
{
ErrorList = string.Concat(ErrorList + "Num: " + inc.ToString() + " " + ListSymbolNoExist[inc].ToString() + "\n");
}
Console.WriteLine("Error" + ErrorList);
}
return null;
}
public object ReadWriteMachine(string VariableName, object DataToWrite = null, bool WorkingDATA = false)
{
string valueToFind = "";
if (ValueExist(VariableName) != "FALSE")
{
if (DataToWrite != null) { MachineConnexion.WriteSymbol(valueToFind, DataToWrite); }
return MachineConnexion.ReadSymbol(valueToFind);
}
return VariableName;
}
}
public Machine() //constructor
{
LinkToPLC = new linkToPLC();
}
}
And It doesn't work telling me that the reference object is not defined to an instance of the object..... in the line : Machine() LinkToPLC = new linkToPLC();//REM I found the bug, it was me ;o)) 24112016
//REM 24112016
What are the main differences between those two concept: static Instance and Interface?
Example:
class Program
{
static void Main(string[] args)
{
ITestInterface InterInstance = new TestInterface();
//test Interface
bool value1 = true;
value1 = InterInstance.invert(value1);
InterInstance.print(value1);
//test Instance static
TestStaticInstance staticInstance = new TestStaticInstance();
staticInstance.Instance.invert(value1);
staticInstance.Instance.print(value1);
Console.ReadKey();
}
}
class TestInterface : ITestInterface
{
public bool invert(bool value)
{
return !value;
}
public void print(bool value)
{
Console.WriteLine(value.ToString()+"\n");
}
private void methodX()
{ }
}
interface ITestInterface
{
bool invert(bool value);
void print(bool value);
}
public class TestStaticInstance
{
public TestStaticInstance Instance;
public TestStaticInstance()
{
Instance = this;
}
internal bool invert(bool value)
{
return !value;
}
internal void print(bool value)
{
Console.WriteLine(value.ToString());
}
}
Thanks
Can you structure your other classes to take an instance of the link class? See:
/// <summary>
/// just a stub to demonstrate the model
/// </summary>
internal class Machine
{
public string ReadData() { return "this is data"; }
public void WriteData(string data) { Console.WriteLine(data); }
}
internal interface IMachineDataAccessor
{
string Read();
void Write(string data);
}
class LinkClass : IMachineDataAccessor
{
protected Machine _machine;
public LinkClass(Machine machine)
{
_machine = machine;
}
public void DoMyWork()
{
// insert work somewhere in here.
string dataFromMachine = Read();
Write("outbound data");
}
public string Read()
{
return _machine.ReadData();
}
public void Write(string data)
{
_machine.WriteData(data);
}
}
class PersistentClass
{
IMachineDataAccessor _machineImpl;
public PersistentClass(IMachineDataAccessor machineAccessImplementation)
{
_machineImpl = machineAccessImplementation;
}
public void DoMyWork()
{
string dataFromMachine = _machineImpl.Read();
// insert work here. Or anywhere, actually..
_machineImpl.Write("outbound data");
}
}
class StateClass
{
IMachineDataAccessor _machineImpl;
public StateClass(IMachineDataAccessor machineAccessImplementation)
{
_machineImpl = machineAccessImplementation;
}
public void DoMyWork()
{
string dataFromMachine = _machineImpl.Read();
// insert work here. Or anywhere, actually..
_machineImpl.Write("outbound data");
}
}
static void Main(string[] args)
{
LinkClass link = new LinkClass(new Machine());
PersistentClass persistent = new PersistentClass(link as IMachineDataAccessor);
StateClass state = new StateClass(link as IMachineDataAccessor);
persistent.DoMyWork();
state.DoMyWork();
link.DoMyWork();
}

C# Runtime Error: InvalidCastException with Generic Class Instance

I'm a java developer and new to C#, I'm stuck with InvalidCastException on the following code below.
I have implemented a Queue, based on a custom Doubly Linked List implementation. Both implementations are generic, and thus, on the test code, I want to use a generic print method.
The test code below is just working fine;
using System;
using System.Collections.Generic;
namespace Queue01
{
public class TestQueue
{
public static void Main(string[] args)
{
Queue<int> queue = new Queue<int>();
queue.Enqueue(4);
queue.Enqueue(5);
queue.Enqueue(6);
Console.WriteLine("*****");
PrintQueue(queue);
Console.WriteLine("*****");
int first = queue.Dequeue();
Console.WriteLine("Enqueued value : " + first);
Console.WriteLine("*****");
PrintQueue(queue);
}
public static void PrintQueue(object queue)
{
Queue<int> q = (Queue<int>)queue;
foreach (object i in q)
{
Console.WriteLine(i);
}
}
}
}
However, I want to make the PrintQueue static method working for all types, thus I've changed the method code as below;
public static void PrintQueue(object queue)
{
Queue<object> q = (Queue<object>)queue;
foreach (object i in q)
{
Console.WriteLine(i);
}
}
The whole test code which is not working is as below;
using System;
using System.Collections.Generic;
namespace Queue01
{
public class TestQueue
{
public static void Main(string[] args)
{
Queue<int> queue = new Queue<int>();
queue.Enqueue(4);
queue.Enqueue(5);
queue.Enqueue(6);
Console.WriteLine("*****");
PrintQueue(queue);
Console.WriteLine("*****");
int first = queue.Dequeue();
Console.WriteLine("Enqueued value : " + first);
Console.WriteLine("*****");
PrintQueue(queue);
}
public static void PrintQueue(object queue)
{
Queue<object> q = (Queue<object>)queue;
foreach (object i in q)
{
Console.WriteLine(i);
}
}
}
}
And then I'm stuck with the InvalidCastException. Where is the problem and how can I fix this exception and what is the best practice to make this code generic?
On java, Object is the base, root class of every class instance. Thus, I've passed the stack instance as an object to the method, assuming that it won't be a problem because int, the alias for Int32 also extended from the Object.
Here down below, I am adding the whole rest files that I've used for compiling the test code above;
1) Here is the DoublyLinkedListNode class that I used in Doubly Linked List implemetation;
using System;
using System.Collections.Generic;
namespace Queue01
{
public class DoublyLinkedListNode<T>
{
// Fields
public T Value { get; set; }
public DoublyLinkedListNode<T> Previous { get; set; }
public DoublyLinkedListNode<T> Next { get; set; }
public DoublyLinkedListNode(T value)
{
Value = value;
}
}
}
2) Here is my DoublyLinkedList class which implements a doubly linked list for the queue implementation I am going to use;
using System;
using System.Collections.Generic;
namespace Queue01
{
public class DoublyLinkedList<T> : ICollection<T>
{
#region Fields
public DoublyLinkedListNode<T> Head { get; private set; }
public DoublyLinkedListNode<T> Tail { get; private set; }
#endregion
#region Constructor
#endregion
#region Add
public void AddFirst(T value)
{
AddFirst(new DoublyLinkedListNode<T>(value));
}
public void AddFirst(DoublyLinkedListNode<T> node)
{
DoublyLinkedListNode<T> temp = Head;
Head = node;
Head.Next = temp;
//if(Count == 0)
if (Empty)
{
Tail = Head;
}
else
{
temp.Previous = Head;
}
Count++;
}
public void AddLast(T value)
{
AddLast(new DoublyLinkedListNode<T>(value));
}
public void AddLast(DoublyLinkedListNode<T> node)
{
//if (Count == 0)
if (Empty)
{
Head = node;
}
else
{
Tail.Next = node;
node.Previous = Tail;
}
Tail = node;
Count++;
}
#endregion
#region Remove
public void RemoveFirst()
{
//if (Count != 0)
if (!Empty)
{
Head = Head.Next;
Count--;
if (Count == 0)
{
Tail = null;
}
else
{
Head.Previous = null;
}
}
}
public void RemoveLast()
{
//if (Count != 0)
if (!Empty)
{
if (Count == 1)
{
Head = null;
Tail = null;
}
else
{
Tail.Previous.Next = null;
Tail = Tail.Previous;
}
Count--;
}
}
#endregion
#region ICollection
public int Count
{
get;
private set;
}
public void Add(T item)
{
AddFirst(item);
}
public bool Contains(T item)
{
DoublyLinkedListNode<T> current = Head;
while (current != null)
{
if (current.Value.Equals(item))
{
return true;
}
current = current.Next;
}
return false;
}
public void CopyTo(T[] array, int arrayIndex)
{
DoublyLinkedListNode<T> current = Head;
while (current != null)
{
array[arrayIndex++] = current.Value;
current = current.Next;
}
}
public bool IsReadOnly
{
get
{
return false;
}
}
public bool Remove(T item)
{
DoublyLinkedListNode<T> previous = null;
DoublyLinkedListNode<T> current = Head;
while (current != null)
{
if (current.Value.Equals(item))
{
if (previous != null)
{
previous.Next = current.Next;
if (current.Next == null)
{
Tail = previous;
}
else
{
current.Next.Previous = previous;
}
Count--;
}
else
{
RemoveFirst();
}
return true;
}
previous = current;
current = current.Next;
}
return false;
}
public void Clear()
{
Head = null;
Tail = null;
Count = 0;
}
//System.Collections.Generic.IEnumerator<T> System.Collections.Generic.IEnumerable<T>.GetEnumerator()
public IEnumerator<T> GetEnumerator()
{
DoublyLinkedListNode<T> current = Head;
while (current != null)
{
yield return current.Value;
current = current.Next;
}
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
//return ((System.Collections.Generic.IEnumerable<T>)this).GetEnumerator();
return this.GetEnumerator();
}
#endregion
#region helper
public void PrintEnumerable()
{
IEnumerator<T> e = this.GetEnumerator();
while (e.MoveNext())
{
T val = e.Current;
Console.WriteLine("Value: " + val);
}
}
public void PrintReverse()
{
for (DoublyLinkedListNode<T> node = Tail; node != null; node = node.Previous)
{
Console.WriteLine(node.Value);
}
}
public bool isEmpty()
{
if (Count == 0)
{
return true;
}
return false;
}
public bool Empty { get { return isEmpty(); } }
public DoublyLinkedListNode<T> First { get { return this.Head; } }
public DoublyLinkedListNode<T> Last { get { return this.Tail; } }
#endregion
}
}
3) And this is my Queue implementation based on doubly linked list implemetation that I've used above;
using System;
using System.Collections.Generic;
namespace Queue01
{
public class Queue<T> : System.Collections.Generic.IEnumerable<T>
{
DoublyLinkedList<T> _items = new DoublyLinkedList<T>();
LinkedList<T> hede = new LinkedList<T>();
public void Enqueue(T item)
{
_items.AddLast(item);
}
public T Dequeue()
{
if(_items.Count == 0)
{
throw new InvalidOperationException("The queue is empty.");
}
T value = _items.First.Value;
_items.RemoveFirst();
return value;
}
public IEnumerator<T> GetEnumerator()
{
return this._items.GetEnumerator();
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
}
}
Fundamentally, you shouldn't try to make PrintQueue work for every object - you should try to make it work for any Queue<T>... and the simplest way of doing that is to make it generic:
public static void PrintQueue<T>(Queue<T> queue)
{
foreach (T item in queue)
{
Console.WriteLine(item);
}
}
Or you could be more general and accept an IEnumerable<T>:
public static void PrintSequence<T>(IEnumerable<T> queue)
{
foreach (T item in queue)
{
Console.WriteLine(item);
}
}
Your original code is failing because a Queue<int> isn't a Queue<object>... in fact, because Queue<T> isn't covariant in T, you can't convert Queue<string> to Queue<object>... but IEnumerable<T> is covariant, so:
Queue<string> stringQueue = new Queue<string>();
...
PrintSequence<object>(stringQueue);
... would be okay.
What about change PrintQueue method. Just like this:
public static void PrintQueue<T>(object queue)
{
var q = (Queue<T>)queue;
foreach (var i in q)
Console.WriteLine(i);
}
and use it like this:
PrintQueue<int>(queue);
change your code like this:
public static void PrintQueue(dynamic queue)
{
foreach (var i in queue)
{
Console.WriteLine(i);
}
}

Error: cannot convert from 'lab3.MultiSet' to 'string[]'

MultiSet.cs and Form.cs
The best overloaded method match for 'string.Join(string, string[])' has some invalid arguments
Argument '2': cannot convert from 'lab3.MultiSet' to 'string[]'
namespace lab3
{
internal class MultiSet : IEnumerable<int>
{
public MultiSet()
{
}
public MultiSet(IEnumerable<int> elements)
{
if (elements == null)
throw new ArgumentNullException("elements");
foreach (int element in elements)
Add(element);
}
public MultiSet(params int[] elements)
: this((IEnumerable<int>)elements)
{
}
public IEnumerator<int> GetEnumerator()
{
return new Enumerator(this);
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public bool Add(int element)
{
if (_cardinal == _elements.Length)
{
int[] newElementsArray = new int[_elements.Length * 2];
_elements.CopyTo(newElementsArray, 0);
_elements = newElementsArray;
}
_elements[_cardinal] = element;
_cardinal++;
_lastModificationTime = DateTime.Now;
return true;
}
public int Count
{
get
{
return _cardinal;
}
}
public override string ToString()
{
return string.Format("{{ {0} }}", string.Join(", ", this));
}
private int _cardinal = 0;
private int[] _elements = new int[8];
private DateTime _lastModificationTime = DateTime.Now;
private sealed class Enumerator: IEnumerator<int>
{
public Enumerator(MultiSet set)
{
if (set == null)
throw new ArgumentNullException("set");
_set = set;
_setLastModificationTime = _set._lastModificationTime;
Reset();
}
public int Current
{
get
{
if (_index < 0 || _set._cardinal <= _index || _setLastModificationTime != _set._lastModificationTime)
throw new InvalidOperationException();
return _set._elements[_index];
}
}
void IDisposable.Dispose()
{
}
object IEnumerator.Current
{
get
{
return Current;
}
}
public bool MoveNext()
{
if (_setLastModificationTime != _set._lastModificationTime)
throw new InvalidOperationException();
_index++;
return (_index < _set.Count);
}
public void Reset()
{
_index = -1;
}
private int _index;
private readonly MultiSet _set;
private readonly DateTime _setLastModificationTime;
}
}
}
namespace lab3
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
_setElementNumericUpDown.Minimum = int.MinValue;
_setElementNumericUpDown.Maximum = int.MaxValue;
_currentSetTextBox.Text = _currentSet.ToString();
}
private void _addSetButton_Click(object sender, EventArgs e)
{
_setsListBox1.Items.Add(_currentSet);
_setsListBox2.Items.Add(_currentSet);
_currentSet = new MultiSet();
_currentSetTextBox.Text = _currentSet.ToString();
}
private void _addElementToSetButton_Click(object sender, EventArgs e)
{
_currentSet.Add((int)_setElementNumericUpDown.Value);
_currentSetTextBox.Text = _currentSet.ToString();
}
private MultiSet _currentSet = new MultiSet();
}
}
Since your class is an IEnumerable< int >, have you tried making a method that returns a string[] of the items in your list?
private string[] ToStringArray()
{
if (this.Count == 0)
return null;
int i = 0;
string[] items = new string[this.Count];
IEnumerator<int> enumerator = this.GetEnumerator();
while(enumerator.MoveNext())
{
items[i] = enumerator.Current.ToString();
i++;
}
// Reset your enumerator index if needed
enumerator.Reset();
return items;
}
Then your ToString() would look like this:
public override string ToString()
{
return string.Format("{{ {0} }}", string.Join(", ", ToStringArray()));
}

how do you calculate and return a total value in c#?

I'm, trying to add a method Takings which calculates and returns the total value of all the bookings for this show. If anyone could lead me in the right direction that would be great :)
namespace GCUShows
{
public class Show
{
private string title;
private Dictionary<int, Booking> bookings;
public string Title
{
get { return title; }
set { title = value; }
}
public Show(string title)
{
this.title = title;
this.bookings = new Dictionary<int, Booking>();
}
public void AddBooking(int bookingID, Booking booking)
{
this.bookings.Add(bookingID, booking);
}
public void RemoveBooking(int bookingID, Booking booking)
{
this.bookings.Remove(bookingID);
}
public Takings
{
}
}
namespace GCUShows
{
public enum TicketType
{
Adult,
Child,
Family
}
public class Booking : ITicket
{
private const int LIMIT = 6;
public Show show;
private int bookingID;
public List<ITicket> tickets;
public int BookingID
{
get { return bookingID; }
set { bookingID = value; }
}
public Booking(Show show)
{
this.BookingID = BookingIDSequence.Instance.NextID;
this.show = show;
show.AddBooking(this);
this.tickets = new List<ITicket>();
}
public void AddTickets(int number, TicketType type, decimal fee)
{
if (type == TicketType.Adult)
{
for(int i =0; i < number; i++)
{
tickets.Add(new AdultTicket(show.Title, fee));
}
}
else if (type == TicketType.Child)
{
for(int i=0; i< number; i++)
{
tickets.Add(new ChildTicket(show.Title));
}
}
else if (type == TicketType.Family)
{
for (int i = 0; i < number; i++)
{
tickets.Add(new FamilyTicket(show.Title, fee));
}
}
}
public string PrintTickets()
{
string ticketInfo = "Booking " + bookingID.ToString() + "\n";
foreach (ITicket ticket in tickets)
{
ticketInfo += ticket.Print();
}
return ticketInfo;
}
public decimal TotalCost()
{
decimal totalCost;
foreach (ITicket ticket in tickets)
{
totalCost += ticket.Fee;
}
return totalCost;
}
public override string ToString()
{
return string.Format("{0}: Total Cost={1:c}", bookingID, TotalCost());
}
}
}
Assuming Bookings contains a property int Val, it could look like:
public int Takes()
{
return bookings.Values.Sum(b => b.Val);
}
If Booking has a Cost property, you can do this:
var total = bookings.Sum(x => x.Value.Cost);
Alternatively to other Linq answer you can do the same thing with a foreach
public decimal Takings()
{
decimal runningTotal = 0;
foreach (KeyValuePair<int, Booking> kvp in bookings) {
runningTotal += kvp.Value.TotalCost();
}
return runningTotal;
}
which might look a little less "magic" if you are new to programming.
this is my bookings class
namespace GCUShows
{
public enum TicketType
{
Adult,
Child,
Family
}
public class Booking : ITicket
{
private const int LIMIT = 6;
public Show show;
private int bookingID;
public List<ITicket> tickets;
public int BookingID
{
get { return bookingID; }
set { bookingID = value; }
}
public Booking(Show show)
{
this.BookingID = BookingIDSequence.Instance.NextID;
this.show = show;
show.AddBooking(this);
this.tickets = new List<ITicket>();
}
public void AddTickets(int number, TicketType type, decimal fee)
{
if (type == TicketType.Adult)
{
for(int i =0; i < number; i++)
{
tickets.Add(new AdultTicket(show.Title, fee));
}
}
else if (type == TicketType.Child)
{
for(int i=0; i< number; i++)
{
tickets.Add(new ChildTicket(show.Title));
}
}
else if (type == TicketType.Family)
{
for (int i = 0; i < number; i++)
{
tickets.Add(new FamilyTicket(show.Title, fee));
}
}
}
public string PrintTickets()
{
string ticketInfo = "Booking " + bookingID.ToString() + "\n";
foreach (ITicket ticket in tickets)
{
ticketInfo += ticket.Print();
}
return ticketInfo;
}
public decimal TotalCost()
{
decimal totalCost;
foreach (ITicket ticket in tickets)
{
totalCost += ticket.Fee;
}
return totalCost;
}
public override string ToString()
{
return string.Format("{0}: Total Cost={1:c}", bookingID, TotalCost());
}
}
}

How to mock protected members with multiple interfaces

How to mock this class in nUnit Tests?
public class OpenDataQuery: PagedQuery, IOpenDataQuery
{
private static Dictionary<string, SortItem> m_sortModes;
protected override Dictionary<string, SortItem> SortModes
{
get
{
if (m_sortModes == null)
{
m_sortModes = new Dictionary<string, SortItem>();
AddSortMode(m_sortModes, new SortItem(ObjectExtensions.GetNameFromExpression<OpenDataCategoriesModel, string>(m => m.Name), "Наименование ↑", true) { IsDefault = true });
AddSortMode(m_sortModes, new SortItem(ObjectExtensions.GetNameFromExpression<OpenDataCategoriesModel, string>(m => m.Name), "Наименование ↓"));
}
return m_sortModes;
}
}
public IEnumerable<OpenDataCategoriesModel> OpenDataCategories { get; set; }
public string OpenDataTags { get; set; }
}
and
public abstract class PagedQuery : IPagedQuery
{
private const int DEFAULT_PAGE = 1;
private const int DEFAULT_COUNT = 5;
private int? m_page;
private int? m_count;
private int? m_total;
private string m_sort;
public int? Page
{
get
{
if (m_page == null || m_page <= 0)
{
return DEFAULT_PAGE;
}
return m_page;
}
set { m_page = value; }
}
public int? Count
{
get
{
if (m_count == null || m_count <= 0)
{
return DEFAULT_COUNT;
}
return m_count;
}
set { m_count = value; }
}
public int? Total
{
get
{
if (m_total == null || m_total <= 0)
{
return 0;
}
return m_total;
}
set { m_total = value; }
}
public string SearchQuery { get; set; }
protected virtual Dictionary<string, SortItem> SortModes
{
get { return null; }
}
public string Sort
{
get
{
var sortMode = GetSortMode(m_sort);
if (sortMode == null)
{
var defaultSort = (from i in SortModes where i.Value.IsDefault select i).FirstOrDefault();
if (!string.IsNullOrWhiteSpace(defaultSort.Key))
{
return defaultSort.Key;
}
return (from i in SortModes select i.Key).First();
}
return m_sort;
}
set
{
m_sort = value;
}
}
protected void AddSortMode(Dictionary<string, SortItem> sortModes, SortItem sortItem)
{
sortModes.Add(
String.Format(
"{0}{1}",
sortItem.FieldName.ToLower(),
sortItem.Asc ? "asc" : "desc"
),
sortItem
);
}
private SortItem GetSortMode(string sort)
{
if (SortModes == null || string.IsNullOrWhiteSpace(sort) ||
!SortModes.ContainsKey(sort.ToLower()))
{
return null;
}
return SortModes[sort.ToLower()];
}
public IOrderBy GetOrderBy()
{
var item = GetCurrentSortItem();
if (item == null)
{
return null;
}
if (item.Asc)
{
return new OrderBy(item.FieldName);
}
return new OrderByDesc(item.FieldName);
}
public SortItem GetCurrentSortItem()
{
return GetSortMode(Sort);
}
public Dictionary<string, SortItem> GetSortItems()
{
return SortModes;
}
}
and
public interface IOpenDataQuery : IPagedQuery
{
string OpenDataTags { get; set; }
}
I have some service method, that used openDataQuery class in parameters and in unit test i am trying mock this class, but this doesn't work:
public partial class OpenDataQueryRepository : Mock<OpenDataQuery>
{
public OpenDataQueryRepository(MockBehavior mockBehavior = MockBehavior.Strict)
: base(mockBehavior)
{
var opendataQuery = new Mock<IOpenDataQuery>();
var pagedQuery = opendataQuery.As<IPagedQuery>();
this.Setup(p=>p.GetOpenDataCategoriesMain(pagedQuery.Object,outttl)).Returns(OpenDataCategories);
}
}
I know that i should use Moq.Protected() for protected methods, but i don't know how use it correctly in this case. Please help me.
UPDATE:
I am testing this controller:
public class ODOpenDataController : ODBaseController
{
private readonly IOpenDataProvider m_openDataProvider;
public ODOpenDataController(IOpenDataProvider openDataProvider)
{
m_openDataProvider = openDataProvider;
}
public ActionResult Index(OpenDataQuery query)
{
int total;
query.OpenDataCategories = m_openDataProvider.GetOpenDataCategoriesMain(query, out total)
query.Total = total;
return View(query);
}
}
Test:
[Test]
public void Index_Test()
{
var opendataController = new ODOpenDataController(new OpenDataRepository().Object);
var result = opendataController.Index(new OpenDataQuery()) as ViewResult;
var model = result.Model as OpenDataQuery;
Assert.IsTrue(model.OpenDataCategories.Count() == 1);
}

Categories

Resources