How to replace tabs with? - c#

How to replace tabs with ? I try it like this:
foreach (var url in urlList)
{
try
{
stopwatch.Start();
requester.DownloadString(url);
url.Replace("\n",string.Empty);
if (url.Contains("/select/"))
{
url.Replace(string.Empty, "?");
}
}
catch (Exception e)
{
Console.WriteLine("An error occured while attempting to connect to {0}", url);
}
finally
{
stopwatch.Stop();
//We use the counter for a friendlier url as the current ones are unwieldly
times.Add("Url " + counter, stopwatch.Elapsed);
counter++;
stopwatch.Reset();
}
}
But this: url.Replace("\n","?"); doesnt do the job. So how to manage that? My post has to much code. But I dont have text to type
Thank you
this is the complete code:
public class Program
{
static void Main(string[] args)
{
//Consider making this configurable
const string sourceFile = "testSolar.txt";
var requester = new WebClient();
var times = new Dictionary<string, TimeSpan>();
var stopwatch = new System.Diagnostics.Stopwatch();
//Add header so if headers are tracked, it will show it is your application rather than something ambiguous
requester.Headers.Add(HttpRequestHeader.UserAgent, "Response-Tester-Client");
var urlList = new List<string>();
//Loop through the lines in the file to get the urls
try
{
stopwatch.Start();
using (var reader = new StreamReader(sourceFile))
{
while (!reader.EndOfStream)
{
urlList.Add(reader.ReadLine());
urlList.Remove("\n");
}
}
}
catch (Exception e)
{
Console.WriteLine("An error occured while attempting to access the source file at {0}", sourceFile);
}
finally
{
//Stop, record and reset the stopwatch
stopwatch.Stop();
times.Add("FileReadTime", stopwatch.Elapsed);
stopwatch.Reset();
}
//Try to connect to each url
var counter = 1;
foreach (var url in urlList)
{
try
{
stopwatch.Start();
requester.DownloadString(url);
url.Replace("\t","?");
if (url.Contains("/select/"))
{
url.Replace(string.Empty, "?");
}
}
catch (Exception e)
{
Console.WriteLine("An error occured while attempting to connect to {0}", url);
}
finally
{
stopwatch.Stop();
//We use the counter for a friendlier url as the current ones are unwieldly
times.Add("Url " + counter, stopwatch.Elapsed);
counter++;
stopwatch.Reset();
}
}
//Release the resources for the WebClient
requester.Dispose();
//Write the response times
foreach (var key in times.Keys)
{
Console.WriteLine("{0}: {1}", key, times[key].TotalSeconds);
}
Console.ReadKey();
}
}
This was doing the work:
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
line = line.Replace("\t", "?");
urlList.Add(line);
}

Issue here is you are not re-assinging the string back to variable:
url = url.Replace("\n",string.Empty);
and to replace tabs try \t as mentioned by others:
url = url.Replace("\t","?");

A tab string is represent by \t.
So if you want to replace tab by question mark:
url.Replace("\t","?");
Should do the job.
Edit:
Right, as explain by Zaheer Ahmed, you need also to reaffect the result of the Replace function...

Related

While statement for downloading URL strings

