Attach screenshot to Test Step Result (ITestStepResult) - VSTS - c#

I am able to create a new Test Run and update each Test Step status and finally complete the Automated Test RUN. I have used C# library files to do all these to VSTS.
Also I am currently working on attaching screenshot to the Test Step result. I can see that screenshot getting attached to the Test Step under Run tab but the upload was not complete and not able to see the screenshot getting loaded.
Following is the code used to attach screenshot:
ITestAttachment attachment = stepResult.CreateAttachment(screenShotPath);
stepResult.Attachments.Add(attachment);
Also please find the screenshot attached to understand my problem much better.
Thanks for the help in advance

With this code below, it uploads the attachment to test step, when I check the test result, the image isn’t displayed correctly (the same as you), but after a minute, it displays correctly. So, you can check image whether displays correctly now.
int testpointid = 56;
var u = new Uri("https://XXX.visualstudio.com");
var c = new VssClientCredentials();
c.Storage = new VssClientCredentialStorage(storageKind: "VssApp", storageNamespace: "VisualStudio");
TfsTeamProjectCollection _tfs = new TfsTeamProjectCollection(u, c);
_tfs.EnsureAuthenticated();
ITestManagementService test_service = (ITestManagementService)_tfs.GetService(typeof(ITestManagementService));
ITestManagementTeamProject _testproject = test_service.GetTeamProject("{proejct}");
ITestPlan _plan = _testproject.TestPlans.Find(89);
ITestRun testRun = _plan.CreateTestRun(false);
testRun.Title = "apiTest2";
ITestPoint point = _plan.FindTestPoint(testpointid);
testRun.AddTestPoint(point, test_service.AuthorizedIdentity);
testRun.Save();
testRun.Refresh();
ITestCaseResultCollection results = testRun.QueryResults();
ITestIterationResult iterationResult;
foreach (ITestCaseResult result in results)
{
iterationResult = result.CreateIteration(1);
foreach (Microsoft.TeamFoundation.TestManagement.Client.ITestStep testStep in result.GetTestCase().Actions)
{
ITestStepResult stepResult = iterationResult.CreateStepResult(testStep.Id);
stepResult.Outcome = Microsoft.TeamFoundation.TestManagement.Client.TestOutcome.Passed; //you can assign different states here
Microsoft.TeamFoundation.TestManagement.Client.ITestAttachment attachment = stepResult.CreateAttachment(#"{image path}");
stepResult.Attachments.Add(attachment);
iterationResult.Actions.Add(stepResult);
}
iterationResult.Outcome = Microsoft.TeamFoundation.TestManagement.Client.TestOutcome.Passed;
result.Iterations.Add(iterationResult);
result.Outcome = Microsoft.TeamFoundation.TestManagement.Client.TestOutcome.Passed;
result.State = TestResultState.Completed;
result.Save(true);
}
testRun.State = Microsoft.TeamFoundation.TestManagement.Client.TestRunState.Completed;
results.Save(true);

Related

LibreOffice Calc C# SDK: program to insert images into cells, stuck trying to create XGraphic

Background: I'm trying to write a program to insert an image into a cell of a spreadsheet. LibreOffice recently changed how this is done, and all the samples I could find use the old method which no longer works.
Technically I know that you can't "insert" an image into a cell and that such an image is an overlay on a DrawPage that sits on top of the spreadsheet to "decorate" it.
One of the first steps in doing this (the new way) is to create an XGraphic object which contains the image. The process is to create an XGraphicProvider and call it with MediaProperties that specify the image file URL to be loaded. I have a program that is supposed to do this but the resulting XGraphic is null. The LO SDK gives pretty much no information when you do something wrong; it just doesn't work.
Here is the code I have, with all the headers removed:
// addpic
// add picture to spreadsheet - debug version
class OpenOfficeApp {
[STAThread]
static void Main(string[] args) {
bool lreadonly;
string pqfile;
string pqURL;
string pqpic;
pqfile = "file:///D:/Documents/NSexeye/ODS%20File%20Access/"+
"addpix/addpic.ods";
pqpic = "addpic2";
pqURL = pqpic+".jpg";
lreadonly = false;
Console.WriteLine("Using: "+pqfile);
// get the desktop
XComponentContext XCC = uno.util.Bootstrap.bootstrap();
XMultiComponentFactory XMCF =
(XMultiComponentFactory)XCC.getServiceManager();
XMultiServiceFactory XMSF = (XMultiServiceFactory)XCC.getServiceManager();
XComponentLoader XCL =
(XComponentLoader)XMSF.createInstance("com.sun.star.frame.Desktop");
// open the spreadsheet
PropertyValue[] pPV = new PropertyValue[2];
pPV[0] = new PropertyValue();
pPV[0].Name = "Hidden";
pPV[0].Value = new uno.Any(true);
pPV[1] = new PropertyValue();
pPV[1].Name = "ReadOnly";
if (lreadonly) pPV[1].Value = new uno.Any(true);
else pPV[1].Value = new uno.Any(false);
XComponent XCo = XCL.loadComponentFromURL(pqfile,"_blank",0,pPV);
// create graphic object containing image
object oGP = XMCF.createInstanceWithContext(
"com.sun.star.graphic.GraphicProvider",XCC);
if (oGP == null) {
Console.WriteLine("oGP is null. Aborting.");
return;
}
XGraphicProvider XGP = (XGraphicProvider)oGP;
if (XGP == null) {
Console.WriteLine("XGP is null. Aborting.");
return;
}
pPV = new PropertyValue[1];
pPV[0] = new PropertyValue();
pPV[0].Name = "URL";
pPV[0].Value = new uno.Any(pqURL);
Console.WriteLine("Creating XGraphic containing "+pqURL);
XGraphic XG = XGP.queryGraphic(pPV);
// *** XG is null here
if (XG == null) {
Console.WriteLine("XG is null. Aborting.");
return;
}
// ... lots of stuff to be added here
// save and close the spreadsheet
XModifiable XM = (XModifiable)XCo;
XM.setModified(true);
XStorable XSt = (XStorable)XCo;
XSt.store();
XCloseable XCl = (XCloseable)XCo;
XCl.close(true);
// terminate LibreOffice
// *** I want this to not terminate it if something else is open
XDesktop XD = (XDesktop)XCL;
if (XD != null) XD.terminate();
}
}
I get a null for the XGraphic, in the place indicated in the comments. I don't know if the call to create it is failing, or if one of the earlier steps of the process are incorrect.
My goal here, in addition to getting my program working, is to create a sample program showing how to add an image to a Calc spreadsheet cell, and to manipulate such images. There are a fair number of people asking questions about this and none of the examples I've found will work. I think a good working sample will be of value.
I've spent a lot of time searching for information and code samples for this, with nothing that helps. I've tried to find ways to verify the validity of the XGraphicProvider interface with no luck. I've run out of things to try.
I'm hoping someone who knows about the LibreOffice SDK can take a look and maybe see what I'm doing wrong.
Update: I figured out what I was doing wrong: I was passing a bare filename in the "URL" property to XGraphicProvider. It has to be the same format (starting with "file:///") as the spreadsheet's file name specification.
Now I'm stuck with another property problem. The XGraphic has to be specified as a parameter to the GraphicObjectShape's Graphic property, but the setPropertyValue() function requires that it be a uno.Any type. I can't figure out how to specify an interface name like XGraphic as a uno.Any.
Here is the piece of code that won't compile, complaining that it can't convert an XGraphic to a uno.Any, in the first setPropertyValue call:
// set image XGraphic
XPropertySet XPS = (XPropertySet)XS;
XPS.setPropertyValue("Graphic",XG);
XPS.setPropertyValue("Name",new uno.Any(pqpic));
XG is an XGraphic type. Using "new uno.Any(XG)" doesn't work either, giving a similar compiler error.
After trying unsuccessfully for a few hours to get the latest LO SDK up and running, let me offer some untested ideas.
First of all, here is some working Basic code, no doubt similar to what you're translating from. The important line is oShape.Graphic = oProvider.queryGraphic(Props()).
oDoc = ThisComponent
oSheet = oDoc.CurrentController.ActiveSheet
pqURL = "file:///C:/Users/JimK/Desktop/addpic.jpg"
oProvider = createUnoService("com.sun.star.graphic.GraphicProvider")
oShape = oDoc.createInstance("com.sun.star.drawing.GraphicObjectShape")
Dim Props(0) as new com.sun.star.beans.PropertyValue
Props(0).Name= "URL"
Props(0).Value = pqURL
oShape.Graphic = oProvider.queryGraphic(Props())
oCell = oSheet.getCellByPosition(5,5)
oShape.Name = oCell.AbsoluteName + "##" + Props(0).Value
oShape.Anchor = oCell
oSheet.DrawPage.add(oShape)
'Resize
w = oShape.Graphic.Size.Width
h = oShape.Graphic.Size.Height
wcl = oCell.Size.Width
hcl = oCell.Size.Height
If w<>0 and h<>0 then
oCell.String=""
Dim Size as new com.sun.star.awt.Size
Size.Width = wcl
Size.Height = h*wcl/w
If Size.Height > hcl then
Size.Width = hcl*w/h
Size.Height = hcl
Endif
oShape.setSize(Size)
oShape.setPosition(oCell.Position)
erase oShape
Else
oShape.dispose()
Endif
Now, how to translate this to C#? It looks like you may need to explicitly specify the type. In the SDK example, there are calls like this.
xFieldProp.setPropertyValue(
"Orientation",
new uno.Any(
typeof (unoidl.com.sun.star.sheet.DataPilotFieldOrientation),
unoidl.com.sun.star.sheet.DataPilotFieldOrientation.DATA ) );
So in your case, something like this:
XPS.setPropertyValue(
"Graphic"
new uno.Any(
typeof(unoidl.com.sun.star.graphic.XGraphic),
XG));
Alternatively, follow the suggestion here: set GraphicURL, which should load the image and set Graphic for you.

How can i access the console logs on chrome and assert if a line exists?

Quite new to selenium, have been looking to find an answer to this question, but so far, all the times I have tried I was not able to get my desired result.
I followed other answers to access the chrome console logs but i get an exception:
ChromeOptions options = new ChromeOptions();
options.SetLoggingPreference(LogType.Browser, LogLevel.All);
var driver = new ChromeDriver(options);
driver.Manage().Window.Maximize();
driver.Url = "https://test.test";
var homePage = new HomePage(driver); //POM
homePage.SignIn().Click();
homePage.Email("email");
homePage.Password("pw");
homePage.LogIn();
var logs = driver.Manage().Logs.GetLog(LogType.Browser);
foreach (var log in logs)
{
Console.WriteLine(log.ToString());
}
the exception is thrown on : var logs = driver.Manage().Logs.GetLog(LogType.Browser);
System.NullReferenceException: 'Object reference not set to an instance of an object.'
I haven't been able to understand why it is thrown.
After that, i would like to assert the console logs to see if a specific entry is present. Is it possible?
So, this is a dirty workaround. If you get any good answer, please don't use mine.
Modify the default console.log method to store data in a newly introduced global variable:
IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
//Multiline string used for readability. Write it in single line
js.ExecuteScript("
window.oldConsoleLog = window.console.log;
window.logCalls = [];
window.console.log = function(){
oldConsoleLog.apply(window.console, arguments);
window.logCalls.push(arguments);
}
");
Now you'll be able to get all calls using the next code:
var calls = js.ExecuteScript("return window.logCalls");
If you need a cleanup:
js.ExecuteScript("delete window.logCalls;window.console.log = window.oldConsoleLog;")

Link TFS test run to a release via c#

Using the new TFS api:
Microsoft.TeamFoundationServer. ExtendedClient
I have succeeded creating a test run and attaching a release and release environment to it so a link to the release appears at the test run summery.
However, when I go to the release page and click the "Tests" tab I cannot see the test run and it's statistics.
How can I "make" the release know the test run and add it to the release via c# code?
Here is my code:
// Creates a TFS test run
public static void CreateTestRun(ITestPlan testPlan, int testCaseId, string testResult,
string buildIdStr, string releaseUri, string releaseEnvironmentUri, string testRunName)
{
// --------------------------------Biuld the RunCreateModel for the test run:------------------------------------------------
// Find the test points of the current test case
List<int> testPointIds = new List<int>();
ITestPointCollection testPoints = testPlan.QueryTestPoints("SELECT * FROM TestPoint WHERE testPoint.TestCaseId='" + testCaseId + "'");
foreach (ITestPoint testPoint in testPoints)
{
testPointIds.Add(testPoint.Id);
}
int buildId;
int.TryParse(buildIdStr, out buildId);
// Init RunCreateModel:
RunCreateModel runCreateModel = new RunCreateModel(
name: testRunName,
startedDate: DateTime.Now.ToString("M/d/y h:m:s tt"),
plan: new ShallowReference(id: testPlan.Id.ToString()),
pointIds: testPointIds.ToArray(),
buildId: buildId,
releaseUri: releaseUri,
releaseEnvironmentUri: releaseEnvironmentUri
);
// ----------------------------------------------------------------------------------------------------------------------------
// -------------------------------------------------Create test run in progress--------------------------------------------
TestManagementHttpClient testManagementClient =
new TestManagementHttpClient(new Uri(TFS_COLLECTION_NAME), new VssCredentials());
// Use RunCreateModel to create a test run on TFS (using the extended API):
TestRun testRunExtended =
testManagementClient.CreateTestRunAsync(runCreateModel, TFS_TEAM_PROJECT_NAME).Result;
// ---------------------------------------------------------------------------------------------------------------------------
// Using the regular client api, add results to the test run to complete it:
TfsTeamProjectCollection tfsCollection = new TfsTeamProjectCollection(new Uri(TFS_COLLECTION_NAME), new VssCredentials());
ITestManagementService testManagement = tfsCollection.GetService<ITestManagementService>();
IEnumerable<ITestRun> testRuns = testManagement.QueryTestRuns(
"SELECT * FROM TestRun WHERE TestRunID='" + testRunExtended.Id + "'");
ITestRun testRun = testRuns.First();
// Update the outcome of the test
ITestCaseResultCollection results = testRun.QueryResults();
foreach (ITestCaseResult result in results)
{
result.Outcome = testResult == "Pass" ?
Microsoft.TeamFoundation.TestManagement.Client.TestOutcome.Passed :
Microsoft.TeamFoundation.TestManagement.Client.TestOutcome.Failed;
result.State = TestResultState.Completed;
result.Save();
}
testRun.Save();
testRun.Refresh();
}
Thx.
Solved by setting the RunCreateModel.isAutomated property to true.
You could use REST API to update test run by its ID, the api is as below:
PATCH https://{accountName}.visualstudio.com/{project}/_apis/test/runs/{runId}?api-version=5.0-preview.2
You need to modify or add the following part in the body:
"releaseUri": "vstfs:///ReleaseManagement/Release/{releaseID}",
"releaseEnvironmentUri": "vstfs:///ReleaseManagement/Environment/{releaseID}",
"release": {
"id": {releaseID},
"name": "{releaseName}",
"environmentId": {releaseID},
"environmentName": "{EnvironmentName}",
"definitionId": {definitionId},
"environmentDefinitionId": {definitionId},
"environmentDefinitionName": null,
"attempt": 1
},
I've tested on my side, it's working.

Cortana RequestDisambiguationAsync Error

I'm trying to get user interaction with a background app through Cortana working for my app.
Whenever I do RequestDisambiguationAsync(response) Cortana just says that it ran into an error. However, it isn't breaking anywhere in Visual Studio.
Any ideas on what may be causing it? Below is the code that I am using:
var userPrompt = new VoiceCommandUserMessage();
string home1 = data.Structures[0].Name;
string home2 = data.Structures[1].Name;
userPrompt.DisplayMessage = "Which one did you want to set to home?";
userPrompt.SpokenMessage = String.Format("Which one did you want to set to home? {0} or {1}?", home1, home2);
var userReprompt = new VoiceCommandUserMessage();
userReprompt.DisplayMessage = "Which one did you want to set to home?";
userReprompt.SpokenMessage = "Which one did you want to set to home?";
var structuresContentTiles = new List<VoiceCommandContentTile>();
var structureTile = new VoiceCommandContentTile();
structureTile.ContentTileType = VoiceCommandContentTileType.TitleWith68x68IconAndText;
structureTile.Title = home1;
structureTile.AppContext = data.Structures[0].Structure_id;
structuresContentTiles.Add(structureTile);
var structureTile2 = new VoiceCommandContentTile();
structureTile2.ContentTileType = VoiceCommandContentTileType.TitleWith68x68IconAndText;
structureTile2.Title = home2;
structureTile.AppContext = data.Structures[1].Structure_id;
structuresContentTiles.Add(structureTile2);
var response = VoiceCommandResponse.CreateResponseForPrompt(userPrompt, userReprompt, structuresContentTiles);
var voiceCommandDisambiguationResult = await voiceServiceConnection.RequestDisambiguationAsync(response);
This behavior can occur in some cases when you use
structureTile.ContentTileType = VoiceCommandContentTileType.TitleWith68x68IconAndText;
but do not supply an image. Change it to VoiceCommandContentTileType.TitleOnly, or if you're supplying a Line1, use VoiceCommandContentTileType.TitleWithText, or provide an Image, and that should stop the failure from occurring.

R.NET invoke function does not work

I have all the necessary requirements when using the R.NET from http://rdotnet.codeplex.com/
My code works just fine on R Studio, however no luck on GUI. Can anybody let me know what I am doing wrong please?
REngine.SetEnvironmentVariables(#"C:\Program Files\R\R-3.1.1\bin\i386", #"C:\Program Files\R\R-3.1.1");
engine = REngine.GetInstance();
engine.Evaluate(#"source('C:/Users/achugh/Documents/Graphs/characterization.r')");
engine.Evaluate(#"source('C:/Users/achugh/Documents/Graphs/sliderDataToComputer.r')");
var sliderfunc = engine.Evaluate("sliderdata_yprofile").AsFunction();
var directory = engine.CreateCharacterVector(new[] { "C:/Users/achugh/Documents/Graphs/data" });
var oldset = sliderfunc.Invoke(new SymbolicExpression[] { directory }).AsDataFrame();
But for some reason the 'oldset' always evaluates to NULL. I already tried testing this via R-Studio
please advice?
Are you absolutely sure your function returns a data frame and not a matrix? The following behaves exactly as expected, and as you describe. I am working from the latest code but this part of R.NET is identical to the latest 1.5.16. Please mark this post as an answer if indeed correct, just not to confuse readers as to the behavior of R data coercion.
var funcDef = #"function(lyrics) {return(data.frame(a=1:4, b=5:8))}";
var f = engine.Evaluate(funcDef).AsFunction();
var x = f.Invoke(engine.CreateCharacter("Wo willst du hin?"));
Assert.True(x.IsDataFrame());
Assert.True(x.IsList());
var df = x.AsDataFrame();
Assert.NotNull(df);
funcDef = #"function() {return(as.matrix(data.frame(a=1:4, b=5:8)))}";
f = engine.Evaluate(funcDef).AsFunction();
x = f.Invoke();
Assert.False(x.IsDataFrame());
Assert.False(x.IsList());
df = x.AsDataFrame();
Assert.Null(df);
var nm = x.AsNumericMatrix();
Assert.NotNull(nm);
Answer:
var oldset = sliderfunc.Invoke(new SymbolicExpression[] { directory }).AsDataFrame();
change the above line to :
var oldset = sliderfunc.Invoke(new SymbolicExpression[] { directory }).AsNumericMatrix();
The reason are unknown, although the script is returning a data frame , but it fails to recognize this as data frame but recognizes this as Numeric Matrix.

Categories

Resources