Call SVN console client from C# - c#

any ideas how to create a branch from a trunk url in a c# console app.
im trying to create a branching tool, that will create all new branches. for the life of me i have tried almost everything. Sharpsvn has given me no luck.
string command = "cp https://svn:8443/svn/blah/trunk \\ https://svn:8443/svn/blah/branches/newBranch \\";
Process svnBranchProcess = new Process();
svnBranchProcess.StartInfo.FileName = "Svn.exe";
svnBranchProcess.StartInfo.Arguments = command;
svnBranchProcess.StartInfo.UseShellExecute = false;
svnBranchProcess.StartInfo.RedirectStandardOutput = true;
svnBranchProcess.Start();
string output = svnBranchProcess.StandardOutput.ReadToEnd();
svnBranchProcess.WaitForExit();
Console.WriteLine("Output:");
Console.WriteLine(output);
This is the error that i get
svn : Cannot mix repository and working copy sources
Basically i want to be able to create a branch off trunk and then update some externals. why is this such a mission?
thanks for any help :)

Related

Capturing output from powershell commands run from C#

I'm creating a simple C# program used to check various settings on windows 10 builds we're testing. I need to capture the output from a CMD or Powershell invoke and display the result as a string (human-readable). Specifically, I'm trying to capture the output from get-bitlockervolume to check if the drives are encrypted. The program should be able to run without using admin creds.
Get Powershell command's output when invoked through code
unfortunately doesn't quite seem to work, so I thought I'd attempt to capture the output to a txt file and read it from there, but for some reason, the txt ends up being empty. For my latest attempts, I've ditched PowerShell and attempted to get it done using simple CMD.
Process bl = new Process();
bl.StartInfo.WindowStyle = ProcessWindowStyle.Hidden ;
bl.StartInfo.FileName = "cmd.exe";
bl.StartInfo.Arguments = #"/c manage-bde -status > C:\windows\temp\bitlockerstatus.txt";
bl.StartInfo.RedirectStandardOutput = true;
bl.StartInfo.UseShellExecute = false;
bl.Start();
This seems to create the output file I was looking for in the right location, but it always turns up empty. When running the command directly from cmd, there doesn't seem to be an issue recording the output.
I'm still quite new to C#, self-learning as I go along, so any suggestions for an alternate method/way of doing this would be appreciated.
Very late edit:
I've figured out a way by using a Collection.
code:
StringBuilder str = new Stringbuilder();
using (Powershell ps = Powershell.create())
{
ps.addscript ("manage-bde -status");
Collection<PSObject> psoutp = ps.Invoke();
foreach(PSObject outp in psoutp)
{
if (outp != null)
{
str.Append(outp);
}
else str.Append ("Error");
}
return str.ToString();
}
This for a Method that returns the output of manage-bde - status from powershell back to main. If there's no output at all (not even an errormessage) , it'll simply return "error" back to main.
Here's hoping this helps someone else one day.
I think the answer is here:
while (!proc.StandardOutput.EndOfStream)
{
string line = proc.StandardOutput.ReadLine();
// do something with line
}

Gitlab commands not working through IIS web application

I have a requirement to clone gitlab project and get commit details through c# application. I am able to execute all gitlab commands such as clone, pull, fetch, show etc in my machine through command line and mvc application. Same commands are not working when application in deployed on IIS server. clone and pull commands are not working, they are simply hanged and no output is produced. Can someone tell me what settings are required to be done to make gitlab commands work through web application. I have spent 4 days on this issue and still not able to resolve.My c# code is below
compiler.StartInfo.FileName = #"C:\Windows\System32\cmd.exe";
compiler.StartInfo.Arguments = "git pull";
compiler.StartInfo.UseShellExecute = false;
compiler.StartInfo.WorkingDirectory = local_repository;
compiler.StartInfo.RedirectStandardOutput = true;
compiler.StartInfo.RedirectStandardError = true;
compiler.StartInfo.RedirectStandardInput = true;
compiler.StartInfo.CreateNoWindow = true;
compiler.StartInfo.Verb = "runas";
compiler.StartInfo.ErrorDialog = false;
compiler.Start();
try
{
compiler.WaitForExit();
exitcode = compiler.ExitCode;
}
git clone "my_gitlab_url"
git pull

