how to ping database from winform c# - c#

I need to find out if my database is running, and I have to do it in a WinForm in C#.
From the command prompt (in windows 7) I run the following command:
dbping -c "uid=sos;pwd=cdpbszqe;eng=mydatabase;dbn=mydatabase;links=tcpip" -pd file -d > result.txt
The result is written (redirected) to the result.txt file
which I open and see if it was successful
How can i do the same from in C# code using WinForms?
Is it possible to ping and get a result if successful?
Do I have to ping and create a text file from the ping result, then open it in my C# App?
What's the best way to proceed?
thanks.

No need for batch files if you just want to check if you can connect (i.e. it is running). We can test in a few line in C#.
private bool TestConnection()
{
using (var conn = new SqlConnection("connection string")
{
try
{
conn.Open();
return true;
}
catch(Exception ex)
{
//log exception
}
return false;
}
}

just create a batch file with above command and run it from your windows forms application using Process class. Get some help from :
Executing Batch File in C#
Which will create your result.txt file and you can read it using any File.ReadAllLines() or whatever method you want to use.

Related

SSH Connection via C#

This is the situation. I have a Windows machine and a Linux machine. There is a shared drive between these two machines (which is mapped to Q:). I am trying to figure out how to create an SSH session at the Q: drive (shared drive) from C#. I am trying to use the SharpSsh library to do this.
This is what I have so far, however, it is giving me an error:
try
{
ssh = new SshStream(host, username, password);
Console.WriteLine("OK ({0}/{1})", ssh.Cipher, ssh.Mac);
Console.WriteLine("Server version={0}, Client version={1}", ssh.ServerVersion, ssh.ClientVersion);
Console.WriteLine("-Use the 'exit' command to disconnect.");
Console.WriteLine();
//Sets the end of response character
ssh.Prompt = "#";
//Remove terminal emulation characters
ssh.RemoveTerminalEmulationCharacters = true;
//Reads the initial response from the SSH stream
Console.Write(ssh.ReadResponse()); // Blocking here
while (true)
{
string command = Console.ReadLine();
if (command.ToLower().Equals("exit"))
break;
//Write command to the SSH stream
ssh.Write(command);
//Read response from the SSH stream
Console.Write(ssh.ReadResponse());
}
}
catch(Exception e)
{
Console.WriteLine(e.Message);
}
if(ssh != null)
{
ssh.Close();
}
I have added the Tamir.SharpSSH.dll as a reference to the project, and I am using it in the project. There are two other dll's that are included with SharpSSH, do I need to add them as well to the references? The examples I have seen only have the Tamir.SharpSSH.dll as a reference.
I am not sure how to initiate the connection in the correct location, and how to submit commands properly to the ssh.
UPDATE
I realized I needed to close the SSH connection before ending the program. The error does not exist anymore, however, I am still not getting any information from my "ls" command.
UPDATE
I updated the code with what I have now. It seems like the ssh.ReadResponse() is blocking, which leads me to believe the server is not responding. Is that correct?

Compile in C using a Windows Forms Application

I'm creating a compiler App in C#, using Visual Studio 2010.
The goal of this program is to compile a code written in either C# or C at runtime and return the results of the compilation.
I have done the C# part, but the C part is the one I have problems. For this one, I've tried to use the Visual Studio Command Prompt. The way I'm coding this part is like this:
Create a .c file in C:\ using File.Create.
Using a Process, open the Visual Studio Command Prompt and execute the compilation.
Capture the output to return it as the compilation results.
However, it doesn't work. It throws and Win32 exception, but I don't really know why.
I've heard something about using gcc. But I thought about using the Visual Studio Command Prompt as a possible solution.
EDIT: I figured out the steps to do it (I think). But the Win32 exception appears when the program tries to do the process.Start() line. I guess this might be a permissions problem, but I don't really know.
A friend of mine worked on something similar, and helped me to solve this problem.
On steps 2 and 3, I was trying to write the input and read the output using simply the process standard input and output, and also, I was trying to use an .lnk to run the Command Prompt. All those things caused the error.
The solution was:
Create two batch files, one to start up the Command Prompt and the other to compile the .c file (those were created outside the program's code).
(On runtime) Create the .c file, using the code written. If file exists, delete it and create a new one.
Start the process with cmd.exe.
Run the batch files, using a Stream Writer to write them in the cmd.exe.
Retrieve the output using a Stream Reader.
Fortunately, this worked! Code ended like this:
string CompileC (string code)
{
string path = #"C:\sample.c";
string results = "";
try
{
if (File.Exists(path))
File.Delete(path);
using (FileStream fs = File.Create(path))
{
byte[] codeText = new UTF8Encoding(true).GetBytes(code);
fs.Write(codeText, 0, codeText.Length);
}
Process process = new Process();
process.StartInfo.FileName = #"C:\Windows\system32\cmd.exe";
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardInput = true;
process.StartInfo.RedirectStandardOutput = true;
process.Start();
using (StreamWriter sw = process.StandardInput)
{
if (sw.BaseStream.CanWrite)
{
//This batch starts up the Visual Studio Command Prompt.
sw.WriteLine(#"C:\Startup.bat");
//This batch does the compilation, once the Command Prompt
//is running, using the 'cl' command.
sw.WriteLine(#"C:\Compile.bat");
}
}
using (StreamReader sr = process.StandardOutput)
{
if (sr.BaseStream.CanRead)
results = sr.ReadToEnd();
}
}
catch (Exception ex) { MessageBox.Show(ex.ToString()); }
return results;
}

Wix - File is locked for delete after opening its database

I have some problems while trying using WindowsInstaller library or Wix Microsoft.Deployment.WindowsInstaller.
I'm, getting exception that the file being used by the process and I cannot delete it even though I've closed all record,view and database and disposed them.
try
{
string currentDir = Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName;
string msiPath = "PathTo\MyMSI.msi";
using (InstallPackage installPackage = new InstallPackage(msiPath, DatabaseOpenMode.ReadOnly))
{
string query = "SELECT * FROM Property WHERE Property = 'ProductVersion'";
using (View view = installPackage.OpenView(query))
{
view.Execute();
using (Record record = view.Fetch())
{
string version = record.GetString(2);
Console.WriteLine(version);
record.Close();
}
view.Close();
}
installPackage.Close();
}
File.Delete(msiPath);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
And still I get the following:
Access to the path 'PathTo\MyMSI.msi' is denied.
I've also tried with the object
Database
Any help will be appreciated.
I was able to figure out what is blocking the delete action.
It appears that the file was in read only.
I don't know why I got this kind of exception but the following solved it:
//removing read only from file in order to interact with it
FileInfo fileInfo = new FileInfo(msiPath);
if (fileInfo.IsReadOnly)
{
fileInfo.IsReadOnly = false;
}
Hope it will help others.
I appreciate everyone who helped here for your time.
Below are some steps you could follow for ur problem :
Wait a minute and try deleting the file again, sometimes Windows or the program using the file may still be closing and therefore still using the file you're attempting to delete.
Close and Explorer window and re-open.
Locate the program using the file and close it. If you're uncertain what program is using the file, close all programs until you're able to delete the file.
Try using unlocker, a free software program designed to unlock any file being used by Windows or other programs without restarting the computer.
Reboot the computer. If after closing all programs you're still unable to delete the file, it's likely that something in the background is still using the file.
If after rebooting the computer you're still unable to delete the file, boot the computer into Safe Mode and delete the file.
Thanks

How to open an Access form, from within a Visual Studio C# Winform?

I need a link (most likely button, or similar) within my Visual Studio 2010 Windows form (c#), that will open up a pre-developed access form. Is this tricky or is it simpler than it sounds =P
Regards, Bserk
Description
Assuming you mean an Microsoft Access Database, you can use System.Diagnostics.Process to open any file / programm.
Sample
Process.Start("PathAndFileNameOfYourAccessDb");
More Information
MSDN: Process Class
MSDN: Process.Start Method (String)
C# Process.Start Examples
You can use the Library NDde on CodePlex to communicate with the Access application through DDE.
This is a code snippt extracted from one of my projects:
using (DdeClient client = new DdeClient("MSAccess", Path.GetFileName(theAccessApp))) {
if (!TryConnect(client)) {
Process.Start(theAccessApp);
Thread.Sleep(2000);
if (!TryConnect(client)) {
Messagebox.Show("Could not start: " + theAccessApp);
return;
}
}
// Close the form if open
client.Execute("[Close 2, \"MyForm\"]", 10000);
// Open the form
string openCmd = String.Format("[OpenForm \"MyForm\",,,,,,\"{0}\"]", anyOpenArgsParam);
client.Execute(openCmd, 10000);
}
With
private static bool TryConnect(DdeClient client)
{
try {
client.Connect();
return true;
} catch (DdeException) {
try {
client.Connect();
return true;
} catch (DdeException) {
return false;
}
}
}
The simplest way of doing this is to use the /x command line switch. This launches a macro named on the command line.
In your database create a new macro,
Drop down the list and select OpenForm,
Enter the name of your predefined form
set the options you require.
Save the macro and giving it a name such as MyMacro
Then just execute MSAccess with the name of the database and the /x switch like this:
"c:\Program Files\Microsoft Office\Office14\MSACCESS.EXE" "C:\Users\user\Documents\Database1.accdb" /x MyMacro
And access will open up the database with the named form.

C# SQL server connection

HI
As a daily check I have to check the SQL connection to all our servers. At the moment this is done by manually logging on through SQL server managment studio. I was just wondering if this can be coded in C# so that I can run it first thing in a morning and its checks each server and the instance for a valid SQL connection and reports back to say if the connection is live or not.
Thanks Andy
Here's a little console app example that will cycle through a list of connections and attempt to connect to each, reporting success or failure. Ideally you'd perhaps want to extend this to read in a list of connection strings from a file, but this should hopefully get you started.
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Text;
namespace SQLServerChecker
{
class Program
{
static void Main(string[] args)
{
// Use a dictionary to associate a friendly name with each connection string.
IDictionary<string, string> connectionStrings = new Dictionary<string, string>();
connectionStrings.Add("Sales Database", "< connection string >");
connectionStrings.Add("QA Database", "< connection string >");
foreach (string databaseName in connectionStrings.Keys)
{
try
{
string connectionString = connectionStrings[databaseName];
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
Console.WriteLine("Connected to {0}", databaseName);
}
}
catch (Exception ex)
{
// Handle the connection failure.
Console.WriteLine("FAILED to connect to {0} - {1}", databaseName, ex.Message);
}
}
// Wait for a keypress to stop the console closing.
Console.WriteLine("Press any key to finish.");
Console.ReadKey();
}
}
}
Look at the SqlConnection Class. It includes a basic sample. Just put a loop around that sample to connect to each server, and if any server fails to connect it throws an exception.
Then just set it up as a scheduled task in Windows.
A nice way to report the status might be with an email, which can easily be sent out with SmtpClient.Send (the link has a nice simple sample.
Why c#? You could make a simple batch file that does this using the osql command.
osql -S servername\dbname -E -Q "select 'itworks'"
You can also have a look at this method:
SqlDataSourceEnumerator.Instance.GetDataSources()
It gives you a list of SQL servers available on the network.
You know, they make monitoring tools that let you know if your sql server goes down . . .

Categories