How do I get newly inserted USB drive letter in c#? - c#

I wrote a c# program to find newly inserted USB drive and its drive letter. Now when I run this program I got the insertion event and couldn't get the drive letter. Can anyone suggest me an idea to do this?
code
static void Main(string[] args)
{
ManagementEventWatcher mwe_creation; //Object creation for 'ManagementEventWatcher' class is used to listen the temporary system event notofications based on specific query.
WqlEventQuery q_creation = new WqlEventQuery(); //Represents WMI(Windows Management Instrumentation) event query in WQL format for more information goto www.en.wikipedia.org/wiki/WQL
q_creation.EventClassName = "__InstanceCreationEvent";// Sets the eventclass to the query
q_creation.WithinInterval = new TimeSpan(0, 0, 2); // Setting up the time interval for the event check(here, it is 2 Seconds)
q_creation.Condition = #"TargetInstance ISA 'Win32_DiskDriveToDiskPartition'"; //Sets which kind of event to be notified
mwe_creation = new ManagementEventWatcher(q_creation); //Initializing new instance
mwe_creation.EventArrived += new EventArrivedEventHandler(USBEventArrived_Creation);//Calling up 'USBEventArrived_Creation' method when the usb storage plug-in event occured
mwe_creation.Start(); // Starting to listen to the system events based on the given query
while (true) ;
}
static void USBEventArrived_Creation(object sender, EventArrivedEventArgs e){
Console.WriteLine("USB PLUGGED IN!");
ManagementBaseObject instance = (ManagementBaseObject)e.NewEvent["TargetInstance"];
foreach (var property in instance.Properties)
{
if (property.Name == "Name")
Console.WriteLine(property.Name + " = " + property.Value);
}
}

You may be working too hard to recreate a pre-existing soultion. Here is a Public-Licensed project made by Stephen Mcohn that provides exactly the interface you need and appears to be well documented:
http://www.codeproject.com/Articles/63878/Enumerate-and-Auto-Detect-USB-Drives
Here is how he filtered for just USB drives
new ManagementObjectSearcher(
"select DeviceID, Model from Win32_DiskDrive " +
"where InterfaceType='USB'").Get())
Here is how the specific drive letter was recovered
Getting the specific drive letter was accomplished using Associators to get the Win32_LogicalDisk which can then give the device ID (e.g. drive letter).
Microsoft Provided a VB code example that you can port if you don't want to just import Stephen's whole module:
ComputerName = "."
Set wmiServices = GetObject ( _
"winmgmts:{impersonationLevel=Impersonate}!//" & ComputerName)
' Get physical disk drive
Set wmiDiskDrives = wmiServices.ExecQuery ( "SELECT Caption, DeviceID FROM Win32_DiskDrive")
For Each wmiDiskDrive In wmiDiskDrives
WScript.Echo "Disk drive Caption: " & wmiDiskDrive.Caption & VbNewLine & "DeviceID: " & " (" & wmiDiskDrive.DeviceID & ")"
'Use the disk drive device id to
' find associated partition
query = "ASSOCIATORS OF {Win32_DiskDrive.DeviceID='" _
& wmiDiskDrive.DeviceID & "'} WHERE AssocClass = Win32_DiskDriveToDiskPartition"
Set wmiDiskPartitions = wmiServices.ExecQuery(query)
For Each wmiDiskPartition In wmiDiskPartitions
'Use partition device id to find logical disk
Set wmiLogicalDisks = wmiServices.ExecQuery _
("ASSOCIATORS OF {Win32_DiskPartition.DeviceID='" _
& wmiDiskPartition.DeviceID & "'} WHERE AssocClass = Win32_LogicalDiskToPartition")
For Each wmiLogicalDisk In wmiLogicalDisks
WScript.Echo "Drive letter associated" _
& " with disk drive = " _
& wmiDiskDrive.Caption _
& wmiDiskDrive.DeviceID _
& VbNewLine & " Partition = " _
& wmiDiskPartition.DeviceID _
& VbNewLine & " is " _
& wmiLogicalDisk.DeviceID
Next
Next
Next

