SQL Server 2016 list instances - smo

I am using the code below in my windows application to get local servers, when I was using SQL Server 2012 it was working without any errors, but when I downloaded SQL Server 2016, I got the exception :
Exception: An exception occurred in SMO while trying to manage a service.
Inner Exception: Failed to retrieve data for this request.
The Code:
public List<string> findLocalServers()
{
var servers = new List<string>();
try
{
var serverCollection = new ManagedComputer().ServerInstances.Cast<ServerInstance>().Select(instance => String.IsNullOrEmpty(instance.Name) ?
instance.Parent.Name : instance.Parent.Name)
.ToArray();
foreach (var server in serverCollection.Where(server => !servers.Contains(server)))
{
servers.Add(server);
}
return servers;
}
catch (Exception ex)
{
return null;
}
}

I had same problem. These steps helped me.
Reference to Microsoft.SqlServer.ConnectionInfo increased to version 13.x.x.x (via Add reference -> and find upper version in Extensions).
Same step for Microsoft.SqlServer.Management.Sdk.Sfc and Microsoft.SqlServer.Smo.
I did not find increased version for Microsoft.SqlServer.SqlWmiManagement. So I removed reference to this assembly and via browse I founded C:\Program Files\Microsoft SQL Server\130\SDK\Assemblies\Microsoft.SqlServer.SqlWmiManagement.dll.
That´s all.

Related

MS Dynamics 365 Online Plugin External Rest API access gives error

I am trying to access an external third party API from a Dynamics 365 Online plugin using the following code:
public void Execute(IServiceProvider serviceProvider)
{
//Extract the tracing service for use in plug-in debugging.
ITracingService tracingService =
(ITracingService)serviceProvider.GetService(typeof(ITracingService));
try
{
tracingService.Trace("Downloading the target URI: " + webAddress);
try
{
//<snippetWebClientPlugin2>
// Download the target URI using a Web client. Any .NET class that uses the
// HTTP or HTTPS protocols and a DNS lookup should work.
using (WebClient client = new WebClient())
{
byte[] responseBytes = client.DownloadData(webAddress);
string response = Encoding.UTF8.GetString(responseBytes);
//</snippetWebClientPlugin2>
tracingService.Trace(response);
// For demonstration purposes, throw an exception so that the response
// is shown in the trace dialog of the Microsoft Dynamics CRM user interface.
throw new InvalidPluginExecutionException("WebClientPlugin completed successfully.");
}
}
catch (WebException exception)
{
string str = string.Empty;
if (exception.Response != null)
{
using (StreamReader reader =
new StreamReader(exception.Response.GetResponseStream()))
{
str = reader.ReadToEnd();
}
exception.Response.Close();
}
if (exception.Status == WebExceptionStatus.Timeout)
{
throw new InvalidPluginExecutionException(
"The timeout elapsed while attempting to issue the request.", exception);
}
throw new InvalidPluginExecutionException(String.Format(CultureInfo.InvariantCulture,
"A Web exception occurred while attempting to issue the request. {0}: {1}",
exception.Message, str), exception);
}
}
catch (Exception e)
{
tracingService.Trace("Exception: {0}", e.ToString());
throw;
}
}
}
But I am getting the error:
Request for the permission of type 'System.Security.Permissions.SecurityPermission, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.'
I have checked MS documentation but nothing suggests why I am unable to do this. I know about sandboxed plugins but according to MS I should be able to do this using their own sample code.
This is expected in CRM Online, as this is SaaS and you're in a shared tenant in cloud. You can do either webhook or Azure service hub to trigger external endpoint with CRM context for processing. Read more
And if you've got CRM Online, then the normal solution is to offload the processing to an environment that you have more control over. The most common option is to offload the processing to Azure, using the Azure Service Bus or Azure Event Hub. The alternative, new to CRM 9, is to send the data to a WebHook, which can be hosted wherever you like.

Powershell Invoke method neither throwing exception nor returning result

