UnitTesting with Moles for tightly coupled 3rd party DLL - moles

I'm new to PEX and Moles just wondering how to UnitTest with moles something like below.
I just need a UniDynArray to test. But Creating a UniDynArray depends on the UniSession and UniSession Depends on UniObjects.OpenConnection. When i run this code i get error from ThirdParty dll saying sessions aren't open
Please help
[TestMethod, HostType("Moles")]
public void Constructor2WithMoles()
{
using (MolesContext.Create())
{
//Should I make the Third party session like this ???
MUniSession msession = new MUniSession();
//Here What Actually Happens in the code is uniObject opensession return session
// UniSession session = UniObjects.OpenSession(a,b,c,d); How should i do this
//???? MUniObjects.OpenSessionStringStringStringString = (a, b, c, d) => msession;
MUniDynArray mdata = new MUniDynArray();
mdata.InsertInt32Int32String = (column, index, strValue) =>
{
column = 1;
index = 1;
strValue = "Personal Auto";
};
mdata.InsertInt32Int32String = (column, index, strValue) =>
{
column = 2;
index = 1;
strValue = "1.1";
};
mdata.InsertInt32Int32String = (column, index, strValue) =>
{
column = 3;
index = 1;
strValue = "05/05/2005";
};
mdata.InsertInt32Int32String = (column, index, strValue) =>
{
column = 4;
index = 1;
strValue = "Some Description";
};
mdata.InsertInt32Int32String = (column, index, strValue) =>
{
column = 5;
index = 1;
strValue = "20";
};
mdata.InsertInt32Int32String = (column, index, strValue) =>
{
column = 6;
index = 1;
strValue = "1";
};
History target = new History(mdata, 1);
Assert.AreEqual<string>("Some Description", target.Description);
}
// TODO: CREATE Mole asserts
}

First, I strongly recommend waiting to use Fakes Stub and Shim types, in .NET 4.5 and Visual Studio 2012 (releasing 12 SEP 2012). Fakes is the productized version of Moles. To start using Fakes, download the free Ultimate version of VS2012 Release Candidate.
To answer your question, you should isolate your 3rd party dependency, using the Dependency Injection design pattern. Many users of Shim/Mole types overlook implementing the Dependency Injection pattern -- use Shim/Mole types, only when no other options remain. I assume the 3rd party library exposes interfaces. Fakes/Moles automatically converts interfaces to Stub types that can be used for tests. You'll need to create concrete stubs from the interfaces, for the production code to use. These stubs are simply a wrapper for the targeted 3rd party library type. Look up any article on Dependency Injection, for details on how to implement the pattern -- this pattern is quick and easy to implement, especially when using a refactoring tool, such as Resharper or Refactor!Pro.
Stub type method calls are detoured, using the same lambda/delegate syntax as Shim/Mole types. Stub types are good for generating stubs unique to a single or small number of tests. Otherwise, creating a concrete test stub for use in several tests is the best option.

Related

Check if values are those same objects

I'm pretty new to Dart and I got some problems with understanding what is going on under the hood. I've simple code like this:
void main() {
String s1 = "test1";
StringBuffer sb = StringBuffer();
sb.write("test");
sb.write("1");
String s2 = sb.toString();
print(identical(s1, s2));
print(s1 == s2);
int a = 1;
int b = 1;
print(identical(a, b));
}
result of this code is 3x true
Which is little tricky for me. As I understands all variables refers to some values, and since == operator is expected to return true, I'm little confused why identical also return true. If I would use code like:
String s1 = "test1";
String s2 = "test1";
Then I would expect that there is compiler optimization for immutable strings. But since I combine it via StringBuffer I would expect that I got two different values in memory. I suspect that identical uses == operator internally... Why I'm curious: I'm working on app which will use sets of tags. And I'm not sure If should I create some pool of strings and checks if some strings are already created and reuse it or just spawn strings and Dart has it's own string pool?

Concatenate multiple PDF/A with different conformance levels

