How to find Commit Charge programmatically? - c#

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

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.

How do I get newly inserted USB drive letter in 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

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?

Get sorted folders by size when getting them from outlook

I use the following code to retrieve all folders from outlook :
public void getFolderPath()
{
try
{
OutLook.Application oApp = new OutLook.Application();
OutLook.NameSpace oNS = (OutLook.NameSpace)oApp.GetNamespace("MAPI");
oNS.Logon(Missing.Value, Missing.Value, false, true);
foreach (MAPIFolder folder in oNS.Folders)
{
GetFolders(folder);
}
Marshal.ReleaseComObject(oApp);
}
catch (System.Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
This show me all folders from top to bottom as listed in OutLook , is there a way that i can show them or go trough them i ascending order by their size.
Something similar to :
foreach (MAPIFolder folder in oNS.Folders.sortbysize())
{
GetFolders(folder);
}
No, Folders collection in Outlook is not sortable.
Even if you were to use Extended MAPI (C++ or Delphi only) or Redemption (any language), sorting folders on the PR_MESSAGE_SIZE property won't work: PST provider does not expose it, and Exchange tends to return 0 for all folders.
You can sort by the PR_CONTENT_COUNT property (number of messages in the folder), but not by size. The following script (Outlook VBA) uses Redemption (I am its author) to sort the folders by PR_CONTENT_COUNT:
set Session = CreateObject("Redemption.RDOSession")
Session.MAPIOBJECT = Application.Session.MAPIOBJECT
set Folders = Session.Stores.DefaultStore.IPMRootFolder.Folders
Folders.MAPITable.Sort "http://schemas.microsoft.com/mapi/proptag/0x36020003", true
for each Folder in Folders
Debug.print Folder.Name & " (" & Folder.Fields("http://schemas.microsoft.com/mapi/proptag/0x36020003") & ")"
next
And an even faster version (it does not open the child folders and uses ExecSQL method) will be
set Session = CreateObject("Redemption.RDOSession")
Session.MAPIOBJECT = Application.Session.MAPIOBJECT
set Folders = Session.Stores.DefaultStore.IPMRootFolder.Folders
set MAPITable = Folders.MAPITable
MAPITable.Sort "http://schemas.microsoft.com/mapi/proptag/0x36020003", true
set Recordset = MAPITable.ExecSQL("SELECT ""http://schemas.microsoft.com/mapi/proptag/0x3001001E"" AS PR_DISPLAY_NAME, " & _
" ""http://schemas.microsoft.com/mapi/proptag/0x36020003"" AS PR_CONTENT_COUNT " & _
" from Table")
while not Recordset.EOF
Debug.Print Recordset.Fields("PR_DISPLAY_NAME").Value & " (" & Recordset.Fields("PR_CONTENT_COUNT").Value & ")"
Recordset.MoveNext
wend

best way to calculate statistics from a file in c#

I have around 300k image files in a remote location. I download (have to) and write the details of these files to a text file (with some additional info). Due to the nature of the info I'm getting, I have to process each file as they arrive (Also I write each file info to a file line) to get some form of statistics for example, I have a list of objects with attributes size and count to see how many images of certain sizes I have.
I have also thought about getting everything read and written to a file without keeping any statistics info where I could just open the file again to add the statistics. But I can't think of a way to process a 250k line multi attribute file for statistics info.
I know the lists (yeah I have 2 of them) and the constant loop for each item is bugging the application down but is there another way? Right now it's been 2 hours and the application is still on 26k. For each image item, I do something like this to keep count where I check if an image comes with a certain size that did come before, I add it to that List item.
public void AddSizeTokens(Token token)
{
int index = tokenList.FindIndex(item => item.size== token.size);
if (index >= 0)
tokenList[index].count+=1;
else
tokenList.Add(token);
}
What a single line from the file I write to looks like
Hits Size Downloads Local Loc Virtual ID
204 88.3 4212 .../someImage.jpg f-dd-edb2-4a64-b42
I'm downloading the files like below;
try
{
using (WebClient client = new WebClient())
{
if (File.Exists(filePath + "/" + fileName + "." + ext))
{
return "File Exists: " + filePath + "/" + fileName + "." + ext;
}
client.DownloadFile(virtualPath, filePath + "/" + fileName + "." + ext);
return "Downloaded: " + filePath + "/" + fileName + "." + ext;
}
}
catch (Exception e) {
return"Problem Downloading " + fileName + ": " + e.Message;
}
You should be changing your tokenList from List<Token> to Dictionary<long, Token>.
The key is the size.
Your code would look like this:
Dictionary<long, Token> tokens = new Dictionary<long, Token>();
public void AddSizeTokens(Token token)
{
Token existingToken;
if(!tokens.TryGetValue(token.size, out existingToken))
tokens.Add(token.size, token);
else
existingToken.count += 1;
}
That will change it from an O(n) operation to a O(1) operation.
Another point to consider is Destrictor's comment. Your internet connection speed is very possibly the bottle neck here.
Well, I thought perhaps the coding was the issue. Some of the problem was indeed so. As per Daniel Hilgarth's instructions, changing to dictionary helped a lot, but only the first 30 minutes. Then It was getting worse by every minute.
The problem was apparently the innocent looking UI elements that I've fed information. They ate away so much cpu that it killed the application eventually. Minimizing UI info feed helped (1.5k per minute to at slowest 1.3k). Unbelievable! Hope it helps others who have similar problems.

Categories

Resources