I am trying to build an ASP.Net, c# application to expose few IIS management related activities through web interface for a distributed Admin group.
I am making use of System.Management.Automation V3.0 library to wrap power shell commands. As a first step I wanted to list all Web Applications that are currently up and running on local IIS by invoking Get-WebApplication command.
This is where I am facing the issue. Method call is neither throwing any exception nor its returning the result. Does anyone know the root cause of this issue? Please share your experience of building such interface using System.Management.Automation.dll.
var shell = PowerShell.Create();
shell.Commands.AddScript("Get-WebApplication | Out-String");
try
{
var results = shell.Invoke();
if (results.Count > 0)
{
var builder = new StringBuilder();
foreach (var psObject in results)
{
builder.Append(psObject.BaseObject.ToString() + "\r\n");
}
}
}
catch(Exception ex)
{
throw;
}
PS: Get-Service in place of Get-WebApplication works absolutely fine by returning list of services available on the machine.
PowerShell.Create() does not create new PowerShell process. If you does not specify Runspace for it, then it will create new in-process Runspace. Since it run in your process, it will match your process bitness and you can not change that. To create Runspace with different bitness you need to create out of process Runspace. Here is a sample console application, which demonstrate how you can do that:
using System;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
public static class TestApplication {
public static void Main() {
Console.WriteLine(Environment.Is64BitProcess);
using(PowerShellProcessInstance pspi = new PowerShellProcessInstance()) {
string psfn = pspi.Process.StartInfo.FileName;
psfn=psfn.ToLowerInvariant().Replace("\\syswow64\\", "\\sysnative\\");
pspi.Process.StartInfo.FileName=psfn;
using(Runspace r = RunspaceFactory.CreateOutOfProcessRunspace(null, pspi)) {
r.Open();
using(PowerShell ps = PowerShell.Create()) {
ps.Runspace=r;
ps.AddScript("[Environment]::Is64BitProcess");
foreach(PSObject pso in ps.Invoke()) {
Console.WriteLine(pso);
}
}
}
}
}
}
If you compile this application as x32, it still will use x64 out of process Runspace on x64 operation system.

MongoDB Driver 2.0 C# is there a way to find out if the server is down? In the new driver how do we run the Ping command?

How do you call the Ping command with the new C# driver 2.0?
In the old driver it was available via Server.Ping()? Also, Is there a way to find out if the server is running/responding without running the actual query?
Using mongoClient.Cluster.Description.State doesn't help because it still gave the disconnected state even after the mongo server started responding.
You can check the cluster's status using its Description property:
var state = _client.Cluster.Description.State
If you want a specific server out of that cluster you can use the Servers property:
var state = _client.Cluster.Description.Servers.Single().State;
This worked for me on both c# driver 2 and 1
int count = 0;
var client = new MongoClient(connection);
// This while loop is to allow us to detect if we are connected to the MongoDB server
// if we are then we miss the execption but after 5 seconds and the connection has not
// been made we throw the execption.
while (client.Cluster.Description.State.ToString() == "Disconnected") {
Thread.Sleep(100);
if (count++ >= 50) {
throw new Exception("Unable to connect to the database. Please make sure that "
+ client.Settings.Server.Host + " is online");
}
}
As #i3arnon's answer I can tell it was reliable for me in this way:
var server = client.Cluster.Description.Servers.FirstOrDefault();
var serverState = ServerState.Disconnected;
if (server != null) serverState = server.State;
or in new versions of .Net
var serverState = client.Cluster.Description.Servers.FirstOrDefault()?.State
?? ServerState.Disconnected;
But if you realy want to run a ping command you can do it like this:
var command = new CommandDocument("ping", 1);
try
{
db.RunCommand<BsonDocument>(command);
}
catch (Exception ex)
{
// ping failed
}

Handle JDBC exception in BIRT API

