Insert existing database file in project using C# - 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.

Related

How does this log method work in a .NET application?

I am working on a .NET project using C# and I have the following doubt.
I have this method that write some error information into a .log file in a specific directory on my file system:
private static void writeErrorLog(string error)
{
string date = DateTime.Now.ToString("yyyyMMdd_HHmmss");
string currDir = Directory.GetCurrentDirectory();
System.IO.File.AppendAllText(currDir + "\\FILE\\LOG\\Error_" + date + ".txt", error);
}
Ok this writeErrorLog() method will be called into some try catch block of my code, something like this:
try
{
currentAttachmentFileData = currentAttachmentFile.OpenBinary();
currentAttachementModel = new AttachmentModel(currentAttachment, currentAttachmentFileData);
attachmentsModelList.Add(currentAttachementModel);
}
catch (Exception ex)
{
//writeLog(2, String.Format("Unable to read the attachment, it may be corrupted {0} - {1}", fileName, ex.Message));
writeErrorLog("Errore inserimento attachment. Numero protocollo: " + recNumber
+ " Data protocollo: " + recDate
+ " Nome attachment: " + currentAttachmentFile
+ " INFO: " + ex.ToString() + " | " + ex.Message + " | " + ex.StackTrace);
}
It happens in different places of my code.
My doubt is: the file is the same, so it means that it will be added a new line to this file every time that an error occours.
Is it my reasnong correct?
The file name is string date = DateTime.Now.ToString("yyyyMMdd_HHmmss"); so it changes every second.
You should definitely add some abstraction here and hide writeErrorLog behind an interface. Behind the interface you could have your own implementation of writeErrorLog, but as others suggested I would strongly recommend using libs over your custom solution.
More on available libraries:
benchmarking-5-popular-net-logging-libraries
dotnetlogging.com

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?

Emailing in C# why isn't the information sending correctly?

I have a form that the users for my website will fill out. Once they click submit the information they filled out is supposed to be sent to my email. For some reason the information they fill out is not being sent. I am posting the code below. For a while it was working, but I must have changed something simple when I was trying to get other parts of the code to work and now I can't figure it out.
protected void Submit_Click1(object sender, EventArgs e)
{
try
{
string strMessage = "Bug Name: " + txtBugName.Text.Trim()
+ "<br/>" + "Module Name: " + ddlModule.SelectedValue
+ "<br/>" + "Page Name: " + ddlPage.SelectedValue
+ "<br/>" + "Description: " + txtComments.Text.Trim()
+ "<br/>" + "Email is" + " " + txtemail.Text.Trim()
+ "<br/>" + "The request was sent at" +
SendMessage(ConfigurationManager.AppSettings["EmailAddrTo"],
ConfigurationManager.AppSettings["EmailAddrFrom"],
txtBugName.Text.Trim(),
strMessage, "", "");
}
catch
{
}
}
As you can see I have this code pulling the information they fill out and then also I am formatting it for the email that will be sent to myself. But now I just get a blank email or actually the subject line will have something, but the email will be blank.
Also at the bottom of the code you can see i put this email was sent at + dandt I am trying to have the date and time sent in that part is there any code I can just put there to send the date and time the email was sent at? Like is there any syntax specifically just for date and time?
Thank you all
You're swallowing the exception. Remove the try/catch to see any errors that may occur as you change your code; only apply exception handling after testing.
Verify your method signature (params) here because that's where the mistake lies:
UPDATE:
You need to pass the parameters in the following order (read the link below):
public void Send(
string from,
string to,
string subject,
string body
)
SmtpClient.Send Method (String, String, String, String)
Your wrote the following, with extra strings snipped:
string strMessage = "..." + ... + SendMessage(..., strMessage, ...);
You're calling SendMessage() before assigning strMessage.

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