What to troubleshoot MEF C# - c#

The following demo application on MEF technology does not work.
Can't build the simplest extensible application. I started with the simplest, a console application that will simply display text on the screen according to the specified parameters. And even here he did not go to me. Where to dig?
IDemoInterface.cs
public interface IDemoInretface
{
void Run(int sleep, int count);
}
MEFDataDemo
Program.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.IO;
namespace MEFDataDemo
{
class Program
{
static void Main(string[] args)
{
Program p = new Program();
p.Run();
}
public void Run()
{
DoImport();
int count = 1;
foreach (var item in Plugin)
{
item.Value.Run(count * 1000, count * 10);*** This is Error
count++;
}
}
[ImportMany(typeof(IDemoInretface))]
public IEnumerable<Lazy<IDemoInretface>> Plugin { get; set; }
public void DoImport()
{
var catalog = new AggregateCatalog();
var path = Path.Combine(Directory.GetCurrentDirectory(), "Plugins");
catalog.Catalogs.Add(new DirectoryCatalog(path));
var container = new CompositionContainer(catalog);
container.ComposeParts(this);
}
}
}
Plugin1 Class1.cs
using System;
using System.ComponentModel.Composition;
using System.Threading;
namespace Plugin1
{
[Export(typeof(IDemoInretface))]
internal class Class1 : IDemoInretface
{
public void Run(int sleep, int count)
{
for (int i = 0; i < count; i++)
{
Console.WriteLine("This plugin1 print {0}/{1} in {2}ms", i, count, sleep);
Thread.Sleep(sleep);
}
}
}
}
What am I doing wrong?
The program compiles, but either does not read plugins, or reads but does not run the (RUN) method

Related

How to fix duplicated questions (using Readline() and return)

I'm new to C#.
I'm creating a small program that input number by a user returns to the number and display it.
It works but a user is asked the same questions twice.
I just need one.
I'd appreciate if anyone help me with that.
Here is output of the program.
Here is my programming.
Class1
using System;
using System.Numerics;
using System.Reflection.Emit;
using static System.Console;
using System.IO;
namespace aaaa
{
public class Program
{
public static void Main(string[] args)
{
TryReturn tryreturn = new TryReturn();
tryreturn.template();
}
}
}
Class2
using System;
using System.Numerics;
using System.Reflection.Emit;
using static System.Console;
using System.IO;
namespace aaaa
{
public class TryReturn
{
public int entryNum;
public void template()
{
returnyNumber();
DisplayNumber();
}
public void DisplayNumber()
{
entryNum = returnyNumber();
WriteLine("number is " + entryNum);
Read();
}
public int returnyNumber()
{
int entryNum;
Write("Choose 1 or 2 >> ");
do
{
int.TryParse(ReadLine(), out entryNum);
if (entryNum == 1 || entryNum == 2)
{
break;
}
else
{
Write("Invalid entry! Enter either '1' or '2' >> ");
}
}
while (true);
return entryNum;
}
}
}
//remove the call of returnyNumber from template as you are calling it from DisplayNumber
public void template()
{
// returnyNumber();
DisplayNumber();
}
public void DisplayNumber()
{
entryNum = returnyNumber();
WriteLine("number is " + entryNum);
Read();
}

Test Executed successfully but report doesn't extent report doesn't generate in specflow

