I'm creating a partial mock to test a protected helper method of a base class. I'm not too interested in the debate on whether or not the protected method should be there or if it should be an injected dependency because I'm really interested in seeing the process below work.
EnumerationServiceBase_Accessor is the VSTS 2010 generated private access object. Everything below works well except for the fact that line 17 does not effectively set up an expectation that intercepts the call to CreateNewContextResponse(request), which is the protected method that is being called by partialTarget.EnumerateOp(request) during playback. Instead the actual implementation on the base class is being called. What am I doing wrong here?
1 PrivateObject p = new PrivateObject(mocks.PartialMock<EnumerationServiceBase>(contextManager, requestValidator, configProvider, faultProvider, logger));
2 EnumerationServiceBase_Accessor partialTarget = mocks.PartialMock<EnumerationServiceBase_Accessor>(p);
3
4 EnumerateOpRequest request = new EnumerateOpRequest()
5 {
6 Enumerate = new Enumerate()
7 {
8 Item = new EnumerateNewContext()
9 }
10 };
11
12 using (mocks.Record())
13 {
14 requestValidator.Expect(r => r.ValidateEndTo(request));
15 requestValidator.Expect(r => r.ValidateMaxElements(request, allowNulls: true));
16 partialTarget.Expect(t => t.EnumerateOp(request)).CallOriginalMethod(OriginalCallOptions.CreateExpectation);
17 partialTarget.Expect(t => t.CreateNewContextResponse(request)).Return(null);
18 contextManager.Expect(t => t.RemoveExpiredContexts());
19 }
20
21 using (mocks.Playback())
22 {
23 partialTarget.EnumerateOp(request);
24 }
And this is EnumerateOp(request) as implemented in the EnumerationServiceBase.cs
1 public virtual EnumerateOpResponse EnumerateOp(EnumerateOpRequest request)
2 {
3 EnumerateOpResponse response = null;
4
5 if (request.Enumerate.Item is EnumerateNewContext)
6 {
7 try
8 {
9 _contextManager.RemoveExpiredContexts();
10 }
11 catch (Exception ex)
12 {
13 _logger.Warn("We're not cleaning up contexts effectively.", ex);
14 }
15
16 _requestValidator.ValidateEndTo(request);
17 _requestValidator.ValidateMaxElements(request, allowNulls: true);
18 response = CreateNewContextResponse(request);
19 }
20 else if (request.Enumerate.Item is EnumerationContextType)
21 {
22 _requestValidator.ValidateMaxElements(request, allowNulls: false);
23 response = CreateEnumerationContextResponse(request);
24 }
25 else
26 {
27 throw _faultProvider.GetItemNotRecognizedFault("The Enumerate.Item value was not of type EnumerateNewContext or EnumerationContextType.");
28 }
29 return response;
30 }
EDIT: Removed unnecessary info.
The problem is that your CreateNewContextResponse is protected and You can't mock protected methods with Rhino Mocks.
Related
Please consider this scenario:
For some math calculations I should find a number in specific place in a sorted list. For example consider this list:
1 - 2 - 3 - ... 17 - 18 - 19 - 20
I should to find number placed in 25% of count (count / 4). In above series I should get 5. It is worth noting that we haven't round count number but it's not a problem.
Now consider this table:
Type Number
----------------------
1 10
1 11
1 12
1 13
2 22
2 23
2 24
2 25
2 26
2 27
2 28
3 39
3 38
3 37
3 36
3 35
3 34
3 33
3 32
4 41
4 43
4 42
4 44
4 45
4 47
4 46
4 48
4 49
4 50
4 51
Another point is I'm sure that in every Type I have at least 1000
numbers, so above data in just for example.
according to above data I want to get this result:
Type Number
----------------------
1 11
2 23
3 33
4 43
One way to achieve this result is to loop throw distinct Type and get list of number and then sort it and then calculate count of that list and divide it by 4, then round the result and get specific Number with the index has been gotten.
But the problem with this approach is it needs many connection to database (1 for each Type). Is there any better solution to get desired result with 1 connection and 1 query execution. thanks
Interesting puzzle. In Sql Server you could use something like the following query;
select a.*
from (
select *, row_number() over(partition by type order by number) as row_number
from table_name
) a
join (
select type, count(*) as count
from table_name
group by type
) b on a.type = b.type
where a.row_number = b.count/4
(With whatever rounding you want for when count%4 != 0)
But I can't think how you would build that as a linq expression.
var percent = 0.25;
var val = res.GroupBy(x => x.type)
.ToDictionary(x => x.Key, x => x.OrderBy(y=>y).ToList());
var valuesTobeTaken = val.Select(x => new
{
x.Key,
index = ((int)Math.Round(x.Value.Count * percent))-1
});
Edge cases are not handled and the code is not too much optimized. You can work on that i guess
foreach (var rec in valuesTobeTaken)
{
Console.WriteLine(val[rec.Key][rec.index]);
}
I have been stuck on this problem now for 8 weeks and I think that I almost have a solution however the last bit of math is racking my mind. I will try to explain a simple problem that requires a complex solution. I am programing in C#.net MVC Web Project. Here is the situation.
I have an unknown group of quantities incoming to look for like items. Those like items share a max level to make it a full box. Here is an example of this:
Revision******
This is the real world case
I have many, let say candy, orders coming in to a company.
Qty Item MaxFill Sold-To DeliverNumber
60 candy#14 26 Joe 1
1 candy#12 48 Jim 2
30 candy#11 48 Jo 3
60 candy#15 48 Tom 4
6 candy#8 48 Kat 5
30 candy#61 48 Kim 6
44 candy#12 48 Jan 7
10 candy#12 48 Yai 8
10 candy#91 48 Jun 9
55 candy#14 26 Qin 10
30 candy#14 26 Yo 11
40 candy#14 26 Moe 12
in this list I am looking for like candy items to combine to make all the full boxes of candy that I can based off the MaxFill number. Here we see the like items are:
Qty Item MaxFill Sold-To DeliverNumber
60 candy#14 26 Joe 1
55 candy#14 26 Qin 10
30 candy#14 26 Yo 11
40 candy#14 26 Moe 12
1 candy#12 48 Jim 2
44 candy#12 48 Jan 7
10 candy#12 48 Yai 8
Now lets take the first set of numbers for candy#14.
I know that the total of candy#14 is 185 and I can get 7 full boxes of 26 with one box having only 3 in the last box. So how do I do this with the values that I have without losing the information of the original order. So this is how I am working it out right now
See below
End of Revision******
Like candy#14 max fill level is 26.
Like candy#14 quantities:
60
55
30
40
Now I already have a recursive function to break these down to the 26 level and is working fine. I feel that I need another recursive function to deal with the remainders that come out of this. As you can see most of the time there will be remainders from any given list but those remainders could total up to another full box of 26.
60 = 26+26+8
55 = 26+26+3
30 = 26+4
40 = 26+14
The 8,3,4,14 = 29 so I can get another 26 out of this. But in the real unknown world I could have the remainders come up with a new set of remainders that could repeat the same situation. To make this even more complicated I have to save the data that is originality with the 60,55,30,40 that is carried with it such as who it was sold to and delivery number. This will also be helpful with knowing how the original amount was broken down and combined together.
from the 8,3,4,14 the best way that I was think to add to that value is to take the 8,4,14 this will give me the 26 that I am looking for and I would not have to split any value because 3 is the remainder and I could save all other data without issue. However this just works in this situation only. If I go in a linear motion 8+3+4=15 so I would have to take 11 from the next value 14 with a remainder of 3.
In reading about different algorithms I was thinking that this might fall into the NP,NP-Complete,NP-Hard category. But with all the situations it is very technical and not a lot of real world scenarios are to be found.
Any suggestions would help here if I should go through the list of number to find the best combinations to reach the 26 or if the linear progression and splitting of the next value is the best solution. I know that I can solve to get how many full boxes I could get from the remainders and what the left over amount would be such as 8+3+4+14=29 which would give me 1, 26 and 1, 3 but I have no idea about the math in a recursive way to solve this. I have this much done and I "feel" that this is on the right track but can't see how to adjust to make this work with the linear or "test every possible combination".
public static void Main(string[] args)
{
var numbers = new List<int>() { 8, 3, 4, 14 };
var target = 26;
sum_up(numbers, target);
}
private static void sum_up(List<int> numbers, int target)
{
sum_up_recursive(numbers, target, new List<int>());
}
private static void sum_up_recursive(List<int> numbers, int target, List<int> partial)
{
int s = 0;
foreach (int x in partial) s += x;
if (s == target)
{
var outputtext = "sum(" + string.Join(",", partial.ToArray()) + ")=" + target;
}
if (s >= target)
return;
for (int i = 0; i < numbers.Count; i++)
{
List<int> remaining = new List<int>();
int n = numbers[i];
for (int j = i + 1; j < numbers.Count; j++) remaining.Add(numbers[j]);
List<int> partial_rec = new List<int>(partial);
partial_rec.Add(n);
sum_up_recursive(remaining, target, partial_rec);
}
}
I wrote sample project in javascript.
Please check my repo.
https://github.com/panghea/packaging_sample
Title may not explain fully what I want to do, so I made an image.
You can see there are 4 1D arrays(red numbers, black colored numbers are indexes), each of this array goes from 0 to 63. I want to somehow translate them, that for example, index 16 will point to first index of second array.
What I was thinking of, is a function where I give List of arrays and index that I want to get as input, and its returns me the index of array and exact index in this array as output.
I would like to have some hints or suggestions on how to proceed here to achieve this functionality.
Ok, your image shows an interleaved data of 16 elements, so you want to have (showing an example of only two matrices because of space :D)
Global index
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
-----------------------------------------------------------------------------------------------------
Array0 indexes - Array1 indexes
0 1 2 3 4 5 6 7 8 9 A B C D E F - 0 1 2 3 4 5 6 7 8 9 A B C D E F
-------------------------------------------------------------------------------------------------
Global index
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
-----------------------------------------------------------------------------------------------------
Array0 indexes - Array1 indexes
10 11 12 13 14 15 16 17 18 19 1A 1B 1C 1D 1E 1F - 10 11 12 13 14 15 16 17 18 19 1A 1B 1C 1D 1E 1F
To get it you can do something like this:
public class CompositeIndex
{
public int ArrayNumber { get; set; }
public int ElementNumber { get; set; }
}
public static CompositeIndex GetIndex(int GlobalIndex, int ArrayCount, int ElementsToInterleave)
{
CompositeIndex index = new CompositeIndex();
int fullArrays = GlobalIndex / ElementsToInterleave; //In your example: 16 / 16 = 1;
index.ArrayNumber = fullArrays % ArrayCount; //In your example: 1 mod 4 = 1;
index.ElementNumber = GlobalIndex - (fullArrays * ElementsToInterleave); //In your example: 16 - (1 * 16) = 0;
return index;
}
Then, if you have 4 matrices and want to get the "global" index 16 you do:
var index = GetIndex(16, 4, 16);
This function allows you to use an indeterminated number of arrays and interleaved elements.
BTW, another time ask better your question, a lot more people will help you if they don't have to solve a puzzles to understand what you want...
My scenario:
I need to process a list of elements. Each element processing is highly time consuming (1-10 seconds)
Instead of a
List retval = new List();
foreach (item in myList)
retval.Add(ProcessItem(item));
return retval;
I want to parallel process each item.
I know .NET has got a number of approach for parallel processing: what is the best one? (note, I'm stuck to 3.5 framework version, cannot use Task, async and all nancy features coming with .Net 4...)
Here my try using delegates:
private void DoTest(int processingTaskDuration)
{
List<int> itemsToProcess = new List<int>();
for (int i = 1; i <= 20; i++)
itemsToProcess.Add(i);
TestClass tc = new TestClass(processingTaskDuration);
DateTime start = DateTime.Now;
List<int> result = tc.ProcessList(itemsToProcess);
TimeSpan elapsed = DateTime.Now - start;
System.Diagnostics.Debug.WriteLine(string.Format("elapsed (msec)= {0}", (int)elapsed.TotalMilliseconds));
}
public class TestClass
{
static int s_Counter = 0;
static object s_lockObject = new Object();
int m_TaskMsecDuration = 0;
public TestClass() :
this(5000)
{
}
public TestClass(int taskMsecDuration)
{
m_TaskMsecDuration = taskMsecDuration;
}
public int LongOperation(int itemToProcess)
{
int currentCounter = 0;
lock (s_lockObject)
{
s_Counter++;
currentCounter = s_Counter;
}
System.Diagnostics.Debug.WriteLine(string.Format("LongOperation\tStart\t{0}\t{1}\t{2}", currentCounter, System.Threading.Thread.CurrentThread.ManagedThreadId, DateTime.Now.ToString("HH:mm:ss.ffffff")));
// time consuming task, e.g 5 seconds
Thread.Sleep(m_TaskMsecDuration);
int retval = itemToProcess * 2;
System.Diagnostics.Debug.WriteLine(string.Format("LongOperation\tEnd \t{0}\t{1}\t{2}", currentCounter, System.Threading.Thread.CurrentThread.ManagedThreadId, DateTime.Now.ToString("HH:mm:ss.ffffff")));
return retval;
}
delegate int LongOperationDelegate(int itemToProcess);
public List<int> ProcessList(List<int> itemsToProcess)
{
List<IAsyncResult> asyncResults = new List<IAsyncResult>();
LongOperationDelegate del = LongOperation;
foreach (int item in itemsToProcess)
{
IAsyncResult res = del.BeginInvoke(item, null, null);
asyncResults.Add(res);
}
// list of waitHandles to wait for
List<WaitHandle> waitHandles = new List<WaitHandle>();
asyncResults.ForEach(el => waitHandles.Add(el.AsyncWaitHandle));
// wait for processing every item
WaitHandle.WaitAll(waitHandles.ToArray());
// retrieve result of processing
List<int> retval = new List<int>();
asyncResults.ForEach(res =>
{
int singleProcessingResult = del.EndInvoke(res);
retval.Add(singleProcessingResult);
}
);
return retval;
}
}
And thats some output (column #3 is a progressive counter, use it to match start with end of a call, #4 is threadID and last is a timeStamp)
LongOperation Start 1 6 15:11:18.331619
LongOperation Start 2 12 15:11:18.331619
LongOperation Start 3 13 15:11:19.363722
LongOperation Start 4 14 15:11:19.895775
LongOperation Start 5 15 15:11:20.406826
LongOperation Start 6 16 15:11:21.407926
LongOperation Start 7 17 15:11:22.410026
LongOperation End 1 6 15:11:23.360121
LongOperation End 2 12 15:11:23.361122
LongOperation Start 8 12 15:11:23.363122
LongOperation Start 9 6 15:11:23.365122
LongOperation Start 10 18 15:11:23.907176
LongOperation End 3 13 15:11:24.365222
LongOperation Start 11 13 15:11:24.366222
LongOperation End 4 14 15:11:24.897275
LongOperation Start 12 14 15:11:24.898275
LongOperation Start 13 19 15:11:25.407326
LongOperation End 5 15 15:11:25.408326
LongOperation Start 14 15 15:11:25.412327
LongOperation Start 15 20 15:11:26.407426
LongOperation End 6 16 15:11:26.410426
LongOperation Start 16 16 15:11:26.410426
LongOperation Start 17 21 15:11:27.408526
LongOperation End 7 17 15:11:27.411527
LongOperation Start 18 17 15:11:27.413527
LongOperation End 8 12 15:11:28.365622
LongOperation Start 19 12 15:11:28.366622
LongOperation End 9 6 15:11:28.366622
LongOperation Start 20 6 15:11:28.389624
LongOperation End 10 18 15:11:28.908676
LongOperation End 11 13 15:11:29.367722
LongOperation End 12 14 15:11:29.899775
LongOperation End 13 19 15:11:30.411827
LongOperation End 14 15 15:11:30.413827
LongOperation End 15 20 15:11:31.407926
LongOperation End 16 16 15:11:31.411927
LongOperation End 17 21 15:11:32.413027
LongOperation End 18 17 15:11:32.416027
LongOperation End 19 12 15:11:33.389124
LongOperation End 20 6 15:11:33.391124
elapsed (msec)= 15075
So:
Is Delegate approach the right one?
Did I implement it right?
If so, why the 3rd operations starts one second after the first two (and so on)?
I mean, I'd like the whole processing complete in more or less the time of one single processing, but it seems the system uses thread pool in a strange way. After all, I'm asking 20 threads, and it waits to span the 3rd one just after the first two calls.
I think the 3.5 backport of Reactive Extensions comes with an implementation of Parallel.ForEach() that you should be able to use. The port should just contain only what was needed to get Rx to work on 3.5, but that should be enough.
Others have tried implementing it as well, basically just queuing work items on ThreadPool.
void Main()
{
var list = new List<int>{ 1,2,3 };
var processes = list.Count();
foreach (var item in list)
{
ThreadPool.QueueUserWorkItem(s => {
ProcessItem(item);
processes--;
});
}
while (processes > 0) { Thread.Sleep(10); }
}
static void ProcessItem(int item)
{
Thread.Sleep(100); // do work
}
I got rid of my third question:
If so, why the 3rd operations starts one second after the first two
(and so on)?
The problem seems to be in the default way ThreadPool manages thread spawning: see http://msdn.microsoft.com/en-us/library/0ka9477y%28v=VS.90%29.aspx. Quote:
The thread pool has a built-in delay (half a second in the .NET
Framework version 2.0) before starting new idle threads. If your
application periodically starts many tasks in a short time, a small
increase in the number of idle threads can produce a significant
increase in throughput. Setting the number of idle threads too high
consumes system resources needlessly.
It seems a call to ThreadPool.SetMinThreads with a proper value helps a lot.
At the start of my ProcessList, I inserted a call to this method:
private void SetUpThreadPool(int numThreadDesired)
{
int currentWorkerThreads;
int currentCompletionPortThreads;
ThreadPool.GetMinThreads(out currentWorkerThreads, out currentCompletionPortThreads);
//System.Diagnostics.Debug.WriteLine(string.Format("ThreadPool.GetMinThreads: workerThreads = {0}, completionPortThreads = {1}", workerThreads, completionPortThreads));
const int MAXIMUM_VALUE_FOR_SET_MIN_THREAD_PARAM = 20;
int numMinThreadToSet = Math.Min(numThreadDesired, MAXIMUM_VALUE_FOR_SET_MIN_THREAD_PARAM);
if (currentWorkerThreads < numMinThreadToSet)
ThreadPool.SetMinThreads(numThreadDesired, currentCompletionPortThreads);
}
public List<int> ProcessList(List<int> itemsToProcess)
{
SetUpThreadPool(documentNumberList.Count);
...
}
Now all thread (up to 20) start at the same moment, without delay. I think 20 is a good compromise for MAXIMUM_VALUE_FOR_SET_MIN_THREAD_PARAM: not too hight, and fits my particular requirements
Still wondering about main questions
Is Delegate approach the right one?
Did I implement it right?
Thanks to everyone helping.
Microsoft gives this as an Bubble sort example for learning generics. It makes sense until I get to lines 76 and 77. How are those declarations possible? Node is a class. Don't you have to instantiate it with new?
How would you optimize the sort? Which is part is generic and which is non-generic?
1 public class GenericList<T> : System.Collections.Generic.IEnumerable<T>
2 {
3 protected Node head;
4 protected Node current = null;
5
6 // Nested class is also generic on T
7 protected class Node
8 {
9 public Node next;
10 private T data; //T as private member datatype
11
12 public Node(T t) //T used in non-generic constructor
13 {
14 next = null;
15 data = t;
16 }
17
18 public Node Next
19 {
20 get { return next; }
21 set { next = value; }
22 }
23
24 public T Data //T as return type of property
25 {
26 get { return data; }
27 set { data = value; }
28 }
29 }
30
31 public GenericList() //constructor
32 {
33 head = null;
34 }
35
36 public void AddHead(T t) //T as method parameter type
37 {
38 Node n = new Node(t);
39 n.Next = head;
40 head = n;
41 }
42
43 // Implementation of the iterator
44 public System.Collections.Generic.IEnumerator<T> GetEnumerator()
45 {
46 Node current = head;
47 while (current != null)
48 {
49 yield return current.Data;
50 current = current.Next;
51
52 }
53 }
54
55 System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
56 {
57 return GetEnumerator();
58 }
59 }
60
61 public class SortedList<T> : GenericList<T> where T : System.IComparable<T>
62 {
63 // A simple, unoptimized sort algorithm that
64 // orders list elements from lowest to highest:
65
66 public void BubbleSort()
67 {
68 if (null == head || null == head.Next)
69 {
70 return;
71 }
72 bool swapped;
73
74 do
75 {
76 Node previous = null;
77 Node current = head;
78
79
80 //Console.WriteLine(previous.GetType());
81 //Console.ReadLine();
82
83 swapped = false;
84
85
86 //Debug.WriteLine(p);
87 //Debug.WriteLine("Testing " + current.ToString());
88
89 while (current.next != null)
90 {
91 // Because we need to call this method, the SortedList
92 // class is constrained on IEnumerable<T>
93 if (current.Data.CompareTo(current.next.Data) > 0)
94 {
95 Node tmp = current.next;
96 current.next = current.next.next;
97 tmp.next = current;
98
99 if (previous == null)
100 {
101 head = tmp;
102 }
103 else
104 {
105 previous.next = tmp;
106 }
107 previous = tmp;
108 swapped = true;
109 }
110 else
111 {
112 previous = current;
113 current = current.next;
114 }
115 }
116 } while (swapped);
117 }
118 }
A class type in C# can be initialized with null or a value which is of a compatible type with the declaration. Lines 76 and 77 look like so
Node previous = null;
Node current = head;
Here the value null is legal. It essentially says "I have no value". The assignment to head is also legal because head is also of type Node. The result is the two references head and current refer to the same Node object value. Modifying the Node instance through one of the references will be visible to the other.
You're assigning previous and next to null and head respectively. It's an assignment operation, just like any other. You don't need to use new unless you're actually creating a new instance of the object.
The generic parts are anything that refers to T. It's a generic type that is supplied when the class is instanciated. A good example is List<T>, which creates a list of objects of type T. You could instance this as List<string> for a list of strings, List<int> for a list of ints, etc.
These are references that could be pointing to instances of a class or can be just null.
You can assign references to other references:
Foo f1 = new Foo();
Foo f2 = f1;
Foo f3 = null;
No objects are being instantiated on lines 76 and 77 in that code. As you said, Node is a class. Classes in .NET are always reference types which means that:
The value of a variable of a reference type is a reference to an object (or nothing).
Variables of a reference type can be assigned the value null, which means that the variable references nothing.
Assigning one variable of a reference type to another variable of a reference type copies the reference, not the object.