Get nunit (2.5.10) TestCases with parameters from dll - c#

I got a compiled dll and I need to run every TestCase from this dll seperately with the nunit console tool, one test after the other. To run a TestCase I need to read the name and the parameters of the TestCase from the dll.
I tried reflection, but so far I ran into several problems. Is there a simple way to get the whole TestCase to run it with the nunit console? I heard of the --explore option of nunit3 to get all information of a dll, but unfortunately I have to use the version 2.5.10.
First of all I do not get the amount of methods defined when I try this:
List<MethodInfo> testMethods = new List<MethodInfo>(from type in
assembly.GetTypes()
from method in type.GetMethods()
where method.IsDefined(typeof(TestAttribute)) ||
method.IsDefined(typeof(TestCaseAttribute))
select method);
Afterwards I iterate over the items of the list and try to get the corresponding parameters with "CustomAttributeData.GetCustomAttributes(method)". But every TestCase has a different signature, so its difficult building the form nunit-console wants, like so: methodname(param1,...,paramN)
foreach (CustomAttributeData cad in attributes)
{
String test = method.Name + "(";
String attr = String.Empty;
foreach (CustomAttributeTypedArgument cata in cad.ConstructorArguments)
{
if (cata.Value.GetType() == typeof(ReadOnlyCollection<CustomAttributeTypedArgument>))
{
foreach (CustomAttributeTypedArgument cataElement in
(ReadOnlyCollection<CustomAttributeTypedArgument>)cata.Value)
{
if (cataElement.ArgumentType.Name == "String")
{
String elem = String.Empty;
if (cataElement.Value == null)
{
attr += "null" + ",";
}
else
{
elem = cataElement.Value.ToString().Replace(#"\", #"\\");
//escape quotation marks
attr += #"\" + "\"" + elem + #"\" + "\"" + ",";
}
}
else if (cataElement.ArgumentType.IsEnum)
{
var enumName = cataElement.ArgumentType.Name;
foreach (var fieldInfo in cataElement.ArgumentType.GetFields())
{
if (fieldInfo.FieldType.IsEnum)
{
var fName = fieldInfo.Name;
var fValue = fieldInfo.GetRawConstantValue();
if (cataElement.Value.ToString().Equals(fValue.ToString()))
{
attr += fName + ",";
}
}
}
}
else
{
attr += cataElement.Value + ",";
}
}
}
else if (cata.ArgumentType.IsEnum)
{
var enumName = cata.ArgumentType.Name;
foreach (var fieldInfo in cata.ArgumentType.GetFields())
{
if (fieldInfo.FieldType.IsEnum)
{
var fName = fieldInfo.Name;
var fValue = fieldInfo.GetRawConstantValue();
if (cata.Value.ToString().Equals(fValue.ToString()))
{
attr = fName;
}
}
}
}
else if (cata.Value.GetType() == typeof(String))
{
String elem = String.Empty;
if (cata.Value == null)
{
attr = "null";
}
else
{
elem = cata.Value.ToString().Replace(#"\", #"\\");
attr = #"\" + "\"" + elem + #"\" + "\"";
}
}
else
{
attr = cata.ToString();
}
//do stuff to get form of TestCase
Indeed it needs to be refactored, but I wonder if there is an easier way to get all TestCases and its Parameters.

Related

pass datatype of custom entity into function c#

I am having four different Datatypes, all as Lists:
List<DataRowTenant> tenantlist;
List<DataRowOwner> ownerlist;
List<DataRowCustomer> customerlist;
List<DataRowHWDevice> hwdevicelist;
List<DataRowHWCategory> hwcategorslist;
And i want to be able to export them into a CSV. Currently i copied my CSV-export Function five times, just with a different name and parameter definition. So, i was asking myself if i can somehow identify the Datatype of a variable and pass that also in the function?
i already tried the approaches in this Thread, but i couldn't get it to work.
my CSV-Export function is as follows:
public static void ExportOwnerCSV(List<DataRowOwner> list)
{
string columnNames = "";
string[] outputCsv = new string[list.Count + 1];
if (list.Count > 0)
{
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "CSV (*.csv)|*.csv";
sfd.FileName = "Output.csv";
bool fileError = false;
bool? result = sfd.ShowDialog();
if (result == true)
{
if (File.Exists(sfd.FileName))
{
try
{
File.Delete(sfd.FileName);
}
catch (IOException ex)
{
fileError = true;
MessageBox.Show("It wasn't possible to write the data to the disk." + ex.Message);
}
}
if (!fileError)
{
try
{
//var columnCount = DataRowOwner.GetType().GetFields();
var list_single = list[0];
var columnCount = list_single.GetType().GetProperties(BindingFlags.DeclaredOnly |
BindingFlags.Public |
BindingFlags.Instance);
//Header schreiben
foreach (PropertyInfo item in columnCount)
{
outputCsv[0] += "\"" + item.Name + "\"" + ",";
}
//Body schreiben
int row = 1;
foreach (var DataRowitem in list)
{
foreach (PropertyInfo item in columnCount)
{
outputCsv[row] += "\"" + item.GetValue(list[row - 1]) + "\"" + ",";
}
row++;
}
File.WriteAllLines(sfd.FileName, outputCsv, Encoding.UTF8);
MessageBox.Show("Data Exported Successfully!", "Info");
}
catch (Exception ex)
{
MessageBox.Show("Error :" + ex.Message);
}
}
}
}
else
{
MessageBox.Show("No Record To Export!", "Info");
}
}
thanks, any suggestions are appreciated.
You can declare the function as a generic function, where the type argument of the function is used as the type argument of the list parameter like so:
public static void ExportOwnerCSV<T>(IList<T> list)
{
...
}

Cast TreeViewItem to XElement?

I'm trying to iterate through the XElement of two collections so I can compare them, but I get the error :
System.InvalidCastException: 'Unable to cast object of type
'System.Windows.Controls.TreeViewItem' to type
'System.Xml.Linq.XElement'.'
My code is:
private void CompareTrees(ItemCollection xml,ItemCollection xsd )
{
bool isMatch = false;
string header = string.Empty;
foreach (XElement xexsd in xsd)
{
foreach (XElement xexml in xml)
{
if (xexsd.Name.LocalName + " - " + xexsd.Value == xexml.Name.LocalName + " - " + xexsd.Value)
{
CompareTrees(xml, xsd);
isMatch = true;
break;
}
}
if (isMatch == true)
{
continue;
}
else
{
var item = new ListBoxItem();
lbItems.Items.Add(item);
}
}
}
Apparently the ItemCollection contains TreeViewItems. Try this:
foreach (TreeViewItem tvi in xml.OfType<TreeViewItem>())
{
XElement xexsd = tvi.DataContext as XElement;
if (xexsd != null && xexsd.Name.LocalName + " - " + xexsd.Value == xexml.Name.LocalName + " - " + xexsd.Value)
{
CompareTrees(xml, xsd);
isMatch = true;
break;
}
}

Get Parent Class from external .cs file

I have a small Console app where I search for keywords in a large group of .cs files. I now want to follow the inheritance of a subfile to its parent root file. So far I have completed this by using a very noobish method that I don't like.
I think Reflection will be perfect but then I struggle to figure out how to use Reflection on an external file.
Can someone advise me on how I can achieve this?
EDIT:
static string GetParent(string location, string word)
{
string[] file = location.Split(new[] { "\\" }, StringSplitOptions.None);
try
{
using (StreamReader test = new StreamReader(location))
{
while ((line = test.ReadLine()) != null)
{
if (word == "ControlEventStates" && line.Contains(file.Last().ToString().Replace(".cs", "")))
{
string[] a = line.Split(new[] { " ", "(", ")", ";", ".", ",", "<", ">" }, StringSplitOptions.None);
for (int p = 0; p < a.Length; p++)
{
if (a[p] == ":" && a[p + 1] != "FunctionBase")
{
recValue = a[p + 1] + ".cs";
foreach (var item in Frontendfiles)
{
//newlocation = item;
string loc = Path.GetFileName(item);
if (loc == recValue)
{
GetParent(item, word);
}
else if (loc != recValue)
{
FindLine(item, a[p + 1] + " : ");
}
}
}
}
if (location != "" && location != null)
{
//LinesList = FindLine(newlocation, word);
return line;
}
}
}
}
return "";
}
catch (Exception ex)
{
throw ex;
}
}
So as I said this is terrible coding for what I want to accomplish. Basically I search for the line containing the current class name then filtering out the strings to find where the parent file is. Then I use the parent file name to search for its directory and then start the process over again.

Build XML file from XPathExpressions

I have a bunch of XPathExpressions that I used to read an XML file. I now need go the other way. (Generate an XML file based on the values I have.)
Here is an example to illustrate. Say I have a bunch of code like this:
XPathExpression hl7Expr1 = navigator.Compile("/ORM_O01/MSH/MSH.6/HD.1");
var hl7Expr2 = navigator.Compile("/ORM_O01/ORM_O01.PATIENT/PID/PID.18/CX.1");
var hl7Expr3 = navigator.Compile("/ORM_O01/ORM_O01.PATIENT/ORM_O01.PATIENT_VISIT/PV1/PV1.19/CX.1");
var hl7Expr4 = navigator.Compile("/ORM_O01/ORM_O01.PATIENT/PID/PID.3[1]/CX.1");
var hl7Expr5 = navigator.Compile("/ORM_O01/ORM_O01.PATIENT/PID/PID.5[1]/XPN.1/FN.1");
var hl7Expr6 = navigator.Compile("/ORM_O01/ORM_O01.PATIENT/PID/PID.5[1]/XPN.2");
string hl7Value1 = "SomeValue1";
string hl7Value2 = "SomeValue2";
string hl7Value3 = "SomeValue3";
string hl7Value4 = "SomeValue4";
string hl7Value5 = "SomeValue5";
string hl7Value6 = "SomeValue6";
Is there a way to take the hl7Expr XPathExpressions and generate an XML file with the corresponding hl7Value string in it?
Or maybe just use the actual path string to do the generation (instead of using the XPathExpression object)?
Note: I saw this question: Create XML Nodes based on XPath? but the answer does not allow for [1] references like I have on hl7Expr4.
I found this answer: https://stackoverflow.com/a/3465832/16241
And I was able to modify the main method to convert the [1] to attributes (like this):
public static XmlNode CreateXPath(XmlDocument doc, string xpath)
{
XmlNode node = doc;
foreach (string part in xpath.Substring(1).Split('/'))
{
XmlNodeList nodes = node.SelectNodes(part);
if (nodes.Count > 1) throw new ApplicationException("Xpath '" + xpath + "' was not found multiple times!");
else if (nodes.Count == 1) { node = nodes[0]; continue; }
if (part.StartsWith("#"))
{
var anode = doc.CreateAttribute(part.Substring(1));
node.Attributes.Append(anode);
node = anode;
}
else
{
string elName, attrib = null;
if (part.Contains("["))
{
part.SplitOnce("[", out elName, out attrib);
if (!attrib.EndsWith("]")) throw new ApplicationException("Unsupported XPath (missing ]): " + part);
attrib = attrib.Substring(0, attrib.Length - 1);
}
else elName = part;
XmlNode next = doc.CreateElement(elName);
node.AppendChild(next);
node = next;
if (attrib != null)
{
if (!attrib.StartsWith("#"))
{
attrib = " Id='" + attrib + "'";
}
string name, value;
attrib.Substring(1).SplitOnce("='", out name, out value);
if (string.IsNullOrEmpty(value) || !value.EndsWith("'")) throw new ApplicationException("Unsupported XPath attrib: " + part);
value = value.Substring(0, value.Length - 1);
var anode = doc.CreateAttribute(name);
anode.Value = value;
node.Attributes.Append(anode);
}
}
}
return node;
}

webbrowser not refreshing stylesheet

I post the complete code below, so you can see what I'm doing.
Situation:
I create a IHTMLDocument2 currentDoc pointing to the DomDocument
I write the proper string
I close the currentDoc
program shows me the html code including the CSS stuff 100% correct. Works
Now I want to change the CSS, instead of 2 columns I set it to 3 columns
(Simply change the width:48% to width:33%)
and rerun the code with the new 33%
now it suddenly doesn't apply any CSS style anymore.
When I close the program, and then change the CSS to 33% again, it works flawless
So, somehow, without disposing the complete webbrowser, I can't load the CSS a 2nd time..
or, the first CSS is somewhere in some cache, and conflicts with the 2nd CSS.. Just riddling here.. really need help on how to solve this
I searched the internet and stackoverflow long enough that I need to post this, even if someone else on this planet already posted it somewhere, I didn't find it.
private void doWebBrowserPreview()
{
if (lMediaFiles.Count == 0)
{
return;
}
Int32 iIndex = 0;
for (iIndex = 0; iIndex < lMediaFiles.Count; iIndex++)
{
if (!lMediaFiles[iIndex].isCorrupt())
{
break;
}
}
String strPreview = String.Empty;
String strLine = String.Empty;
// Set example Media
String strLinkHTM = lMediaFiles[iIndex].getFilePath();
FileInfo movFile = new FileInfo(strLinkHTM + lMediaFiles[iIndex].getFileMOV());
String str_sizeMB = (movFile.Length / 1048576).ToString();
if (str_sizeMB.Length > 3)
{
str_sizeMB.Insert(str_sizeMB.Length - 3, ".");
}
//Get info about our media files
MediaInfo MI = new MediaInfo();
MI.Open(strLinkHTM + lMediaFiles[iIndex].getFileM4V());
String str_m4vDuration = // MI.Get(0, 0, 80);
MI.Get(StreamKind.Video, 0, 74);
str_m4vDuration = "Duration: " + str_m4vDuration.Substring(0, 8) + " - Hours:Minutes:Seconds";
String str_m4vHeightPixel = MI.Get(StreamKind.Video, 0, "Height"); // "Height (Pixel): " +
Int32 i_32m4vHeightPixel;
Int32.TryParse(str_m4vHeightPixel, out i_32m4vHeightPixel);
i_32m4vHeightPixel += 16; // for the quicktime embed menu
str_m4vHeightPixel = i_32m4vHeightPixel.ToString();
String str_m4vWidthPixel = MI.Get(StreamKind.Video, 0, "Width"); //"Width (Pixel): " +
foreach (XElement xmlLine in s.getTemplates().getMovieHTM().Element("files").Elements("file"))
{
var query = xmlLine.Attributes("type");
foreach (XAttribute result in query)
{
if (result.Value == "htm_header")
{
foreach (XElement xmlLineDes in xmlLine.Descendants())
{
if (xmlLineDes.Name == "dataline")
{
strLine = xmlLineDes.Value;
strLine = strLine.Replace(#"%date%", lMediaFiles[iIndex].getDay().ToString() + " " + lMediaFiles[iIndex].getMonth(lMediaFiles[iIndex].getMonth()) + " " + lMediaFiles[iIndex].getYear().ToString());
strPreview += strLine + "\n";
}
}
}
}
}
strLine = "<style type=\"text/css\">" + "\n";
foreach (XElement xmlLine in s.getTemplates().getLayoutCSS().Element("layoutCSS").Elements("layout"))
{
var query = xmlLine.Attributes("type");
foreach (XAttribute result in query)
{
if (result.Value == "layoutMedia")
{
foreach (XElement xmlLineDes in xmlLine.Elements("layout"))
{
var queryL = xmlLineDes.Attributes("type");
foreach (XAttribute resultL in queryL)
{
if (resultL.Value == "layoutVideoBox")
{
foreach (XElement xmlLineDesL in xmlLineDes.Descendants())
{
if (xmlLineDesL.Name == "dataline")
{
strLine += xmlLineDesL.Value + "\n";
}
}
}
}
}
}
}
}
strLine += "</style>" + "\n";
strPreview = strPreview.Insert(strPreview.LastIndexOf("</head>", StringComparison.Ordinal), strLine);
for (Int16 i16Loop = 0; i16Loop < 3; i16Loop++)
{
foreach (XElement xmlLine in s.getTemplates().getMovieHTM().Element("files").Elements("file"))
{
var query = xmlLine.Attributes("type");
foreach (XAttribute result in query)
{
if (result.Value == "htm_videolist")
{
foreach (XElement xmlLineDes in xmlLine.Descendants())
{
if (xmlLineDes.Name == "dataline")
{
strLine = xmlLineDes.Value;
strLine = strLine.Replace(#"%m4vfile%", strLinkHTM + lMediaFiles[iIndex].getFileM4V());
strLine = strLine.Replace(#"%moviefile%", strLinkHTM + lMediaFiles[iIndex].getFileMOV());
strLine = strLine.Replace(#"%height%", str_m4vHeightPixel);
strLine = strLine.Replace(#"%width%", str_m4vWidthPixel);
strLine = strLine.Replace(#"%duration%", str_m4vDuration);
strLine = strLine.Replace(#"%sizeMB%", str_sizeMB);
strLine = strLine.Replace(#"%date%", lMediaFiles[iIndex].getDay().ToString() + " " + lMediaFiles[iIndex].getMonth(lMediaFiles[iIndex].getMonth()) + " " + lMediaFiles[iIndex].getYear().ToString());
strPreview += strLine + "\n";
}
}
}
}
}
}
foreach (XElement xmlLine in s.getTemplates().getMovieHTM().Element("files").Elements("file"))
{
var query = xmlLine.Attributes("type");
foreach (XAttribute result in query)
{
if (result.Value == "htm_footer")
{
foreach (XElement xmlLineDes in xmlLine.Descendants())
{
if (xmlLineDes.Name == "dataline")
{
strPreview += xmlLineDes.Value + "\n";
}
}
}
}
}
webBrowserPreview.Navigate("about:blank");
webBrowserPreview.Document.OpenNew(false);
mshtml.IHTMLDocument2 currentDoc = (mshtml.IHTMLDocument2)webBrowserPreview.Document.DomDocument;
currentDoc.clear();
currentDoc.write(strPreview);
currentDoc.close();
/*
try
{
if (webBrowserPreview.Document != null)
{
IHTMLDocument2 currentDocument = (IHTMLDocument2)webBrowserPreview.Document.DomDocument;
int length = currentDocument.styleSheets.length;
IHTMLStyleSheet styleSheet = currentDocument.createStyleSheet(#"", 0);
//length = currentDocument.styleSheets.length;
//styleSheet.addRule("body", "background-color:blue");
strLine = String.Empty;
foreach (XElement xmlLine in s.getTemplates().getLayoutCSS().Element("layoutCSS").Elements("layout"))
{
var query = xmlLine.Attributes("type");
foreach (XAttribute result in query)
{
if (result.Value == "layoutMedia")
{
foreach (XElement xmlLineDes in xmlLine.Elements("layout"))
{
var queryL = xmlLineDes.Attributes("type");
foreach (XAttribute resultL in queryL)
{
if (resultL.Value == "layoutVideoBox")
{
foreach (XElement xmlLineDesL in xmlLineDes.Descendants())
{
if (xmlLineDesL.Name == "dataline")
{
strLine += xmlLineDesL.Value;
}
}
}
}
}
}
}
}
//TextReader reader = new StreamReader(Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "basic.css"));
//string style = reader.ReadToEnd();
styleSheet.cssText = strLine;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}*/
webBrowserPreview.Refresh();
}
I now successfully implemented the berkelium-sharp method to my project
Has the same bug!
Found a solution!
First attempt which didn't work:
I had a persistent form (main form) and inside it a nested WebBrowser.
After changing the html with it's css, i told it to navigate to this new html!
This didn't work either:
Then I tried putting webbrowser on an own form. Which I simply open/close each
time I need a refresh. TO be sure the garbage collector cleans everything
Then I tried the Berkelium and rewrote it to my needs:
same logic as attempt 2 with the webbrowser. No luck either.
So I tried to open firefox itself and see if I can emulate this behaviour with a real browser. Indeed! When I open firefox, and force open the file (if you simply open a new file, firefox doesn't actually navigate to it, but detects this was already opened and simply refreshes it)
I noticed this due to the fast opening of the page!
A little scripting to force opening the same file twice (navigating) in 1 firefox session had the same effect: all CSS corrupt!
so, for some reason, you shouldn't navigate the same file twice, but instead of closing anything, simply force a refresh! Not a "Navigate"
Hope this info can help others, since I lost a lot of time finding out that it is the "navigate" to the same file more then once causing the corruption of stylesheets

Categories