Related

Insert existing database file in project using C#

I am working on an application, which gets the public IP address of the user, looks up in a database for the location of that IP address, gets the Latitude an Longitude and finally displays the time of sunrise and sunset at that place.
To make step two work, I need to implement a database file in my project. I have downloaded the database file (.bin - format) already but I couldn't make it work to connect my program with the downloaded database file.
Download of database file below:
How can I solve this?
Cheers!
You can use the IP2Location NuGet package https://www.nuget.org/packages/IP2Location.IPGeolocation/ and call it like below:
Dim oIPResult As New IP2Location.IPResult
Dim oIP2Location As New IP2Location.Component
Try
Dim strIPAddress = "8.8.8.8"
If strIPAddress.Trim <> "" Then
oIP2Location.Open("C:\myfolder\IP-COUNTRY-REGION-CITY-LATITUDE-LONGITUDE-ZIPCODE-TIMEZONE-ISP-DOMAIN-NETSPEED-AREACODE-WEATHER-MOBILE-ELEVATION-USAGETYPE-ADDRESSTYPE-CATEGORY.BIN", True)
oIPResult = oIP2Location.IPQuery(strIPAddress)
Select Case oIPResult.Status
Case "OK"
Console.WriteLine("IP Address: " & oIPResult.IPAddress)
Console.WriteLine("City: " & oIPResult.City)
Console.WriteLine("Country Code: " & oIPResult.CountryShort)
Console.WriteLine("Country Name: " & oIPResult.CountryLong)
Console.WriteLine("Postal Code: " & oIPResult.ZipCode)
Console.WriteLine("Domain Name: " & oIPResult.DomainName)
Console.WriteLine("ISP Name: " & oIPResult.InternetServiceProvider)
Console.WriteLine("Latitude: " & oIPResult.Latitude)
Console.WriteLine("Longitude: " & oIPResult.Longitude)
Console.WriteLine("Region: " & oIPResult.Region)
Console.WriteLine("TimeZone: " & oIPResult.TimeZone)
Console.WriteLine("NetSpeed: " & oIPResult.NetSpeed)
Console.WriteLine("IDD Code: " & oIPResult.IDDCode)
Console.WriteLine("Area Code: " & oIPResult.AreaCode)
Console.WriteLine("Weather Station Code: " & oIPResult.WeatherStationCode)
Console.WriteLine("Weather Station Name: " & oIPResult.WeatherStationName)
Console.WriteLine("MCC: " & oIPResult.MCC)
Console.WriteLine("MNC: " & oIPResult.MNC)
Console.WriteLine("Mobile Brand: " & oIPResult.MobileBrand)
Console.WriteLine("Elevation: " & oIPResult.Elevation)
Console.WriteLine("Usage Type: " & oIPResult.UsageType)
Console.WriteLine("Address Type: " & oIPResult.AddressType)
Console.WriteLine("Category: " & oIPResult.Category)
Case "EMPTY_IP_ADDRESS"
Console.WriteLine("IP Address cannot be blank.")
Case "INVALID_IP_ADDRESS"
Console.WriteLine("Invalid IP Address.")
Case "MISSING_FILE"
Console.WriteLine("Invalid Database Path.")
End Select
Else
Console.WriteLine("IP Address cannot be blank.")
End If
Catch ex As Exception
Console.WriteLine(ex.Message)
Finally
oIP2Location.Close()
oIPResult = Nothing
oIP2Location = Nothing
End Try
Example code came from https://github.com/ip2location/ip2location-dotnet.

SharpSVN Repo-Browser

