I have currently wrote a code which scans the local network with a function called "bool ping()". I want to add a capability to provide basic device information when the function returns 'true'. I've found 'ManagementObjectSearcher'.
At first it looked perfect but when It gets used for a non-windows device it crash. Therefore I suppose that this method cannot be used for non-windows devices.
As I want to add the below code ( or login , after enough polishing ), to an android app that scans the local network and returns the
A) IP address and
B) (one of the following )
the device type ( desktop , laptop , smartphone)
and/or
the OS type ( android , windows , linux , tvOS )
Is there a valid way I can do what I am looking for? I believe I have experienced apps that do stuff like that, though I don't know what language they were based on.
namespace LanConsole
{
class Program
{
static void Main(string[] args)
{
string host = "192.168.1.10"; // android smartphone IP
string temp = null;
// arguments I found
string[] _searchClass = { "Win32_ComputerSystem", "Win32_OperatingSystem", "Win32_BaseBoard", "Win32_BIOS" };
string[] param = { "UserName", "Caption", "Product", "Description" };
bool v = ping(host, 10, 900); // bool function send ping to host
if (v == true)
{
Console.WriteLine("true");
for (int i = 0; i <= _searchClass.Length - 1; i++)
{
ManagementObjectSearcher searcher = new ManagementObjectSearcher("\\\\" + host + "\\root\\CIMV2", "SELECT *FROM " + _searchClass[i]);
foreach (ManagementObject obj in searcher.Get())
{
temp += obj.GetPropertyValue(param[i]).ToString() + "\n";
if (i == _searchClass.Length - 1)
{
Console.WriteLine(temp, "Hostinfo: " + host);
break;
}
}
Console.WriteLine("");
}
}
else
Console.WriteLine("false");
}
public static bool ping(string host, int attempts, int timeout)
{
System.Net.NetworkInformation.Ping ping = new System.Net.NetworkInformation.Ping();
System.Net.NetworkInformation.PingReply pingReply;
for (int i = 0; i < attempts; i++)
{
try
{
pingReply = ping.Send(host, timeout);
// If there is a successful ping, return true.
if (pingReply != null &&
pingReply.Status == System.Net.NetworkInformation.IPStatus.Success)
{
return true;
}
}
catch
{
// supressing errors
}
}
// Return false if ping fales "attempts" times
return false;
}
}
}
I'm making a Windows store device app to go onto the auto play when my device is plugged in, However when I try to access any of the data from the app I keep getting deniedBySystemand I'm not sure how to access my device.
private async void OpenDevice()
{
UInt32 vid = 1234;/*stand in vid and pid not real ones i use in my code*/
UInt32 pid = 5678;
lstResults.Items.Clear();
string aqs = UsbDevice.GetDeviceSelector(vid, pid);
int counter = 0;
var myDevices = await Windows.Devices.Enumeration.DeviceInformation.FindAllAsync();
//var myDevices = await Windows.Devices.Enumeration.DeviceInformation.FindAllAsync(aqs); /*I was using this but it wasn't returning any device*/
for (int i = 0; i < myDevices.Count; i++)
{
try
{
if (myDevices[i].Id[4] == 'U' && myDevices[i].Id[8] == 'V' && myDevices[i].Id.Substring(12, 4) == vid.ToString())/* this if statements makes it so I only get the device I want*/
{
lstResults.Items.Add("VID " + myDevices[i].Id.Substring(12, 4) +
" PID " + myDevices[i].Id.Substring(21, 4));
counter++;
var deciceAccessInfo = Windows.Devices.Enumeration.DeviceAccessInformation.CreateFromId(myDevices[i].Id);
lstResults.Items.Add(deciceAccessInfo.CurrentStatus.ToString()); // this line informs me access is denied
// lstResults.Items.Add(myDevices[i].Id);
var usbDevice = await UsbDevice.FromIdAsync(myDevices[i].Id);//this line returns usbDevice to equal null
}
}
catch (Exception exception)
{
lstResults.Items.Add(exception.Message.ToString());
}
}
lstResults.Items.Add(counter + " out of " + myDevices.Count + " Have the correct VID");
}
In the Package.appxmanifestI have checked all the capabilities in case it was one of them denieing me access but it wasn't. I have also tried running the program as an admin to see if that gave me access but no joy. so my question is what is denying me access and is there a way around it?
We are developing an desktop application based on WPF, which has a feature that user can send feedback to us. We can receive the Name, Email, Body and so on.
For some historical problems we used MSMAPI to help us send mail, as time goes on we found all its function work very well until we did tests on clean machine.
The ActiveX control said, please offer me a license so I can move on, well that's make us quite confused, because that control doesn't have license at all.
Ok, I will talk about the detail now.
In folder C:\Windows\SysWOW64 (On Win7 x64), we have msmapi32.ocx. From MSDN, we have to wrapper it so can be host on a Windows Form. We did it, and got two assemblies: MSMAPI.dll and AxMSMAPI.dll, so we make our application reference these two DLLs.
Here is our code(XAML):
<Window x:Class="WpfApplication14.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ax="clr-namespace:AxMSMAPI;assembly=AxMSMAPI"
Title="MainWindow"
Width="525"
Height="350">
<StackPanel>
<WindowsFormsHost>
<ax:AxMAPIMessages Name="axMAPIMessage" />
</WindowsFormsHost>
<WindowsFormsHost>
<ax:AxMAPISession Name="axMAPISession" />
</WindowsFormsHost>
</StackPanel>
</Window>
Ofcourse, we have to change our project build target to X86, otherwise it would throw ClassNotDefined exception. Pretty well, press F5, the main window shows successfully.
Then we copy the Debug folder of our demo application, double click, Oops... It said, WpfAPplication14 has stopped work. We captured the exption, here is the stack:
System.Windows.Markup.XamlParseException occurred
_HResult=-2146233087
_message='Initialization of 'AxMSMAPI.AxMAPIMessages' threw an exception.' Line number '-' and line position '-'.
HResult=-2146233087
IsTransient=false
Message='Initialization of 'AxMSMAPI.AxMAPIMessages' threw an exception.' Line number '-' and line position '-'.
Source=PresentationFramework
LineNumber=-
LinePosition=-
StackTrace:
at System.Windows.Markup.WpfXamlLoader.Load(XamlReader xamlReader, IXamlObjectWriterFactory writerFactory, Boolean skipJournaledProperties, Object rootObject, XamlObjectWriterSettings settings, Uri baseUri)
InnerException: System.ComponentModel.LicenseException
_HResult=-2146232063
_message=You must have a license to use this ActiveX control.
HResult=-2146232063
IsTransient=false
Message=You must have a license to use this ActiveX control.
Source=System.Windows.Forms
StackTrace:
at System.Windows.Forms.AxHost.CreateInstance()
at System.Windows.Forms.AxHost.GetOcxCreate()
at System.Windows.Forms.AxHost.TransitionUpTo(Int32 state)
at System.Windows.Forms.AxHost.CreateHandle()
at System.Windows.Forms.Control.CreateControl(Boolean fIgnoreVisible)
at System.Windows.Forms.Control.CreateControl(Boolean fIgnoreVisible)
at System.Windows.Forms.AxHost.EndInit()
at MS.Internal.Xaml.Runtime.ClrObjectRuntime.InitializationGuard(XamlType xamlType, Object obj, Boolean begin)
InnerException:
Then we wrote a Windows Forms application, in the beginning we did excatly the same with WPF demo, reference the two DLLs to project, and even the result is the same. It only can show window in our develpment machine, cannot run on clean Test Machine.
So we followed some steps on MSDN, add the ActiveX control (C:\Windows\SysWOW64\msmapi32.ocx) to Visual Studio Toolbox, and drag them to the surface, and it works very well on Test Machine.
The last try by us is, follow the Windows Forms demo did, we intended to add the ocx to toolbox, but the Visual Studio said it is successfully added to toolbox, but it is not enabled in the active designer due to incompatible with the current designer and .NET framework version (VS2012/.NET 4.0/WPF).
We don'n know what's the reason the demo window thrown exception when parse XAML in Test Machine, it seems we need a license, but does it need a license???
We tried to achieve it follow Windows Forms demo did, but we even cannot add the ocx to toolbox.
So, if you have some advices towards below questions or any of them, please feel free to let us know:
Where does the msmapi32.ocx come from? Does any windows machine has it or only after installed something. By the way, we also tried to install Office 2013 on our Test Machine, it sitll the same exception thrown.
We know our ocx version is 6.0, which released at 2000. So if we would like to use it in our WPF application, any suggestions?
What factors can affect this? we searched the Dev and Test machine, both have the ocx in the folder, and both registry have the MSAPI related item (and the Windows Forms works very well).
So if above questions can be answered, it can help us a lot. From your experience, how can you achieve this feature using WPF, using the native API provided by .NET or some else 3rd party control/plugin? In fact our requirement is so eary that user send feedback to some fixed address. That's all we need to do.
Very appreciate if you have some thoughts about our question, and feel free to ask us questions which puzzled you.
Thanks.
Did you try registering the ocx? (Make sure that a newer ocx is not already registered)
I had used native .NET APIs to send mails in the past. Here is a code snippet:
/// <summary>
///Method to Send an Email informing interested parties about the status of data extraction.
/// INPUTS : int iProcessIsSuccess : int informing about the success of the process. -1 means failure, 0 means partial success, 1 means success.
/// string szLogDataToBeSent : Log data to be sent incase process not successful.
/// OUTPUTS : bool. True if success, else false.
/// </summary>
public bool SendEmailNotification(string szEmailAddressFileName, int iProcessIsSuccess, string szLogDataToBeSent)
{
bool bSuccess = false;
//the the SMTP host.
SmtpClient client = new SmtpClient();
//SMTP Server
client.Host = CommonVariables.EMAIL_SMTP_SERVER;
//SMTP Credentials
client.Credentials = new NetworkCredential(CommonVariables.EMAIL_USERNAME, CommonVariables.EMAIL_PASSWORD);
//Creating a new mail.
MailMessage mail = new MailMessage();
//Filling 'From' Tab.
mail.From = new MailAddress(CommonVariables.EMAIL_SENDERS_ADDRESS, CommonVariables.EMAIL_SENDERS_NAME);
//Filling 'To' tab.
List<EmailAddress> EmailAddressList = new List<EmailAddress>();
try
{
using (System.IO.FileStream fs = new FileStream(szEmailAddressFileName, FileMode.Open))
{
XmlSerializer xs = new XmlSerializer(typeof(List<EmailAddress>));
EmailAddressList = xs.Deserialize(fs) as List<EmailAddress>;
}
foreach (EmailAddress addr in EmailAddressList)
{
mail.To.Add(addr.RecepientEmailAddress);
}
}
catch(Exception Ex)
{
mail.To.Add("somedefaultemail#companyname.com");
}
//Filling mail body.
string szMailBody = "";
string szMailSubject = "";
if (1 == iProcessIsSuccess) //Success
{
szMailSubject = String.Format(CommonVariables.EMAIL_SUBJECT_BOILER_PLATE, "a SUCCESS");
szMailBody = String.Format(CommonVariables.EMAIL_BODY_BOILER_PLATE, DateTime.UtcNow.ToString(), Environment.MachineName);
szMailBody += "\r\n" + szMailSubject + "\r\n";
}
else if (0 == iProcessIsSuccess) //Partially Success
{
szMailSubject = String.Format(CommonVariables.EMAIL_SUBJECT_BOILER_PLATE, "a PARTIAL SUCCESS"); ;
szMailBody = String.Format(CommonVariables.EMAIL_BODY_BOILER_PLATE, DateTime.UtcNow.ToString(), Environment.MachineName);
szMailBody += "\r\n"+ szMailSubject + "\r\n";
szMailBody += "\r\n" + "The Log data is as follows:\r\n";
szMailBody += szLogDataToBeSent;
mail.Priority = MailPriority.High;
}
else //Failed
{
szMailSubject = String.Format(CommonVariables.EMAIL_SUBJECT_BOILER_PLATE, "a FAILURE"); ;
szMailBody = String.Format(CommonVariables.EMAIL_BODY_BOILER_PLATE, DateTime.UtcNow.ToString(), Environment.MachineName);
szMailBody += "\r\n" + szMailSubject + "\r\n";
szMailBody += "\r\n" + "The Log data is as follows:\r\n";
szMailBody += szLogDataToBeSent;
mail.Priority = MailPriority.High;
}
mail.Body = szMailBody;
mail.Subject = szMailSubject;
//Send Email.
try
{
client.Send(mail);
bSuccess = true;
}
catch (Exception Ex)
{
bSuccess = false;
}
// Clean up.
mail.Dispose();
return bSuccess;
}
My post is not an answer to your questions, but provides a solution (if you like it).
In the past I've used this class (mapi compliant).
This class doesn't use native SmtpClient class (that sends an email but doesn't interact with your default mailing app) but is able to invoke your email application and popup email window (filled with every detail you need) so your customer can modify it as needed.
More, email sent remains is "sent email" folder...
enum HowTo { MAPI_ORIG = 0, MAPI_TO, MAPI_CC, MAPI_BCC };
public class MAPI
{
[DllImport("MAPI32.DLL")]
static extern int MAPISendMail(IntPtr sess, IntPtr hwnd, MapiMessage message, int flg, int rsv);
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public class MapiMessage
{
public int reserved;
public string subject;
public string noteText;
public string messageType;
public string dateReceived;
public string conversationID;
public int flags;
public IntPtr originator;
public int recipCount;
public IntPtr recips;
public int fileCount;
public IntPtr files;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public class MapiFileDesc
{
public int reserved;
public int flags;
public int position;
public string path;
public string name;
public IntPtr type;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public class MapiRecipDesc
{
public int reserved;
public int recipClass;
public string name;
public string address;
public int eIDSize;
public IntPtr entryID;
}
List<MapiRecipDesc> m_recipients = new List<MapiRecipDesc>();
List<string> m_attachments = new List<string>();
private int m_lastError = 0;
private const int MAPI_LOGON_UI = 0x00000001;
private const int MAPI_DIALOG = 0x00000008;
private const int maxAttachments = 20;
#region Private methods
private bool AddRecipients(HowTo howTo, params string[] emails)
{
bool ret = true;
foreach (string email in emails)
{
try
{
MapiRecipDesc recipient = new MapiRecipDesc();
recipient.recipClass = (int)howTo;
recipient.name = email;
m_recipients.Add(recipient);
}
catch { ret = false; }
}
return ret;
}
private int SendMail(string strSubject, string strBody, int how)
{
MapiMessage msg = new MapiMessage();
msg.subject = strSubject;
msg.noteText = strBody;
msg.recips = GetRecipients(out msg.recipCount);
msg.files = GetAttachments(out msg.fileCount);
m_lastError = MAPISendMail(new IntPtr(0), new IntPtr(0), msg, how, 0);
if (m_lastError > 1)
MessageBox.Show("MAPISendMail failed! " + LastError, "MAPISendMail");
Cleanup(ref msg);
return m_lastError;
}
private IntPtr GetRecipients(out int recipCount)
{
recipCount = 0;
if (m_recipients.Count == 0)
return IntPtr.Zero;
int size = Marshal.SizeOf(typeof(MapiRecipDesc));
IntPtr intPtr = Marshal.AllocHGlobal(m_recipients.Count * size);
int ptr = (int)intPtr;
foreach (MapiRecipDesc mapiDesc in m_recipients)
{
Marshal.StructureToPtr(mapiDesc, (IntPtr)ptr, false);
ptr += size;
}
recipCount = m_recipients.Count;
return intPtr;
}
private IntPtr GetAttachments(out int fileCount)
{
fileCount = 0;
if (m_attachments == null)
return IntPtr.Zero;
if ((m_attachments.Count <= 0) || (m_attachments.Count > maxAttachments))
return IntPtr.Zero;
int size = Marshal.SizeOf(typeof(MapiFileDesc));
IntPtr intPtr = Marshal.AllocHGlobal(m_attachments.Count * size);
MapiFileDesc mapiFileDesc = new MapiFileDesc();
mapiFileDesc.position = -1;
int ptr = (int)intPtr;
foreach (string strAttachment in m_attachments)
{
mapiFileDesc.name = Path.GetFileName(strAttachment);
mapiFileDesc.path = strAttachment;
Marshal.StructureToPtr(mapiFileDesc, (IntPtr)ptr, false);
ptr += size;
}
fileCount = m_attachments.Count;
return intPtr;
}
private void Cleanup(ref MapiMessage msg)
{
int size = Marshal.SizeOf(typeof(MapiRecipDesc));
int ptr = 0;
if (msg.recips != IntPtr.Zero)
{
ptr = (int)msg.recips;
for (int i = 0; i < msg.recipCount; i++)
{
Marshal.DestroyStructure((IntPtr)ptr, typeof(MapiRecipDesc));
ptr += size;
}
Marshal.FreeHGlobal(msg.recips);
}
if (msg.files != IntPtr.Zero)
{
size = Marshal.SizeOf(typeof(MapiFileDesc));
ptr = (int)msg.files;
for (int i = 0; i < msg.fileCount; i++)
{
Marshal.DestroyStructure((IntPtr)ptr, typeof(MapiFileDesc));
ptr += size;
}
Marshal.FreeHGlobal(msg.files);
}
m_recipients.Clear();
m_attachments.Clear();
m_lastError = 0;
}
#endregion
#region Public methods
public bool AddTo(params string[] emails)
{
return AddRecipients(HowTo.MAPI_TO, emails);
}
public bool AddCC(params string[] emails)
{
return AddRecipients(HowTo.MAPI_CC, emails);
}
public bool AddBCC(params string[] emails)
{
return AddRecipients(HowTo.MAPI_BCC, emails);
}
public void AddAttachment(string strAttachmentFileName)
{
m_attachments.Add(strAttachmentFileName);
}
public int SendMailPopup(string strSubject, string strBody)
{
return SendMail(strSubject, strBody, MAPI_LOGON_UI | MAPI_DIALOG);
}
public int SendMailDirect(string strSubject, string strBody)
{
return SendMail(strSubject, strBody, MAPI_LOGON_UI);
}
public string LastError
{
get
{
switch (m_lastError)
{
case 0: return "OK";
case 1: return "User abort [1]";
case 2: return "General MAPI failure [2]";
case 3: return "MAPI login failure [3]";
case 4: return "Disk full [4]";
case 5: return "Insufficient memory [5]";
case 6: return "Access denied [6]";
case 7: return "-unknown- [7]";
case 8: return "Too many sessions [8]";
case 9: return "Too many files were specified [9]";
case 10: return "Too many recipients were specified [10]";
case 11: return "A specified attachment was not found [11]";
case 12: return "Attachment open failure [12]";
case 13: return "Attachment write failure [13]";
case 14: return "Unknown recipient [14]";
case 15: return "Bad recipient type [15]";
case 16: return "No messages [16]";
case 17: return "Invalid message [17]";
case 18: return "Text too large [18]";
case 19: return "Invalid session [19]";
case 20: return "Type not supported [20]";
case 21: return "A recipient was specified ambiguously [21]";
case 22: return "Message in use [22]";
case 23: return "Network failure [23]";
case 24: return "Invalid edit fields [24]";
case 25: return "Invalid recipients [25]";
case 26: return "Not supported [26]";
default: return String.Format("MAPI error [{0}]", m_lastError);
}
}
}
#endregion
}
I got myself some Kit-Starter code from google uploaded by someone else.
I hooked on my USB-Serial Cable and set my COM port to COM1.
When i build and ran it , it gave me error on this line, im not sure what's happening.
private int parseLGResponseHexa(string resp) {
var splitter = new string[1];
splitter[0] = "OK";
String[] partes = resp.Split(splitter, StringSplitOptions.RemoveEmptyEntries);
String naco = partes[1];
String num = naco.Substring(0, 2);
int decAgain = int.Parse(num, NumberStyles.HexNumber);
return decAgain;
}
Error At "String Naco = partes[1];"
How to enumerate available database Services(SQL Server or Oracle or MySQL or PostgreSQL, etc) in a network using C#?
I also need to find their port-numbers and service-instance names.
For example:
class Server
{
#region DLL Inports
[DllImport("odbc32.dll")]
private static extern short SQLAllocHandle(short hType, IntPtr inputHandle, out IntPtr outputHandle);
[DllImport("odbc32.dll")]
private static extern short SQLSetEnvAttr(IntPtr henv, int attribute, IntPtr valuePtr, int strLength);
[DllImport("odbc32.dll")]
private static extern short SQLFreeHandle(short hType, IntPtr handle);
[DllImport("odbc32.dll", CharSet = CharSet.Ansi)]
private static extern short SQLBrowseConnect(IntPtr hconn, StringBuilder inString,
short inStringLength, StringBuilder outString, short outStringLength,
out short outLengthNeeded);
#endregion
#region Constants
private const short SQL_HANDLE_ENV = 1;
private const short SQL_HANDLE_DBC = 2;
private const int SQL_ATTR_ODBC_VERSION = 200;
private const int SQL_OV_ODBC3 = 3;
private const short SQL_SUCCESS = 0;
private const short SQL_NEED_DATA = 99;
private const short DEFAULT_RESULT_SIZE = 1024;
private const string SQL_DRIVER_STR = "DRIVER=SQL SERVER";
#endregion
#region static string[] GetServers()
public static string[] GetNames()
{
string[] retval = null;
string txt = string.Empty;
IntPtr henv = IntPtr.Zero;
IntPtr hconn = IntPtr.Zero;
StringBuilder inString = new StringBuilder(SQL_DRIVER_STR);
StringBuilder outString = new StringBuilder(DEFAULT_RESULT_SIZE);
short inStringLength = (short)inString.Length;
short lenNeeded = 0;
try
{
if (SQL_SUCCESS == SQLAllocHandle(SQL_HANDLE_ENV, henv, out henv))
{
if (SQL_SUCCESS == SQLSetEnvAttr(henv, SQL_ATTR_ODBC_VERSION, (IntPtr)SQL_OV_ODBC3, 0))
{
if (SQL_SUCCESS == SQLAllocHandle(SQL_HANDLE_DBC, henv, out hconn))
{
if (SQL_NEED_DATA == SQLBrowseConnect(hconn, inString, inStringLength, outString,
DEFAULT_RESULT_SIZE, out lenNeeded))
{
if (DEFAULT_RESULT_SIZE < lenNeeded)
{
outString.Capacity = lenNeeded;
if (SQL_NEED_DATA != SQLBrowseConnect(hconn, inString, inStringLength, outString,
lenNeeded, out lenNeeded))
{
throw new ApplicationException("Unabled to aquire SQL Servers from ODBC driver.");
}
}
txt = outString.ToString();
int start = txt.IndexOf("{") + 1;
int len = txt.IndexOf("}") - start;
if ((start > 0) && (len > 0))
{
txt = txt.Substring(start, len);
}
else
{
txt = string.Empty;
}
}
}
}
}
}
catch (Exception ex)
{
//Throw away any error if we are not in debug mode
//#if (DEBUG)
//MessageBox.Show(ex.Message,"Acquire SQL Servier List Error");
//#endif
txt = string.Empty;
throw ex;
}
finally
{
if (hconn != IntPtr.Zero)
{
SQLFreeHandle(SQL_HANDLE_DBC, hconn);
}
if (henv != IntPtr.Zero)
{
SQLFreeHandle(SQL_HANDLE_ENV, hconn);
}
}
if (txt.Length > 0)
{
retval = txt.Split(",".ToCharArray());
}
return retval;
}
#endregion
}
This code only works for SqlServers and up to WindowsXP.
It doesn't work for other DBMS Servers and on Win7.
I am in need of a canonical solution.
You could use the SqlDataSourceEnumerator class for this as well. Keep in mind, this is MS SQL Server specific...
var results = SqlDataSourceEnumerator.Instance.GetDataSources();
foreach (var row in results.Rows)
{
Console.WriteLine("{0}\{1}", row["ServerName"], row["InstanceName"]);
}
See this link for additional info
Does it work for any RDBMS Server?
Your answer is always going to be "no" here. Every RDBMS lets you set up a custom port - MySQL could be on 1433 or 1434 or 99999. Every RDBMS responds differently from other RDBMSes and even sometimes from previous versions of itself... You'd have to check every networking port possible on every computer for every RDBMS (and every version of that RDBMS if they change response strings often) and HOPE they have them configured with standard plaintext responses instead of being encrypted or whatnot. This is basic networking - first you portscan the IP range, then you can try to appscan on the active ports you've found to see how they respond to various requests, then you use that information to say "these IPs have apps that appear to be databases on the following ports" -- you're still not going to get things like MS Instance Name without going through the proper channels (as listed with code samples above).
Your best bet for understanding where to start is probably - http://www.nmap.org
To combine things said in the previous answers / comments:
Contact your sysadmin, becasue this is undoable. You would need to account for every version of every (R)DBMS out there (or at least the latest ones).
In addition to the other responses:
I have found Oracle.DataAccess.Client.OracleDataSourceEnumerator in the Oracle.DataAccess dll (Oracle.DataAccess.client)
By adding Oracle.managment.omo.dll and DataAccess.dll,you can manipulate Oracle objects like sql;management.SMO in MS SQLSERVER
Resources:
http://msdn.microsoft.com/en-us/library/ms162169.aspx
http://www.microsoft.com/downloads/details.aspx?FamilyId=C6C3E9EF-BA29-4A43-8D69-A2BED18FE73C&displaylang=en
You would want to look into SMO. This requires each client to have the Sql Management Objects and CLR types installed. Below is a code snippet from one of my working applications that does just this.
private void OnClicked_RefreshDataSources(object sender, EventArgs e) {
Cursor = Cursors.WaitCursor;
DataTable dt = SmoApplication.EnumAvailableSqlServers(false);
uxDataSource.Items.Clear();
foreach (DataRow row in dt.Rows) {
uxDataSource.Items.Add(row["Name"]);
}
if (dt.Rows.Count > 0) {
uxDataSource.SelectedIndex = 0;
}
Cursor = Cursors.Default;
}
private void OnSelectedIndexChanged_PopulateDatabases(object sender, EventArgs e) {
ConnectionString.DataSource = uxDataSource.SelectedItem.ToString();
Server server = new Server(uxDataSource.SelectedItem.ToString());
server.ConnectionContext.LoginSecure = false;
server.ConnectionContext.Login = Program.DesktopService.AccountName;
uxInitialCatalog.Items.Clear();
try {
foreach (Database db in server.Databases) {
uxInitialCatalog.Items.Add(db.Name);
}
if (server.Databases.Count > 0) {
uxInitialCatalog.SelectedIndex = 0;
}
}
catch {
MessageBox.Show("You do not have access to this server.", "Sql Connection", MessageBoxButtons.OK,
MessageBoxIcon.Warning);
uxInitialCatalog.Items.Clear();
}
}