I have a scheduler job which is based on a standalone RunAndRenderTask. The report design connects to a remote mysql database to fetch data. The scheduler generates a PDF and emails the report as attachment to a set of people. This works as long as the database is available.
But when the database is unavailable, then I can see the error in the logs, but the RunAndRenderTask still generates a PDF report which is blank and useless, and this gets emailed by the scheduler. I need to be able to catch this exception and instead email another set of people who can fix the DB issue. I tried various things but couldn't figure out how to do it.
In the code below, I expect the API to return an exception, and hence print "BirtException" or "Exception", but this code prints "Success" even when there is a JDBC exception.
Any help is appreciated.
Here's the code I have.
IReportEngine engine = null;
IRunAndRenderTask runAndRenderTask = null;
try {
EngineConfig config = new EngineConfig();
config.setEngineHome("birt-runtime-4_4_0/RuntimeEngine");
Platform.startup(config);
IReportEngineFactory factory = (IReportEngineFactory) Platform
.createFactoryObject(IReportEngineFactory.EXTENSION_REPORT_ENGINE_FACTORY);
engine = factory.createReportEngine(config);
IReportRunnable reportRunnable = engine.openReportDesign(DATA_PATH + "sample.rptdesign");
runAndRenderTask = engine.createRunAndRenderTask(reportRunnable);
PDFRenderOption option = new PDFRenderOption();
option.setOutputFileName(DATA_PATH + "output.pdf");
option.setOutputFormat("pdf");
runAndRenderTask.setRenderOption(option);
runAndRenderTask.run();
System.out.println("Success!");
} catch (BirtException e) {
System.out.println("BirtException");
e.printStackTrace();
} catch (Throwable e) {
System.out.println("Exception");
e.printStackTrace();
} finally {
if (runAndRenderTask != null) {
runAndRenderTask.close();
}
if (engine != null) {
engine.destroy();
}
Platform.shutdown();
RegistryProviderFactory.releaseDefault();
}
This is the exception stacktrace, which never gets propagated back by RunAndRenderTask.run()
INFO: Loaded JDBC driver class in class path: com.mysql.jdbc.Driver
Jun 26, 2014 9:26:43 PM org.eclipse.birt.data.engine.odaconsumer.ConnectionManager openConnection
SEVERE: Unable to open connection.
org.eclipse.birt.report.data.oda.jdbc.JDBCException: There is an error in get connection, Communications link failure
The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server..
at org.eclipse.birt.report.data.oda.jdbc.JDBCDriverManager.doConnect(JDBCDriverManager.java:336)
at org.eclipse.birt.report.data.oda.jdbc.JDBCDriverManager.getConnection(JDBCDriverManager.java:235)
at org.eclipse.birt.report.data.oda.jdbc.Connection.connectByUrl(Connection.java:252)
at org.eclipse.birt.report.data.oda.jdbc.Connection.open(Connection.java:162)
at org.eclipse.datatools.connectivity.oda.consumer.helper.OdaConnection.open(OdaConnection.java:250)
at org.eclipse.birt.data.engine.odaconsumer.ConnectionManager.openConnection(ConnectionManager.java:165)
at org.eclipse.birt.data.engine.executor.DataSource.newConnection(DataSource.java:224)
at org.eclipse.birt.data.engine.executor.DataSource.open(DataSource.java:212)
at org.eclipse.birt.data.engine.impl.DataSourceRuntime.openOdiDataSource(DataSourceRuntime.java:217)
at org.eclipse.birt.data.engine.impl.QueryExecutor.openDataSource(QueryExecutor.java:435)
at org.eclipse.birt.data.engine.impl.QueryExecutor.prepareExecution(QueryExecutor.java:322)
at org.eclipse.birt.data.engine.impl.PreparedQuery.doPrepare(PreparedQuery.java:463)
at org.eclipse.birt.data.engine.impl.PreparedDataSourceQuery.produceQueryResults(PreparedDataSourceQuery.java:190)
at org.eclipse.birt.data.engine.impl.PreparedDataSourceQuery.execute(PreparedDataSourceQuery.java:178)
at org.eclipse.birt.data.engine.impl.PreparedOdaDSQuery.execute(PreparedOdaDSQuery.java:178)
at org.eclipse.birt.report.data.adapter.impl.DataRequestSessionImpl.execute(DataRequestSessionImpl.java:637)
at org.eclipse.birt.report.engine.data.dte.DteDataEngine.doExecuteQuery(DteDataEngine.java:152)
at org.eclipse.birt.report.engine.data.dte.AbstractDataEngine.execute(AbstractDataEngine.java:275)
at org.eclipse.birt.report.engine.executor.ExtendedGenerateExecutor.executeQueries(ExtendedGenerateExecutor.java:205)
at org.eclipse.birt.report.engine.executor.ExtendedGenerateExecutor.execute(ExtendedGenerateExecutor.java:65)
at org.eclipse.birt.report.engine.executor.ExtendedItemExecutor.execute(ExtendedItemExecutor.java:62)
at org.eclipse.birt.report.engine.internal.executor.dup.SuppressDuplicateItemExecutor.execute(SuppressDuplicateItemExecutor.java:43)
at org.eclipse.birt.report.engine.internal.executor.wrap.WrappedReportItemExecutor.execute(WrappedReportItemExecutor.java:46)
at org.eclipse.birt.report.engine.internal.executor.l18n.LocalizedReportItemExecutor.execute(LocalizedReportItemExecutor.java:34)
at org.eclipse.birt.report.engine.layout.html.HTMLBlockStackingLM.layoutNodes(HTMLBlockStackingLM.java:65)
at org.eclipse.birt.report.engine.layout.html.HTMLPageLM.layout(HTMLPageLM.java:92)
at org.eclipse.birt.report.engine.layout.html.HTMLReportLayoutEngine.layout(HTMLReportLayoutEngine.java:100)
at org.eclipse.birt.report.engine.api.impl.RunAndRenderTask.doRun(RunAndRenderTask.java:181)
at org.eclipse.birt.report.engine.api.impl.RunAndRenderTask.run(RunAndRenderTask.java:77)
at test.ReportTester.test(ReportTester.java:50)
at test.ReportTester.main(ReportTester.java:19)
In addition to catching BirtException, you should be aware that the way BIRT handles Javascript errors is - by default - browser-like. That is, BIRT tries to continue generating the report.
There are different ways to handle this for production-quality code (where task is a RunAndRenderTask or RunTask or RenderTask):
Use task.setErrorHandlingOption(CANCEL_ON_ERROR) (see BIRT docs). Personally, I have never tried this.
After task.run(...), but before task.close(), call task.getErrors(). If this list is not empty, your code should output these messages and throw an exception.
You need to add catch block that catches EngineException, not JDBC exception.
You can find javadocs at link.

