c# express back up/restore database - c#

I am completely lost here and I am running out of time. Let me explain my situation:
I have created a software in C# express 2010 and SQL Server Express 2008 R2.
Now in the settings section of my software, the user is supposed to be able to make manual back ups/restores of the database.
Also he is supposed to be able to schedule back ups of the database, which will run at time that he will set.
I do not have a clue on how to get both of these working and I am hoping that someone here may point me in the correct direction.
I need to be able to create a
backup/restore of the database from
the click of a button
I need to be able to schedule backup
processes
Please keep in mind that when the user will install the software on his computer, he will not have sql server installed (I am saying this because I am under the impression that SMO requires sql server to be pre installed on the client machine).
Thank you

You could always try Google.
Backup
Restore
Automate backup scripts using the SQL Job Agent
I'm assuming you can create Windows Forms and wire up OnClick events, and run SqlCommand's against the database. Then it's just a matter of using the documentation above to write the appropriate queries when the user presses the appropriate button.
BTW: This is a Q&A site, not an emergency consultant shop. Don't say things like "I'm running out of time" and don't write up large lists of requirements and say tell me how to do this. You'll get absolutely no help that way. Ask specific questions after demonstrating your effort and specific technical problem.

You could look at this C# example for using SMO to backup the database
http://social.msdn.microsoft.com/forums/en-US/sqlexpress/thread/95750bdf-fcb1-45bf-9247-d7c0e1b9c8d2/
The other option is to run a process and call sqlcmd from code
http://www.sqldbatips.com/showarticle.asp?ID=27
Here is some sample code to execute process
string fileName = #"C:\Backup.sql";
ProcessStartInfo info = new ProcessStartInfo("sqlcmd", #" -S .\SQLExpress -U sa -d mydatabasename -o C:\sqlout.txt -i """ + #fileName + #""" -P");
info.UseShellExecute = false;
info.CreateNoWindow = true;
info.WindowStyle = ProcessWindowStyle.Hidden;
info.RedirectStandardOutput = true;
Process p = new Process();
p.StartInfo = info;
p.Start();

Related

C#0 net use connection

So I am having issues with the "net use" command in C#. Basically, I am using the code written here. The code works great, however I have multiple ids that need to be used sequentially. Unfortunately, when trying to connect to another ID, the connection remains in "net use " in Windows, so this exception is thrown:
Win32Exception: Multiple connections to a server or shared resource by the same user, using more than one user name, are not allowed.
Now to me, the obvious thing would be to execute the command prompt programmatically to delete the connection when I am done using it. Here is the code that I am running to delete the connection:
System.Diagnostics.Process process = new System.Diagnostics.Process();
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal;
startInfo.FileName = "cmd.exe";
startInfo.Arguments = "/K net use delete \\IPAddrofserver";
process.StartInfo = startInfo;
process.Start();
I only use /k so I can see if the command works. After this code executes, it says "The network connection cannot be found." However, if I manually open the start menu, and type net use, I can see and delete the connection. I think this may be related to the fact that when running the command prompt programmatically, I notice its being given administrative privilege as opposed to running it under my user token, but I cannot be sure. Any help regarding this would be greatly appreciated.
EDIT: Adding in the command prompt deletion code during the WnetCancelConnection2 actually operates correctly, and deletes the connection from net use. However, checking net use manually outside of the program reveals that the history of the connection still exists and is open. Whoami command reveals the same user. Any reason why there is a discrepancy between what happens programmatically and what happens when I check manually?
You probably need to start your process with elevated privileges. See the accepted answer here for how to do this. You could also choose to call the relevant Windows API directly, to avoid spawning other processes and dealing with those complications.

Running Bash Commands from C#

I am trying to figure out how to run a bash command from C# running on IIS 7/.Net 4.5.
I've been searching the web and a lot of answers presume you have certain things installed/in place.
I already have Git 1.9.4.msysgit.2 installed with Git Bash and Git Giu. I'm looking for some help as to what else I need installed to run even the simplest of bash commands. And how to run it.
I've looked at posts like bash pipes - I am trying to call script from c# but that uses cygwin. Can I do the same without it and if so, how do I go about it?
Goal
If what I'm asking above doesn't make sense or seems to ask separate questions, here my ultimate goal. I'm trying to write my own server-side git hook. When a developer pushes their commits to our GitHub repo, I want GitHub to call our callback url. I want my callback url to run a git pull command to update our staging server with what was just pushed.
I got to this question based on a previous question I asked at GitHub - setup auto deployment with remote server. based on answers there I'm trying to run a simple command, either but hard coding the command, or putting it in a script and running it, e.g.: cd $REPO_DIR && git pull origin $branch_name.
I am aware of Jenkins and other software, but I want to perform these commands myself vs. installing another software.
If further information is needed please feel free to ask.
Update 1
So based on a few answers below I've come up with the following
using System.Diagnostics;
Process process = new Process();
ProcessStartInfo processStartInfo = new ProcessStartInfo();
processStartInfo.WindowStyle = ProcessWindowStyle.Hidden;
processStartInfo.FileName = #"C:\Program Files (x86)\Git\bin\bash.exe";
processStartInfo.WorkingDirectory = #"C:\myrepo\mysite";
processStartInfo.Arguments = "git status";
processStartInfo.RedirectStandardOutput = true;
processStartInfo.RedirectStandardError = true;
processStartInfo.UseShellExecute = false;
process.StartInfo = processStartInfo;
process.Start();
String error = process.StandardError.ReadToEnd();
String output = process.StandardOutput.ReadToEnd();
ViewBag.Error = error;
ViewBag.Ouput = output;
With the code above I am getting "C:/Program Files (x86)/Git/bin/bash.exe": git: No such file or directory. I know the exe is there. What's am I doing wrong?
Update 2
As per #SurgeonofDeath comment I followed this post http://blog.countableset.ch/2012/06/07/adding-git-to-windows-7-path/ and added the paths of Git to my environmental variables. However I still am getting the same issues. Any ideas?
Thanks.
Instead of calling the bash.exe, simply call git and pass the status as argument:
processStartInfo.FileName = "git";
processStartInfo.Arguments = "status";
perhaps i misunderstood your question but what about execve?
here is an excerpt of it's man page.
NAME
execve - execute program
SYNOPSIS
#include <unistd.h>
int execve(const char *filename, char *const argv[],
char *const envp[]);
DESCRIPTION
execve() executes the program pointed to by filename. filename must > be
either a binary executable, or a script starting with a line of > the
form:
#! interpreter [optional-arg]
Check your PATH environment variable and update it
C:/Program Files (x86)/Git/bin/bash.exe": git: No such file or directory
means that it's git which is not found by bash.
1. Check the PATH environment variable in bash (which is and should remain different from Windows one)
Adjust this
processStartInfo.WindowStyle = ProcessWindowStyle.Hidden;
to make the terminal visible.
In the terminal you will create with the Process.Start()
Type:
echo ${PATH}
2. Update your path
You could update the global path of windows (which requires a restart)
You could update the user path of windows (which should require a logoff, but I'm not sure).
You just set Path to what you like with System.Environment.SetEnvironmentVariable before starting the Process
Additional note:
If you have like me several versions of bash, command interpreters, git and so on, it could be really messy if you try to concatenate all the paths and hope to find the ideal order. You could see some weird behavior of you beloved commands until you realize it's not the one you intend to run ... think of FIND.exe... And I didn't even think of the user-friendly interface of windows to edit environment variables ...

Execute batch from asp.net hangs

I'm running a batch from my ASP.NET c# page. I'm trying to use the System.Diagnostics.ProcessStartInfo method described in the link below. When I click my button to run the batch, the page just hangs with "Waiting for ".
The original code I'm using
Here are some similar problems with solutions:
Possible solution 1
Possible solution 2
Unfortunately, I don't understand solution 1 at all and solution 2 does seem to indicate there is a problem with the paths I'm trying to use, but I'm a little unclear on this as well. Any help is greatly appreciated.
My code:
protected void RunPkg_Click(object sender, EventArgs e)
{
// Get the full file path
string strFilePath = "C:\\inetpub\\wwwroot\\DecisionSupport\\CMSBenPerfUpload\\RunPackage.bat";
// Create the ProcessInfo object
System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo("cmd.exe");
psi.UseShellExecute = false;
psi.RedirectStandardOutput = true;
psi.RedirectStandardInput = true;
psi.RedirectStandardError = true;
psi.WorkingDirectory = "C:\\inetpub\\wwwroot\\DecisionSupport\\CMSBenPerfUpload\\";
// Start the process
System.Diagnostics.Process proc = System.Diagnostics.Process.Start(psi);
// Open the batch file for reading
System.IO.StreamReader strm = System.IO.File.OpenText(strFilePath);
// Attach the output for reading
System.IO.StreamReader sOut = proc.StandardOutput;
// Attach the in for writing
System.IO.StreamWriter sIn = proc.StandardInput;
// Write each line of the batch file to standard input
while(strm.Peek() != -1)
{
sIn.WriteLine(strm.ReadLine());
}
strm.Close();
// Exit CMD.EXE
string stEchoFmt = "# {0} run successfully. Exiting";
sIn.WriteLine(String.Format(stEchoFmt, strFilePath));
sIn.WriteLine("EXIT");
// Close the process
proc.Close();
// Read the sOut to a string.
string results = sOut.ReadToEnd().Trim();
// Close the io Streams;
sIn.Close();
sOut.Close();
// Write out the results.
string fmtStdOut = "<font face=courier size=0>{0}</font>";
this.Response.Write(String.Format(fmtStdOut,results.Replace(System.Environment.NewLine, "<br>")));
UPDATE: I changed the paths to C:\Temp\ just to see if it made a difference, but it didn't. I opened my security wide open on the dirs I'm using, no go.
UPDATE 2: Running this on my dev box is the same, but I actually get feedback shown in the block below. If I manually perform this in cmd, it executes no problem. If I manually run the batch itself, there's no problem.
> Microsoft Windows [Version 6.1.7601]
>Copyright (c) 2009 Microsoft Corporation. All rights reserved.
>
>C:\inetpub\wwwroot\DecisionSupport\CMSBenPerfUpload>dtexec /f "ACO-SHS-PatDB.dtsx"
>Microsoft (R) SQL Server Execute Package Utility
>Version 10.50.1600.1 for 32-bit
>Copyright (C) Microsoft Corporation 2010. All rights reserved.
>
>Option "#" is not valid.
>
>C:\inetpub\wwwroot\DecisionSupport\CMSBenPerfUpload>
Your process identity doesn't have right to the directory.
Another queston where do you plan to publish this. A sane administrator would prvent any website to run executables or batch file on the server
I'm going to put an answer in here because I hate leaving things unresolved. I never could get this to work exactly right in this form. I had a network admin check permissions just to make sure I wasn't overlooking something, and they couldn't find anything that made a difference either. All permissions seemed to be properly granted.
Somewhere between the version differences in my dev PC and the server for all parts, Windows, SQL Server, Visual Studio, somewhere in there the problem kept itself well-hidden. Kudos to Microsoft for making products that fail to work properly from one machine to the next without wasting far too many hours hunting for a resolution.
Either way, I ended up going a different route. I built very simple SSIS packages on my SQL 2012 server that could be executed from Stored Procedures built on the server. This kept permission and version issues at bay. I then used C# scripting to write out my XML results files to the directories needed. The one issue to overcome was that C# executescalar will not handle XML larger than 2033 characters so I had to use ExecuteXmlReader and loop through the results to built my string before writing it to file.
This problem, though ending differently than it began, is resolved.

Automating IISRESET via remote desktop connection after a TFS build

I want to automate a process, which is invoked after a successful build on TFS. The process will RDP to a test server, then call a C# application on that server, and reset IIS on that server. Each step will return the result so whether or not to call next step is based on the previous step.
There are a few obstacles in implementing it. Below is what I want to know if it is possible, and how to code it.
1) Invoking the process via a build on TFS
There is an option in Build definition to invoke automated test. I assume that the process can be invoked by implementing it as a test.
2) RDP to remote server
I found the links below, which might be a solution
Process rdcProcess = new Process();
rdcProcess.StartInfo.FileName = Environment.ExpandEnvironmentVariables(#"%SystemRoot%\system32\cmdkey.exe");
rdcProcess.StartInfo.Arguments = "/generic:TERMSRV/192.168.0.217 /user:" + "username" + " /pass:" + "password";
rdcProcess.Start();
rdcProcess.StartInfo.FileName = Environment.ExpandEnvironmentVariables(#"%SystemRoot%\system32\mstsc.exe");
rdcProcess.StartInfo.Arguments = "/v " + "192.168.0.217"; // ip or name of computer to connect
rdcProcess.Start();
Run mstsc.exe with specified username and password
Automating remote desktop connection
3) IISReset
I think it should be simply invoke "IISRESET" after RDP, but the problem is that, HOW to captrue the result of running IISRESET.
The tools that might be suitable are:
1) Powershell - I don't know much about Powershell but am willing to learn if required
2) C#
My question is that how to implement it, any code example, and idea would be very much appreciated.
Check my answer here which is somewhat related: Answer
If the user which runs the TFSBuild Service on the build server have enough rights on the test server then you can use psexec or powershell to run your commands remotely. Read the below links:
PSEXEC
PowerShell Remote commands
There is no inbuilt activity/process which can help you run scripts on remote machines in TFS build workflow.
Step 1 for you is to identify how you are going to run scripts on the remote machine, as mentioned above you can either use PSEXEC or Powershell (though running PowerShell on remote computers may be a little more complicated to set up).
Step2, write the actual scripts to do the work, stop services, install MSI etc.
Step3, Edit your current build defintion - create a new custom activity or make use of InvokeProcess activity from within your build definition to invoke the script that you have created in Step 2. InvokeProcess Activity
in most cases you do not need to run iisreset
if you want to upgrade an asp.net application, try to put app_offline.htm in the application folder, it will stop an application and application files will be unlocked
after upgrading an application, it will restart automatically, or you can "touch" web.config to force restart
You might be better using the Lab Build to run the scripts as part of an environment ob the target computer. It can run any powershell against that machine as well as deploy and execute applications....
Question: HOW to capture the result of running IISRESET
I believe the old fashioned way, Hope this is what you are looking for
c:> IISRESET >> C:\temp.log
You can use the above either from CMD or powershell
In the past I have used Psexec to run commands against a remote server and where ever we need to control flow on the result of that command, we simply piped the console out to a shared folder and checked for our success flag.
I am not sure if TFS can run commands in this manner but we implemented it on hudson/jenkins.
This won't answer your question directly but it may offer a better way forward
An Example:
psexec.exe \remoteserver "iisreset > h:\iisreset.log"
Then run a grep or similar against the iisreset.log with your success flag as a condition to run the next step.

