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.
Related
I try to unit-test a Gui application code that uses
Application.Current.Dispatcher.Invoke() and would like to use the solution provided by #informatorius in the similar thread Using the WPF Dispatcher in unit tests. The code is listed below.
The problem I have is that Application is not resolved, even if I add using System.Windows. Is there some special mechanism to resolve
Application from within a class library that defines the testcases ?
I have the MSTest.TestFramework and MSTest.TestAdapter packages installed.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Threading.Tasks;
using Microsoft.VisualStudio.TestTools.UnitTesting;
[TestClass]
public class ApplicationInitializer
{
[AssemblyInitialize]
public static void AssemblyInitialize(TestContext context)
{
var waitForApplicationRun = new TaskCompletionSource<bool>();
Task.Run(() =>
{
var application = new Application();
application.Startup += (s, e) => { waitForApplicationRun.SetResult(true); };
application.Run();
});
waitForApplicationRun.Task.Wait();
}
[AssemblyCleanup]
public static void AssemblyCleanup()
{
Application.Current.Dispatcher.Invoke(Application.Current.Shutdown);
}
}
[TestClass]
public class MyTestClass
{
[TestMethod]
public void MyTestMethod()
{
// implementation can access Application.Current.Dispatcher
}
}
Answer pointed me into the right direction:
using System.Windows is not enough, I also needed to add reference to PresentationFramework to the project. Dont really understand the auto magic behind that.
I recently inherited another vendor's project and I am trying to turn it into a usable Visual Studio 2010 solution.
The error I'm currently running into is:
Make sure that the class defined in this code file matches the
'inherits' attribute, and that it extends the correct base class (e.g.
Page or UserControl).
I have found this question posed several other times, but none of the solutions seem to work in this case. Below is the code in question:
~/layouts/Header.ascx.cs
using System;
using Client._Classes.Global;
using Client._Classes.Helpers;
using Client._Classes.Utilities;
namespace Layouts.layouts_Header
{
public partial class layouts_Header : BaseControl
{
private void Page_Load(object sender, EventArgs e)
{
}
protected void lnkSignIn_OnClick(object sender, EventArgs e)
{
Session["CurrentPageURL"] = Sitecore.Context.RawUrl;
Response.Redirect("/en/Community/Register.aspx");
}
protected void btnSearchSubmit_OnClick(object sender, EventArgs e)
{
string redirectURL = "/en/Search%20Results.aspx?cx=005917832522243245879:kpcudcaotoo&cof=FORID:11&ie=UTF-8&q=" + txtSearchQueryStr.Text;
Response.Redirect(redirectURL);
}
}
}
~/layouts/Header.ascx
<%# Control Language="C#" AutoEventWireup="true" CodeFile="~/layouts/Header.ascx.cs" Inherits="Layouts.layouts_Header.layouts_Header" %>
BaseControl.cs
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI.WebControls;
using System.Globalization;
using Sitecore.Data.Items;
using Sitecore.Diagnostics;
using Sitecore.Web;
using Sitecore.SharedSource.Data.Comparers.ItemComparers;
using Sitecore.Data.Fields;
using Sitecore.SharedSource.Searcher;
using Sitecore.SharedSource.Searcher.Parameters;
using Sitecore.SharedSource.Searcher.Utilities;
using Sitecore.Collections;
using Client._Classes.Utilities;
using Client._Classes.Helpers;
using Client._Classes.Global;
namespace Client._Classes.Global
{
public class BaseControl : System.Web.UI.UserControl
{
...
}
}
It should be noted that several other .ascx controls inherit from BaseControl as well, and there does not appear to be any issues.
I think that the problem is that your namespace name ends with your class name:
namespace Layouts.layouts_Header
{
public partial class layouts_Header // * snip *
Try removing the layouts_Header part from your namespace and then change the value of the Inherits attribute to Layouts.layouts_Header
It appears that the solution provided to me contained a folder structure as such:
/temp/installation_history/681FBB6D58774C7D96B37D1353B7441E/layouts
which contained copies of Header.ascx and Header.ascx.cs. I discovered these files when I excluded the actual copies from Header.ascx and Header.ascx.cs from my project.
Once I removed the temp folder and all of its contents, the solution compiled. Thanks everyone for the advice.
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).
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.
I am trying to learn how to use CefSharp as a browser in c# (unless anyone can suggest any better alternatives).
Initially I set the configuration to Any CPU (and edited the .csproj and app.config) , but the browser didn't display any content, instead it just shows a white/grey screen.
I then tried changing the configuration to x64 (as my PC is x64), but after doing got the following errors:
The type or namespace name 'Winforms' does not exist in the
namespace 'CefSharp'
The type or namespace name 'ChromiumWebBrowser' could not be found
The "FindUnderPath" task was not given a value for the required parameter
"Path".
The OutputPath property is not set for project 'cef.csproj'. Please check
to make sure that you have specified a valid combination of Configuration
and Platform for this project. Configuration='Debug' Platform='x64'. This
error may also appear if some other project is trying to follow a project-
to-project reference to this project, this project has been unloaded or is
not included in the solution, and the referencing project does not build
using the same or an equivalent Configuration or Platform.
My code is:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using CefSharp;
using CefSharp.WinForms;
namespace WindowsFormsApp3
{
public partial class Form1 : Form
{
public ChromiumWebBrowser chrome;
public Form1()
{
InitializeComponent();
InitializeChromium();
}
private void Form1_Load(object sender, EventArgs e)
{
}
public void InitializeChromium()
{
CefSettings settings = new CefSettings();
Cef.Initialize(settings);
string url = "https://www.google.co.uk/";
chrome = new ChromiumWebBrowser(url);
this.pContent.Controls.Add(chrome);
chrome.Dock = DockStyle.Fill;
}
private void pContent_Paint(object sender, PaintEventArgs e)
{
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
Cef.Shutdown();
}
}
}
Any help or suggestions are greatly appreciated.