Is it possible to concatenate a number of pdf/a (with possibly different conformance levels: some pdf/a-1b, some pdf/a-3b ecc) into a single pdfa ?
I was thinking that using the latest level (3-a or 3b) would be ok but I get errors when validating with VeraPDF:
Here is my code (where :
public static byte[] CreateConformantCopy(List<byte[]> sourcePdfs)
{
var version = PdfVersion.PDF_1_7;
var type = PdfAType.PDF_A_3B;
WriterProperties wp = new WriterProperties();
wp.UseSmartMode();
wp.SetPdfVersion(version.ToPdfVersion());
PdfOutputIntent oi = new PdfOutputIntent("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1", Assembly.GetExecutingAssembly().GetManifestResourceStream("xxx.Resources.sRGB_CS_profile.icm"));
using (var mergedPdf = new MemoryStream())
{
var writer = new PdfWriter(mergedPdf, wp);
using (PdfADocument newDoc = new PdfADocument(writer, type.ToPdfAConformanceLevel(), oi, new DocumentProperties() { }))
{
Document document = new Document(newDoc, PageSize.A4.Rotate());
newDoc.SetTagged();
newDoc.GetCatalog().SetLang(new PdfString(Thread.CurrentThread.CurrentUICulture.Name));
newDoc.GetCatalog().SetViewerPreferences(
new PdfViewerPreferences()
.SetDisplayDocTitle(true)
.SetCenterWindow(true)
);
PdfMerger merger = new PdfMerger(newDoc);
for (int k = 0; k < sourcePdfs.Count; k++)
{
using (var inDoc = PdfHelper.GetDocument(sourcePdfs[k]))
{
var numberOfPages = inDoc.GetNumberOfPages();
merger.Merge(inDoc, 1, numberOfPages);
}
}
newDoc.Close();
}
return mergedPdf.ToArray();
}
}
PDF/A-1 and PDF/A-2 have several differences in the requirements. So, merging them together might not be possible. Looking on your validation errors, I think this is exactly the case. For example, the very first one is about XMP metadata. The PDF/A-2 is more strict here, and you get this error because your first file (which is probably a valid PDF/A-1) does not actually satisfy the PDF/A-2 rules.
What is possible however is to attach a PDF/A-1 document to PDF/A-2 one. This does not even require the use of PDF/A-3, which allows arbitrary attachments. The PDF/A-2 standard does allow attaching valid PDF/A-1 (as well as PDF/A-2 documents).

How to populate table with specific values instead of pseudo-random?

i'm trying to modify the vaadin addressbook app to a little different one with just the field names changed. but i do not know how to populate it with specific value instead of the pseudo-random as done in the vaadin tutorial example.
here is my code.
private static IndexedContainer createDummyDatasource() {
IndexedContainer ic = new IndexedContainer();
for (String p : fieldNames) {
ic.addContainerProperty(p, String.class, "");
}
String[] cnumber = { "1", "2", "3" };
String[] ctitle = { "a", "b", "c" };
String[] faculty = { "xxx" };
for (int i = 0; i < 3; i++) {
Object id = ic.addItem();
ic.getContainerProperty(id, CNUMBER).setValue(cnumber[(int) (cnumber.length * Math.random())]);
ic.getContainerProperty(id, CTITLE).setValue(ctitle[(int) (ctitle.length * Math.random())]);
ic.getContainerProperty(id, FACULTY).setValue(faculty[(int) (faculty.length * Math.random())]);
}
return ic;
}
please help..!!
You use the setValue to set the values shown in table. And also make sure the corresponding container property is set before populating them.
If you just want to know how to bind the address book demo to an MySQL database using SQLContainer, then you can have a look at https://vaadin.com/tutorial/sql which pretty much continues where the in-memory container left you.
Of course if you have some other binding to your data JPA, in-memory beans etc, you might want to have a look at the appropriate one for your needs.

Referencing other documents' content

We need to create a matrix from 2 other documents' contents. For example:
doc has fields like:
4.2 Requirements A
Blah
doc has fields like:
2.1 Analysis A
Blah Blah
and we want to create another document (called Traceability Matrix) which is like:
Col1 Col2 Col3
4.2 2.1 Blah Blah Blah
4.2 and 2.1 should be dynamically updated in doc3.
We checked using hyperlink, cross referencing but nothing seems to be useful for combining different documents. Is there anyway to do this?
EDIT:
Here is an example:
Technical Specification Num Requirement Num Requirement
4.2 2.1 A sentence that explains the relationship btw 2 cols: Technical Specification and Requirement Num
I have now created a working example of how this can be implemented using MS Word Interop and C#.
The code contains comments that should explain the most interesting parts.
The sample is implemented as a C# console application using:
.NET 4.5
Microsoft Office Object Library version 15.0, and
Microsoft Word Object Library version 15.0
... that is, the MS Word Interop API that ships with MS Office 2013 Preview.
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Office.Interop.Word;
using Application = Microsoft.Office.Interop.Word.Application;
namespace WordDocStats
{
internal class Program
{
private static void Main()
{
// Open word
var wordApplication = new Application() { Visible = true };
// Open document A, get its headings, and close it again
var documentA = wordApplication.Documents.Open(#"C:\Users\MyUserName\Documents\documentA.docx", Visible: true);
var headingsA = GetHeadingsInDocument(documentA);
documentA.Close();
// Same procedure for document B
var documentB = wordApplication.Documents.Open(#"C:\Users\MyUserName\Documents\documentB.docx", Visible: true);
var headingsB = GetHeadingsInDocument(documentB);
documentB.Close();
// Open the target document (document C)
var documentC = wordApplication.Documents.Open(#"C:\Users\MyUserName\Documents\documentC.docx", Visible: true);
// Add a table to it (the traceability matrix)
// The number of rows is the number of headings + one row reserved for a table header
documentC.Tables.Add(documentC.Range(0, 0), headingsA.Count+1, 3);
// Get the traceability matrix
var traceabilityMatrix = documentC.Tables[1];
// Add a table header and border
AddTableHeaderAndBorder(traceabilityMatrix, "Headings from document A", "Headings from document B", "My Description");
// Insert headings from doc A and doc B into doc C's traceability matrix
for (var i = 0; i < headingsA.Count; i++)
{
// Insert headings from doc A
var insertRangeColOne = traceabilityMatrix.Cell(i + 2, 1).Range;
insertRangeColOne.Text = headingsA[i].Trim();
// Insert headings from doc B
var insertRangeColTwo = traceabilityMatrix.Cell(i + 2, 2).Range;
insertRangeColTwo.Text = headingsB[i].Trim();
}
documentC.Save();
documentC.Close();
wordApplication.Quit();
}
// Based on:
// -> http://csharpfeeds.com/post/5048/Csharp_and_Word_Interop_Part_4_-_Tables.aspx
// -> http://stackoverflow.com/a/1817041/700926
private static void AddTableHeaderAndBorder(Table table, params string[] columnTitles)
{
const int headerRowIndex = 1;
for (var i = 0; i < columnTitles.Length; i++)
{
var tableHeaderRange = table.Cell(headerRowIndex, i+1).Range;
tableHeaderRange.Text = columnTitles[i];
tableHeaderRange.Font.Bold = 1;
tableHeaderRange.Font.Italic = 1;
}
// Repeat header on each page
table.Rows[headerRowIndex].HeadingFormat = -1;
// Enable borders
table.Borders.Enable = 1;
}
// Based on:
// -> http://stackoverflow.com/q/7084270/700926
// -> http://stackoverflow.com/a/7084442/700926
private static List<string> GetHeadingsInDocument(Document document)
{
object headingsAtmp = document.GetCrossReferenceItems(WdReferenceType.wdRefTypeHeading);
return ((Array)(headingsAtmp)).Cast<string>().ToList();
}
}
}
Basically, the code first loads all headings from the two given documents and stores them in memory. Then it opens the target document, creates and styles the traceability matrix, and finally, it inserts the headings into the matrix.
The code is based on the assumptions that:
A target document (documentC.docx) exists.
The number of headings in the two input documents (documentA.docx, and documentB.docx) contains the same amount of headings - this assumption is made based on your comment about not wanting a Cartesian product.
I hope this meets your requirements :)

Matlab: How to survey compiled m-code progression from external API?

My question is extremely specific to the arcanes of the matlab compiler and runtime. As only people familiar with matlab runtime API may answer, I shortened much details. Please let me know if I should be more verbose.
Introduction
Using the matlab compiler & runtime I can call a function written in m-code from a C# program. Let's say calling:
function [result] = foo(n)
%[
result = 0;
for k = 1:n,
pause(1.0); % simulate long processing
result = result + 42;
end
%]
with (somewhere behind some dllimports in the C# code):
mclFeval(IntPtr inst, string name, IntPtr[] plhs, IntPtr[] prhs)
So far, so good, I have no issue with this (i.e intializing the runtime, loading the '.cft' file, marshalling back and forth MxArray with .Net types, etc...)
My Problem
I would like to survey the progression of my foo function using some cancel and progress callbacks:
function [result] = foo(n, cancelCB, progressCB)
%[
if (nargin < 3), progressCB = #(ratio, msg) disp(sprintf('Ratio = %f, Msg = %s', ratio, msg)); end
if (nargin < 2), cancelCB = #() disp('Checking cancel...'); end
result = 0;
for k = 1:n,
if (~isempty(cancelCB)),
cancelCB(); % Up to the callback to raise some error('cancel');
end;
if (~isempty(progressCB)),
progressCB(k/n, sprintf('Processing (%i/%i)', k, n));
end
pause(1.0); % simulate long processing
result = result + 42;
end
%]
But of course I would like these callbacks to be in the C# code, not within the m-one.
Investigations
Looking at 'mclmcr.h' header file, it looks like these functions may be of help:
extern mxArray* mclCreateSimpleFunctionHandle(mxFunctionPtr fcn);
extern bool mclRegisterExternalFunction(HMCRINSTANCE inst, const char* varname, mxFunctionPtr fcn);
Unfortunatly these are fully undocumented and I found no use case I could mimic to understand how they work.
I've also thought about creating a COM visible object in C# and pass it as a parameter to the matlab code:
// Somewhere within C# code:
var survey = new ComSurvey();
survey.SetCancelCallback = () => { if (/**/) throw new OperationCancelException(); };
survey.SetProgressCallback = (ratio, msg) => { /* do something */ };
function [result] = foo(n, survey)
%[
if (nargin < 2), survey = []; end
result = 0;
for k = 1:n,
if (~isempty(survey)),
survey.CheckCancel(); % up to the COM object to raise exception
survey.SetProgress(k/n, sprintf('Processing... %i/%i', k, n));
end
pause(1.0); % simulate long processing
result = result + 42;
end
%]
I'm very familiar with functions to create numeric and structure arrays and know how to use them:
extern mxArray *mxCreateNumericArray(...)
extern mxArray *mxCreateStructArray(...)
Anyhow, how COM objects are packaged to MxArrays, I don't know?
Further investigations
Day+1
Even if still unstable, I succeeded to have matlab to callback into my C# code and it seems that mclCreateSimpleFunctionHandle is the direction to go.
Note: Below code is for reference only. It may not be suitable in your own context as is. I'll provide simpler code later on (i.e. once I'll get stable solution).
Looking to the signature of the mxFunctionPtr, I created two delegates like this:
// Mimic low level signature for a Matlab function pointer
[UnmanagedFunctionPointer(CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
delegate void MCRInteropDelegate(int nlhs, IntPtr[] plhs, int nrhs, IntPtr[] prhs);
and
// Same signature (but far more elegant from .NET perspective)
delegate void MCRDelegate(MxArray[] varargouts, MxArray[] varargins);
I also linked to the runtime like this:
[DllImport("mclmcrrt74.dll", EntryPoint = "mclCreateSimpleFunctionHandle", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, ExactSpelling = true)]
static extern IntPtr _mclCreateSimpleFunctionHandle(MCRInteropDelegate fctn);
Assuming MxArray is a .NET class of mine that simply encapsulate for mxArray* handles, I then marshaled my delegates like this:
// Create MxArray from corresponding .NET delegate
static MxArray CreateFromDelegate(MCRDelegate del)
{
// Package high level delegate signature to a 'dllimport' signature
MCRInteropDelegate interopDel = (nlhs, plhs, nrhs, prhs) =>
{
int k = 0;
var varargouts = new MxArray[nlhs];
var varargins = new MxArray[nrhs];
// (nrhs, prhs) => MxArray[] varargins
Array.ForEach(varargins, x => new MxArray(prhs[k++], false)); // false = is to indicate that MxArray must not be disposed on .NET side
// Call delegate
del(varargouts, varargins); // Todo: varargouts created by the delegate must be destroyed by matlab, not by .NET !!
// MxArray[] varargouts => (nlhs, plhs)
k = 0;
Array.ForEach(plhs, x => varargouts[k++].getPointer());
};
// Create the 1x1 array of 'function pointer' type
return new MxArray(MCRInterop.mclCreateSimpleFunctionHandle(interopDel));
}
Finally, assuming module is an instance of MCRModule (again, a class of mine to encapsulate hInst* in low level mclFeval API), I was able to call foo function and have it to enter my .NET cancel delegate like this:
// Create cancel callback in .NET
MCRDelegate cancel = (varargouts, varargins) =>
{
if ((varargouts != null) && (varargouts.Length != 0) { throw new ArgumentException("'cancel' callback called with too many output arguments"); }
if ((varargins != null) && (varargins.Length != 0) { throw new ArgumentException("'cancel' callback called with too many input arguments"); }
if (...mustCancel...) { throw new OperationCanceledException(); }
}
// Enter the m-code
// NB: Below function automatically converts its parameters to MxArray
// and then call low level mclFeval with correct 'mxArray*' handles
module.Evaluate("foo", (double)10, cancel);
This .NET code worked fine, and foo really made callback to the cancel delegate properly.
Only problem, is that it is quite unstable. My guess is that I used too many anonymous functions, and probably some of them are disposed too early ...
Will try to provide with stable solution within the next few days (hopefully with simpler code to read and copy-paste in your own context for immediate testing).
Please let me know if you think I'm going the wrong direction with mclCreateSimpleFunctionHandle.
Got it
mclCreateSimpleFunctionHandle was effectively the right API function to call at in order to create an array variable (on matlab's side) holding for a function pointer (on external's side). I'm now able to have compiled m-code to call back into my C# code for cancellation and progression purposes.
Correct marshalling for mclCreateSimpleFunctionHandle is described here