How to skip System.InvalidOperationException when application running on C#? - c#

I have used thread , task function to remove UI block after method is executing. I used following code but it gave me System.InvalidOperationException. Here is code I tried:
private void FindVariation()
{
string[] idlist = richTextBox7.Text.Split('\n'); // < == System.InvalidOperationException
// foreach (string id in idlist)
for (int i = 0; i < Convert.ToInt32(idlist.Length); i++)
{
string url = "http://www.ebay.com/itm/" + idlist[i];
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader sr = new StreamReader(response.GetResponseStream());
// richTextBox2.Text += sr.ReadToEnd();
string a = sr.ReadToEnd();
sr.Close();
string source = null;
source = string.Join(Environment.NewLine,
a.Split(',', ']', '[')
.Where(m => m.Length == 12 && m.All(char.IsDigit)));
if (string.IsNullOrEmpty(source))
{
// MessageBox.Show("String is null");
}
else
{
richTextBox6.Text += idlist[i] + Environment.NewLine;
}
richTextBox1.Text = richTextBox7.Text;
}
}
Task fv = new Task(FindVariation);
fv.Start();
Could anybody show me what is the error?

Here's the kind of approach you need:
async Task Main()
{
string input = richTextBox7.Text;
string result = await Task.Run(() => FindVariation(input));
richTextBox1.Text = result;
}
private string FindVariation(string richTextBox7Text)
{
string[] idlist = richTextBox7Text.Split('\n');
//your code - but no access to any UI element.
return result;
}
The key thing is that inside the FindVariation you cannot access or update any UI element. Everything has to be passed in or passed out before UI is updated.

Related

C# Roslyn CompletionService where to get method overload information