Open new database connection and query window in SSMS through C# application?

I have a C# application that, when a user clicks a button, will open SQL Server Management Studio query editor with a specified server and database connection. What I would like to do is be able to have this same functionality, but with an already running instance of SSMS (not start a new process).
My code so far:
if (IsProcessOpen("Ssms") == false)
{
Process ssms = new Process();
ssms.StartInfo.FileName = "C:\\Program Files (x86)\\Microsoft SQL Server\\110\\Tools\\Binn\\ManagementStudio\\Ssms.exe";
ssms.StartInfo.Arguments = "-S " + StaticVariables.Getserver + " -d " + StaticVariables.Getdatabase;
ssms.Start();
}
else
{
//In already running SSMS process, open connection to server and database with new query window.
}
As far my research goes, there is no API available to interact with an existing SSMS processs. (http://stackoverflow.com/questions/2334435/how-do-i-programmatically-open-a-new-tab-in-an-open-instance-of-sql-management-s)
You could try doing a hack involving SendKeys, but this would have a downside of not knowing the current state of the SSMS window (if it has any active windows open or anything)
If you could share the original requirement, we may look at some better alternatives.
This problem was driving me crazy, and I finally found that when I changed from logging in as "sa" to using Windows Authentication, the problem was resolved.

Categories

Resources