versioncontrol.GetAllTeamProjects() returning 0 - c#

I'm working on a project where I'll have a C# application search all TFS project's .cs files for a string or string patterns. I found some code that looks similar to what I was looking to do here.
namespace TFSSearch
{
class Program
{
static string[] textPatterns = new[] { "void main(", "exception", "RegisterScript" }; //Text to search
static string[] filePatterns = new[] { "*.cs", "*.xml", "*.config", "*.asp", "*.aspx", "*.js", "*.htm", "*.html",
"*.vb", "*.asax", "*.ashx", "*.asmx", "*.ascx", "*.master", "*.svc"}; //file extensions
static void Main(string[] args)
{
try
{
var tfs = TfsTeamProjectCollectionFactory
.GetTeamProjectCollection(new Uri("https://{tfsserver}/tfs"));
tfs.EnsureAuthenticated();
var versionControl = tfs.GetService<VersionControlServer>();
StreamWriter outputFile = new StreamWriter(#"C:\Find.txt");
var allProjs = versionControl.GetAllTeamProjects(true);
foreach (var teamProj in allProjs)
{
foreach (var filePattern in filePatterns)
{
var items = versionControl.GetItems(teamProj.ServerItem + "/" + filePattern, RecursionType.Full).Items
.Where(i => !i.ServerItem.Contains("_ReSharper")); //skipping resharper stuff
foreach (var item in items)
{
List<string> lines = SearchInFile(item);
if (lines.Count > 0)
{
outputFile.WriteLine("FILE:" + item.ServerItem);
outputFile.WriteLine(lines.Count.ToString() + " occurence(s) found.");
outputFile.WriteLine();
}
foreach (string line in lines)
{
outputFile.WriteLine(line);
}
if (lines.Count > 0)
{
outputFile.WriteLine();
}
}
}
outputFile.Flush();
}
}
catch (Exception e)
{
string ex = e.Message;
Console.WriteLine("!!EXCEPTION: " + e.Message);
Console.WriteLine("Continuing... ");
}
Console.WriteLine("========");
Console.Read();
}
// Define other methods and classes here
private static List<string> SearchInFile(Item file)
{
var result = new List<string>();
try
{
var stream = new StreamReader(file.DownloadFile(), Encoding.Default);
var line = stream.ReadLine();
var lineIndex = 0;
while (!stream.EndOfStream)
{
if (textPatterns.Any(p => line.IndexOf(p, StringComparison.OrdinalIgnoreCase) >= 0))
result.Add("=== Line " + lineIndex + ": " + line.Trim());
line = stream.ReadLine();
lineIndex++;
}
}
catch (Exception e)
{
string ex = e.Message;
Console.WriteLine("!!EXCEPTION: " + e.Message);
Console.WriteLine("Continuing... ");
}
return result;
}
}
}
The problem I'm having is when I try to get the projects using versionControl.GetAllTeamProjects(true); allProjs seems to get no information back. It is an empty array of TeamProject. When I debug, tfs.HasAuthenticated is true and it doesn't throw any exceptions. The TFS server is on a https domain. How can I make sure I'm exactly connecting to TFS?

I test at my side, everything works correctly.
Install the Nuget package
Microsoft.TeamFoundationServer.ExtendedClient by running below
command in Package Manager Console:
PM> Install-Package Microsoft.TeamFoundationServer.ExtendedClient -Version 15.112.1
Make sure you specify the correct TFS server,
eg : http://servername:8080/tfs/DefaultCollection
Then check it again.

Related

Unable to change some js/html file content on container start. getting access denied exception

I have a case where i need to inject some Envrionment variable values in compiled vuejs js/html file which resides inisde my .net core 3.1 application.
I have put the content changing logic on startup.cs in Configure method.
I am getting Access denied exception
My code is
private void ReplaceEnvironmentVariableWithVal()
{
try
{
string apiurlToken = "VUE_APP_BEAPI_URL";
string relevantPath = "VUE_APP_RELEVANTPATH";
string path = Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), "clientapp", "dist", "js");
Console.WriteLine($"{apiurlToken} env value is {GetEnvVariable(apiurlToken)}");
Console.WriteLine($"{relevantPath} env value is {GetEnvVariable(relevantPath)}");
Console.WriteLine("Application Root Path of js files " + path);
DirectoryInfo dir = new DirectoryInfo(path);
Dictionary<string, string> dict = new Dictionary<string, string>();
if (dir != null)
{
foreach (var file in dir.GetFiles())
{
if (file.Extension == "js" || file.Extension == ".js")
{
var fileContent = File.ReadAllText(file.FullName);
if (!String.IsNullOrWhiteSpace(fileContent))
{
if (fileContent.Contains(apiurlToken))
{
string variableValue = GetEnvVariable(apiurlToken);
if (!String.IsNullOrWhiteSpace(variableValue))
{
fileContent = fileContent.Replace(apiurlToken, variableValue);
dict[file.FullName] = fileContent;
}
}
if (fileContent.Contains(relevantPath))
{
string variableValue = GetEnvVariable(relevantPath);
//if (!String.IsNullOrWhiteSpace(variableValue))
{
fileContent = fileContent.Replace(relevantPath, variableValue);
dict[file.FullName] = fileContent;
}
}
}
}
}
}
else
{
Console.WriteLine("Application Root Path of js files not exists");
}
foreach (KeyValuePair<string, string> entry in dict)
{
Console.WriteLine("Updating " + entry.Key);
using (var fs = new FileStream(entry.Key, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None))
{
using var sr = new StreamWriter(fs);
sr.Write(entry.Value);
}
Console.WriteLine("Update Completed " + entry.Key);
}
}
catch (Exception ex)
{
Console.WriteLine("Exception in ReplaceEnvironmentVariableWithVal:" + ex.Message);
}
}
I have achieve the writing of files my giving the user right's. i have log the user under which application was running and it was default.
then added following line in my docker file
COPY --chown=default:default . .
which basically given right's to the user

