How can I determine the SATA channel for a given disk? - c#

Using DISKPART command line utility, I can get something called a "Location path" which appears to give me what I need, you can view this by using the command detail disk after selecting one of your disks in diskpart.
It appears I can get this information programatically via this class: MSFT_Disk
I am unsure about how to get an instance of this class. I have a few examples of using a ManagementObjectSearcher for WMI classes but that method is not working for me, I am also unsure of MSFT_Disk's availability in Windows 7 as the page mentions that this is for Windows 8.
Does anyone know of a good way to get SATA channel information or the "location path" of a disk?

If you want to not require Windows 8, I believe WMI is the way to go:
using System;
using System.Linq;
using System.Management;
namespace DiskScanPOC
{
class Program
{
static void Main()
{
var managementScope = new ManagementScope();
//get disk drives
var query = new ObjectQuery("select * from Win32_DiskDrive");
var searcher = new ManagementObjectSearcher(managementScope, query);
var oReturnCollection = searcher.Get();
//List all properties available, in case the below isn't what you want.
var colList = oReturnCollection.Cast<ManagementObject>().First();
foreach (var property in colList.Properties)
{
Console.WriteLine("Property: {0} = {1}", property.Name, property.Value);
}
//loop through found drives and write out info
foreach (ManagementObject oReturn in oReturnCollection)
{
Console.WriteLine("Name : " + oReturn["Name"]);
Console.WriteLine("Target Id: " + oReturn["SCSITargetId"]);
Console.WriteLine("Port: " + oReturn["SCSIPort"]);
}
Console.Read();
}
}
}
I didn't crack open my case to verify the SATA port numbers, but the above app looks like it gives reasonable results on my machine with 3 SATA hard drives.

If you want to get the location path, SetupDiGetDeviceRegistryProperty is the function you're looking for. Set the property value to SPDRP_LOCATION_INFORMATION.
I'm assuming you already know how to enumerate devices to get the DeviceInfoSet and DeviceInfoData.

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 System.Management;
namespace Hard_Disk_Interface
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnCheck_Click(object sender, EventArgs e)
{
WqlObjectQuery q = new WqlObjectQuery("SELECT * FROM Win32_IDEController");
ManagementObjectSearcher res = new ManagementObjectSearcher(q);
lblHDDChanels.Text = string.Empty;
foreach (ManagementObject o in res.Get())
{
string Caption = o["Caption"].ToString();
lblHDDChanels.Text += Caption + "\n\n";
if (Caption.Contains("Serial"))
{
lblInterface.Text = "S-ATA";
}
}
}
}
}
Note: First Add the reference of System.Management.dll of .net freamwork 4.0

Related

Get all connected device information

I want to get all information of connected devices as the below picture using C# (device name, location, status is required).
https://i.stack.imgur.com/8cFXs.png
Please help me with this issue.
Retrieve using WMI.
You need to install System.Management from nuget.
Computer System Hardware Classes
Here is an example of getting keyboard information.
It is unclear how Location is obtained, but it is probably determined from the DeviceID string.
using System;
using System.Management;
using System.Runtime.Versioning;
internal class Program
{
[SupportedOSPlatform("windows5.0")]
private static void Main()
{
var scope = new ManagementScope("\\\\.\\ROOT\\cimv2");
var query = new ObjectQuery("SELECT * FROM Win32_Keyboard");
using (var sercher = new ManagementObjectSearcher(scope, query))
using (var queryCollection = sercher.Get())
{
foreach (var o in queryCollection)
{
Console.WriteLine(o["Description"].ToString());
Console.WriteLine(o["Status"].ToString());
Console.WriteLine(o["DeviceID"].ToString());
o.Dispose();
}
}
}
}

RallyApi.Net Getting Workspaces from a Subscription Version 2.0

Following this link How to obtain a list of workspaces using Rally REST .NET
I tried the example however when I try to query against sub["Workspaces"] I get the error
RuntimeBinderException was unhandled;
The best overloaded method match for 'Rally.RestApi.RallyRestApi.Query(Rally.RestApi.Request)' has some invalid arguments
I cannot find any other ways to gather a list of workspaces from the subscription using the RallyApi dll for .Net which I obtained from the link provided.
Any help will be much appreciated.
Try to modify that code as follows:
Request wRequest = new Request(sub["Workspaces"]);
QueryResult queryResult = restApi.Query(wRequest);
Here is an entire app:
using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
using Rally.RestApi;
using Rally.RestApi.Response;
namespace Rest_v2._0_test
{
class Program
{
static void Main(string[] args)
{
//Initialize the REST API
RallyRestApi restApi;
restApi = new RallyRestApi("user#co.com", "secret", "https://rally1.rallydev.com", "v2.0");
//get the current subscription
DynamicJsonObject sub = restApi.GetSubscription("Workspaces");
Request wRequest = new Request(sub["Workspaces"]);
//query the Workspaces collection
QueryResult queryResult = restApi.Query(wRequest);
foreach (var result in queryResult.Results)
{
var workspaceReference = result["_ref"];
var workspaceName = result["Name"];
Console.WriteLine( workspaceName + " " + workspaceReference);
}
}
}
}

