With the below code I get thee following error:
NinjaSteps.cs(16,13): error CS0103: The name 'ninja' does not exist in the current context
The command line I use to compile is:
csc /target:library /reference:C:\Ruby193\lib\ruby\gems\1.9.1\gems\
cuke4nuke-0.4.0\dotnet\Cuke4Nuke.Framework.dll /reference:C:\Fitnesse\FitNesseRo
ot\jediwhale-fitsharp-a78d820\binary\tools\nunit\framework\nunit.framework.dll /
reference:C:\Users\Rahul\Documents\Visual~1\Projects\ConsoleApplication3\Console
Application3\Ninja.dll NinjaSteps.cs
The code I am trying to compile is from a tutorial on Cucumber automation technology:
NinjaSteps.cs:
http://cuke4ninja.com/sec_ninja_survival_net.html
using System;
using System.Collections.Generic;
using System.Text;
using Cuke4Nuke.Framework;
using NUnit.Framework;
using NinjaSurvivalRate;
namespace ConsoleApplication3
{
class NinjaSteps
{ [Given(#"^the ninja has a ([a-z]*) level black-belt$")]
public void TheNinjaHasABlackBelt(String level)
{ ninja = new Ninja(level);
}
[When(#"^attacked by [a\s]*(.*)$")]
public void AttackedBy(String opponent)
{
actions = ninja.AttackedBy(opponent);
}
[Then("^the ninja should (.*)$")]
public void TheNinjaShould(String action)
{
Assert.IsTrue(actions.Contains(action));
}
}
}
Ninja.cs is below, compiled to Ninja.dll:
using System;
using System.Collections.Generic;
//using System.Linq;
using System.Text;
namespace NinjaSurvivalRate
{
public class Ninja
{
public Ninja(String beltLevel)
{
}
public List<String> AttackedBy(String opponent)
{
if ("Chuck Norris" == opponent)
return new List<string>(
new String[] { "run for his life" });
else
return new List<string>(
new String[] { "engage the opponent" });
}
}
}
Answers and feedback will be appreciated. Going through similar threads, I found that the resolution depended on a case by case basis and their was no consistent root cause, and felt I had to detail exact code details to get an understanding of the cause. You time and help will be greatly appreciated. Thanks.
You haven't defined the variable ninja. You need:
var ninja = new Ninja(level);
Do the same for actions.
EDIT:
Actually both the variables are supposed to be fields/properties in the class itself, if I understand your intentions correctly.
The tutorial is not telling you the whole history. If you go to the source code you will see that there is actually a field ninja declared that is initialized in the method TheNinjaHasABlackBelt (that you already have).
Related
Xamarin forms newbie here, and I am trying to establish an SQLite connection so that I may interact with a created database in my application.
I get no flags on this in the IDE, but when I compile, I'm getting a null reference error! Specifically, my _SQLiteConnection var is null, and I think it may have something to do with not setting the path properly?
I've referenced a few guides on doing this online, and although a little dated, they go about setting this up in the same manner I am.
Heres some code:
UserDb.cs:
using PluralBuddy.Models;
using SQLite;
using System.Collections.Generic;
using System.Linq;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace PluralBuddy.Data
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public class UserDB
{
private SQLiteConnection _SQLiteConnection;
public UserDB()
{
_SQLiteConnection = DependencyService.Get<ISQLiteInterface>().GetConnection();
_SQLiteConnection.CreateTable<User>();
}
ISQLiteInterface.cs:
using SQLite;
namespace PluralBuddy.Models
{
public interface ISQLiteInterface
{
SQLiteConnection GetConnection();
}
}
References:
https://code.tutsplus.com/tutorials/an-introduction-to-xamarinforms-and-sqlite--cms-23020
https://dzone.com/articles/register-and-login-using-sqlite-in-xamarinforms
As always, any help is appreciated!
So for anyone who stumbles across this post looking for an answer to a similar problem, make sure that you are initializing your database and giving it a path. Be very careful following guides as they will often leave out vital context, either on purpose or by mistake.
Here is what I did
in App.Xaml
using PluralBuddy.Data;
using PluralBuddy.Views;
using System;
using System.IO;
using Xamarin.Forms;
namespace PluralBuddy
{
public partial class App : Application
{
static UserDB userDB;
public static UserDB UserDB
{
get
{
if (userDB == null)
{
userDB = new UserDB(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "user.db3"));
}
return userDB;
}
}
UserDB.cs
namespace PluralBuddy.Data
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public class UserDB
{
private readonly SQLiteConnection _SQLiteConnection;
public UserDB(string dbPath)
{
_SQLiteConnection = new SQLiteConnection(dbPath);
_SQLiteConnection.CreateTable<User>();
}
and just in case anyone needs it, here is a more up to date guide from one of the same guys as referenced in the original post:
https://xmonkeys360.com/2019/07/10/register-login-and-update-using-sqlite-in-xamarin-forms/
.......So, I have the below class which I have created as part of my automated test pack, but I am getting an error against the 'ListPostsPage.GoTo(PostType.Page)' line of code, advising that: 'the name PostType does not exist in the current context'. The code for this class is below:
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WordpressTests
{
[TestClass]
public class PageTests
{
[TestInitialize]
public void Init()
{
Driver.Initialise();
}
[TestMethod]
public void CanEditAPage()
{
LoginPage.GoTo();
LoginPage.LoginAs("XXXXXX").WithPassword("XXXXXX").Login();
**ListPostsPage.GoTo(PostType.Page);**
ListPostsPage.SelectPost("Sample Page");
Assert.IsTrue(NewPostPage.IsInEditMode(), "Wasn't in edit mode");
Assert.AreEqual("Sample Page", NewPostPage.Title, "Title did not match");
}
[TestCleanup]
public void Cleanup()
{
Driver.Close();
}
}
}
Just for reference, the code for the ListPostsPage class is as follows:
using OpenQA.Selenium;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WordpressTests
{
public class ListPostsPage
{
public static void GoTo(PostType postType)
{
switch (postType)
{
case PostType.Page:
Driver.Instance.FindElement(By.Id("menu-pages")).Click();
Driver.Instance.FindElement(By.LinkText("All Pages")).Click();
break;
}
}
public static void SelectPost(string title)
{
var postLink = Driver.Instance.FindElement(By.LinkText("Sample Page"));
postLink.Click();
}
public enum PostType
{
Page
}
}
}
Does anyone have any ideas as to what the issue may be? Please bear in mind I am fairly new to this, so please be nice! :-)
Any help would be much appreciated.
Cheers
Andy
PostType is an enum member of ListPostsPage but you're trying to access it as if it were a static class.
You should do this:
ListPostsPage.GoTo(ListPostsPage.PostType.Page);
A bit rusty here with regards to WCF Services.
I have a custom class named cSecurity.cs which does some custom functions.
I want to use this custom class inside my Service:
This is the App.svc.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
namespace AppServices
{
public class App : IApp
{
public cSecurity _csec;
public string GetItems(int agentID, string agentName)
{
// Need to use some functions from the cSecurity class here???
return _csec.getItems();
}
}
}
This is the cSecurity.cs class:
using System.Collections;
using System.Configuration;
using System.Net;
namespace AppServices
{
public class cSecurity
{
// Some functions defined here....
public string getItems(){
return string.Empty;
}
}
}
But I am getting an error on the line:
public cSecurity _csec;
"The type or namespace name 'cSecurity' could not be found."
This seems pretty trivial but I seem to be lost here.
Appreciate any insight. Thanks.
For some reason, the solution for this was for me to close and restart VS. Not sure what caused the class for it to be not referenced by VS.
I am trying to use ManagementEventWatcher in a service to keep track of when a computer goes in and out of sleep mode. I am new to .NET and C# so I am struggling quite a bit to come up with syntax to make this work.
I have found a blog post that details how he used ManagementEventWatcher to keep track of this status, but he did not post up his entire code. I am trying to go through and make a simple service that creates a .txt log file stating that the computer has been suspended/resumed but am running into problems with the namespaces and types.
Here is the code to the service.cs file:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Management;
namespace SleepNotifierService
{
public class WqlEventQuery : EventQuery { }
public partial class Service1 : ServiceBase
{
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
WqlEventQuery query = new WqlEventQuery("Win32_PowerManagementEvent");
_watcher = new ManagementEventWatcher(query);
_watcher.EventArrived += new EventArrivedEventHandler(watcher_EventArrived);
_watcher.Start();
}
protected override void OnStop()
{
_watcher.Stop();
}
void watcher_EventArrived(object sender, EventArrivedEventArgs e)
{
try
{
int eventType = Convert.ToInt32(e.NewEvent.Properties["EventType"].Value);
switch (eventType)
{
case 4:
Sleep();
break;
case 7:
Resume();
break;
}
}
catch (Exception ex)
{
//Log(ex.Message);
}
}
public void Sleep()
{
}
public void Resume()
{
}
}
}
Again, this is the first time that I am programming with .NET and C# so I apologize for my ignorance.
I am getting namespace errors such as:
The type or namespace name
'ManagementEventWatcher' could not be
found (are you missing a using
directive or an assembly reference?)
Thanks,
Tomek
You need the System.Management namespace, which is included in the code sample provided by you. I believe you need to reference the System.Management library in your project settings. Follow the following steps to do this( I am assuming you are suing Visual Studio):
Go to the Solution Explorer, and expand your project, right click on the References folder/option and select Add References from the context menu. Now select the .Net tab and select the System.Management from the list and click OK.
I'm experimenting with MEF and created a test program to call "plugins" that implement some given interface, which follows:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ProbeContract
{
public interface IProbe
{
int DoProbe(string what);
List<string> GetCapabilities();
}
}
I created a sample console program which loads the "plugins" from its own assembly and, if any found, from a diretory in which one puts additional DLLs. The program works OK whether the plugins directory is empty (only the "native" plugins are called) or it has compatible DLLs to start with. BUT... if a new DLL is added between loop iterations, the Refresh() method of DirectoryCatalog throws a ChangeRejectedException, which is explained thusly:
The composition remains unchanged. The
changes were rejected because of the
following error(s): The composition
produced a single composition error.
The root cause is provided below.
Review the CompositionException.Errors
property for more detailed
information.
1) Change in exports prevented by
non-recomposable import
'MEFTest.Program.ProberSet
(ContractName="ProbeContract.IProbe")'
on part 'MEFTest.Program'.
The program is below, follow by the code for the DLL I try to add. What am I doing wrong?
using System;
using System.IO;
using System.Reflection;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ProbeContract;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
namespace MEFTest
{
class Program
{
[ImportMany]
IEnumerable<IProbe> ProberSet { get; set; }
CompositionContainer exportContainer;
DirectoryCatalog pluginCatalog;
AggregateCatalog catalog;
private void Run()
{
catalog = new AggregateCatalog();
catalog.Catalogs.Add(new AssemblyCatalog(Assembly.GetExecutingAssembly()));
string myExecName = Assembly.GetExecutingAssembly().Location;
string myPath = Path.GetDirectoryName(myExecName);
pluginCatalog = new DirectoryCatalog(myPath + "/Plugins");
catalog.Catalogs.Add(pluginCatalog);
exportContainer = new CompositionContainer(catalog);
CompositionBatch compBatch = new CompositionBatch();
compBatch.AddPart(this);
compBatch.AddPart(catalog);
exportContainer.Compose(compBatch);
for (; ; )
{
Console.Write("Press any key to run all probes: ");
Console.ReadKey(true);
Console.WriteLine();
pluginCatalog.Refresh();
foreach (var Prober in ProberSet)
{
Prober.DoProbe("gizmo");
}
}
}
static void Main(string[] args)
{
Program p = new Program();
p.Run();
}
}
}
The plugin. The other two plugins are similar, the only difference being they reside in the same assembly as the main program:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.Composition;
using ProbeContract;
namespace OtherProbes
{
[Export(typeof(IProbe))]
public class SpankyNewProber : IProbe
{
public int DoProbe(string what)
{
Console.WriteLine("I'm Spanky and New and I'm probing [{0}]", what);
return 0;
}
public List<string> GetCapabilities()
{
List<string> retVal = new List<string>();
retVal.Add("spanky");
retVal.Add("new");
return retVal;
}
}
}
I'm assuming you are using MEF preview 6 because you are seeing rejection exceptions. The reason you are seeing the change being rejected is because your ProberSet is not recomposable. Try changing your ProberSet import to:
[ImportMany(AllowRecomposition=true)]
IEnumerable<IProbe> ProberSet { get; set; }
Doing so will allow for new IProbe exports to be introduced into the Catalog/Container after this import has already been composed.
The idea here is that once you get a stable composition we reject any changes that could potentially destablize that composition and in your case you stated you want a set of non-recomposable IProbe objects so adding new IProbe's after it was intially set would violate that requirement.