UnInstalling Programs By registry (UnistallString)

I want to uninstall a software by using my code, my code is working on unistallString "msiexec.exe /x {your-product-code-guid}" and "C:\Program Files\TeamViewer\uninstall.exe\".
but now working on uninstallString like "C:\Program Files\Common Files\Adobe AIR\Versions\1.0\Resources\Adobe AIR Updater.exe -arp:uninstall"..
this throwing exception ("The system cannot find the file specified")
(Here S= MyUnistallString)
try
{
s = s.Replace("\"", ""); //Replace <">
string uninstallArguments = null;
string uninstallAssembly = null;
if (!s.Contains("/"))
{
uninstallAssembly = s;
}
else
{
string[] uninstallArgumentsArray = s.Split(new string[] { " /" }, StringSplitOptions.RemoveEmptyEntries); // Split for any parameters
if (uninstallArgumentsArray.Count() > 1)
{
for (int count = 1; count < uninstallArgumentsArray.Count(); count++)
{
uninstallArguments = "/" + uninstallArgumentsArray[count];
}
}
uninstallAssembly = uninstallArgumentsArray[0];
}
if (!string.IsNullOrWhiteSpace(uninstallAssembly))
{
Process uninstallProcess = new Process();
uninstallProcess.StartInfo = new ProcessStartInfo();
uninstallProcess.StartInfo.FileName = uninstallAssembly;
uninstallProcess.StartInfo.Arguments = uninstallArguments;
uninstallProcess.Start();
}
}
catch (Exception)
{
}
So,I've Found my mistake and it will also help others
Add this after
if (!s.Contains("/"))
if(s.Contains(" -"))
{
string[] uninstallArgumentsArray = s.Split(new string[] { " -" }, StringSplitOptions.RemoveEmptyEntries); // Split for any parameters
if (uninstallArgumentsArray.Count() > 1)
{
for (int count = 1; count < uninstallArgumentsArray.Count(); count++)
{
uninstallArguments += " -" + uninstallArgumentsArray[count];
}
}
this code works for all UnInstallString

C# System.IO.IOException

I have following code:
using System;
using System.Collections.Generic;
using System.IO;
using VirusTotalNET;
using VirusTotalNET.Objects;
using System.Linq;
using System.Security.Permissions;
namespace VirusTotalNETClient
{
class Program
{
private const string ScanUrl = "http://www.google.com/";
static void Main(string[] args)
{
VirusTotal virusTotal = new VirusTotal("5d8684f50946c2bdeaf5c4fd966f61f3661de808e9d7324b99788d6f4fb7ad57");
//Use HTTPS instead of HTTP
virusTotal.UseTLS = true;
//creating folder for programs reliqies and output log
string folderName = "C:\\OnlineScanner";
System.IO.Directory.CreateDirectory(folderName);
//get list of files to analyse
var paths = Traverse("C:\test");
File.WriteAllLines("C:\\OnlineScanner\\test.txt", paths);
foreach (string line in File.ReadLines("C:\\test.txt"))
{
//Define what file you want to analyse
FileInfo fileInfo = new FileInfo(line);
//Check if the file has been scanned before.
FileReport fileReport = virusTotal.GetFileReport(fileInfo);
bool hasFileBeenScannedBefore = fileReport.ResponseCode == ReportResponseCode.Present;
//If the file has been scanned before, the results are embedded inside the report.
if (hasFileBeenScannedBefore)
{
int detekce = fileReport.Positives;
if (detekce >= 1)
{
using (var writer = new StreamWriter("C:\\OnlineScanner\\OnlineScannerLog.txt"))
{
writer.WriteLine(line);
writer.WriteLine("URL to test: " + fileReport.Permalink);
writer.WriteLine("Detect ratio: " + fileReport.Positives + "/54");
writer.WriteLine("Message: " + fileReport.VerboseMsg);
writer.WriteLine();
writer.WriteLine();
}
}
System.Threading.Thread.Sleep(16000);
}
else
{
ScanResult fileResult = virusTotal.ScanFile(fileInfo);
int detekce = fileReport.Positives;
if (detekce >= 1)
{
using (var writer = new StreamWriter("C:\\OnlineScanner\\OnlineScannerLog.txt"))
{
writer.WriteLine(line);
writer.WriteLine("URL to test: " + fileReport.Permalink);
writer.WriteLine("Detect ratio: " + fileReport.Positives + "/54");
writer.WriteLine("Message: " + fileReport.VerboseMsg);
writer.WriteLine();
writer.WriteLine();
}
}
System.Threading.Thread.Sleep(16000);
}
}
}
private static IEnumerable<string> Traverse(string rootDirectory)
{
IEnumerable<string> files = Enumerable.Empty<string>();
IEnumerable<string> directories = Enumerable.Empty<string>();
try
{
// The test for UnauthorizedAccessException.
var permission = new FileIOPermission(FileIOPermissionAccess.PathDiscovery, rootDirectory);
permission.Demand();
files = Directory.GetFiles(rootDirectory);
directories = Directory.GetDirectories(rootDirectory);
}
catch
{
// Ignore folder (access denied).
rootDirectory = null;
}
foreach (var file in files)
{
yield return file;
}
// Recursive call for SelectMany.
var subdirectoryItems = directories.SelectMany(Traverse);
foreach (var result in subdirectoryItems)
{
yield return result;
}
}
}
}
This code run some time (arround 15secs) but then program crashs.
The error is
System.IO.IOException, process can't access to file C:\hiberfil.sys.
http://upnisito.cz/images/2016_12/319crasherrror.png
Do you have any idea how to solve it?

Backup Windows 7 with specific filetypes. Some folders unavilable

Im trying to backup a computer with Windows 7 installed.
In older systems I created a backup that found and copyied specific images and office files.
Now when trying in Windows 7, I face some problems regarding some folders that arent available for me like they used to be in older systems.
How can I tweek this problem. I really like this way of backing the system up prior to upgrading etc.
Thanks in advance.
Feel free to ask and comment.
using System;
using System.Collections.Generic;
using System.IO;
//using System.IO.Directory.CreateDirectory;
static class Program
{
static void Main(string[] args)
{
ShowAllFoldersUnder(#"c:\",0);
}
private static void ShowAllFoldersUnder(string path,int indent)
{
int idx = 0;
string sourcePath = #"c:\";
string destinPath = #"h:\20160714\";
string fldr = #"C:\";
string[] fileTypes = new string[2];
fileTypes[idx] = ".docx"; idx++;
fileTypes[idx] = ".xlsx"; idx++;
try
{
if ((File.GetAttributes(path) & FileAttributes.ReparsePoint) != FileAttributes.ReparsePoint)
{
foreach (string folder in Directory.GetDirectories( path ) )
{
//Console.WriteLine(folder);
//if (#folder.IndexOf(fldr) != -1) // COMMENT
//{
Console.WriteLine( folder );
foreach ( string file in Directory.GetFiles( folder ) )
{
string e = Path.GetExtension( file );
//Console.WriteLine(e);
for (int i =0;i<=fileTypes.GetUpperBound(0);i++)
{
string[] filesToCopy = Directory.GetFiles(folder, "*" + Convert.ToString(fileTypes[i]));
foreach (string name in filesToCopy)
{
if (Convert.ToString(fileTypes[i]).ToLower() == Path.GetExtension(file).ToLower())
{
Console.WriteLine("From: {0}",name);
Console.WriteLine("To: {0}", name.Replace(sourcePath, destinPath) );
try
{
DirectoryInfo di = Directory.CreateDirectory( Path.GetDirectoryName( name.Replace(sourcePath, destinPath) ) );
Console.WriteLine("Copying.");
File.Copy(name, name.Replace(sourcePath, destinPath), true);
}
catch (Exception ex)
{
Console.WriteLine("The process failed: {0}", ex.ToString());
}
finally {}
}
}
}
}
// break;
//}
ShowAllFoldersUnder(folder, indent);
}
}
}
catch (UnauthorizedAccessException)
{ }
}
}

Gurobi does not recognize LP file

When trying to open a Linear Programming problem from text with Gurobi+C# it throws the error: 10012 Unable to open file "Maximize" for input.
Maximise is the first word of the text and when using
foreach (string s in args)
{
Console.WriteLine(s);
}
i get the correct output from the text file. Please help!
using System;
using Gurobi;
class lp_cs
{
static void Main(string[] args)
{
args = System.IO.File.ReadAllLines(#"C:\Users\Ben\Documents\Visual Studio 2015\Projects\ConsoleApplication5\ConsoleApplication5\mps.lp");
foreach (string s in args)
{
Console.WriteLine(s);
}
if (args.Length < 1)
{
Console.Out.WriteLine("Please Wait..");
return;
}
try
{
GRBEnv env = new GRBEnv();
GRBModel model = new GRBModel(env, args[0]);
model.Optimize();
int optimstatus = model.Get(GRB.IntAttr.Status);
if (optimstatus == GRB.Status.INF_OR_UNBD)
{
model.GetEnv().Set(GRB.IntParam.Presolve, 0);
model.Optimize();
optimstatus = model.Get(GRB.IntAttr.Status);
}
if (optimstatus == GRB.Status.OPTIMAL)
{
double objval = model.Get(GRB.DoubleAttr.ObjVal);
Console.WriteLine("Optimal objective: " + objval);
}
else if (optimstatus == GRB.Status.INFEASIBLE)
{
Console.WriteLine("Model is infeasible");
model.ComputeIIS();
model.Write("model.ilp");
}
else if (optimstatus == GRB.Status.UNBOUNDED)
{
Console.WriteLine("Model is unbounded");
}
else
{
Console.WriteLine("Optimization was stopped with status = "
+ optimstatus);
}
model.Dispose();
env.Dispose();
}
catch (GRBException e)
{
Console.WriteLine("Hibakód: " + e.ErrorCode + ". " + e.Message);
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
}
}
With
args = System.IO.File.ReadAllLines(#"C:\Users\Ben\Documents\Visual Studio 2015\Projects\ConsoleApplication5\ConsoleApplication5\mps.lp");
you are overwriting the args parameter of your main() method with an array of all lines of the input file. That's why in
GRBModel model = new GRBModel(env, args[0]);
args[0] contains a string with the first line of your LP file instead of the filename.

Categories

Resources