Viewing the repository data of TortoiseSVN is done by right click on a file -> TortiseSVN -> Repo-Browser.
I would like to get this data using SharpSVN, in order to retrieve the name of lock owner.
Is it possible? How? Where does this data being saved?
I've tried to get a lock owner name using the following code, however, I get the lock infirmation just in case I'm on the machine where the lock was done from. If I'm another user, I cannot get the lock information.
using (SvnClient client = new SvnClient())
{
client.GetInfo(#"path\to\working\copy\file.xml", out info);
SvnLockInfo lc = info.Lock;
if (lc != null)
{
MessageBox.Show("Owner: " + lc.Owner + "\n" +
"Creation time: " + lc.CreationTime + "\n" +
"Comment: " + lc.Comment + "\n" +
"Expiration time: " + lc.ExpirationTime);
}
}
Even when I set the target as the repository URI- instead of path to the local working copy I get the same result:
Uri target = client.GetUriFromWorkingCopy(#"path\to\working\copy\file.xml");
client.GetInfo(target, out info);
The way I can see the lock owner name from another working copy is, as mentioned, by right click on file -> repo-browser.
Any ideas how to perform it programmatically?

Outlook add-in : programmatically perform an “advanced Find” on the “SelectNamesDialog”

In my Outlook Add-In I’m bringing up the SelectNamesDialog to select a contact set on GAL. I would like to perform an Advance Find in order to look for Example for contact of a particular Company (See Screenshot).
Do you know if this is something that is actually doable? Is there an interface I’m Missing? You can look at my code with some unsuccessful ties out.
Outlook.SelectNamesDialog snd = Globals.ThisAddIn.Application.Session.GetSelectNamesDialog();
Outlook.AddressList contactsAddrList = null;
Outlook.AddressList gal = Globals.ThisAddIn.Application.Session.GetGlobalAddressList();
String company = "My Company";
// Try to look > Dead code not working
//Outlook.MAPIFolder galFolder = Globals.ThisAddIn.Application.GetNamespace("MAPI").GetDefaultFolder(Outlook.OlDefaultFolders.);
//String sScope = "SCOPE ('shallow traversal of " + (char)34 + + (char)34 + "')";
//String sFilter = (char)34 + "urn:content-classes:person" + (char)34 + " LIKE 'RE:%'";
//Outlook.Search search = Globals.ThisAddIn.Application.AdvancedSearch(sScope, sFilter, false, company);
//contactsAddrList = search.Save(company).;
// Set InitialAddressList to Contacts folder AddressList.
snd.SetDefaultDisplayMode(Outlook.OlDefaultSelectNamesDisplayMode.olDefaultSingleName);
snd.InitialAddressList = contactsAddrList;
snd.AllowMultipleSelection = false;
snd.ForceResolution = true;
snd.ShowOnlyInitialAddressList = true;
snd.Display();
There is no way to invoke this the Outlook Object Model or even Redemption.
You can do this on the Extended MAPI level (C++ or Delphi) - open the PR_SEARCH property as IMAPIContainer, set various properties (PR_DISPLAY_NAME, PR_ACCOUNT, etc.), then call IMAPIContainer::GetContentsTable.

C# / Webservice app on server throwing strange exception

We use ADP for employee information. I had to create a small app that called some web services that ADP has to pull employee information. The app is fairly procedural..not really object orientated in a sense. Basically I go through some web services to pull general information, work information, employee status, etc.
I have most of this data writing out to a text file as a log so I can ensure that everything is working correctly. Finally got it all done, and it works perfect on my local machine. Thought I'd just copy the entire structure onto a server and use windows scheduler to schedule the exe to run nightly (once a day). When it tries to run the app it looks like it is dying when it calls the first web service. The task scheduler log says:
""ADP.job" (ADP.exe)
Started 2/11/2010 2:14:34 PM
"ADP.job" (ADP.exe)
Finished 2/11/2010 2:14:38 PM
Result: The task completed with an exit code of (e0434f4d)."
So I checked the event viewer and it says this:
EventType clr20r3, P1 adp.exe, P2 1.0.0.0, P3 4b745bb9, P4 adp, P5 1.0.0.0, P6 4b745bb9, P7 289, P8 2d, P9 system.io.filenotfoundexception, P10 NIL.
For more information, see Help and Support Center at http://go.microsoft.com/fwlink/events.asp.
I put in some console.writelines to see where it is failing...
Here is a simple example of main:
static void Main(string[] args)
{
OpenTextFile();
Console.WriteLine("About to process employee work information...");
tw.WriteLine("About to process employee work information...");
//work info service
EmpWorkInfo();
}
And inside of opentextfile:
public static void OpenTextFile()
{
//used to log data
String sLogName;
Console.WriteLine("Inside of opentextfile");
if (Directory.Exists(logPath))
{
//directory exists
}
else
{
Directory.CreateDirectory(logPath);
}
Console.WriteLine("Inside of opentextfile2");
sLogName = "log_" + DateTime.Today.ToString("MM_dd_yyyy") + ".txt";
tw = new StreamWriter(logPath + sLogName);
}
I see all the console.writelines on the server but as soon as it hits this line from main:
EmpWorkInfo();
Thats when all hell breaks lose (basically it doesn't work). The EmpWorkInfo() is simply a function to get work related information from a web service (as I said this works locally).
static void EmpWorkInfo()
{
Console.Writeline("THIS NEVER PRINTS!!!");
SQLClass s=null;
// Create the web service proxy client.
GetEmployeeWorkInfoService oService = new GetEmployeeWorkInfoService();
oService.Timeout = Int32.MaxValue;
// Serialize the UsernameToken into XML.
// Create the UsernameToken as defined in the WS-I secure profile.
UsernameToken oUsernameToken = new UsernameToken(USERNAME, SECRET);
System.Xml.XmlElement oSecurityHeaderXml =
oUsernameToken.GetXml(new System.Xml.XmlDocument());
ADP.GetEmployeeWorkInfoWebService.SecurityHeaderType oSecurityHeader = new ADP.GetEmployeeWorkInfoWebService.SecurityHeaderType();
oSecurityHeader.Any = new System.Xml.XmlElement[] { oSecurityHeaderXml };
oService.Security = oSecurityHeader;
GetEmployeeWorkInfoRequestFilter oFilter = new GetEmployeeWorkInfoRequestFilter();
//filter by thyssenkrupp company
oFilter.Companies = new String[] { COMPANY_IDENTIFIER };
GetEmployeeWorkInfoRequest oRequest = new GetEmployeeWorkInfoRequest();
oRequest.Filter = oFilter;
try
{
EmployeeWorkInfoType[] arPersonalInfo = oService.GetEmployeeWorkInfo(oRequest);
try
{
s = new SQLClass();
}
catch (Exception e)
{
throw new System.Exception(e.Message.ToString());
}
for (int i = 0; i < arPersonalInfo.Length; i++)
{
String stID = arPersonalInfo[i].EmployeeKey.Identifier.EmployeeId; //employee number
String stEmailAddress = arPersonalInfo[i].WorkInfo.EmailAddress; //employee email address (work)
String stFax = arPersonalInfo[i].WorkInfo.Fax; //employee fax number
DateTime dtHireDate = arPersonalInfo[i].WorkInfo.OriginalHireDate;
String stPhone = arPersonalInfo[i].WorkInfo.Phone; //employee phone number
String stWireless = arPersonalInfo[i].WorkInfo.Wireless; //employee wireless number
tw.WriteLine("Processing ID:" + stID + " Email Work: " + stEmailAddress + " Fax Work: " + stFax + " Hire Date: " + dtHireDate + " Phone Work: " + stPhone + " Wireless Work: " + stWireless + ".");
Console.WriteLine("Processing ID:" + stID + " Email Work: " + stEmailAddress + " Fax Work: " + stFax + " Hire Date: " + dtHireDate + " Phone Work: " + stPhone + " Wireless Work: " + stWireless + ".");
s.SetSQLCommand("dbo.ADP_uiEmployeeWorkInfo");
s.AddSQLCmdParameter("#EmployeeNumber", System.Data.SqlDbType.VarChar, stID);
s.AddSQLCmdParameter("#EmailAddress", System.Data.SqlDbType.VarChar, stEmailAddress);
s.AddSQLCmdParameter("#Fax", System.Data.SqlDbType.VarChar, stFax);
s.AddSQLCmdParameter("#HireDate", System.Data.SqlDbType.DateTime, dtHireDate);
s.AddSQLCmdParameter("#Telephone", System.Data.SqlDbType.VarChar, stPhone);
s.AddSQLCmdParameter("#Mobile", System.Data.SqlDbType.VarChar, stWireless);
s.SQLExecuteNonQuery();
Console.WriteLine("Processed ID:" + stID + " Email Work: " + stEmailAddress + " Fax Work: " + stFax + " Hire Date: " + dtHireDate + " Phone Work: " + stPhone + " Wireless Work: " + stWireless + ".");
Console.WriteLine(Environment.NewLine);
}
s.CloseSQLDB();
s.Dispose();
}
//catch any exception from adp side.
catch (Exception e)
{
throw new System.Exception(e.Message.ToString());
}
}
This functions code is irrelevant (its ugly but do not let that bother you, the code works...). My issue is I cannot even get to the first console.writeline of that function. Is there anything special I need to do when it comes to working with webservices?
Edit
Logpath is defined as simply a static string outside of main:
private static string logPath = Environment.CurrentDirectory + "\\log\\";
I suspect that your application is not able to load the types referenced in that function - EmpWorkInfo.
1) Can you run this application on the target server in a commannd window (cmd.exe) ?
2) Are you using any assemblies from ADP that are installed in the global assembly cache (GAC)? Run "gacutil -l" on your localmachine to see if you are using any assemblies from ADP that are installed in thr gac. If they are, you will need to install these into the machine on which you are running the app.
Does logPath have a trailing backslash? Either way, you ought to use Path.Combine, rather than the string catenation operator (+).
What happens if you comment out all the code in EmpWorkInfo() apart from the first Console.Writeline? Does it still not get written out?
Found out I need the Microsoft.Web.Services3 dll installed on the server.
Continuation on "feroze" answer;
If you want to figure out if the 'loading of dependencies' is causing you grief here, i suggest using the "FUSLOGVW.EXE" tool *(part of .Net). When you run this it will give you a little dialog window with a few options. Create a directory somewhere (like "c:\temp\fusion_logs"), set the mode of FUSLOGVW to "log bind failures only", "custom location->c:\temp\fusion_logs".
Now restart your application and check that it failed. Now look into your fusion_logs directory. This should give you sub directories with different (maybe only 1 for now) application names. Inside each directory you will find the log files. These log files contain the "failed assembly loads" and who (which calling assembly) caused them.
They might help your hunt for a working application,
Hope this helps,
Edit: Posted this after you found the cause. The fuslogvw.exe would have shown you the missing assembly.

How to find Commit Charge programmatically?

I'm looking for the total commit charge.
public static long GetCommitCharge()
{
var p = new System.Diagnostics.PerformanceCounter("Memory", "Committed Bytes");
return p.RawValue;
}
Here's an example using WMI:
strComputer = "."
Set objSWbemServices = GetObject("winmgmts:\\" & strComputer)
Set colSWbemObjectSet = _
objSWbemServices.InstancesOf("Win32_LogicalMemoryConfiguration")
For Each objSWbemObject In colSWbemObjectSet
Wscript.Echo "Total Physical Memory (kb): " & _
objSWbemObject.TotalPhysicalMemory
WScript.Echo "Total Virtual Memory (kb): " & _
objSWbemObject.TotalVirtualMemory
WScript.Echo "Total Page File Space (kb): " & _
objSWbemObject.TotalPageFileSpace
Next
If you run this script under CScript, you should see the number of kilobytes of physical memory installed on the target computer displayed in the command window. The following is typical output from the script:
Total Physical Memory (kb): 261676
Edit: Included total page file size property also
taken from: http://www.microsoft.com/technet/scriptcenter/guide/sas_wmi_dieu.mspx?mfr=true

Categories

Resources