I've got a method that returning back from CompletionService.GetDescriptionAsync(Document, CompletionItem) gives me the following description:
void SQL.GetSQLiteDB(string url) (+ 1 overload)
This is a method I made on a Xamarin project, here are both method signatures:
public static void GetSQLiteDB(string url);
public static string GetSQLiteDB(string url, string name);
What's the Roslyn way to get information on both?
Here's how I'm setting up completions:
async Task InitCodeCompletion()
{
host = MefHostServices.Create(MefHostServices.DefaultAssemblies);
workspace = new AdhocWorkspace(host);
Type[] types =
{
typeof(object),
typeof(System.Linq.Enumerable),
typeof(System.Collections.IEnumerable),
typeof(Console),
typeof(System.Reflection.Assembly),
typeof(List<>),
typeof(Type),
typeof(SQL)
};
imports = types.Select(x => x.Namespace).Distinct().ToImmutableArray();
assemblies = types.Select(x => x.Assembly).Distinct().ToImmutableArray();
references = assemblies.Select(t => MetadataReference.CreateFromFile(t.Location) as MetadataReference).ToImmutableArray();
compilationOptions = new CSharpCompilationOptions(
OutputKind.DynamicallyLinkedLibrary,
usings: imports);
projectInfo = ProjectInfo.Create(ProjectId.CreateNewId(), VersionStamp.Create(), "Script", "Script", LanguageNames.CSharp, isSubmission: true)
.WithMetadataReferences(references).WithCompilationOptions(compilationOptions);
project = workspace.AddProject(projectInfo);
documentInfo = DocumentInfo.Create(DocumentId.CreateNewId(project.Id), "Script", sourceCodeKind: SourceCodeKind.Script,
loader: TextLoader.From(TextAndVersion.Create(SourceText.From(""), VersionStamp.Create())));
document = workspace.AddDocument(documentInfo);
var services = workspace.Services;
completionService = CompletionService.GetService(document);
}
async Task<CodeCompletionResults> GetCompletions(string code)
{
string codeModified = "using SQL = XamTestNET5.Services.SQLiteGeneratorService; " + Environment.NewLine;
codeModified += "using HtmlSvc = XamTestNET5.Services.HtmlRetrievalService;" + Environment.NewLine;
// ^^^ The above two lines set up some simple namespace aliases in my project, if you know how to put this in a separate project document and use it in code completion please let me know in comments as otherwise doing so gives me an exception that you can't have multiple syntax trees
codeModified += code;
var source = SourceText.From(codeModified);
document = document.WithText(source);
// cursor position is at the end
var position = source.Length;
var completions = await completionService.GetCompletionsAsync(document, position);
return new CodeCompletionResults() { InputCode = code, ModifiedCode = codeModified, Completions = completions };
}
Here's how I'm getting them now and putting them in a browser control:
private async void CSharpShellEnvironment_EntryCodeCompletionEntry(object sender, CSharpShellEnvironment.EntryEventArgs e)
{
if (e.Value != "")
{
CodeCompletionResults results = await GetCompletions(e.Value);
CompletionList list = results.Completions;
if (list != null)
{
if (list.Items != null)
{
StringBuilder sb = new StringBuilder();
foreach (var item in list.Items)
{
string spanText = (item.Span.Start != item.Span.End) ? results.ModifiedCode.Substring(item.Span.Start, item.Span.Length) : "";
bool recommended = spanText == "" ? true : item.DisplayText.StartsWith(spanText);
if (recommended)
{
string fText = item.DisplayText.Substring(spanText.Length);
string props = "";
foreach(var p in item.Properties)
{
props += $"<span data-key=\"{p.Key}\" data-value=\"{p.Value}\"></span>";
}
string tags = "";
foreach(var t in item.Tags)
{
tags += $"<span data-tag=\"{t}\"></span>";
}
string descStr = "";
if (item.Tags != null)
{
if (item.Tags.Where(x => x.ToLower() == "method").FirstOrDefault() != null && item.Tags.Where(x => x.ToLower() == "public").FirstOrDefault() != null)
{
var desc = await completionService.GetDescriptionAsync(document, item);
descStr += $"<span data-desc=\"{desc.Text}\">";
foreach(var part in desc.TaggedParts)
{
descStr += $"<span data-desc-part-tag=\"{part.Tag}\" data-desc-part-text=\"{part.Text}\"></span>";
}
descStr += "</span>";
}
}
sb.AppendLine($"<div class=\"codecompleteentry\" data-display-text=\"{item.DisplayText}\" data-span-text=\"{spanText}\" data-final-text=\"{fText}\">{props}{tags}{descStr}{fText}</div>");
}
}
string scriptInputClick = "Array.prototype.forEach.call(document.getElementsByClassName('codecompleteentry'), function(el) { el.addEventListener('click', function(elem) { var text = { MessageType: 'CodeCompletion', Parameters: JSON.stringify({ DataDisplayText: el.getAttribute('data-display-text'), DataSpanText: el.getAttribute('data-span-text'), DataFinalText: el.getAttribute('data-final-text') }), Message: el.innerText }; window.chrome.webview.postMessage(text); } ); });";
sb.AppendLine($"<script type=\"text/javascript\">{scriptInputClick}</script>");
env.EnterCodeCompletionResponse(sb.ToString());
}
else
{
env.EnterCodeCompletionResponse(strNoSuggestions);
}
}
else
{
env.EnterCodeCompletionResponse(strNoSuggestions);
}
}
else
{
env.EnterCodeCompletionResponse(strNoSuggestions);
}
}
It seems on the surface that CompletionSurface has everything you need, but it doesn't, you need to reference the Document's SemanticModel in order to get all of the signature overloads of a method when the user types ( on a method during code completion.
It wasn't very obvious to me until I started looking through the RoslynPad source, which I recommend doing for a practical example: https://github.com/aelij/RoslynPad
List<IEnumerable<ReferencedSymbol>> allMethodRefs = new List<IEnumerable<ReferencedSymbol>>();
async Task<CodeCompletionResults> GetCompletions(string code)
{
string codeModified = "using SQL = XamTestNET5.Services.SQLiteGeneratorService; " + Environment.NewLine;
codeModified += "using HtmlSvc = XamTestNET5.Services.HtmlRetrievalService;" + Environment.NewLine;
// ^^^ I put my namespace aliases in the same SyntaxTree for now,
// I'd like a better solution though.
codeModified += code;
var source = SourceText.From(codeModified);
document = document.WithText(source);
// cursor position is at the end
var position = source.Length;
var completions = await completionService.GetCompletionsAsync(document, position);
syntaxRoot = await document.GetSyntaxRootAsync();
semanticModel = await document.GetSemanticModelAsync();
var methods = syntaxRoot.DescendantNodes().OfType<InvocationExpressionSyntax>();
allMethodRefs = new List<IEnumerable<ReferencedSymbol>>();
if (methods != null)
{
if (methods.Count() > 0)
{
foreach(var m in methods)
{
var info = semanticModel.GetSymbolInfo(m);
if (info.Symbol != null)
{
allMethodRefs.Add(await SymbolFinder.FindReferencesAsync(info.Symbol, solution));
}
else
{
foreach(var symbol in info.CandidateSymbols)
{
allMethodRefs.Add(await SymbolFinder.FindReferencesAsync(symbol, solution));
}
}
}
}
}
return new CodeCompletionResults() { InputCode = code, ModifiedCode = codeModified, Completions = completions };
}

Call method inside multiple tasks C#

I am having a problem calling a method in a list of Tasks. I have a method that creates N number of tasks. In each task I perform some operations that in the end results an fetching data via HttpWebRequest and writing that data into a file. I use lock objects to lock the access to shared resources like variables. Everything performs great except the call for a method that creates a executes an HttpWebRequest (method GetData). Whenever I don't lock that call for the method (GetData) it seems that some data/files are skipped. For example:
With the lock object I get file 1,2,3 and 4
Without the lock object I get file 2,4 and 3
Here's the code for the method that creates the tasks
private object lockObjectWebRequest= new object();
private object lockObjectTransactions = new object();
public List<Task> ExtractLoanTransactionsData(string URLReceived, string Headers, string Body)
{
List<Task> Tasks = new List<Task>();
try
{
int Limit = 0;
int OffsetItemsTotal = 0;
int NumberOftasks = 4;
// Create the task to run in parallel
for (int i = 0; i <= NumberOftasks; i++)
{
int OffsetCalculated = 0;
if (i > 0)
{
OffsetCalculated = Limit * i;
}
Tasks.Add(Task.Factory.StartNew(() =>
{
string URL = URLReceived+ "&offset=" + OffsetCalculated .ToString() + "&limit=" + Limit.ToString();
string Output = string.Empty;
lock (lockObjectWebRequest)
{
Output = GetData(URL, Headers,Body);
}
if (Output != "[]")
{
lock (lockObjectTransactions)
{
Identifier++;
Job.Identifier = Identifier;
// write to file
string json = JValue.Parse(Output).ToString(Formatting.Indented);
string FileName = OffSet.ToString() + Identifier;
string Path = #"C:\FileFolder\" + FileName + ".json";
File.WriteAllText(Path, json);
}
}
}));
}
}
catch (Exception ex)
{
Tasks = new List<Task>();
}
return Tasks;
}
Here's the code that performs the HttpWebRequest:
public string GetData(string URL, string Headers, string Body)
{
string Data = string.Empty;
Headers = Headers.Trim('{').Trim('}');
string[] HeadersSplit = Headers.Split(new char[] { ',', ':' });
HttpWebRequest WebRequest = (HttpWebRequest)HttpWebRequest.Create(URL);
WebRequest.Credentials = new NetworkCredential();
WebRequest.Method = "POST";
HttpWebResponse WebResponse;
// Set necessary Request Headers
for (int i = 0; i < HeadersSplit.Length; i = i + 2)
{
string HeaderPart1 = HeadersSplit[i].Replace("\"", "").Trim();
string HeaderPart2 = HeadersSplit[i + 1].Replace("\"", "").Trim();
if (HeaderPart1 == "Content-Type")
{
WebRequest.ContentType = HeaderPart2;
}
else if (HeaderPart1 == "Accept")
{
WebRequest.Accept = HeaderPart2;
}
else if (HeaderPart1 == "Authorization")
{
WebRequest.Headers["Authorization"] = HeaderPart2;
}
}
WebRequest.Headers.Add("cache-control", "no-cache");
// Add body to Request
using (var streamWriter = new StreamWriter(WebRequest.GetRequestStream()))
{
streamWriter.Write(Body);
streamWriter.Flush();
streamWriter.Close();
}
// Execute Request
WebResponse = (HttpWebResponse)WebRequest.GetResponse();
// Validate Response
if (WebResponse.StatusCode == HttpStatusCode.OK)
{
using (var streamReader = new StreamReader(WebResponse.GetResponseStream()))
{
Data = streamReader.ReadToEnd();
}
}
return Data;
}
What am I doing wrong here? The method doesn't have global data that is shared between tasks.
But you do have data that is shared between the tasks: the local varibleIdentifier and the method argument Job.
You are writing to a file using the Identifier in the file-name. If the lock is not in place, that piece of code will be running simultaniously.
The implications for Job can't be deduced from your question.
I think you can solve the identifier problem by doing this:
var identifier = Interlocked.Increment(ref Identifier);
Job.Identifier = identifier; // Use 'identifier', not 'Identifier'
// write to file
string json = ...;
string FileName = OffSet.ToString() + "_" +
"MAMBU_LT_" + DateTime.Now.ToString("yyyyMMddHHmmss") + "_" +
identifier; // Use 'identifier', not 'Identifier'
...

ThreadPool.QueueUserWorkItem Makes UI hangs

I am using ThreadPool.QueueUserWorkItem for threading in C# WinForms, but it makes the main UI hangs don't know why, is there any other good way for threading rather than ThreadPool which make the UI goes smooth!
ThreadPool.QueueUserWorkItem(new WaitCallback(KeywordSearch), cts);
private void KeywordSearch(object r)
{
string alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
char[] alphas = (alphabet + alphabet.ToLower()).ToCharArray();
if (this.InvokeRequired)
{
this.BeginInvoke((MethodInvoker)delegate ()
{
this.Cursor = Cursors.WaitCursor;
});
}
else
{
this.Cursor = Cursors.WaitCursor;
}
foreach (char a in alphas)
{
MessageBox.Show(a.ToString());
string correctkeywordforQuery = KeywordTxt.Text + " " + a;
var webRequest = WebRequest.Create(#"https://clients1.google.com/complete/search?client=youtube&hl=en&gl=us&sugexp=ytfdc%2Ccfro%3D1%2Cfp.dquf%3D1&gs_rn=64&gs_ri=youtube&ds=yt&cp=2&gs_id=6l&q=" + correctkeywordforQuery + "&callback=google.sbox.p50&gs_gbg=7dNuEZN941O5Tlh1iM");
string result;
using (var response = webRequest.GetResponse())
using (var content = response.GetResponseStream())
using (var reader = new StreamReader(content))
{
var strContent = reader.ReadToEnd();
result = strContent.Replace("google.sbox.p50 && google.sbox.p50(", ""); ;
//text.Remove(text.ToString().LastIndexOf(character), character.Length);
result = result.Remove(result.Length - 1);
}
var jsonser = new JavaScriptSerializer();
var obj = jsonser.Deserialize<dynamic>(result);
foreach (var x in obj[1])
{
//CancellationToken token = (CancellationToken)r;
//if (token.IsCancellationRequested)
//{
// cts.Cancel();
// return;
//}
var value1 = x[0]; // bd felek
// MessageBox.Show(value1);
string thecorrectlinktogetallthedata = "https://www.youtube.com/results?search_query=" + value1+ "&hl=en";
// Process.Start(thecorrectlinktogetallthedata);
if (richTextBox1.InvokeRequired)
{
this.BeginInvoke((MethodInvoker)delegate ()
{
richTextBox1.Text += "\r\n"+thecorrectlinktogetallthedata;
});
}
else
{
richTextBox1.Text += "\r\n" + thecorrectlinktogetallthedata;
}
// Process.Start(thecorrectlinktogetallthedata);
// create the constructor with post type and few data
//show the response string on the console screen.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(thecorrectlinktogetallthedata);
string htmlcontent = string.Empty;
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
using (Stream stream = response.GetResponseStream())
using (StreamReader reader = new StreamReader(stream))
{
htmlcontent = reader.ReadToEnd();
}
HtmlAgilityPack.HtmlWeb web = new HtmlAgilityPack.HtmlWeb();
HtmlAgilityPack.HtmlDocument document = new HtmlAgilityPack.HtmlDocument();
document.LoadHtml(htmlcontent);
if (richTextBox1.InvokeRequired)
{
this.BeginInvoke((MethodInvoker)delegate ()
{
richTextBox1.Text += "\r\n" + htmlcontent;
});
}
else
{
richTextBox1.Text += "\r\n" + htmlcontent;
}
//watch?v
HtmlAgilityPack.HtmlNodeCollection Nodes = document.DocumentNode.SelectNodes("//a");
//MessageBox.Show(Nodes.Count.ToString());
foreach (HtmlAgilityPack.HtmlNode node in Nodes)
{
string ahref = node.Attributes["href"].Value;
string classname = node.GetAttributeValue("classname", string.Empty);
//MessageBox.Show(ahref);
if (ahref.Contains("watch?v"))
{
string title = node.GetAttributeValue("title",string.Empty);
if(title.Trim().ToString()!= string.Empty)
{
//newRows[0] = title;
//newRows[1] = ahref; ;
if (ResultGrid.InvokeRequired)
{
ResultGrid.BeginInvoke((MethodInvoker)delegate ()
{
object[] newRows = { title, "https://www.youtube.com" + ahref };
//MessageBox.Show(title);
ResultGrid.Rows.Add(newRows);
ResultGrid.Update();
//ResultCountLabel.Text = ResultGrid.Rows.Count.ToString();
});
}
else
{
object[] newRows = { title, "https://www.youtube.com" + ahref };
//
ResultGrid.Rows.Add(newRows);
ResultGrid.Update();
//ResultCountLabel.Text = ResultGrid.Rows.Count.ToString();
}
}
}
}
break;
}
}
if (this.InvokeRequired)
{
this.BeginInvoke((MethodInvoker)delegate ()
{
this.Cursor = Cursors.Default;
});
}
else
{
this.Cursor = Cursors.Default;
}
}

request.getResponse() is getting error

This is my code which is returning the expected output on my friend's PC, but not on mine.
We are both working with Visual Studio 2017 Community:
enter image description here
This is the code that will return latitude and longitude of the entered address:
[enter image description here][2]
The first time it works fine but after that its throwing (403 forbidden error !!! / mainly problem is on the request.getResponse())
private static String[] x = new String[3];
public static String[] GetFirstLastName(string address)
{
try {
string url = "http://maps.google.com/maps/api/geocode/xml?address=" + address + "&sensor=false";
WebRequest request = WebRequest.Create(url);
// request.UseDefaultCredentials = true;
// request.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
// request.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
using (WebResponse response = (HttpWebResponse)request.GetResponse())
{
using (var reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
{
var ds = new DataSet("Employee");
ds.ReadXml(reader);
DataRow dr = null;
var dt = new DataTable("Employee");
dt.Columns.AddRange(new DataColumn[2]
{
new DataColumn("Latitude", typeof (string)),
new DataColumn("Longitude", typeof (string))
});
int i = 0;
try
{
foreach (DataRow row in ds.Tables["result"].Rows)
{
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
return x;
}
foreach (DataRow row in ds.Tables["result"].Rows)
{
if (i == 0)
{
string geometry_id = ds.Tables["geometry"].Select("result_id = " + row["result_id"])[0]["geometry_id"].ToString();
dr = ds.Tables["location"].Select("geometry_id = " + geometry_id)[0];
dt.Rows.Add(dr["lat"], dr["lng"]);
// Console.WriteLine(dr["lat"].ToString() + " " + dr["lng"].ToString());
i = 1;
break;
}
}
x[0] = dr["lat"].ToString();
x[1] = dr["lng"].ToString();
reader.Close();
}
// request.Timeout = 0;
// request.Abort();
response.Close();
return x;
}
}
catch(Exception e)
{
Console.WriteLine(e);
x[0] = "";
x[1] = "";
return x;
}
}
public static String[] GetFirstLastName1(string address)
{
try
{
string url = "http://maps.google.com/maps/api/geocode/xml?address=" + address + "&sensor=false";
WebRequest request = WebRequest.Create(url);
// request.UseDefaultCredentials = true;
// request.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
// request.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
using (WebResponse response = request.GetResponse())
{
using (var reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
{
var ds = new DataSet("Employee");
ds.ReadXml(reader);
DataRow dr = null;
var dt = new DataTable("Employee");
dt.Columns.AddRange(new DataColumn[2]
{
new DataColumn("Latitude", typeof (string)),
new DataColumn("Longitude", typeof (string))
});
int i = 0;
try
{
foreach (DataRow row in ds.Tables["result"].Rows)
{
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
return x;
}
foreach (DataRow row in ds.Tables["result"].Rows)
{
if (i == 0)
{
string geometry_id = ds.Tables["geometry"].Select("result_id = " + row["result_id"])[0]["geometry_id"].ToString();
dr = ds.Tables["location"].Select("geometry_id = " + geometry_id)[0];
dt.Rows.Add(dr["lat"], dr["lng"]);
// Console.WriteLine(dr["lat"].ToString() + " " + dr["lng"].ToString());
i = 1;
break;
}
}
x[0] = dr["lat"].ToString();
x[1] = dr["lng"].ToString();
reader.Close();
}
//// request.Timeout = 0;
/// request.Abort();
response.Close();
return x;
}
}
catch (Exception e)
{
Console.WriteLine(e);
x[0] = "";
x[1] = "";
return x;
}
}
static void Main(string[] args)
{
int i = 0;
for (;;)
{
String x = Console.ReadLine();
if (i == 0)
{
String[] y = GetFirstLastName(x);
Console.WriteLine(y[0] + " " + y[1]);
}
else
{
String[] y = GetFirstLastName1(x);
Console.WriteLine(y[0] + " " + y[1]);
}
i++;
}
//Console.ReadKey();
}
}
}
/*(Same Code above)
enter code here
///My Friends Output
/// My Output
[2]: https://i.stack.imgur.com/qeDcz.png */
Glad to see you've joined StackOverflow!
Now a 403 error occurs usually not in relation to a syntax error in your code but in relation to the response received from Google's servers.
Now Google in particular is very restrictive on how many API calls you can make a day (Google makes a lot of money off developers who pay for lots of API calls). This page contains the limits. If you've made more than the numbers in here, that's why you're getting the error and you'll have to wait until tomorrow. Do keep in mind not to send too many http requests and accidentally DOS them, as they'll blacklist you for this.
Make sure you are not caching their page or storing the js script locally as this will also cause a blacklist.
Make sure you use https: and not http: here.

Filtering text from string

I have it now like this:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApplication2
{
public class Program
{
static void Main(string[] args)
{
//Consider making this configurable
const string sourceFile = "test2.txt";
const string pattern = "http://10.123.9.66:80";
//var FirstSeparatorLastNameExact = new[] { "nosyn_name_last_exact:(qxq" };
//var SecondSeparatorLastNameExact = new[] { "qxq)" };
string[] FirstSeparator = new string[] { "nosyn_name_last_exact:(qxq" };
string[] SecondSeparator = new string[] { "qxq)" };
string[] FirstSeperatorFirstName = new string[] {"nosyn_name_first_exact:(qxq"};
string[] secondSeperatorFirstName = new string[]{"qxq)"};
Regex re = new Regex("^(http|https)://");
HttpWebResponse response;
// var webClient = 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
//webClient.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)
{
var urNewList = new List<string>();
var line = reader.ReadLine();
//line = line.Substring(line.IndexOf(pattern));
//line.Split("\t");
var columns = line.Split('\t');
//var result = line.Split(Seperator, StringSplitOptions.RemoveEmptyEntries)[1].Split(')')[0];
if (columns[2] == "R")
{
var url = columns[4] + "?" + columns[5];
urlList.Add(url);
Thread.Sleep(250);
}
//if (line.Contains(result))
//{
//MatchCollection matches = Regex.Matches(line, lastName);
//foreach (string lines in File.ReadLines(sourceFile))
//{
//var LastNameSearch = line.Split(FirstSeparatorLastNameExact, StringSplitOptions.RemoveEmptyEntries)[1];
//var resultLastNameSearch = LastNameSearch.Split(FirstSeparatorLastNameExact, StringSplitOptions.RemoveEmptyEntries)[0];
//var temp = line.Split(FirstSeparator, StringSplitOptions.RemoveEmptyEntries)[1];
//var result2 = temp.Split(SecondSeparator, StringSplitOptions.RemoveEmptyEntries)[0];
//Console.WriteLine(result2);
string[] result = line.Split(FirstSeperatorFirstName, StringSplitOptions.RemoveEmptyEntries);
if (result.Length > 2)
{
string[] inner = result[1].Split(')');
if (inner.Length > 1)
{
Console.WriteLine(inner[0]);
Console.WriteLine(result);
}
}
//var split = line.Split(FirstSeperatorFirstName, StringSplitOptions.RemoveEmptyEntries);
//if (split.Length > 1)
//{
// Console.WriteLine(split[1].Split(')')[0]);
// // Console.WriteLine(split);
//}
}
}
}
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();
using (WebClient webClient = new WebClient())
{
webClient.Headers.Add(HttpRequestHeader.UserAgent, "Response-Tester-Client");
// HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
//webClient.Dispose();
}
}
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
//webClient.Dispose();
//Write the response times
Console.WriteLine("Url " + "\t\t\t\tLast Name");
foreach (var key in times.Keys)
{
Console.WriteLine("{0}: {1}", key, times[key].TotalSeconds);
}
Console.ReadKey();
}
}
}
But I still get the error: Index was outside the bounds of the array. So how to change it? And in fact It also has to be remove the qxq. I try it with two string that I declared above
Thank you
how to skip the line if there is no nosyn_name_first_exact
Split your code to not assume there is one. You have:
test.Split(FirstSeperatorFirstName, StringSplitOptions.RemoveEmptyEntries)[1]
.Split(')')[0]
.Dump();
Change it to something like:
var split = test.Split(FirstSeperatorFirstName, StringSplitOptions.RemoveEmptyEntries);
if (split.Length > 1)
{
split[1].Split(')')[0].Dump();
}
You see the same problem can occur within the if, repeat if necessary.
You are trying to fetch a index from an array that do not have that many values (index is out of bounds).
Check if the array is long enough before you try to fetch the index, like:
string[] result = test.Split(FirstSeperatorFirstName, StringSplitOptions.RemoveEmptyEntries);
if(result.Length > 2) {
string[] inner = result[1].Split(')');
if(inner.Length > 1) {
inner[0].Dump();
}
}
Or check if the string contains the given substring before even trying to split:
if(test.Contains("nosyn_name_first_exact:(qxq")) {
// Split and do whatever.
}

Categories