Deploying a project that includes an MDF file to an external computer

Basically, I have a Windows Forms Application that includes a dataGridView with the DataSource being an MDF file named VoRteXData.mdf. Now, I need to deploy this to an external location. For my forms code, it includes:
private void Form1_Load(object sender, EventArgs e)
{
SqlConnection sqlCon = new SqlConnection();
sqlCon.ConnectionString = #"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Moderator\Documents\VoRteXData.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True";
sqlCon.Open();
SqlDataAdapter sda = new SqlDataAdapter("select * from VoRteXBanTable", sqlCon);
DataTable dt = new DataTable();
sda.Fill(dt);
dataGridView1.DataSource = dt;
}
private void button1_Click(object sender, EventArgs e)
{
string searchFilter = textBox1.Text;
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
if (dataGridView1.Rows[i].Cells[0].Value.ToString() == searchFilter)
{
dataGridView1.Rows[i].Selected = true;
dataGridView1.Rows[i].Visible = true;
}
else
{
dataGridView1.CurrentCell = null;
dataGridView1.Rows[i].Visible = false;
dataGridView1.Rows[i].Selected = false;
}
}
}
}
Next, in my MDF file is one table and 5 fields with around 50 records. Upon publishing the project to an external computer, I get an error: "A network-related or instance-specific error occurred while establishing a connection to SQL server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL server is configured to allow remote connections". However, I'm not using SQL Server Management Studio because I need to deploy this at an external location without a host. I don't want the user to install all the SQL prerequisites because, that would be ridiculous. So is there any way to get C# to run this MDF file at all? Or mabye upload it to the web for free?
The client machine must have SQL Server Express installed. You can include this in the setup.exe by including it as a prerequisite. This will only install the database engine. But, if you do not want the client machine to have SQL Server Express installed then you need to change your app to use SQL Server Compact. That way it will not need a SQL Server instance installed on the client.