Run git commands from a C# function

How can my C# code run git commands when it detects changes in tracked file? I am writing a VisualStudio/C# console project for this purpose.
I am new to the the .NET environment and currently working on integrating automated GIT commits to a folder. I need to automatically commit any change/add/delete on a known folder and push that to a git remote. Any guidance appreciated. Thank you.
Here is what I have and the last one is the one I need some guidance with:
Git repository initially set up on folder with proper ignore file (done).
I am using C# FileSystemWatcher to catch any changes on said folder (done).
Once my project detects a change it needs to commit and push those changes (pending).
Tentative commands the project needs to run:
git add -A
git commit "explanations_of_changes"
git push our_remote
NOTE: This code (with no user interaction) will be the only entity committing to this repo so I am not worried about conflicts and believe this flow will work.
I realize this is an old question but I wanted to add the solution I recently came across to help those in the future.
The PowerShell class provides an easy way to interact with git. This is part of the System.Management.Automation namespace in .NET. Note that System.Management.Automation.dll is available via NuGet.
string directory = ""; // directory of the git repository
using (PowerShell powershell = PowerShell.Create()) {
// this changes from the user folder that PowerShell starts up with to your git repository
powershell.AddScript($"cd {directory}");
powershell.AddScript(#"git init");
powershell.AddScript(#"git add *");
powershell.AddScript(#"git commit -m 'git commit from PowerShell in C#'");
powershell.AddScript(#"git push");
Collection<PSObject> results = powershell.Invoke();
}
In my opinion this is cleaner and nicer than using the Process.Start() approach. You can modify this to your specfic needs by editing the scripts that are added to the powershell object.
As commented by #ArtemIllarionov, powershell.Invoke() does not return errors but the Streams property has output information. Specifically powerShell.Streams.Error for errors.
If you want to do it in C#, you can call the external git command by Process.Start when you detect file change
string gitCommand = "git";
string gitAddArgument = #"add -A";
string gitCommitArgument = #"commit ""explanations_of_changes""";
string gitPushArgument = #"push our_remote";
Process.Start(gitCommand, gitAddArgument);
Process.Start(gitCommand, gitCommitArgument);
Process.Start(gitCommand, gitPushArgument);
Not the best solution but it works in C#
using System.Diagnostics;
using System.Text;
//Console.WriteLine(CommandOutput("git status"));
public static string CommandOutput(string command,
string workingDirectory = null)
{
try
{
ProcessStartInfo procStartInfo = new ProcessStartInfo("cmd", "/c " + command);
procStartInfo.RedirectStandardError = procStartInfo.RedirectStandardInput = procStartInfo.RedirectStandardOutput = true;
procStartInfo.UseShellExecute = false;
procStartInfo.CreateNoWindow = true;
if (null != workingDirectory)
{
procStartInfo.WorkingDirectory = workingDirectory;
}
Process proc = new Process();
proc.StartInfo = procStartInfo;
proc.Start();
StringBuilder sb = new StringBuilder();
proc.OutputDataReceived += delegate (object sender, DataReceivedEventArgs e)
{
sb.AppendLine(e.Data);
};
proc.ErrorDataReceived += delegate (object sender, DataReceivedEventArgs e)
{
sb.AppendLine(e.Data);
};
proc.BeginOutputReadLine();
proc.BeginErrorReadLine();
proc.WaitForExit();
return sb.ToString();
}
catch (Exception objException)
{
return $"Error in command: {command}, {objException.Message}";
}
}
Try LibGit2Sharp, a native implementation of git for .NET:
https://github.com/libgit2/libgit2sharp/
One alternative would be to setup Grunt and TaskRunner with your project.
Grunt should be able to provide the automation of detecting changes to a folder(or folders) in your project and execute the appropriate git commands to commit it.
Task Runner allows you to initialize and run Grunt from within Visual Studio.
The Visual Studio team has indicated that Task Runner is going to become integrated into future releases of Visual Studio, so this could be a long term solution.
Note: It has been mentioned in the comments, but I feel it worth mentioning again that auto-commiting anytime a file is saved to the repository isn't best practice. You want functional / atomic code changes to get pushed in, not simple text changes. Auto-Commit at your own risk.
The Package Manager Console is Powershell console. So you can run your git commands from there.

asp.net c# connecting to putty ssh and running a command line like status

ok folks i have seen alot of questions about this but none that i can use or understand
What i am attempting to do is connect to putty from asp.net c# and then run a command to get the status
i will then use the results to draw a report every 3 seconds and display it on my web page
this is the first time a have attempted this so i am rather ignorant
private void connect_putty()
{
Process sh = new Process();
sh.StartInfo.FileName = "Putty.exe";
sh.StartInfo.UseShellExecute = false;
sh.StartInfo.CreateNoWindow = false;
sh.StartInfo.Arguments = "";
}
what i presently have which to be honest is pathetic any help will be appreciated
Thanks in advance
I would suggest using Tamir.SSH.
This will allow you to do everything from C#.
Also, I wrote some code once, it may help you.
https://github.com/daneb/Push2Linux/blob/master/Form1.cs
Sample:
SshShell ssh; // create our shell
ssh = new SshShell(aHost.host, aHost.username, aHost.password);
// Command Output
string commandoutput = string.Empty;
// Remove Terminal Emulation Characters
ssh.RemoveTerminalEmulationCharacters = true;
// Connect to the remote server
ssh.Connect();
//Specify the character that denotes the end of response
commandoutput = ssh.Expect(promptRegex);
PuTTY includes all the terminal emulation (hence the name), so assuming you mean 'connect via ssh', instead of the putty app specifically, then SSH.NET and SharpSSH are 2 good choices.
See this related question: C# send a simple SSH command

get git command line return value using c#

I want to run git commands from c#. below is the coded I had written and it does execute the git command but I am not able to capture the return value. When I manually run it from command line this is the output I get.
When I run from the program the only thing I get is
Cloning into 'testrep'...
Rest of the info is not capture, but the command is executed successfully.
class Program
{
static void Main(string[] args)
{
ProcessStartInfo startInfo = new ProcessStartInfo("git.exe");
startInfo.UseShellExecute = false;
startInfo.WorkingDirectory = #"D:\testrep";
startInfo.RedirectStandardInput = true;
startInfo.RedirectStandardOutput = true;
startInfo.Arguments = "clone http://tk1:tk1#localhost/testrep.git";
Process process = new Process();
process.StartInfo = startInfo;
process.Start();
List<string> output = new List<string>();
string lineVal = process.StandardOutput.ReadLine();
while (lineVal != null)
{
output.Add(lineVal);
lineVal = process.StandardOutput.ReadLine();
}
int val = output.Count();
process.WaitForExit();
}
}
From the manual page for git clone:
--progress
Progress status is reported on the standard error stream by default when it is attached to
a terminal, unless -q is specified. This flag forces progress status even if the standard
error stream is not directed to a terminal.
The last three lines in the output when running git clone interactively are sent to standard error, not standard output. They won't show up there when you run the command from your program, however, since it's not an interactive terminal. You could force them to appear, but the output isn't going to be anything usable for a program to parse (lots of \rs to update the progress values).
You are better off not parsing the string output at all, but looking at the integer return value of git clone. If it's nonzero, you had an error (and there will probably be something in standard error that you can show to your user).
Have you tried libgit2sharp? The documentation is not complete, but it is pretty easy to use and there's a nuget package for it. You can always look at the test code to see about usage as well. A simple clone would be like this:
string URL = "http://tk1:tk1#localhost/testrep.git";
string PATH = #"D:\testrep";
Repository.Clone(URL, PATH);
Fetching changes is easy as well:
using (Repository r = new Repository(PATH))
{
Remote remote = r.Network.Remotes["origin"];
r.Network.Fetch(remote, new FetchOptions());
}
Once you call process.WaitForExit() and the process has terminated, you can simply use process.ExitCode which will get you the value that you want.
Your code Looks OK.
this is git problem.
git clone git://git.savannah.gnu.org/wget.git 2> stderr.txt 1> stdout.txt
stderr.txt is empty
stdout.txt:
Cloning into 'wget'...
It looks like git not uses standard console.write() like output you can see it when it writes percentage it's all in one line not like:
10%
25%
60%
100%
process.StandardError.ReadToEnd() + "\n" + process.StandardOutput.ReadToEnd();

Categories

Resources