C# - Prevent duplicate retrieval of posts

i'm rather new and am trying to create a C# program that retrieves post from Facebook using FB API.
I have a word count feature which checks against a negative word dictionary.
This means that it would display the negative word along with its frequency occurrence.
The problem i'm facing now is that, i want to display the posts that contains this negative words. However, if the negative word exists 3 times in the post, the post would appear thrice. How do i solve this problem?
Below is my code:
(For designer)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace empTRUST
{
public partial class PostAnalysis : Form
{
DBStatusDL ad;
string target_fbid;
public PostAnalysis(string target_fbid)
{
InitializeComponent();
this.target_fbid = target_fbid;
ad = new DBStatusDL();
}
private void button_Displayposts_Click(object sender, EventArgs e)
{
int i = 1;
var dir = new DirectoryInfo(Application.StartupPath + "\\Dictionary"); //Load the dictionary from debug folder
var ed = new matchingWordsWithPosts();
var rows = ad.LoadStatus(target_fbid); //Call the load status function based on fb_id
foreach (FileInfo file in dir.GetFiles()) //For loop, to loop through files
{
var dict = File.ReadAllLines(dir.FullName + "\\" + file);
foreach (var row in rows)
{
List<DataRow> words = ed.countWordsInStatus(row, dict); // Retrieves word dictionary returned from function
foreach (var word in words)
{
var item = new ListViewItem(new[] { i.ToString() ,word["Status_message"].ToString(), word["Status_time"].ToString() });
listViewPosts.Items.Add(item);
i++;
}
}
}
}
private void button_Back_Click(object sender, EventArgs e)
{
this.Close();
var abc = new AnalysisPage(target_fbid);
abc.Show();
}
}
}
(For class)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Data;
namespace empTRUST
{
class matchingWordsWithPosts
{
public List<DataRow> countWordsInStatus(DataRow status, string[] dictArray)
{
List<DataRow> statusList = new List<DataRow>();
var words = new Dictionary<string, int>(StringComparer.CurrentCultureIgnoreCase); // local word dictionary is created here
foreach (var dictEntry in dictArray)
{
var wordPattern = new Regex(#"\w+");
string smallDictEntry = dictEntry.ToLower();
foreach (Match match in wordPattern.Matches(status["Status_message"].ToString()))
{
if (match.ToString() == smallDictEntry)
{
statusList.Add(status);
}
}
}
return statusList; // returns local word dictionary to receiving end
}
}
}
Because you didn't provide the countWordsInStatus() function, I can't know if that's the problem. However, it looks like the problem is that that function continues going through a post even if it has already matched one such word. To fix this, you could put continue; (or perhaps a break;, depending on the code you're using) after adding a post to the list you're returning. This would have the loop skip to the next post, and make sure it doesn't continue counting words in the post that has already had a match.
If you post that function, it should be much easier to understand the issue.
After a word is matched and you process the post exit the loop.

Search For Win32_Directory using the Volume Guid

I am trying to check if a directory exists on a remote computer by using the Volume GUID rather than the Volume Name. Is there any way in WMI to accomplish this? I have a tried a few different approaches but my WQL syntax never seems to be correct, most likely becuase of poor character escaping. Below is one of my attempts at the problem:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Management;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
ObjectQuery query = new ObjectQuery("Select * From Win32_Directory Where Name=\"" + #"\\\\?\\Volume{10b4259b-f659-11df-b8cc-806e6f6e6963}\\test" + "\"");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
ManagementObjectCollection coll = searcher.Get();
foreach (ManagementObject mo in coll)
{
Console.Write("found");
}
Console.Read();
}
}
}
When I execute this code, I receieve an Invalid Query exception. I have tried numerous Powershell attempts at this query and have received the same Invalid Query exception as well. Has anyone attempted this in the past or is it even possible?
Thanks,
Chris

Is there a tool that allows easy exporting of messages from a message queue (MSMQ)?

I am currently working on batch processing application using MSMQ in C#. In the application design, I have an error queue containing XML messages using the ActiveXFormatter. I know that I can write an application to write these error messages to text files or database tables.
Are there other pre-built tools available allowing you to export messages to variety of formats (i.e. text files, database tables, etc.)? I am just looking for best practices.
Ok. I found the solution of writing code to be really easy. Here's my reference solution.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Messaging;
namespace ExportMSMQMessagesToFiles
{
public partial class frmMain : Form
{
public frmMain()
{
InitializeComponent();
}
private void btnExportTextFiles_Click(object sender, EventArgs e)
{
//Setup MSMQ using path from user...
MessageQueue q = new MessageQueue(txtMSMQ.Text);
//Setup formatter... Whatever you want!?
q.Formatter = new ActiveXMessageFormatter();
// Loop over all messages and write them to a file... (in this case XML)
MessageEnumerator msgEnum = q.GetMessageEnumerator2();
int k = 0;
while (msgEnum.MoveNext())
{
System.Messaging.Message msg = msgEnum.Current;
string fileName = this.txtFileLocation.Text + "\\" + k + ".xml";
System.IO.File.WriteAllText(fileName, msg.Body.ToString());
k++;
}
MessageBox.Show("All done!");
}
}
}

Categories

Resources