I would like to ask, How I can use the While statement for downloading URL?
Here's what I want to happen.
I want to check if the url from CheckBoxListItems is already exist from my ListView
There's a case that I'm adding another urls to my listbox and I don't want to download again.
if url is already exists in my listview it will skip and proceed to the next url(which is not yet downloaded).
Here's my current codes:
int count = 0;
int total = LB.CheckedItems.Count;
string counter = string.Empty;
using (cts = new CancellationTokenSource())
{
try
{
if (cts.IsCancellationRequested) { throw new TaskCanceledException(); }
txtOutput.Text = string.Empty;
Cursor = Cursors.WaitCursor;
Parsing = true;
Text = "Getting links information. Please wait...";
foreach (string url in LB.CheckedItems)
{
var info = await Task.Run(() => Parser.GetJsonData(url, cts.Token));
count++;
counter = "( " + count + " of " + total + " )";
lblTotalLinks.Text = counter;
Text = "Parsing in progress. Please wait... " + counter;
AddToListView(info); //ADD DOWNLOADED STRINGS TO LISTVIEW
}
Text = "Parsing done. " + counter;
}
catch (OperationCanceledException ex)
{ Text = ex.Message; }
catch (Exception ex)
{ MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); }
}
Parsing = false;
Cursor = Cursors.Default;
cts = null;
//ADD TO LISTVIEW()
private void AddToListView(MediaInfo info)
{
int count = LV.Items.Count + 1;
var results = new List<ListViewItem> { new ListViewItem(new[]
{
count.ToString(),
info.Series,
"Episode " + info.Episode,
info.Title,
info.Runtime,
info.Resolution,
info.Category,
info.URL, //here's what I want to check if already exists
info.M3u8_url,
info.FileSize,
info.Fragments
})};
ListViewItem[] array = results.ToArray();
LV.BeginUpdate();
LV.ListViewItemSorter = null;
LV.Items.AddRange(array);
LV.Focus();
LV.EndUpdate();
Countlists();
LV.Items[LV.Items.Count - 1].EnsureVisible();
}
this is the example of what I want:
string urlExists = string.Empty;
foreach (ListViewItem item in LV.Items)
{
urlExists = item.SubItems[7].Text;
foreach (string url in LB.CheckedItems)
{
while (url != urlExists)
{
}
}

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.

C# Programming Unisource 4100 GPIB DMM

I am trying to read voltage measurements from my Unisource 4100 GPIB DMM. I know I can connect to the device because I get appropriate responses with the commands '*RST' and '*IDN?', however I cannot get any responses with other commands such as 'SYST:ERR?' or 'CONF:VOLT:DC 1000, 0.001'. I have tested out the code I am trying with on the Agilent 34410A and managed to get the responses I want, but not with the Unisource 4100. I am using the NI GPIB-USB-HS controller to interface with. I have included the code below. Should the SCPI commands not work for all GPIB interfaces? What changes would I have to make to elicit a response from the Unisource 4100?
I have included some code for reference:
using System;
using System.Collections.Generic;
using System.Threading;
using System.Text;
using Ivi.Visa.Interop;
namespace CsharpExample
{
class VoltageExample
{
static void Main(string[] args)
{
VoltageExample DmmClass = new VoltageExample(); //Create an instance of this class so we can call functions from Main
Ivi.Visa.Interop.ResourceManager rm = new Ivi.Visa.Interop.ResourceManager(); //Open up a new resource manager
Ivi.Visa.Interop.FormattedIO488 myDmm = new Ivi.Visa.Interop.FormattedIO488(); //Open a new Formatted IO 488 session
try
{
string DutAddr = "GPIB0::12::INSTR"; //String for GPIB
myDmm.IO = (IMessage)rm.Open(DutAddr, AccessMode.NO_LOCK, 10000, ""); //Open up a handle to the DMM with a 2 second timeout
//myDmm.IO.Timeout = 20000;
myDmm.IO.Clear(); //Send a device clear first
myDmm.WriteString("*RST", true); //Reset the device
myDmm.WriteString("*IDN?", true); //Get the IDN string
string IDN = myDmm.ReadString();
Console.WriteLine(IDN); //report the DMM's identity
myDmm.WriteString("*TST?", true); //Get the IDN string
Thread.Sleep(5000);
string TST = myDmm.ReadString();
Console.WriteLine(TST); //report the DMM's identity
myDmm.WriteString("SYST:ERR?", true); //Get the IDN string
string ERR = myDmm.ReadString();
Console.WriteLine(ERR); //report the DMM's identity
myDmm.WriteString("CONF:VOLT:DC 1000, 0.001", true);
DateTime time = DateTime.Now; //Timer to measure the time difference to get all the readings
TimeSpan diff;
Console.WriteLine("Measurement in Volts");
for(int i = 0; i<10; i++){
//Configure for DCV 100V range, 100uV resolution
myDmm.WriteString("READ?", true);
String DCVResult = myDmm.ReadString();
Console.WriteLine("DCV Reading = " + DCVResult); //report the DCV reading
DmmClass.CheckDMMError(myDmm); //Check if the DMM has any errors
Thread.Sleep(1000);
diff = DateTime.Now.Subtract(time);
//diff = DateTime.Now.Subtract(time.AddSeconds(1).AddMilliseconds(20));
Console.WriteLine("\t\t\t" + diff);
}
myDmm.WriteString("CONF:RES 100, MAX", true);
Console.WriteLine("Measurement in Ohms");
for (int i = 0; i < 10; i++)
{
//Configure for res 1000 Ohm range, 100uV resolution
myDmm.WriteString("READ?", true);
String OHMResult = myDmm.ReadString();
Console.WriteLine("Resistance Measurement = " + OHMResult); //report the DCV reading
DmmClass.CheckDMMError(myDmm); //Check if the DMM has any errors
Thread.Sleep(500);
}
}
catch (Exception e)
{
Console.WriteLine("Error occured: " + e.Message);
}
finally
{
//Close out your resources
try { myDmm.IO.Close(); }
catch{}
try{ System.Runtime.InteropServices.Marshal.ReleaseComObject(myDmm);}
catch {}
try{
System.Runtime.InteropServices.Marshal.ReleaseComObject(rm);
}
catch {}
Console.WriteLine("Press any key to continue...");
Console.ReadKey();
}
}

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.

C# try and catch

I've just signed up to the website so I have probably put this wrong. Anyways, I am trying to use the try and catch in C# to catch my file if it not found. Here is my code for it at the moment. To repeat myself, I want the program to read the file in, as it does- but then if the file is not found, I would like it to give an error saying "cannot find the file" or something along those lines, not simply just crash. (I've just started learning C#)
Thanks for the help!
string file = #"C:\Users\Henry\Desktop\Assessments\Programming and data structures\grades_multiple.txt";
try
{
file = #"C:\Users\Henry\Desktop\Assessments\Programming and data structures\grades_multiple.txt";
}
catch
{
Console.WriteLine("Could not find the file - grades_multiple.txt");
}
//ARRAY for string lines
string[] Line = new string[6];
Line[0] = File.ReadLines(file).Skip(1).Take(1).First();
You should read the file inside the try catch and catch FileNotFoundException, like this:
var file = #"C:\Users\Henry\Desktop\Assessments\Programming and data structures\grades_multiple.txt";
string[] lines;
try
{
lines = File.ReadAllLines(file);
}
catch (FileNotFoundException exnotfound)
{
// file not found exception
}
catch (Exception ex)
{
// handle other exceptions
}
You need to put the code that is error prone inside of try block.
try
{
Line[0] = File.ReadLines(file).Skip(1).Take(1).First();
}
catch(Exception ex)
{
Console.WriteLine("Could not find the file - grades_multiple.txt");
}
BTW, you can handle this situation by checking if file exists first using File.Exists method.There is no need to catch exception for that.
Try catch just doesn't work like this.
You are trying to catch a line of code that changes a string and doesn't change a file, so the file doesn't need to exist, so it will never throw an exception (in your case), and it will never catch it.
You should surround code that can go wrong: File.ReadLines
Your code will become like this:
string file = #"C:\Users\Henry\Desktop\Assessments\Programming and data structures\grades_multiple.txt";
//can go wrong
try
{
//ARRAY for string lines
string[] Line = new string[6];
Line[0] = File.ReadLines(file).Skip(1).Take(1).First();
}
//File.ReadLines is null
catch
{
Console.WriteLine("Could not find the file - grades_multiple.txt");
}
I also think it is even better practice to check it with an if statement, instead of catching it when it goes wrong:
//if file exists
if(File.Exists(file))
{
//ARRAY for string lines
string[] Line = new string[6];
Line[0] = File.ReadLines(file).Skip(1).Take(1).First();
}
//File does not exist
else
{
Console.WriteLine("Could not find the file - grades_multiple.txt");
}
When ever possible you should try to avoid throwing exceptions just to display a message to the user or for conditions that can be easily tested. This is primarily a performance consideration as throwing an exception is expensive. Additionally performance can be impacted by loading the entire file into memory unless you know that the file is relatively small..
Here is a quick and raw example on how you may test for the condition and handle it.
void Main()
{
var filePath ="C:\\TEST.DAT";
if(!File.Exists(filePath)){ DisplayFileNotFoundError(filePath); }
try
{
var lines = GetFileLines(filePath);
if(lines == null) { DisplayFileNotFoundError(filePath);}
// do work with lines;
}
catch (Exception ex)
{
DisplayFileReadException(ex);
}
}
void DisplayErrorMessageToUser(string filePath)
{
Console.WriteLine("The file does not exist");
}
void DisplayFileReadException(Exception ex){
Console.WriteLine(ex.Message);
}
string[] GetFileLines(string filePath){
if(!File.Exists(filePath)){ return null; }
string[] lines;
try
{
lines = File.ReadLines(filePath);
return lines;
}
catch (FileNotFoundException fnf){
Trace.WriteLine(fnf.Message);
return null;
}
catch (Exception ex)
{
Trace.WriteLine(ex.Message);
throw ex;
}
}
Performance Test, FileNotFoundException vs File.Exists
void Main()
{
int max = 100000;
long[] feSampling = new long[max];
long[] exSampling = new long[max];
String pathRoot ="C:\\MISSINGFILE.TXT";
String path = null;
Stopwatch sw = new Stopwatch();
for (int i = 0; i < max; i++)
{
path = pathRoot + i.ToString();
sw.Start();
File.Exists(pathRoot);
sw.Stop();
feSampling[i] = sw.ElapsedTicks;
sw.Reset();
}
StreamReader sr = null;
sw.Reset();
for (int i = 0; i < max; i++)
{
path = pathRoot + i.ToString();
try
{
sw.Start();
sr = File.OpenText(path);
}
catch (FileNotFoundException)
{
sw.Stop();
exSampling[i] = sw.ElapsedTicks;
sw.Reset();
if(sr != null) { sr.Dispose();}
}
}
Console.WriteLine("Total Samplings Per Case: {0}", max);
Console.WriteLine("File.Exists (Ticsk) - Min: {0}, Max: {1}, Mean: {2}", feSampling.Min(), feSampling.Max(), feSampling.Average ());
Console.WriteLine("FileNotFoundException (Ticks) - Min: {0}, Max: {1}, Mean: {2}", exSampling.Min(), exSampling.Max(), exSampling.Average ());
}

Categories

Resources