UnInstalling Programs By registry (UnistallString) - c#

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

Related

versioncontrol.GetAllTeamProjects() returning 0

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.

Save only end line

I have problem with reading a file.
I must write program which take numbers from polish lottery(saved in .txt) and add this to list and answer to questions.
Anyway.. My algorithm save only end line.. I should save all lines in List.. :)
string line;
List<Losuj> losowanko = new List<Losuj>();
Losuj pomocnik = new Losuj();
StreamReader file =
new StreamReader(#"D:\bawmy się\2# apka\Lotto\Lotto\plik.txt");
while ((line = file.ReadLine()) != null)
{
// Console.WriteLine(line);
string[] podzialka = line.Split(new string[] { ".", " ", "," }, StringSplitOptions.None);
pomocnik.NumerLosowania = Int32.Parse(podzialka[0]);
pomocnik.JakiDzien = Int32.Parse(podzialka[2]);
pomocnik.JakiMiesiac =Int32.Parse(podzialka[3]);
pomocnik.JakiRok=Int32.Parse(podzialka[4]);
for (int i = 5, lo=0; i < 11; i++,lo++)
{
pomocnik.Los[lo] =Int32.Parse(podzialka[i]);
}
losowanko.Add(pomocnik);
}
file.Close();
move Losuj object create line to inside the while loop, otherwise you are changing and adding same object again and again
using(StreamReader file =
new StreamReader(#"D:\bawmy się\2# apka\Lotto\Lotto\plik.txt"))
{
while ((line = file.ReadLine()) != null)
{
Losuj pomocnik = new Losuj();
// Console.WriteLine(line);
string[] podzialka = line.Split(new string[] { ".", " ", "," }, StringSplitOptions.None);
pomocnik.NumerLosowania = Int32.Parse(podzialka[0]);
pomocnik.JakiDzien = Int32.Parse(podzialka[2]);
pomocnik.JakiMiesiac =Int32.Parse(podzialka[3]);
pomocnik.JakiRok=Int32.Parse(podzialka[4]);
for (int i = 5, lo=0; i < 11; i++,lo++)
{
pomocnik.Los[lo] =Int32.Parse(podzialka[i]);
}
losowanko.Add(pomocnik);
}
}
In order to avoid such errors (wrong list items creation) I suggest generating losowanko via Linq. You should
read the file by lines
split each line
create Losuj instance
materialize the IEnumerable<Losuj> into List<Losuj>
Implementation:
List<Losuj> losowanko = File
.ReadLines(#"D:\bawmy się\2# apka\Lotto\Lotto\plik.txt")
.Select(line => line.Split(new string[] { ".", " ", "," }, StringSplitOptions.None))
.Select(items => {
Losuj item = new Losuj() {
NumerLosowania = Int32.Parse(items[0]),
JakiDzien = Int32.Parse(items[2]),
JakiMiesiac = Int32.Parse(items[3]),
JakiRok = Int32.Parse(items[4])};
for (int i = 5, lo = 0; i < 11; i++, lo++)
item[lo] = Int32.Parse(items[i]);
return item;})
.ToList();

SSIS DTS Script Task has encountered an exception in user code

I'm trying to execute an SSIS package with a scripting component in Visual Basic 2010. I get the following error when I execute the package:
public void Main()
{
// TODO: Custom Code starts here
/*
* Description: Reads the input CMI Stats files and converts into a more readable format
* This Code for Better CMI Parser is converted as per SC's original code by S.A. on 3/6/2014
* Here is the description from original procedure
* CustType = DOMESTIC/INTERNATIONAL/ETC
* CategoryType = SBU/MAN
* Category = Actual value (AI/CC/etc)
* DataType = INCOMING or SHIP (or something else later?)
*
* 3/23/2010
* Uncommented the CAD file load....
*/
string[,] filesToProcess = new string[2, 2] { {(String)Dts.Variables["csvFileNameUSD"].Value,"USD" }, {(String)Dts.Variables["csvFileNameCAD"].Value,"CAD" } };
string headline = "CustType,CategoryType,CategoryValue,DataType,Stock QTY,Stock Value,Floor QTY,Floor Value,Order Count,Currency";
string outPutFile = Dts.Variables["outputFile"].Value.ToString();
//Declare Output files to write to
FileStream sw = new System.IO.FileStream(outPutFile, System.IO.FileMode.Create);
StreamWriter w = new StreamWriter(sw);
w.WriteLine(headline);
//Loop Through the files one by one and write to output Files
for (int x = 0; x < filesToProcess.GetLength(1); x++)
{
if (System.IO.File.Exists(filesToProcess[x, 0]))
{
string categoryType = "";
string custType = "";
string dataType = "";
string categoryValue = "";
//Read the input file in memory and close after done
StreamReader sr = new StreamReader(filesToProcess[x, 0]);
string fileText = sr.ReadToEnd();
string[] lines = fileText.Split(Convert.ToString(System.Environment.NewLine).ToCharArray());
sr.Close();
//Read String line by line and write the lines with params from sub headers
foreach (string line in lines)
{
if (line.Split(',').Length > 3)
{
string lineWrite = "";
lineWrite = line;
string[] cols = line.Split(',');
if (HeaderLine(cols[1]))
{
string[] llist = cols[0].Split();
categoryType = llist[llist.Length - 1];
custType = llist[0];
dataType = llist[1];
if (dataType == "COMPANY")
{
custType = llist[0] + " " + llist[1];
dataType = llist[2];
}
}
if (cols[0].Contains("GRAND"))
{
categoryValue = "Total";
}
else
{
string[] col0 = cols[0].Split(' ');
categoryValue = col0[col0.Length - 1];
}
int z = 0;
string[] vals = new string[cols.Length];
for (int i = 1; i < cols.Length - 1; i++)
{
vals[z] = cols[i].Replace(',', ' ');
z++;
}
//line = ",".join([CustType, CategoryType, CategoryValue, DataType, vals[0], vals[1], vals[2], vals[3], vals[6], currency])
lineWrite = clean(custType) + "," + clean(categoryType) + "," + clean(categoryValue) + ","
+ clean(dataType) + "," + clean(vals[0]) + "," + clean(vals[1]) + "," + clean(vals[2])
+ "," + clean(vals[3]) + "," + clean(vals[6]) + "," + filesToProcess[x, 1];
if (!HeaderLine(line))
{
w.WriteLine(lineWrite);
w.Flush();
}
}
}
}
}
w.Close();
sw.Close();
//Custom Code ends here
Dts.TaskResult = (int)ScriptResults.Success;
}
public bool HeaderLine(String line)
{
return line.Contains("Stock Qty");
}
public string clean(string str)
{
if (str != null)
return Regex.Replace(str,#"[""]","");
//return str.Replace('"', ' ');
else
return "";
}
#region ScriptResults declaration
/// <summary>
/// This enum provides a convenient shorthand within the scope of this class for setting the
/// result of the script.
///
/// This code was generated automatically.
/// </summary>
enum ScriptResults
{
Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success,
Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure
};
#endregion
}
}
Can anyone suggest what could have possibly gone wrong or maybe how to debug this code in order to understand the errors?
Thanks!
Here's how you debug scripts in SSIS
With the code open, put a breakpoint
Close the code
Run the package
When the script starts running, it will open up a code window and you can walk through the code step by step

using .replace to replace a word in text document (c#)

currently have the following code:
string[] fileLineString = File.ReadAllLines(Server.MapPath("~") + "/App_Data/Users.txt");
for (int i = 0; i < fileLineString.Length; i++)
{
string[] userPasswordPair = fileLineString[i].Split(' ');
if (Session["user"].ToString() == userPasswordPair[0])
{
userPasswordPair[i].Replace(userPasswordPair[1], newPasswordTextBox.Text);
}
}
}
the text file is set out as: 'username' 'password
what i'm trying to do is be able to edit the password and replace it with a new one using my code, but my code seems to do nothing and the text file just stays the same.
string[] fileLineString = File.ReadAllLines(Server.MapPath("~") + "/App_Data/Users.txt");
for (int i = 0; i < fileLineString.Length; i++)
{
string[] userPasswordPair = fileLineString[i].Split(' ');
if (Session["user"].ToString() == userPasswordPair[0])
{
// set the new password in the same list and save the file
fileLineString[i] = Session["user"].ToString() + " " + newPasswordTextBox.Text;
File.WriteAllLines((Server.MapPath("~") + "/App_Data/Users.txt"), fileLineString);
break; // exit from the for loop
}
}
At the moment, you're not storing the file.
Your replace is not assigned to a variable (Replace does not edit or write anything, it just returns the new string object).
Corrected code:
string[] fileLineString = File.ReadAllLines(Server.MapPath("~") + "/App_Data/Users.txt");
for (int i = 0; i < fileLineString.Length; i++)
{
string[] userPasswordPair = fileLineString[i].Split(' ');
if (Session["user"].ToString() == userPasswordPair[0])
{
fileLineString[i] = fileLineString[i].Replace(userPasswordPair[1], newPasswordTextBox.Text);
break;
}
}
File.WriteAllLines((Server.MapPath("~") + "/App_Data/Users.txt", fileLineString);
String _userName = "User";
String _newPassword = "Password";
// Reading All line from file
String _fileContent = System.IO.File.ReadAllLines("filePath").ToString();
// Pattern which user password like to changed
string _regPettern = String.Format(#"{0} ?(?<pwd>\w+)[\s\S]*?", _userName);
Regex _regex2 = new Regex(_regPettern, RegexOptions.IgnoreCase);
String _outPut = Regex.Replace(_fileContent, _regPettern, m => m.Groups[1] + " " + _newPassword);
// Writing to file file
System.IO.File.WriteAllText("filePath", _outPut);

command line output validation in c#

My output in the actual command prompt looks like this:
Name: My Software
Version: 1.0.1
Installed location: c:\my folder
I am trying to get this output via c# code
System.Diagnostics.ProcessStartInfo procStartInfo = new System.Diagnostics.ProcessStartInfo("cmd", "/c " + "my command to execute");
// The following commands are needed to redirect the standard output.
// This means that it will be redirected to the Process.StandardOutput StreamReader.
procStartInfo.RedirectStandardOutput = true;
procStartInfo.UseShellExecute = false;
// Do not create the black window.
procStartInfo.CreateNoWindow = true;
// Now we create a process, assign its ProcessStartInfo and start it
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo = procStartInfo;
proc.Start();
// Get the output into a string
string result = proc.StandardOutput.ReadToEnd();
string[] lines = result.Split(new string[] { System.Environment.NewLine, }, System.StringSplitOptions.None);
foreach (string tmp in lines)
{
if (tmp.Contains("Version"))
{
isAvailable= true;
}
}
I don't want to just check a version tag, I am trying to get the version value and do a compare, for example if the value is 1.0.1, i would want that value and do a comparison with 2.0.0.
I can use indexof(like result.IndexOf("Version:");) - But that doesn't get me the value of the version
Any thoughts will be helpful.
You should use the .NET Version class and it's CompareTo(Object) method to do your comparison.
var input = new Regex(#"(?<=Version:)\s*(.*)").Matches(#"Name: My Software
Version: 1.0.1
Installed location: c:\my folder")[0].Value.Trim();
var a = new Version(input);
var b = new Version("2.0.0");
int comparison = a.CompareTo(b);
if(comparison > 0)
{
Console.WriteLine(a + " is a greater version.");
}
else if(comparison == 0)
{
Console.WriteLine(a + " and " + b +" are the same version.");
}
else
{
Console.WriteLine(b + " is a greater version.");
}
Try like below... it will help you...
Instead of Contains check the word by using IndexOf...
if (tmp.IndexOf("Version") != -1)
{
isAvailable = true;
string[] info = tmp.Split(':');
string version = info[1].Trim();
Console.WriteLine(version);
}
string versionText;
var stuff = tmp.Split(":");
if(stuff[0].Trim() == "Version")
{
isAvailable = true;
versionText = stuff[1].Trim();
}
if(versionText == expectedVersionText) // Do something specfic.
You might want to use Regular Expressions:
^Version:\s*(.*)$
should match the version number inside the parentheses.
string sought = "Version:";
foreach (string tmp in lines)
{
if (tmp.Contains(sought))
{
int position = tmp.IndexOf(sought) + sought.Length;
string version = tmp.Substring(tmp.IndexOf(sought) + sought.Length);
string[] versionParts = version.Split('.');
VersionCompare(versionParts, new string[]{"2", "0", "0"});
}
}
/// <summary>Returns 0 if the two versions are equal, else a negative number if the first is smaller, or a positive value if the first is larder and the second is smaller.</summary>
private int VersionCompare(string[] left, string[] right)
{
for(int i = 0; i < Math.Min(left.Length, right.Length); ++i)
{
int leftValue = int.Parse(left[i]), rightValue = int.Parse(right[i]);
if(leftValue != rightValue) return leftValue - rightValue;
}
return left.Length - right.Length;
}

Categories

Resources