When I'm trying to retrieve my meter from opentelemetry (C#) with telegraf (OpenTelemetry plugin), the data is not being sent.
Example code 1:
class Program
{
static Meter s_meter = new Meter("HatCo.HatStore", "1.0.0");
static Counter<int> s_hatsSold = s_meter.CreateCounter<int>(name: "hats-sold",
unit: "Hats", description: "The number of hats sold in our store");
static void Main(string[] args)
{
using MeterProvider meterProvider = Sdk.CreateMeterProviderBuilder()
.AddMeter("HatCo.HatStore")
.AddPrometheusExporter()
.Build();
Console.WriteLine("Press any key to exit");
while (!Console.KeyAvailable)
{
// Pretend our store has a transaction each second that sells 4 hats
Thread.Sleep(1000);
Console.WriteLine("+4");
s_hatsSold.Add(4);
}
}
}
I get this error:
2023-01-05T13:58:06Z I! Starting Telegraf 1.24.4
2023-01-05T13:58:06Z I! Available plugins: 222 inputs, 9 aggregators, 26 processors, 20 parsers, 57 outputs
2023-01-05T13:58:06Z I! Loaded inputs: opentelemetry
2023-01-05T13:58:06Z I! Loaded aggregators:
2023-01-05T13:58:06Z I! Loaded processors:
2023-01-05T13:58:06Z W! Outputs are not used in testing mode!
2023-01-05T13:58:06Z I! Tags enabled: host= [MY MACHINE]
2023-01-05T13:58:06Z E! [inputs.opentelemetry] Error in plugin: failed to stop OpenTelemetry gRPC service: grpc: the server has been stopped
2023-01-05T13:58:06Z E! [telegraf] Error running agent: input plugins recorded 1 errors
And if I try with this example code 2:
class Program
{
static Meter s_meter = new Meter("HatCo.HatStore", "1.0.0");
static Counter<int> s_hatsSold = s_meter.CreateCounter<int>(name: "hats-sold",
unit: "Hats",
description: "The number of hats sold in our store");
static void Main(string[] args)
{
using MeterProvider meterProvider = Sdk.CreateMeterProviderBuilder()
.AddMeter("HatCo.HatStore")
.AddPrometheusExporter(opt =>
{
opt.StartHttpListener = true;
opt.HttpListenerPrefixes = new string[] { $"http://localhost:9184/" };
})
.Build();
Console.WriteLine("Press any key to exit");
while (!Console.KeyAvailable)
{
// Pretend our store has a transaction each second that sells 4 hats
Thread.Sleep(1000);
Console.WriteLine("+4");
s_hatsSold.Add(4);
}
}
}
I get this result:
2023-01-05T14:02:47Z I! Starting Telegraf 1.24.4
2023-01-05T14:02:47Z I! Available plugins: 222 inputs, 9 aggregators, 26 processors, 20 parsers, 57 outputs
2023-01-05T14:02:47Z I! Loaded inputs: opentelemetry
2023-01-05T14:02:47Z I! Loaded aggregators:
2023-01-05T14:02:47Z I! Loaded processors:
2023-01-05T14:02:47Z W! Outputs are not used in testing mode!
2023-01-05T14:02:47Z I! Tags enabled: host= [MY MACHINE]
2023-01-05T14:02:47Z E! [agent] Starting input inputs.opentelemetry: listen tcp 0.0.0.0:9184: bind: address already in use
All of this is running on Linux ubuntu 20.04, .NET 5.0, and here are the imported dependencies:
using System;
using System.Diagnostics.Metrics;
using System.Threading;
using Microsoft.AspNetCore.Mvc.ModelBinding.Binders;
using OpenTelemetry;
using OpenTelemetry.Metrics;
using OpenTelemetry.Exporter.Prometheus;
Telegraf inputs:
[[inputs.opentelemetry]]
## Override the default (0.0.0.0:4317) destination OpenTelemetry gRPC service
## address:port
service_address = "0.0.0.0:9184"
## Override the default (5s) new connection timeout
# timeout = "5s"
## Override the default (prometheus-v1) metrics schema.
## Supports: "prometheus-v1", "prometheus-v2"
## For more information about the alternatives, read the Prometheus input
## plugin notes.
#metrics_schema = "prometheus-v1"
## Optional TLS Config.
## For advanced options: https://github.com/influxdata/telegraf/blob/v1.18.3/docs/TLS.md
##
## Set one or more allowed client CA certificate file names to
## enable mutually authenticated TLS connections.
# tls_allowed_cacerts = ["/etc/telegraf/clientca.pem"]
## Add service certificate and key.
# tls_cert = "/etc/telegraf/cert.pem"
# tls_key = "/etc/telegraf/key.pem"
Thank you for your time, I've been stuck on this for a week now.
I tried those solutions and I expect the data to be sent to my influxDB database (other telegraf instances are already sending data to it).
Related
This is in continuation to this Question here, I have a PowerShell command which I have created and am able to call the command in a PowerShell window, but when trying to call from C# method, I am getting error as the cmdlet is not recognized, I tried with other existing commands and get same error, so I suspect issue in Importing the Module, though I don't get that error in streams. Error. The only error I get is "Get-RowAndPartitionKey is not a recognized cmndlt, please check the spelling.....".
Would like to know if there is any other way, I should try it or if I can debug more here to see if my Module fetches all command or not. right now I am clueless how to fix this.
public string RunScript( string contentScript, Dictionary<string, EntityProperty> parameters )
{
List<string> parameterList = new List<string>();
foreach( var item in parameters )
{
parameterList.Add( item.Value.ToString() );
}
using( PowerShell ps = PowerShell.Create() )
{
IAsyncResult async =
ps.AddCommand( "Import-Module" ).AddArgument( #"C:\Users\...\.D.PowerShell.dll" )
.AddStatement()
.AddCommand( "Get-RowAndPartitionKey" ).AddParameter( "Properties", "test" )
.BeginInvoke();
StringBuilder stringBuilder = new StringBuilder();
foreach( PSObject result in ps.EndInvoke( async ) )
{
stringBuilder.AppendLine( result.ToString() );
}
return stringBuilder.ToString();
}
}
}
Below method do not return any error in Streams.Error or Verbose but no output also:
public async Task<IEnumerable<object>> RunScript( string scriptContents, List<string> scriptParameters )
{
// create a new hosted PowerShell instance using the default runspace.
// wrap in a using statement to ensure resources are cleaned up.
using( PowerShell ps = PowerShell.Create() )
{
// specify the script code to run.
ps.AddScript( scriptContents );
// specify the parameters to pass into the script.
ps.AddParameter( "Properties" ,"test") ;
// execute the script and await the result.
var pipelineObjects = await ps.InvokeAsync().ConfigureAwait( false );
return pipelineObjects;
}
}
scriptContent
"\"$path = 'C:\\Users...\\.TabularData.PowerShell.dll'\\r\\nImport-Module $path\\r\\nGet-RowAndPartitionKeys\""
The following is self-contained PowerShell sample code that uses on-demand compilation of C# code:
It shows that the approach works in principle, as described in this answer to your original question.
Prerequisites: The PowerShell SDK package and .NET runtime used in the C# project that calls your custom Get-RowAndPartitionKey" cmdlet must be compatible with the PowerShell SDK and .NET runtime that you used to compile the assembly DLL that houses that cmdlet, to be imported via Import-Module.
The sample code below ensures that implicitly, by running directly from PowerShell, using the Add-Type cmdlet to compile C# code on demand - it works in Windows PowerShell as well as in PowerShell (Core) 7+.
In practice I've found that a .NET Framework-compiled DLL (from Windows PowerShell) also works in PowerShell (Core) (.NET (Core) 5.0), but not vice versa.
It shows troubleshooting techniques, namely:
Adding the -Verbose switch to the Import-Module call to produce verbose output that lists the commands being imported from the given module (DLL).
Printing these verbose messages (look for // --- TROUBLESHOOTING CODE)
Printing any non-terminating PowerShell errors that occurred (as opposed to exceptions that you'd have to handle in C# code).
# Create a (temporary) assembly containing cmdlet "Get-RowAndPartitionKey".
# This assembly can directly be imported as a module from PowerShell.
# The cmdlet simply outputs "Hi from Get-RowAndPartitionKey" and
# echoes the elements of the list passed to -Properties, one by one.
$tempModuleDll = Join-Path ([IO.Path]::GetTempPath()) "TempModule_$PID.dll"
Remove-Item -ErrorAction Ignore $tempModuleDll
Add-Type #'
using System.Management.Automation;
using System.Collections.Generic;
[Cmdlet("Get", "RowAndPartitionKey")]
public class GetRowAndPartitionKeyCmdlet : PSCmdlet {
[Parameter] public List<string> Properties { get; set; }
protected override void ProcessRecord() {
WriteObject("Hi from Get-RowAndPartitionKey: ");
WriteObject(Properties, true);
}
}
'# -ErrorAction Stop -OutputAssembly $tempModuleDll
# Compile a C# class ad hoc to simulate your project, and call its static
# method, which imports the module and effectively calls
# Get-RowAndPartitionKey -Properties "foo", "bar"
(Add-Type #"
using System;
using System.Management.Automation;
using System.Collections.Generic;
using System.Text;
public static class Foo {
public static string RunScript(List<string> parameterList)
{
using (System.Management.Automation.PowerShell ps = PowerShell.Create())
{
IAsyncResult async =
// Add -Verbose to the Import-Module call, so that the list of
// commands being imported is written to the verbose output stream.
ps.AddCommand("Import-Module").AddArgument(#"$tempModuleDll").AddParameter("Verbose", true)
.AddStatement()
.AddCommand("Get-RowAndPartitionKey").AddParameter("Properties", parameterList)
.BeginInvoke();
StringBuilder stringBuilder = new StringBuilder();
foreach (PSObject result in ps.EndInvoke(async))
{
stringBuilder.AppendLine(result.ToString());
}
// --- TROUBLESHOOTING CODE
// Print verbose output from the Import-Module call
foreach (var v in ps.Streams.Verbose) { Console.WriteLine("VERBOSE: " + v.ToString()); }
// Print any errors.
foreach (var e in ps.Streams.Error) { Console.WriteLine("ERROR: " + e.ToString()); }
// ---
return stringBuilder.ToString();
}
}
}
"# -ErrorAction Stop -PassThru)::RunScript(("foo", "bar"))
# Clean-up instructions:
if ($env:OS -eq 'Windows_NT') {
Write-Verbose -vb "NOTE: Re-running this code requires you to start a NEW SESSION."
Write-Verbose -vb "After exiting this session, you can delete the temporary module DLL(s) with:`n`n Remove-Item $($tempModuleDll -replace '_.+', '_*.dll')`n "
} else {
Write-Verbose -vb "NOTE: Re-running this code after modifying the embedded C# code requires you to start a NEW SESSION."
Remove-Item $tempModuleDll
}
On my Windows 10 machine, both from PowerShell (Core) 7.0.5 and Windows PowerShell 5.1, the above yields (clean-up instructions omitted) the following, showing that everything worked as intended:
VERBOSE: Loading module from path 'C:\Users\jdoe\AppData\Local\Temp\TempModule_11876.dll'.
VERBOSE: Importing cmdlet 'Get-RowAndPartitionKey'.
Hi from Get-RowAndPartitionKey:
foo
bar
Specifically, line VERBOSE: Importing cmdlet 'Get-RowAndPartitionKey'. indicates that the custom cmdlet was successfully imported into the session.
I have the console project in .NET Framework 4.7.2 which installed Apache.NMS and Apache.NMS.ActiveMQ packages. I copy and paste the sample code from official documentation and when I run it, it hits error Apache.NMS.NMSConnectionException: 'Error connecting to activemqhost:61616.' SocketException
This is my code:
class Program
{
public static void Main(string[] args)
{
// Example connection strings:
// activemq:tcp://activemqhost:61616
// stomp:tcp://activemqhost:61613
// ems:tcp://tibcohost:7222
// msmq://localhost
Uri connecturi = new Uri("activemq:tcp://activemqhost:61616");
Console.WriteLine("About to connect to " + connecturi);
// NOTE: ensure the nmsprovider-activemq.config file exists in the executable folder.
IConnectionFactory factory = new NMSConnectionFactory(connecturi);
using (IConnection connection = factory.CreateConnection())
{
}
}
}
Below is from my activemq.xml
<transportConnectors>
<!-- DOS protection, limit concurrent connections to 1000 and frame size to 100MB -->
<transportConnector name="openwire" uri="tcp://0.0.0.0:61616?maximumConnections=1000&wireFormat.maxFrameSize=104857600"/>
<transportConnector name="amqp" uri="amqp://0.0.0.0:5672?maximumConnections=1000&wireFormat.maxFrameSize=104857600"/>
<transportConnector name="stomp" uri="stomp://0.0.0.0:61613?maximumConnections=1000&wireFormat.maxFrameSize=104857600"/>
<transportConnector name="mqtt" uri="mqtt://0.0.0.0:1883?maximumConnections=1000&wireFormat.maxFrameSize=104857600"/>
<transportConnector name="ws" uri="ws://0.0.0.0:61614?maximumConnections=1000&wireFormat.maxFrameSize=104857600"/>
</transportConnectors>
Solved after I used this connectionstring Uri connecturi = new Uri("tcp://localhost:61616");
I am trying to run a simple WPF application (x86) using CefSharp WPF (75.1.141) in VirtualBox Windows 10 x64, but it crashes when I try to render a web browser.
It runs normally on the developer's machine Windows 10 x64 using Visual Studion 2017 WPF compiling in .Net Framework 4.5.2.
I already tried changing Cefsharp version to 71.0.0 but it didn't help. Also I tried cefsharp settings with commandline arguments "disable-gpu", "no-proxy-server", nothing changed.
Here are the MainWindow.xaml.cs code
ChromiumWebBrowser browser;
public MainWindow()
{
InitializeComponent();
Init();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
if (Init())
{
if (browser == null)
{
browser = new ChromiumWebBrowser();
((ChromiumWebBrowser)browser).IsBrowserInitializedChanged += (s, e2) =>
{
if (((ChromiumWebBrowser)browser).IsBrowserInitialized)
{
((ChromiumWebBrowser)browser).Load(textbox_url.Text);
}
};
gridBrowser.Children.Add(browser);
}
else if (((ChromiumWebBrowser)browser).IsBrowserInitialized)
{
((ChromiumWebBrowser)browser).Load(textbox_url.Text);
}
}
}
static bool init = false;
private bool Init()
{
if (init) return true;
//Monitor parent process exit and close subprocesses if parent process exits first
CefSharpSettings.SubprocessExitIfParentProcessClosed = true;
var settings = new CefSettings()
{
//By default CefSharp will use an in-memory cache, you need to specify a Cache Folder to persist data
CachePath = "cache",
IgnoreCertificateErrors = true,
};
init = Cef.Initialize(settings, performDependencyCheck: true, browserProcessHandler: null);
return init;
}
~MainWindow()
{
if (browser != null)
{
((ChromiumWebBrowser)browser).Dispose();
}
}
Event Viewer shows these errors
1. Info
Error container 1258037397975457498, type 1
Event name: APPCRASH
Response: No data
CAB ID: 0
Problem signature:
P1: CefSharpTest.exe
P2: 1.0.0.0
P3: a8760476
P4: VBoxDispD3D-x86.dll
P5: 6.0.4.28413
P6: 5c4b57a6
P7: c0000005
P8: 0000fb19
P9:
P10:
Included files:
\\?\C:\ProgramData\Microsoft\Windows\WER\Temp\WERCA7F.tmp.dmp
\\?\C:\ProgramData\Microsoft\Windows\WER\Temp\WERCC07.tmp.WERInternalMetadata.xml
\\?\C:\ProgramData\Microsoft\Windows\WER\Temp\WERCC15.tmp.csv
\\?\C:\ProgramData\Microsoft\Windows\WER\Temp\WERCC26.tmp.txt
These files can be found here:
C:\ProgramData\Microsoft\Windows\WER\ReportArchive\AppCrash_CefSharpTest.exe_87545299969ed877b3362d6ccde2f935ae9a282_7a64911f_0491dc52
Analyze symbol:
Repeated search for the issue: 0
Report Id: 011981c1-b0ed-4e02-b4fe-0361ef1885de
Report Status: 268435456
Hashed container: 952737448bb5f0a7517572591c7bdeda
2. Critical
Application: CefSharp.BrowserSubprocess.exe
Platform version: v4.0.30319
Description. The process was completed due to an unhandled exception..
Exception Details: exception code e0000008, exception address 76570882
3. Critical
Name of failed application: CefSharpTest.exe, version: 1.0.0.0, timestamp: 0xa8760476
Failed module name: VBoxDispD3D-x86.dll, version: 6.0.4.28413, timestamp: 0x5c4b57a6
Exception code: 0xc0000005
Error offset: 0x0000fb19
ID of the failed process: 0x1198
Failed application Launch Time: 0x01d55c59eed8c47d
Bad Application Path: C:\Users\Евгений\Desktop\CefSharpTest\CefSharpTest.exe
Failed module path: C:\Windows\SYSTEM32\VBoxDispD3D-x86.dll
Report Id: 011981c1-b0ed-4e02-b4fe-0361ef1885de
Failed Package Full Name:
Bad Package Application Code:
I also tried with installed vc++ (but I wanted without). I finally managed this to work by building with cefsharp version 67.0.0 and copying msvcp140.dll and vcruntime140.dll along with .exe. Thank you for your reply anyway.
I am attempting to write a C# core program to run powershell scripts on remote linux systems. Running on .net core is a requirement for this project. I am trying to loosely follow a guide I found on CodeProject.
This is my code:
using System;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
SSHConnectionInfo connectionInfo = new SSHConnectionInfo(userName: "user", computerName: "server", keyFilePath: "id_rsa");
using (Runspace runspace = RunspaceFactory.CreateRunspace(connectionInfo))
{
runspace.Open(); // The program errors out here
runspace.Close();
}
}
}
}
I have the "id_rsa" file located int the same folder as the program. I have verified that openssh for windows, powershell core 6.0.2, and .net core 2 SDK are installed and working. I am using the following nuget packages from the Microsoft Powershell Core repository: Microsoft.PowerShell.SDK (6.0.2) and Sytem.Managment.Automation (6.0.2)
This is the error I am receiving:
Unhandled Exception: System.Management.Automation.Remoting.PSRemotingDataStructureException: An error has occurred which PowerShell cannot handle. A remote session might have ended. ---> System.ArgumentException: The path is not of a legal form.
Parameter name: path
at System.IO.Path.GetDirectoryName(String path)
at System.Management.Automation.Runspaces.SSHConnectionInfo.StartSSHProcess(StreamWriter& stdInWriterVar, StreamReader& stdOutReaderVar, StreamReader& stdErrReaderVar)
at System.Management.Automation.Remoting.Client.SSHClientSessionTransportManager.CreateAsync()
at System.Management.Automation.Remoting.ClientRemoteSessionDSHandlerImpl.SendNegotiationAsync(RemoteSessionState sessionState)
at System.Management.Automation.Remoting.ClientRemoteSessionDSHandlerImpl.HandleStateChanged(Object sender, RemoteSessionStateEventArgs arg)
at System.Management.Automation.ExtensionMethods.SafeInvoke[T](EventHandler`1 eventHandler, Object sender, T eventArgs)
at System.Management.Automation.Remoting.ClientRemoteSessionDSHandlerStateMachine.RaiseStateMachineEvents()
at System.Management.Automation.Remoting.ClientRemoteSessionDSHandlerStateMachine.ProcessEvents()
--- End of inner exception stack trace ---
at System.Management.Automation.Runspaces.AsyncResult.EndInvoke()
at System.Management.Automation.Runspaces.Internal.RunspacePoolInternal.EndOpen(IAsyncResult asyncResult)
at System.Management.Automation.Runspaces.Internal.RemoteRunspacePoolInternal.Open()
at System.Management.Automation.RemoteRunspace.Open()
at ConsoleApp1.Program.Main(String[] args) in C:\ConsoleApp1\ConsoleApp1\Program.cs:line 18
Press any key to continue . . .
At this point I am not sure what I am missing.
I ended up opening an issue on github for this error. To work around this issue currently you will need to add the following code to your program until this issue gets resolved in a future version of powershell core (>6.0.4 or >6.1.0-rc.1). Here is the specific post regarding the issue.
if (System.Management.Automation.Runspaces.Runspace.DefaultRunspace == null)
{
var defaultRunspace = RunspaceFactory.CreateRunspace();
defaultRunspace.Open();
System.Management.Automation.Runspaces.Runspace.DefaultRunspace = defaultRunspace;
}
The following answer is derived from the Bruc3 work-around answer above and the RemoteRunspace Sample 01 from the Powershell SDK.
namespace Sample.PowerShell.Runspace
{
using System;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
/// <summary>
/// This class contains the Main enrty point for the application.
/// </summary>
internal class SshRemoteRunspace
{
public static void Main(string[] args)
{
SSHConnectionInfo sshConnectionInfo = new
SSHConnectionInfo("Administrator", "remote-hyper-v-server.mydomain.com", #"C:\Users\myself\.ssh\id_ed25519.pub");
// Bruc3 Workaround
if (System.Management.Automation.Runspaces.Runspace.DefaultRunspace is null)
{
var defaultRunspace = RunspaceFactory.CreateRunspace();
defaultRunspace.Open();
System.Management.Automation.Runspaces.Runspace.DefaultRunspace = defaultRunspace;
}
// Create a remote runspace using the connection information.
using (Runspace remoteRunspace = RunspaceFactory.CreateRunspace(sshConnectionInfo))
{
remoteRunspace.Open();
// Powershell command
using (PowerShell powershell = PowerShell.Create().AddCommand("Get-VMReplication"))
{
// makes the Powershell command run in the remote runspace instead of locally
powershell.Runspace = remoteRunspace;
// display the results in the local console
foreach (PSObject result in powershell.Invoke())
{
Console.WriteLine(result.ToString());
}
}
Console.WriteLine("Press 'Enter' to exit > ");
Console.ReadKey();
remoteRunspace.Close();
}
}
}
}
I am trying out BBD using Specflow. I am getting an error when I run the feature file.
The error is:
Result Message: Microsoft.CSharp.RuntimeBinder.RuntimeBinderException : 'System.Dynamic.ExpandoObject' does not contain a definition for 'keyword'
The error is somewhere in this method:
[Then(#"I should see the result for keyword")]
public void ThenIShouldSeeTheResultForeyword(Table table)
{
dynamic tableDetail = table.CreateDynamicInstance();
String key = tableDetail.keyword;
if (currentDriver.FindElement(By.PartialLinkText(key)).Displayed == true)
Console.WriteLine("Control Exist");
else
Console.WriteLine("Control not exist");
}
My feature file implementation is:
#SmokeTest
#Browser:Chrome
Scenario: Google Search for Execute Automation
Given I have navigated to Google page
Given I see the Google page fully loaded
When I type search keyword as
| Keyword |
| Formula One |
Then I should see the result for keyword
| keyword |
| Formula One |
My steps defincition file implementation is:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SpecFlow.Assist.Dynamic;
using OpenQA.Selenium;
using System.Configuration;
using TechTalk.SpecFlow;
using Baseclass.Contrib.SpecFlow.Selenium.NUnit.Bindings;
using TechTalk.SpecFlow.Assist;
using SpecFlow.Assist;
using SpecFlow;
namespace SpecFlowFirst.Steps
{
[Binding]
class GoogleSearchSteps
{
IWebDriver currentDriver = null;
[Given(#"I have navigated to Google page")]
public void GivenIhaveNavigatedToGooglePage()
{
Browser.Current.Navigate().GoToUrl(ConfigurationManager.AppSettings["seleniumBaseURL"]);
currentDriver = Browser.Current;
}
[Given(#"I see the Google page fully loaded")]
public void GivenISeeTheGooglePageFullyLoaded()
{
if (currentDriver.FindElement(By.Name("q")).Displayed == true)
Console.WriteLine("Page loaded fully");
else
Console.WriteLine("Page failed to load");
}
[When(#"I type search keyword as")]
public void WhenITypSsearchKeywordAs(Table table)
{
dynamic tableDetail = table.CreateDynamicInstance();
currentDriver.FindElement(By.Name("q")).SendKeys(tableDetail.keyword);
}
[Then(#"I should see the result for keyword")]
public void ThenIShouldSeeTheResultForeyword(Table table)
{
dynamic tableDetail = table.CreateDynamicInstance();
String key = tableDetail.keyword;
if (currentDriver.FindElement(By.PartialLinkText(key)).Displayed == true)
Console.WriteLine("Control Exist");
else
Console.WriteLine("Control not exist");
}
}
}
I am not sure why the error is being thrown when I run the feature. The solution builds without errors.
The full error trace is:
Test Name: GoogleSearchForExecuteAutomation on Chrome
Test FullName: SpecFlowFirst.Features.GoogleSearchFeature.GoogleSearchForExecuteAutomation on Chrome
Test Source: e:\RL Fusion\projects\BDD\C# BDD\SpecFlowFirst\SpecFlowFirst\SpecFlowFirst\Features\GoogleSearch.feature : line 20
Test Outcome: Failed
Test Duration: 0:00:11.715
Result Message: Microsoft.CSharp.RuntimeBinder.RuntimeBinderException : 'System.Dynamic.ExpandoObject' does not contain a definition for 'keyword'
Result StackTrace:
at CallSite.Target(Closure , CallSite , Object )
at System.Dynamic.UpdateDelegates.UpdateAndExecute1[T0,TRet](CallSite site, T0 arg0)
at SpecFlowFirst.Steps.GoogleSearchSteps.WhenITypSsearchKeywordAs(Table table) in e:\RL Fusion\projects\BDD\C# BDD\SpecFlowFirst\SpecFlowFirst\SpecFlowFirst\Steps\GoogleSearchSteps.cs:line 42
at lambda_method(Closure , IContextManager , Table )
at TechTalk.SpecFlow.Bindings.BindingInvoker.InvokeBinding(IBinding binding, IContextManager contextManager, Object[] arguments, ITestTracer testTracer, TimeSpan& duration)
at TechTalk.SpecFlow.Infrastructure.TestExecutionEngine.ExecuteStepMatch(BindingMatch match, Object[] arguments)
at TechTalk.SpecFlow.Infrastructure.TestExecutionEngine.ExecuteStep(StepInstance stepInstance)
at TechTalk.SpecFlow.Infrastructure.TestExecutionEngine.OnAfterLastStep()
at TechTalk.SpecFlow.TestRunner.CollectScenarioErrors()
at SpecFlowFirst.Features.GoogleSearchFeature.ScenarioCleanup() in e:\RL Fusion\projects\BDD\C# BDD\SpecFlowFirst\SpecFlowFirst\SpecFlowFirst\Features\GoogleSearch.feature.cs:line 0
at SpecFlowFirst.Features.GoogleSearchFeature.GoogleSearchForExecuteAutomation(String browser) in e:\RL Fusion\projects\BDD\C# BDD\SpecFlowFirst\SpecFlowFirst\SpecFlowFirst\Features\GoogleSearch.feature:line 26
Thanks for help, Riaz
briefly looking at the code for that method I think it might be 'fixing' the case of the property, so try using String key = tableDetail.Keyword
I rewrote Baseclass.Contrib.SpecFlow.Selenium.NUnit for 2.1 support.
New codebase, #ignore tag support for nunit3 and several testing services like BrowserStack, SauceLabs, TestingBot. Just in case you want to upgrade to 2.1
Here's the scenario in question:
Scenario: Google Search for Execute Automation
Given I have navigated to Google page
Given I see the Google page fully loaded
When I type search keyword as
| Keyword |
| Formula One |
Then I should see the result for keyword
| keyword |
| Formula One |
I just want to point out that:
Your whenstatement has a table with a Keyword column (with an upper case K),
And your then statement has a table with a keyword column (with a lower case k).
This means if you update both usages of tableDetails.Keyword at the same time (from keyword to Keyword, or vice versa), one of them will always throw.
Debugging advice
If this doesn't work for you, keep in mind that ExpandoObject implements IDictionary<string, object> and IEnumerable<KeyValuePair<string, object>>, which means you can always print to the console the available keys to understand what is actually being created by CreateDynamicInstance