Currently I am working designing my project in Specflow. I want to implement some reporting to my project. Currently I have created one separate .cs file and kept all my report setting. But when i execute my code test run successfully but report doesn't generate. i am using the given code please check and suggest me
SeleniumDriver.cs
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Firefox;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ReportDemoPOC
{
class SeleniumDriver
{
public static IWebDriver WebDriver { get; set; }
public static string BaseAddress
{
get { return Constants.Url; }
}
public static void Intitialize()
{
WebDriver = new ChromeDriver();
WebDriver.Manage().Window.Maximize();
TurnOnWait();
}
public static void Navigate()
{
WebDriver.Navigate().GoToUrl(BaseAddress);
}
public static void Close()
{
WebDriver.Close();
}
public static void Quit()
{
WebDriver.Quit();
}
private static void TurnOnWait()
{
WebDriver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(5);
WebDriver.Manage().Timeouts().PageLoad = TimeSpan.FromMinutes(2);
}
public void Shutdown()
{
WebDriver.Quit();
}
}
}
Start.cs
using AventStack.ExtentReports;
using AventStack.ExtentReports.Reporter;
using AventStack.ExtentReports.Reporter.Configuration;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TechTalk.SpecFlow;
namespace ReportDemoPOC
{
public class Start
{
public static ExtentReports extent;
public static ExtentHtmlReporter htmlReporter;
public static ExtentTest test;
static Start()
{
if (extent == null)
{
BasicSetUp();
}
}
[BeforeScenario]
public void Setup()
{
SeleniumDriver.Intitialize();
SeleniumDriver.Navigate();
test = extent.CreateTest(ScenarioContext.Current.ScenarioInfo.Title);
}
[AfterScenario]
public void TearDown()
{
if (ScenarioContext.Current.TestError != null)
{
var error = ScenarioContext.Current.TestError;
var errormessage = "<pre>" + error.Message + "</pre>";
//Add capture screen shot line here
extent.AddTestRunnerLogs(errormessage);
test.Log(Status.Error, errormessage);
test.Fail(errormessage);
}
SeleniumDriver.Close();
}
[OneTimeSetUp]
public static void BasicSetUp()
{
string pth = System.Reflection.Assembly.GetCallingAssembly().CodeBase;
// string pth = System.IO.Directory.GetCurrentDirectory();
string actualPath = pth.Substring(0, pth.LastIndexOf("bin"));
string projectPath = new Uri(actualPath).LocalPath;
Console.WriteLine(" -----------Project Path--------------------------------------");
Console.WriteLine(projectPath);
// string reportPath = projectPath + "Reports\\" + FeatureContext.Current.FeatureInfo.Title + ".html";
string reportPath = projectPath + "Reports\\TestRunReport.html";
// Console.WriteLine("Report Path is " + reportPath);
htmlReporter = new ExtentHtmlReporter(reportPath);
htmlReporter.Configuration().Theme = Theme.Dark;
htmlReporter.Configuration().DocumentTitle = "SpecFlow Test Resport Document";
htmlReporter.Configuration().ReportName = "Feature Run Results";
extent = new ExtentReports();
extent.AttachReporter(htmlReporter);
//extent.LoadConfig(projectPath + "Extent-Config.xml");
}
[AfterFeature()]
public static void EndReport()
{
extent.Flush();
}
}
}
LoginSteps.cs
using NUnit.Framework;
using ReportDemoPOC.Page;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TechTalk.SpecFlow;
namespace ReportDemoPOC.Steps
{
[Binding]
[TestFixture]
class LoginSteps : Start
{
LoginPage loginPage;
[Given(#"I am at Facebook login page")]
public void GivenIAmAtFacebookLoginPage()
{
//Navigate();
loginPage = new LoginPage();
}
[When(#"I enter ashusoni(.*)#gmail\.com in the Email or Phone textbox")]
public void WhenIEnterAshusoniGmail_ComInTheEmailOrPhoneTextbox(String p0)
{
loginPage.enterValueInUser("abcd" + p0 + "#gmail.com");
}
[When(#"I Enter (.*) in the password")]
public void WhenIEnterInThePassword(String p0)
{
loginPage.enterValueInPassword(p0);
}
[When(#"Click on the Login button")]
public void WhenClickOnTheLoginButton()
{
loginPage.clickOnLoginButton();
}
[Then(#"Application should display an error message")]
public void ThenApplicationShouldDisplayAnErrorMessage()
{
Console.WriteLine("Verification");
// loginPage.Shutdown();
}
}
}
It may sound like off topic, but still...
I'm not sure it makes sense to use ExtentReports for you automation frameworkwritten in C#.
Starting from v.4 ExtentReports they don't support it anymore.
The reply from them was that they were going to support only Java.
This is a feature of NUnit 3. You should install the Visual Studio Test Adapter ( https://github.com/nunit/docs/wiki/Visual-Studio-Test-Adapter ) via NuGet package named "NUnit3TestAdapter" to get the OneTimeSetup to work.
Then you can check your implementation of the report :-)
Maybe your report is created in the temporary folder (after some time I found it, using windows search). I have the same when running my tests, using Visual Studio. Try to run your test, using Nunit console application. Download it separately, then run tests using console command
nunit "path to compiled .dll with tests"
In this case, I think you should found reports near .dll file. This happens in my case (using Allure reports).

im getting error of program does not contain a static 'main' method suitable for an entry point

I'm getting an error, "Program does not contain a static 'main' method suitable for an entry point."
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;
namespace ConsoleApplication1
{
class Program<T>
{
List<T> a1 = new List<T>();
public void AddData(T data1)
{
a1.Add(data1);
}
public void Insert(T arrayValue, int arrayPosition)
{
// var key = arrayPosition.ToInt();
var key1 = arrayValue.ToString();
for (int i = 0; i < a1.Count; i++)
{
if (i == arrayPosition)
{
a1.Add(arrayValue);
break;
}
}
}
public void Delete(int arrayPosition)
{
for (int i = 0; i < a1.Count; i++)
{
if (i == arrayPosition)
{
a1.Remove(a1[i]);
break;
}
}
}
public void DisplayData()
{
foreach (T x in a1)
{
Console.WriteLine(x);
}
}
static void Main(string[] args)
{
Program<int> obj = new Program<int>();
obj.AddData(123);
obj.AddData(56);
obj.AddData(34);
obj.AddData(87);
obj.DisplayData();
obj.Insert(125, 3);
obj.DisplayData();
obj.Delete(2);
obj.DisplayData();
}
}
}
Per Microsoft documentation (https://learn.microsoft.com/en-us/dotnet/csharp/misc/cs0402) you cannot put your main function in a generic class. It's strange that this was reported as a warning, and the error was less helpful, but that is your problem.
using System;
using System.Collections.Generic;
namespace ConsoleApplication1
{
public static class Program
{
[STAThread]
public static void Main(string[] args)
{
List<Int32> obj = new List<Int32>();
obj.Add(123);
obj.Add(56);
obj.Add(34);
obj.Add(87);
foreach (Int32 value in obj)
Console.WriteLine(value.ToString());
obj.Insert(3, 125);
foreach (Int32 value in obj)
Console.WriteLine(value.ToString());
obj.RemoveAt(2);
foreach (Int32 value in obj)
Console.WriteLine(value.ToString());
}
}
}
Defining a custom class to handle this tasks looked to me like an overkill. This code should reproduct what you were attempting to do without errors. Anyway, I suggest you to take a look at some basic C# tutorial.

how to add to the list an object of class property in c sharp

I cannot add class instances correctly to a List. It adds only the last object. And when I debug the List vocabulary shows only adding the last class instance. So by second looping it has two entries of second object, by third looping it has three entries of third object. What I am doing wrong. Here is my code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace myVocabulary
{
public class Word
{
string _original_word;
string _translated_word;
public string Original_Word
{
get
{
return this._original_word;
}
set
{
this._original_word = value;
}
}
public string Translated_Word
{
get
{
return this._translated_word;
}
set
{
this._translated_word = value;
}
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace myVocabulary
{
class Program
{
static List<Word> vocabulary = new List<Word>();
static void Main(string[] args)
{
Word entry = new Word();
for (int i = 0; i < 5; i++)
{
Console.WriteLine("Enter word");
entry.Original_Word = Console.ReadLine();
Console.WriteLine("Enter Translation");
entry.Translated_Word = Console.ReadLine();
vocabulary.Add(entry);
}
}
}
}
Try this - You need to create a new Word object with each iteration of your loop, otherwise you're just overwriting the same instance repeatedly.
namespace myVocabulary
{
class Program
{
static List<Word> vocabulary = new List<Word>();
static void Main(string[] args)
{
for (int i = 0; i < 5; i++)
{
Word entry = new Word();
Console.WriteLine("Enter word");
entry.Original_Word = Console.ReadLine();
Console.WriteLine("Enter Translation");
entry.Translated_Word = Console.ReadLine();
vocabulary.Add(entry);
}
}
}
}

Linux Mono + Postsharp + Log4Net = No automated Exception catching

We are developing a C# project with Monodevelop under Linux.
We have added Log4Net(1.2.11.0), Postsharp (4.1.24.0) and also Postsharp for Log4Net to our project via NuGet.
The following code throws an IndexOutOfRangeException:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using PostSharp;
using PostSharp.Aspects;
[System.Diagnostics.DebuggerStepThrough]
[Loggable]
class Program
{
static void Main (string[] args)
{
String[] myArray= new String[] { "X" };
for (int i = 0; i <= 100; i++) {
Console.WriteLine (myArray[i]);
}
}
}
Unfortunately, Postsharp doesn't even catch the exception.
We even tried to replace "[Loggable]" with "[LoggableAttribute]", since the Class' name is like that.
Here it is:
using System;
using System.Collections.Generic;
using System.Linq;
using PostSharp;
using PostSharp.Aspects;
using System.Collections;
[Serializable]
public class LoggableAttribute : OnExceptionAspect
{
public override void OnException(MethodExecutionArgs event_args)
{
Logging.SetExecutionTime(DateTime.Now);
Logging.SetParameter("parameters", ParametersToString(event_args));
Logging.SetParameter("method_name", event_args.Method.Name);
Logging.SetParameter("class_name", event_args.Instance.GetType().ToString());
Logging.Error("Error Encountered in " + event_args.Method, event_args.Exception);
}
private static String ParametersToString(MethodExecutionArgs event_args)
{
String output = "";
if (event_args.Method.GetParameters() != null)
{
for (int i = 0; i < event_args.Method.GetParameters().Length; i++)
{
output += String.Format("[{0} = {1}]", event_args.Method.GetParameters()[i].Name, event_args.Method.GetParameters()[i]);
}
}
return output;
}
}
Even a break point within OnException doesn't help. It doesn't get in there.
PostSharp works fine with mono, I actually use it there for quite some time already. I cannot now test on your mono version (3.2.8 is quite old already), but on 4.0.4 this code runs without problem:
[Loggable]
internal class Program {
private static void Main(string[] args) {
String[] myArray = new String[] {"X"};
for (int i = 0; i <= 100; i++) {
Console.WriteLine(myArray[i]);
}
}
}
[Serializable]
public class LoggableAttribute : OnExceptionAspect {
public override void OnException(MethodExecutionArgs args) {
Console.WriteLine("Caught by postsharp: " + args.Exception);
args.FlowBehavior = FlowBehavior.Continue;
}
}
Outputs "Caught by postsharp: ..." and no exception is thrown. As for log4net, you say yourself that it's not related to your question in any way - your code does not enter block where log4net is used.
So, just update to modern mono version and you'll be fine.

Categories