I'm trying to get status data of my processor on the local machine. I found several tutorials online, but no one of them covers the error I'm getting.
This is my code:
UpdateVisitor visitor = new UpdateVisitor();
Computer computer = new Computer();
computer.Open();
computer.CPUEnabled = true;
computer.Accept(visitor);
It throws an Exception when calling computer.Open() and this is the exception message:
What am i doing wrong? If i can provide some more detail, please let me know.
I'm referencing the library in a .NET Standard 2.0 project.
Solved the problem by referencing the library in a .NET Framework 4.7.1 project, instead that in a .NET Standard 2.0 project. I post this answer just to warn other people trying to achieve this that this library is not fully compatible with .NET Standard code.
I stole this WMI Answer from this question: C# CPU and GPU Temp.
Just install System.Management and start VS in Admin mode, and you can access the sensors.
using System;
using System.Diagnostics;
using System.Management;
class Program
{
static void Main(string[] args)
{
Double CPUtprt = 0;
System.Management.ManagementObjectSearcher mos = new System.Management.ManagementObjectSearcher(#"root\WMI", "Select * From MSAcpi_ThermalZoneTemperature");
foreach (System.Management.ManagementObject mo in mos.Get())
{
CPUtprt = Convert.ToDouble(Convert.ToDouble(mo.GetPropertyValue("CurrentTemperature").ToString()) - 2732) / 10;
Console.WriteLine("CPU temp : " + CPUtprt.ToString() + " °C");
}
}
}
Related
I am trying to create a "Hello World" example in R Language using R.Net version 1.5.5 (loaded from NuGet). Unfortunately, none of the online samples that I have seen work.
THIS IS WHAT I HAVE DONE:
Installed Microsoft R Open 3.2.4, the enhanced R distribution
Installed R Tools for Visual Studio (R version 3.2.4 (2016-03-16))
Created an R Project & tested a simple script
Created an MVC application & referenced R.Net version 1.5.5 from NuGet
MY PROBLEM:
All of the online examples I have seen must be using an earlier version because I cannot create an instance of the REngine for the LIFE of me! In fact, I keep getting:
Dll was not found
...yet C:\Program Files\Microsoft\MRO\R-3.2.4\bin\x64\r.dll does indeed exist.
Q: How do I create an instance of the REngine using R.Net version 1.5.5?
MY CODE LOOKS LIKE:
class Program
{
#region <Methods>
static void Main(string[] args)
{
SetupPath(); // current process, soon to be deprecated
using (REngine engine = REngine.CreateInstance("RDotNet"))
{
engine.Initialize(); // required since v1.5
CharacterVector charVec = engine.CreateCharacterVector(new[] {"Hello, R world!, .NET speaking" });
engine.SetSymbol("greetings", charVec);
engine.Evaluate("str(greetings)"); // print out in the console
string[] a = engine.Evaluate("'Hi there .NET, from the R engine'").AsCharacter().ToArray();
Console.WriteLine("R answered: '{0}'", a[0]);
}
Console.WriteLine("Press any key to exit the program");
Console.ReadKey();
}
public static void SetupPath()
{
var oldPath = System.Environment.GetEnvironmentVariable("PATH");
var rPath = #"C:\Program Files\Microsoft\MRO\R-3.2.4\bin\x64";
if (!Directory.Exists(rPath))
throw new DirectoryNotFoundException(string.Format(" R.dll not found in : {0}", rPath));
var newPath = string.Format("{0}{1}{2}", rPath, System.IO.Path.PathSeparator, oldPath);
System.Environment.SetEnvironmentVariable("PATH", newPath);
}
#endregion
}
I hate to answer my own question, but here it is...
The Microsoft R Open 3.2.4 enhanced R distribution installs x64 files. As such, running under ANY CPU will cause a failure because it will choose x86 (by default).
Under
Project Properties -> Build: in the "General" section
Choose x64 as your Platform Target
I was wondering if there is an online tool that can convert c# code to powershell cmdlet code. I have following code that i need to have it powershell. I dont have visual studio to turn this into an exe or dll. any help or ideas would be great.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
namespace CopyUsersBetweenGroupsInSharepointByRR
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("This tool will copy the users from one group to another group");
Console.WriteLine("Please enter the URL of the site where your groups are available");
String siteUrl = Console.ReadLine();
using (SPSite site = new SPSite(siteUrl))
{
try
{
SPWeb web = site.OpenWeb();
Console.WriteLine("Please enter the name of the source group");
String sourceGroupName = Console.ReadLine();
Console.WriteLine("Please enter the name of the destination group");
String destinationGroupName = Console.ReadLine();
SPGroup sourceGroup = web.Groups[sourceGroupName];
SPGroup destinationGroup = web.Groups[destinationGroupName];
SPUserCollection sourceUsers = sourceGroup.Users;
SPUserInfo[] sourceUserInfoArray = new SPUserInfo[sourceUsers.Count];
for (int i = 0; i < sourceUsers.Count; i++)
{
sourceUserInfoArray[i] = new SPUserInfo();
sourceUserInfoArray[i].LoginName = sourceUsers[i].LoginName;
sourceUserInfoArray[i].Name = sourceUsers[i].Name;
}
destinationGroup.Users.AddCollection(sourceUserInfoArray);
destinationGroup.Update();
web.Update();
Console.WriteLine("Operation Completed Successfully");
Console.ReadLine();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
Console.ReadLine();
}
}
}
}
}
It's comments like those above that are turning people away from SO in droves. The OP's question was unambiguous and displayed genuine need.
There are several ways to achieve this. Rewriting your entire C# code repository is not one of them.
As already discussed, as of PS 2 you are able to either run C# (or most any other language) inline, or refer to well-formed external file. I've had mixed success with this and I don't believe it's what the OP was really after.
If you genuinely want to convert code (particularly compiled assemblies) then a decompiler like Reflector is able to do this and - with the PowerShell addon - is also able to convert it on-the-fly.
http://blog.lekman.com/2011/10/converting-c-to-powershell.html
If you want your input and output to take place within the PS console then you'd still have to perform some obvious re-writes. But this method has proved incredibly useful to me.
The fastest way to do it is to write the PowerShell code yourself.
Below is how the code will look in PowerShell, i would say that most C# developers should be able to grasp the concepts of converting C# code to PowerShell in a very short time.
Functions can be a little odd at the beginning, since the usual PS syntax is
myFunction Parameter1 Parameter2
Also you really should install PowerShell 3.0 and use the Windows PowerShell ISE tool to develop the code.
Anyways it should not take you more than 1-2 hours to get your C# code running along in PowerShell.
[System.Reflection.Assembly]::LoadWithPartialName(”Microsoft.SharePoint”)
Write-Host "This tool will copy the users from one group to another group"
Write-Host "Please enter the URL of the site where your groups are available"
[string] $siteUrl = [Console]::ReadLine()
$site = new-object Microsoft.SharePoint.SPSite($siteUrl)
try
{
$web = $site.OpenWeb()
Write-Host "Please enter the name of the source group"
[string] $sourceGroupName = [Console]::ReadLine()
Write-Host "Please enter the name of the destination group"
[string] $destinationGroupName = [Console]::ReadLine()
$sourceUsers = $web.Groups[$sourceGroupName]
(and so on)
}
catch
{
Write-Error ("Failed to copy sharepoint users." + $_)
}
I doubt there is anything remotely like that, however Visual Studio is not required to compile c# code. You could compile an exe without VS. The compiler (csc.exe) and msbuild are included as part of framework. They are located in C:\Windows\Microsoft.NET\Framework\{version}.
If you really want to call this from powershell, have a look at the Add-Type cmdlet. You provide it the source code and it will compile the source on the fly, then load the assembly into your session.
Not sure about online tools, but download the free Visual Studio Express & follow this tutorial should have you creating a cmdlet in no time
I need to interface R to some C# application. I installed rscproxy_1.3 and R_Scilab_DCOM3.0-1B5 added COM references to the STATCONNECTORCLNTLib, StatConnectorCommonLib and STATCONNECTORSRVLib but I still cannot get it working.
When I run following test program:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
//COM references
using STATCONNECTORCLNTLib;
using StatConnectorCommonLib;
using STATCONNECTORSRVLib;
namespace R_TESTING
{
class Program
{
static void Main(string[] args)
{
StatConnector sc1 = new STATCONNECTORSRVLib.StatConnectorClass();
sc1.Init("R");
}
}
}
I get this exception:
Unhandled Exception: System.Runtime.InteropServices.COMException: Exception from HRESULT: 0x80040013
at STATCONNECTORSRVLib.StatConnectorClass.Init(String bstrConnectorName)
Thanks in advance.
UPDATE:
Ok, still no luck.
I will try to explain what I did so far.
Installed R-2.12.2-win.exe from
rproject to the C:\Program
Files\R\R-2.12.2
Downloaded rscproxy_1.3-1.zip and
copy/pasted it to the C:\Program
Files\R\R-2.12.2\library
Installed R_Scilab_DCOM3.0-1B5.exe to
the C:\Program Files (x86)\R\(D)COM
Server
With Scilab comes a basic test. I tried to run it but I got following error:
Loading StatConnector Server... Done
Initializing R...Function call failed
Code: -2147221485 Text: installation
problem: unable to load connector
Releasing StatConnector Server...Done
Than I looked in the PATH/System Variables and found no path/R_HOME/R_USER info. Also, I couldn't find anything R related in the registry.
I guess I am doing something terribly wrong, so I desperately need help from you guys.
You can have a look at R.NET, for another approach...
Ok, I solved it finally.
The problem is that R (D)Com doesn't work with current version of R. I installed 2.11.1 and it worked out of box.
Thanks a lot.
Use R.NET (I installed mine from NuGet) and the following code in a new C# console app (which was copied with minor changes from http://rdotnet.codeplex.com/).
It will work when pointed at the 32-bit version of R v2.11.1, but it will not work when pointed at the 64-bit version of R v2.11.1 (as noted in the code below).
When I installed NuGet, it automatically added references to the current project: RDotNet (RDotNet.dll) and RDotNet.NativeLIbrary (RDotNet.NativeLibrary.dll). You'll need these references in any new project.
Works under VS2012 (untested under VS2010, but will probably work).
Works when compiled for both "x32" and "All CPU" (under "Build..Configuration Manager" in VS2012).
// Call R from .NET. Advantage is that everything is in process.
// Tested on VS2012, will probably work on VS2010.
using System;
using System.IO;
using System.Linq;
using RDotNet;
class Program
{
static void Main(string[] args)
{
// Set the folder in which R.dll locates.
var envPath = Environment.GetEnvironmentVariable("PATH");
var rBinPath = #"C:\Program Files (x86)\R\R-2.11.1\bin";
//var rBinPath = #"C:\Program Files\R\R-2.11.1-x64\bin"; // Doesn't work ("DLL was not found.")
Environment.SetEnvironmentVariable("PATH", envPath + Path.PathSeparator + rBinPath);
using (REngine engine = REngine.CreateInstance("RDotNet"))
{
// Initializes settings.
engine.Initialize();
// .NET Framework array to R vector.
NumericVector group1 = engine.CreateNumericVector(new double[] { 30.02, 29.99, 30.11, 29.97, 30.01, 29.99 });
engine.SetSymbol("group1", group1);
// Direct parsing from R script.
NumericVector group2 = engine.Evaluate("group2 <- c(29.89, 29.93, 29.72, 29.98, 30.02, 29.98)").AsNumeric();
// Test difference of mean and get the P-value.
GenericVector testResult = engine.Evaluate("t.test(group1, group2)").AsList();
double p = testResult["p.value"].AsNumeric().First();
Console.WriteLine("Group1: [{0}]", string.Join(", ", group1));
Console.WriteLine("Group2: [{0}]", string.Join(", ", group2));
Console.WriteLine("P-value = {0:0.000}", p);
}
}
}
From here:
I think I just remembered how to solve the 80040013 exception. I think it had to do with the fact that my
install of the R files did not include a rscproxy.dll. Somewhere along the way, R changed from using a dll
named (I think) proxy.dll and started using one called rscproxy.dll. You have to find and download
rscproxy.dll to the R\bin folder.
If that doesn't work, check your environment variables to be sure they R_HOME and R_USER values are
pointing to the R\bin folder. Make sure the R (D)Com objects are properly registered with Windows.
Here is how to call a custom R Function from an Rdata file ( not just a built-in R function).
Actually this is what worked for me.
To get StatConnectorClass working, I had to open up the properties for StatConnectorsRVLib and set 'Embed Interop Types' to False.
using StatConnectorCommonLib;
using STATCONNECTORSRVLib;
using STATCONNECTORCLNTLib;
StatConnectorClass rConn = new StatConnectorClass();
try
{
rConn.Init("R"); // here is where we initialize R
Response.Write("Initialized." + "<br />"); Response.Flush();
Response.Write("1" + "<br />"); Response.Flush();
string path = #"C:SOMEPATH\Black-Scholes.RData";
rConn.SetSymbol("path", path);
Response.Write("2" + "<br />"); Response.Flush();
rConn.Evaluate("load(path)");
Response.Write("3" + "<br />"); Response.Flush();
Int16 entry = 27;
rConn.SetSymbol("n1", entry);
Response.Write("6" + "<br />"); Response.Flush();
rConn.Evaluate("x1<-samplefn(n1)" );
Response.Write("Entered : " + entry.ToString() + "<br/> ");
Object o = rConn.GetSymbol("x1");
Response.Write("Ans:" + o.ToString() + "<br />"); Response.Flush();
rConn.Close();
}
catch (Exception ex)
{
Response.Write("Error: " + ex.Message );//+ " xx " + rConn.GetErrorText());
rConn.Close();
}
Hope this helps!
Problem:
Loading StatConnector Server... Done Initializing R...Function call
failed Code: -2147221485 Text: installation problem: unable to load
connector Releasing StatConnector Server...Done
Solution: [By the way, I have R, RStudio, Revolution R in my PC]
1. Install the necessary programs and packages:
For performing exponential smoothing in Eviews (7.2), ExpSmooth add-ins is necessary.
For the ExpSmooth add-ins to properly work, the program R, and the packages forecast and rscproxy must be installed; and statconnDCOM must be installed.
2. Put the files and folders to the correct BIN and LIBRARY locations:
Copy-paste the file rscproxy.dll to the C:\Program Files\R\R-2.15.3\bin and C:\Revolution\R-Enterprise-6.1\R-2.14.2\bin folders.
Put the rscproxy folder in rscproxy_2.0-5.zip file to the C:\Revolution\R-Enterprise-6.1\R-2.14.2\library and C:\Program Files\R\R-2.15.3\library folders.
3. Additional info:
I did not make any changes to environment variables to overcome the problem in question.
I had set some environment variables for the first time when I installed R and Revolution R like that (this setting is irrelavant with the context here):
System variables - Path:
C:\Rtools\bin;C:\Program Files\R\R-3.0.2\bin\i386;C:\Rtools\gcc-4.6.3\bin;
(I offer you to set the R version that you installed and use).
Run Server 01 – Basic Test that existed upon installing statconnDCOM: Start - statconn – DCOM - “Server 01 – Basic Test”.
Press to R.
statconnDCOM worked.
Not to beat the dead horse, however, I am looking for a way to detect the installed .NET frameworks. It seems like the provided solutions (in the links) are all good up until the point a new version of the framework is released and then all bets are off. The reason for this is that the detection relies on the registry keys and it seems that v4 of the framework has broken the convention and one now has to take extra steps to detect v4.
Is there a way to detect the .NET framework that will also work when .NET v5 appears.
EDIT: Ok, for future generations of frustrated .NET Version seekers, here is the code to make it happen:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Diagnostics;
using Microsoft.Win32;
private List<string> GetInstalledDotNetFrameworks()
{
string key = string.Empty;
string version = string.Empty;
List<string> frameworks = new List<string>();
var matches = Registry.LocalMachine
.OpenSubKey(#"SOFTWARE\Microsoft\NET Framework Setup\NDP")
.GetSubKeyNames().Where(keyname => Regex.IsMatch(keyname, #"^v\d"));
// special handling for v4.0 (deprecated) and v4 (has subkeys with info)
foreach (var item in matches)
{
switch (item)
{
case "v4.0": // deprecated - ignore
break;
case "v4":// get more info from subkeys
key = #"SOFTWARE\Microsoft\NET Framework Setup\NDP\" + item;
string[] subkeys = Registry.LocalMachine
.OpenSubKey(key)
.GetSubKeyNames();
foreach (var subkey in subkeys)
{
key = #"SOFTWARE\Microsoft\NET Framework Setup\NDP\" + item + #"\" + subkey;
version = Registry.LocalMachine
.OpenSubKey(key)
.GetValue("Version").ToString();
version = string.Format("{0} ({1})", version, subkey);
frameworks.Add(version);
}
break;
case "v1.1.4322": // special case, as the framework does not follow convention
frameworks.Add(item);
break;
default:
try
{
// get the Version value
key = #"SOFTWARE\Microsoft\NET Framework Setup\NDP\" + item;
version = Registry.LocalMachine
.OpenSubKey(key)
.GetValue("Version").ToString();
frameworks.Add(version);
}
catch
{
// most likely new .NET Framework got introduced and broke the convention
}
break;
}
}
// sort the list, just in case the registry was not sorted
frameworks.Sort();
return frameworks;
}
In short, you can use this approximately (see below for more complete solution):
Microsoft.Win32.Registry.LocalMachine
.OpenSubKey(#"SOFTWARE\Microsoft\NET Framework Setup\NDP")
.GetSubKeyNames().Where(keyname=>Regex.IsMatch(keyname,#"^v\d"))
On my machine, this returns: v2.0.50727, v3.0, v3.5, v4, v4.0. Subkeys could be used to detect service packs (which are probably relevant). Also, using the key SOFTWARE\Microsoft\.NETFramework returns v2.0.50727, v3.0 and v4.0.30319 - ehhh, lovely, slightly different!
There's no guarantee this pattern will hold, but it's a pretty reasonable bet :-). http://support.microsoft.com/kb/318785 has some more info on the details of the registry describing the versioning, and in particular, you may need to check for Install - but that's tricky as v4.0 demonstrates.
Edit: I've extended this to detect arbitrary sub-key's of the registry that include installation info so as to detect v4 Client and Full profiles correctly. Also, the RegistryKey type is IDisposable, and it looks like the Dispose method is indeed doing something (registry key unlocking).
var versionList = new List<string>();
using(var ndpKey=Registry.LocalMachine.OpenSubKey(#"SOFTWARE\Microsoft\NET Framework Setup\NDP")) {
Action<RegistryKey, Action<RegistryKey,string>> processKids = (node, action) => {
foreach(var childname in node.GetSubKeyNames())
using(var child = node.OpenSubKey(childname))
action(child,childname);
};
Action<RegistryKey, Func<RegistryKey, bool>> visitDescendants = null;
visitDescendants = (regkey, isDone) => {
if(!isDone(regkey))
processKids(regkey, (subkey, subkeyname)=>visitDescendants(subkey,isDone));
};
processKids(ndpKey, (versionKey, versionKeyName) => {
if(Regex.IsMatch(versionKeyName,#"^v\d")) {
visitDescendants(versionKey, key => {
bool isInstallationNode = Equals(key.GetValue("Install"), 1) && key.GetValue("Version") != null;
if(isInstallationNode)
versionList.Add(
key.Name.Substring(ndpKey.Name.Length+1)
+ (key.GetValue("SP")!=null ? ", service pack "+ key.GetValue("SP"):"")
+ " ("+key.GetValue("Version") +") "
);
return isInstallationNode;
});
}
});
}
versionList then contains:
v2.0.50727, service pack 2 (2.0.50727.4927)
v3.0, service pack 2 (3.0.30729.4926)
v3.5, service pack 1 (3.5.30729.4926)
v4\Client (4.0.30319)
v4\Full (4.0.30319)
Do you expect we can tell you the future? :) Why do you need that in the first place? I mean, if you write an app for v4, what difference does it make if v5 is installed or not? You can specify in the app.config what versions you support, but you can't know in advance what the next version will be, or even if your app will run on that. Whenever a new framework comes out, you'll have to test your app, and decide if you want to migrate or not. If you migrate, then you make changes to the app.config and possibly the code, too, and release a new version. If you don't, then you'll still require that an older framework version be installed. It's not like v5 comes out and people will start uninstalling all the previous frameworks. I still have v1.1 and v2 on my machine and I guess they'll stick around for a while.
I am in agreement with fejesjoco. Why do you even want to detect a future version that your code has not been compiled against?
If you look in the Framework folder (C:\Windows\Microsoft.NET\Framework) you will see that all previous versions of the Framework are install along with the most recent version. If your code is compiled against 4.0 and 5.0 comes out it will still have a folder for 4.0.
If you could give us a bit more context as to why you want to detect future versions we may be able to help you better.
Include an auto-update feature in the detection tool?
Is there a way to enable the ASP.NET Web Service Extension in IIS6 via C#? I'm trying to simplify a website setup program for people who haven't used IIS before.
C# NET. Framework usage:
Process.Start(#"C:\Windows\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis", "-i -enable");
CMD usage:
C:\Windows\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis -i -enable
It's useful.
Source: https://serverfault.com/questions/1649/why-does-iis-refuse-to-serve-asp-net-content
You could call out to WMI easily enough (System.Management namespace, IIRC) and I believe you can set it from there. However, it may well be much simpler to set it manually, you can't do it from within an ASP.NET site since your server won't be able to run it until it is set...
Principles of doing something similar may be found here
Looking around all the examples of this are written in vbscript. So I cheated and came up with this function:
static void EnableASPNET()
{
var file = "wmi.vbs";
using (var writer = new StreamWriter(file))
{
writer.WriteLine("Set webServiceObject = GetObject(\"IIS://localhost/W3SVC\")");
writer.WriteLine("webServiceObject.EnableWebServiceExtension \"ASP.NET v2.0.50727\"");
writer.WriteLine("webServiceObject.SetInfo");
}
var process = Process.Start("cscript", file);
process.WaitForExit();
File.Delete(file);
}
// if windows 2003
if (Environment.OSVersion.Version.Major == 5 &&
Environment.OSVersion.Version.Minor == 2)
{
DirectoryEntry folderRoot = new DirectoryEntry("IIS://localhost/W3SVC");
folderRoot.Invoke("EnableWebServiceExtension", "ASP.NET v2.0.50727");
}
Copied from: http://lastdon.blogspot.com/2006/12/setup-web-application-on-windows-2003.html
I believe you can also run the following command line:
C:\Windows\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis.exe -s W3SVC
And this will recursively enable the AND.NET framework v2.0.50727 for all configured websites.