I have a need to be able to grab services from a server and display them in a web page for testers to check instead of having them log into the remote server, open up services and check for specific services.
I've looked at a bunch of ways of doing it in the command line using tasklist, sc query, and even a get-service in powershell.
What I'd like to do is hit the remote server and display the running servives in a webpage. Is it possible to do this from a c# page?
I believe what you're looking for is ServiceController.GetServices():
http://msdn.microsoft.com/en-us/library/hde9d63a.aspx
This will allow you to get a list of all the services on a machine. There's an overload that takes a machine name as well: http://msdn.microsoft.com/en-us/library/s21fd6th.aspx
you can do this with the help of WMI, you can use System.Management namespace and try with following code by browsing Win32_Service class :
DataTable dt = new DataTable();
dt.Columns.Add("Name");
dt.Columns.Add("InstallDate");
dt.Columns.Add("State");
dt.Columns.Add("ServiceType");
try
{
ManagementObjectSearcher searcher =
new ManagementObjectSearcher("root\\CIMV2",
"SELECT * FROM Win32_Service");
foreach (ManagementObject queryObj in searcher.Get())
{
DataRow dr = dt.NewRow();
dr["Name"] = queryObj["Name"];
dr["InstallDate"] = queryObj["InstallDate"];
dr["ServiceType"] = queryObj["ServiceType"];
dr["State"] = queryObj["State"];
dt.Rows.Add(dr);
}
GridView1.DataSource = dt;
GridView1.DataBind();
}
catch (ManagementException ex)
{
//"An error occurred while querying for WMI data: " + e.Message;
}
Related
My requirement is to get installed software details of vm machine of azure and store the details in db. but when I try to get the details using System.Management class I am getting the below error
System.Runtime.InteropServices.COMException: 'The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)'
below is my sample code I am using to get the software details
string SoftwareQuery = "SELECT * FROM Win32_Product";
ConnectionOptions connection = new ConnectionOptions();
connection.Username = "bla bla";
connection.Password = "Password";
connection.EnablePrivileges = true;
connection.Impersonation = ImpersonationLevel.Impersonate;
ManagementScope managementScope = new ManagementScope(#"\\xxxx.xxxx.cloudapp.azure.com:3389\root\CIMV2", connection);
managementScope.Path = ManagementPath.DefaultPath;
managementScope.Connect();
ObjectQuery queryObj = new ObjectQuery(SoftwareQuery);
ManagementObjectSearcher searcher = new ManagementObjectSearcher(managementScope, queryObj);
foreach (ManagementBaseObject managementObj in searcher.Get())
{
//get the software list here
}
Note: The above code is working on intranet properly
Please let me know anyone have solution on this.
It might be related to the Windows Management Instrumentation service being in a stopped state. Take a look at Starting and Stopping the WMI Service.
Hope it helps!
I have an ASP.NET website (running v2.0) and a SQL Server database (2012) and I'm getting a strange error when many people hit the page. The error is:
Column 'product_code' does not belong to table . // occurs on line 'if (!row.IsNull("product_code") && !row.IsNull("state"))' below
Which seems to indicate there's some sort of connection sharing going on between threads, but I can't seem to figure out why. In the code behind I have:
private Dictionary<string, string> _saleStates = null;
protected Dictionary<string, string> SalesStates {
get {
if (_saleStates == null)
{
_saleStates = new Dictionary<string, string>();
string sql = #"SELECT [product_code], [state] FROM [jsb_store_items]";
using (DataTable tbl = new DataTable())
{
using (SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["Shop.DbConnection"].ConnectionString))
{
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
using (SqlDataAdapter adapter = new SqlDataAdapter(cmd))
{ adapter.Fill(tbl); }
}
}
if (tbl.Rows.Count > 0)
{
foreach (DataRow row in tbl.Rows)
{
if (!row.IsNull("product_code") && !row.IsNull("state")) // Error thrown here
{ _saleStates.Add(row["product_code"].ToString().ToLower(), salesStateToText(row["state"].ToString().ToLower())); }
}
}
}
}
return _saleStates;
}
}
protected string getSalesStates() {
string output = "";
int i = 0;
foreach (KeyValuePair<string, string> entry in SalesStates) {
output += ((i!=0) ? "," : "") + "\"" + entry.Key + "\":\"" + entry.Value + "\"";
i++;
}
output = "{" + output + "}";
return output;
}
and in the markup I have:
<script type="text/javascript">var sales_states = <% Response.Write(this.getSalesStates()); %>;</script>
If someone can help me figure out why this is happening I'd really appreciate it.
Since you are just populating a dictionary, try using a SqlDataReader instead of the DataTable and SqlDataAdapter. You can then loop through the resultset. This should be a bit faster and do what you need.
Try adding [dbo]. prefix to tablename, like this:
string sql = #"SELECT [product_code], [state] FROM [dbo].[jsb_store_items]";
Odd things can happen without the dbo prefix, especially if you don't have direct control of creating the objects yourself, such as in a production environment.
I have tested the code you have posted on my machine and it works.
Need database details (e.g table,fields etc.) also the connection string which you have used to get the data from the database.To see why issue occurs?
So the answer was kinda silly. In production we have two webservers behind a load-balancer and at some point I decided to test the two servers independently by hitting them directly. This allowed me to discover one server was throwing the error 90% of the time and one server next to 0% of the time. I restarted the website and app pools for the server that was throwing it often and it seems to have stopped.
One of the things that clued me in was that I had updated my error logging routines to try and log additional info about the error and I was still seeing the error being thrown without the newer details.
I think the issue is that the dlls being used were old despite the code being updated. This is a web site and not a web application so the code gets compiled on first request. By resetting the site I think it re-compiled everything and things started working as intended.
I am currently rewriting our deployment scripts to ensure the app pools and web site are reset/recycled on code changes to try and prevent this issue in the future.
Thank you for all your responses and I hope this helps someone else at some point.
I have a call to a 3rd party ODBC driver as follows:
var DbConnection = new OdbcConnection(#"DSN=QuickBooks Data;SERVER=QODBC;OptimizerDBFolder=%UserProfile%\QODBC Driver for QuickBooks\Optimizer;OptimizerAllowDirtyReads=N;SyncFromOtherTables=Y;IAppReadOnly=Y");
var tb = new DataTable();
using (var ad = new OdbcDataAdapter("SELECT * FROM Customer", DbConnection))
{
ad.Fill(tb);
}
It runs from a colsole application fine, takes a few seconds.
But if I change nothing else but run it from a self hosted WCF service like this:
[ServiceContract]
public interface IQuickBooksService
{
[OperationContract]
DataTable GetQuickBooksData(string query);
}
public class QuickBooksService : IQuickBooksService
{
public DataTable GetQuickBooksData(string query)
{
var DbConnection = new OdbcConnection(#"DSN=QuickBooks Data;SERVER=QODBC;OptimizerDBFolder=%UserProfile%\QODBC Driver for QuickBooks\Optimizer;OptimizerAllowDirtyReads=N;SyncFromOtherTables=Y;IAppReadOnly=Y");
var tb = new DataTable();
using (var ad = new OdbcDataAdapter("SELECT * FROM Customer", DbConnection))
{
ad.Fill(tb);
}
return tb;
}
}
I can see the driver working via a status panel it provides but at a pathetic snail pace.
I'm kind of stumped. Any help is appreciated.
Note: the way I'm going to get around this if I don't solve it is to use the database as a message queue and make the (fast) console app poll for messages and put results back into the database (maybe a temp table, I don't know) by dumping the datatable out to XML.
Perhaps due to the reason you serrialize DataTable that contains much data? If you need to poll database through WCF I would use something lighter than DataTable and consider asynch operations
I'm looking to compile data from a few diffrent custome lists in sharepoint 2007
Its a hosted sharepoint site so I don't have access to the machine backend.
Is there any example code to access the sharepoint site using c#?
here is my code thus far (i get the error Cannot connect to the Sharepoint site ''. Try again later.)
DataSet dt = new DataSet();
string query = "SELECT * FROM list";
string site = "http://sp.markonsolutions.com/Lists/Security/";
string list = "35E70EO4-6072-4T55-B741-4B75D5F3E397"; //security db
string myConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;WSS;IMEX=2;RetrieveIds=Yes; DATABASE="+site+";LIST={"+list+"};";
OleDbConnection myConnection = new OleDbConnection();
myConnection.ConnectionString = myConnectionString;
OleDbCommand myAccessCommand = new OleDbCommand(query,myConnection);
OleDbDataAdapter myDataAdapter = new OleDbDataAdapter(myAccessCommand);
myConnection.Open();
myDataAdapter.Fill(dt);
//execute queries, etc
myConnection.Close();
If you can't deploy code on the SharePoint machine, then you pretty much have to use the web services.
The lists web service is what you're after.
It will be located on http://yousharepointsite.com/_vti_bin/Lists.asmx and should be open by default. Note that if your site is configured with FBA, you will have to use the _vti_bin/Authentication.asmx to log in before you query lists.asmx.
Here is an article that gives all the information you need :
http://sharepointmagazine.net/articles/writing-caml-queries-for-retrieving-list-items-from-a-sharepoint-list
For the reasons mentioned above, skip the part on using the object model to query SharePoint lists and go directly to Retrieving list items with CAML using the SharePoint web services.
The article is pretty complete, so I think you should be OK with that.
As per your edit, I don't think that you can create a connection to your remote site like that. You can't query SharePoint with SQL like that, you really need to use CAML...
Once you've added the reference to the web service :
ListService listsClient = new ListService.Lists();
listsClient.Url = #"http://sp.markonsolutions.com/" + #"/_vti_bin/lists.asmx";
listsClient.Credentials = System.Net.CredentialCache.DefaultCredentials;
listsClient.GetListItems(...);
Read more on the GetListItems here
Like I said, you need to use the web services. You are heading towards a dead end if you are trying to create connection like that to query the database directly. It is not recommended.
Not sure if what you try to do is possible unless you use an ado.net connector for SharePoint, have a look at http://www.bendsoft.com/net-sharepoint-connector/
It enables you to talk to SharePoint lists as if they where ordinary sql-tables
In example to insert some data
public void SharePointConnectionExample1()
{
using (SharePointConnection connection = new SharePointConnection(#"
Server=mysharepointserver.com;
Database=mysite/subsite
User=spuser;
Password=******;
Authentication=Ntlm;
TimeOut=10;
StrictMode=True;
RecursiveMode=RecursiveAll;
DefaultLimit=1000;
CacheTimeout=5"))
{
connection.Open();
using (SharePointCommand command = new SharePointCommand("UPDATE `mytable` SET `mycolumn` = 'hello world'", connection))
{
command.ExecuteNonQuery();
}
}
}
Or to select list data to a DataTable
string query = "SELECT * FROM list";
conn = new SharePointConnection(connectionString);
SharePointDataAdapter adapter = new SharePointDataAdapter(query, conn);
DataTable dt = new DataTable();
adapter.Fill(dt);
Or using a helper method to fill a DataGrid
string query = "Select * from mylist.viewname";
DataGrid dataGrid = new DataGrid();
dataGrid.DataSource = Camelot.SharePointConnector.Data.Helper.ExecuteDataTable(query, connectionString);
dataGrid.DataBind();
Controls.Add(dataGrid);
I am trying to build a .NET web application using SQL to query AS400 database. This is my first time encountering the AS400.
What do I have to install on my machine (or the AS400 server) in order to connect?
(IBM iSeries Access for Windows ??)
What are the components of the connection string?
Where can I find sample codes on building the Data Access Layer using SQL commands?
Thanks.
You need the AS400 .Net data provider. Check here:
https://www-01.ibm.com/support/docview.wss?uid=isg3T1027163
For connection string samples, check here:
https://www.connectionstrings.com/as-400/
Also, check out the redbook for code examples and getting started.
http://www.redbooks.ibm.com/redbooks/pdfs/sg246440.pdf
Following is what I did to resolve the issue.
Installed the IBM i Access for Windows. Not free
Referred the following dlls in the project
IBM.Data.DB2.iSeries.dll
Interop.cwbx.dll (If Data Queue used)
Interop.AD400.dll (If Data Queue used)
Data Access
using (iDB2Command command = new iDB2Command())
{
command.Connection = (iDB2Connection)_connection;
command.CommandType = CommandType.Text;
command.Parameters.AddWithValue(Constants.ParamInterfaceTransactionNo, 1);
command.CommandText = dynamicInsertString;
command.ExecuteScalar();
}
Connection String
<add name="InterfaceConnection"
connectionString="Data Source=myserver.mycompany.com;User ID=idbname;Password=mypassxxx;
Default Collection=ASIPTA;Naming=System"/>
UPDATE
i Access for Windows on operating systems beyond Windows 8.1 may not be supported. Try the replacement product IBM i Access Client Solutions
IBM i Access Client Solutions
As mentioned in other answers, if you have the IBM i Access client already installed, you can use the IBM.Data.DB2.iSeries package.
If you don't have the IBM i Access software, you can leverage JTOpen and use the Java drivers. You'll need the nuget package JT400.78 which will pull in the IKVM Runtime.
In my case I needed to query a DB2 database on an AS400 and output a DataTable. I found several hints and small snippets of code but nothing comprehensive so I wanted to share what I was able to build up in case it helps someone else:
using com.ibm.as400.access;
using java.sql;
var sql = "SELECT * FROM FOO WITH UR";
DriverManager.registerDriver(new com.ibm.as400.access.AS400JDBCDriver());
Connection conn = DriverManager.getConnection(
"jdbc:as400:" + ServerName + ";prompt=false", UserName, Password);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql);
ResultSetMetaData md = rs.getMetaData();
int ct = md.getColumnCount();
DataTable dt = new DataTable();
for(int i=1; i<=ct; i++)
dt.Columns.Add(md.getColumnName(i));
while (rs.next())
{
var dr = dt.NewRow();
for (int i = 1; i <= ct; i++)
dr[i - 1] = rs.getObject(i);
dt.Rows.Add(dr);
}
rs.close();
The conversion from RecordSet to DataTable is a little clunky and gave me bad flashbacks to my VBScript days. Performance likely isn't blinding fast, but it works.
Extremely old question - but this is still relevant. I needed to query our AS/400 using .NET but none of the answers above worked and so I ended up creating my own method using OleDb:
public DataSet query_iseries(string datasource, string query, string[] parameterName, string[] parameterValue)
{
try
{
// Open a new stream connection to the iSeries
using (var iseries_connection = new OleDbConnection(datasource))
{
// Create a new command
OleDbCommand command = new OleDbCommand(query, iseries_connection);
// Bind parameters to command query
if (parameterName.Count() >= 1)
{
for (int i = 0; i < parameterName.Count(); i++)
{
command.Parameters.AddWithValue("#" + parameterName[i], parameterValue[i]);
}
}
// Open the connection
iseries_connection.Open();
// Create a DataSet to hold the data
DataSet iseries_data = new DataSet();
// Create a data adapter to hold results of the executed command
using (OleDbDataAdapter data_adapter = new OleDbDataAdapter(command))
{
// Fill the data set with the results of the data adapter
data_adapter.Fill(iseries_data);
}
return iseries_data;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return null;
}
}
And you would use it like so:
DataSet results = query_iseries("YOUR DATA SOURCE", "YOUR SQL QUERY", new string[] { "param_one", "param_two" }, new string[] { "param_one_value", "param_two_value"});
It returns a DataSet of the results returned. If anyone needs/wants a method for inserting/updating values within the IBM AS/400, leave a comment and I'll share...
I'm using this code and work very good for me!
Try
Dim sqltxt As String = "SELECT * FROM mplib.pfcarfib where LOTEF=" & My.Settings.loteproceso
dt1 = New DataTable
Dim ConAS400 As New OleDb.OleDbConnection
ConAS400.ConnectionString = "Provider=IBMDA400;" & _
"Data Source=192.168.100.100;" & _
"User ID=" & My.Settings.usuario & ";" & _
"Password=" & My.Settings.contrasena
Dim CmdAS400 As New OleDb.OleDbCommand(sqltxt, ConAS400)
Dim sqlAS400 As New OleDb.OleDbDataAdapter
sqlAS400.SelectCommand = CmdAS400
ConAS400.Open()
sqlAS400.Fill(dt1)
grid_detalle.DataSource = dt1
grid_detalle.DataMember = dt1.TableName
Catch ex As Exception
DevExpress.XtraEditors.XtraMessageBox.Show("ComunicaciĆ³n Con El AS400 No Establecida, Notifique a Informatica..", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
Me.Close()
End Try
I recently found the ADO.Net driver available on NuGet. I have the iSeries client access installed on my PC, so I can't say if it works as a standalone, but it does connect. Theonly problem is I can't actually see any tables or procedures. I think there may be a schema or library or something I still haven't gotten down to. I will post if I find the answer. Meanwhile I can still get to the server and write most of my code with the NuGet adapter.
Check out http://asna.com/us/ as they have some development tools working with SQL and the AS400.