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.
}
Related
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.
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;
}
}
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.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I have this c# class that I am trying to make multi-threaded, or able to run 100 threads (requests?) at once.
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 ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string[] lines = File.ReadAllLines("C:\\checker/in.txt");
var accCount = File.ReadLines(#"C:\checker/in.txt").Count();
Console.Write("Accounts loaded: " + accCount);
Console.WriteLine();
foreach (string line in lines)
{
string[] account = line.Split(new char[] { ':' });
string user = account[0];
string pass = account[1];
addThreads(user, pass);
Threads.ForEach(t => t.Start());
Console.WriteLine();
}
// Suspend the screen.
Console.ReadLine();
}
public static List<Thread> Threads = new List<Thread>();
public static void addThreads(string user, string pass)
{
var checker = new Checker();
Threads.Clear();
Threads.Add(new Thread(() => { checker.checkAccount(user, pass); }));
Threads.Add(new Thread(() => { checker.checkAccount(user, pass); }));
Threads.Add(new Thread(() => { checker.checkAccount(user, pass); }));
Threads.Add(new Thread(() => { checker.checkAccount(user, pass); }));
Threads.Add(new Thread(() => { checker.checkAccount(user, pass); }));
Threads.Add(new Thread(() => { checker.checkAccount(user, pass); }));
Threads.Add(new Thread(() => { checker.checkAccount(user, pass); }));
}
}
public class Checker
{
//declare vars
string getUsername;
string getMember;
string getAuth;
string check;
public void checkAccount(string username, string password)
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
byte[] data = Encoding.ASCII.GetBytes(
$"username={username}&password={password}&mod=www&ssl=1&dest=account_settings.ws");
WebRequest request = WebRequest.Create("https://secure.runescape.com/m=weblogin/login.ws");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
using (Stream stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
string responseContent = null;
using (WebResponse response = request.GetResponse())
{
using (Stream stream = response.GetResponseStream())
{
using (StreamReader sr99 = new StreamReader(stream))
{
responseContent = sr99.ReadToEnd();
}
}
}
//parse captcha
string patternCaptcha = #"Please\s*complete\s*the\s*reCAPTCHA\s*box";
string inputCaptcha = responseContent;
Match matchCaptcha = Regex.Match(inputCaptcha, patternCaptcha);
string captcha = matchCaptcha.Value;
if (captcha == "Please complete the reCAPTCHA box")
{
captcha = "true";
Console.Write("captcha,captcha,captcha,captcha");
Console.WriteLine();
//return "captcha,captcha,captcha,captcha";
}
else
{
//parse valid/invalid
string patternCheck = #"Your\s*login\s*or\s*password\s*was\s*incorrect";
string inputCheck = responseContent;
Match matchCheck = Regex.Match(inputCheck, patternCheck);
check = matchCheck.Value;
if (check == "Your login or password was incorrect")
{
check = "Invalid";
}
else
{
check = "Valid";
//parse display name
string pattern = #"(<span.*class=.header-top__name.>(.*?)</span>)";
string input = responseContent;
Match match = Regex.Match(input, pattern);
getUsername = match.Groups[2].Value;
byte[] bytes = Encoding.Default.GetBytes(getUsername);
getUsername = Encoding.UTF8.GetString(bytes);
getUsername = getUsername.Replace("?", " ");
//parse member status
string patternMember = #"(Currently\s*Not\s*a\s*Member)";
string inputMember = responseContent;
Match matchMember = Regex.Match(inputMember, patternMember);
getMember = matchMember.Value;
if (getMember == "Currently Not a Member")
{
getMember = "Non Member";
}
else
{
getMember = "Member";
}
//parse auth status
string patternAuthUrl = #"iframe src=\""(.*?)""";
string inputAuthUrl = responseContent;
Match matchAuthUrl = Regex.Match(inputAuthUrl, patternAuthUrl);
string getAuthUrl = matchAuthUrl.Groups[1].Value;
using (WebClient client = new WebClient())
{
string authSource = client.DownloadString(getAuthUrl);
string patternAuth = #"RuneScape\s*Authenticator\s*is\s*disabled";
string inputAuth = authSource;
Match matchAuth = Regex.Match(inputAuth, patternAuth);
getAuth = matchAuth.Value;
if (getAuth == "RuneScape Authenticator is disabled")
{
getAuth = "Auth Disabled";
}
else
{
getAuth = "Authed";
}
}
}
captcha = "false";
string curldata = getUsername + "," + getMember + "," + getAuth + "," + check;
Console.Write(curldata);
Console.WriteLine();
}
}
}
}
Instead of making my program check once per few seconds per post webrequest, how can I make this happen 50-100 times at the same time? Is this possible? Or do I need to do this a different way?
You need to avoid using threads as each thread uses in excess of 1MB of RAM and they are slow to create. You really want to use tasks (TPL) or observables (Rx).
In this case it is quite straight forward to use tasks.
Try this code:
string[] lines = File.ReadAllLines("C:\\checker/in.txt");
var accCount = lines.Count();
Console.Write("Accounts loaded: " + accCount);
Console.WriteLine();
var checker = new Checker();
var tasks =
from line in lines
let account = line.Split(new char[] { ':' })
let user = account[0]
let pass = account[0]
select Task.Factory.StartNew(() => checker.checkAccount(user, pass));
Task.WaitAll(tasks.ToArray());
Console.ReadLine();
That will read the text file and queue up a set of tasks to be run to check each line. The Task.WaitAll pauses the code until all of the tasks are completed.
This make efficient use of the thread-pool so that you're not wasting valuable resources starting up threads.
Your checkAccount is also not thread-safe at the moment. You need to move the field-level variables to be inside your method. It should look something like this:
public void checkAccount(string username, string password)
{
string getUsername;
string getMember;
string getAuth;
string check;
It's pretty simple first you need to do a method to call the threads
public void CallingThreadsMethod()
{
ThreadStart ts = new ThreadStart(SomeFunction);
Thread t = Thread(ts);
t.IsBackground = true;
t.Start();
}
void Somefunction(){}
or if you want many threads you can make a thread list
public static List<Thread> Threads = new List<Thread>();
public static void addThreads()
{
Threads.Clear();
Threads.Add(new Thread(Method1));
Threads.Add(new Thread(Method2));
}
And start it in you'r main function
Vars.addThreads();
Vars.Threads.ForEach(t => t.Start());
but if you're using windows forms or wpf i recommend using BackgroundWorkers
I am new to json and web api.
I created a service called AdminService which has a get method. Kindly see below the get method:
[Route("{iUserId:long}/{iSegmentId:long}/GetUserSegmentItemBySegmentIdAndUserId")]
public IEnumerable<spADGetUserSegmentItemBySegmentIdAndUserId> GetUserSegmentItemBySegmentIdAndUserId(long iUserId, long iSegmentId)
{
using (ADMINEntities context = new ADMINEntities())
{
var usibsu = context.spADGetUserSegmentItemBySegmentIdAndUserId(iUserId, iSegmentId);
if (usibsu != null) return usibsu.ToList();
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.NotFound));
}
}
The service is working correctly.
Now, I have another service called TestService in which i want to call the get method i created in the adminservice.
Below is my code:
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;
using Newtonsoft.Json;
using NPAService.Models;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
namespace NPAService.Controllers
{
public class HomeController : Controller
{
private string ServiceURLBase = ConfigurationManager.AppSettings["AdminUrl"];
public ActionResult Index()
{
return View();
}
private void MoveImageFiles()
{
DirectoryInfo dirInfo = new DirectoryInfo(Server.MapPath("~/Reports/"));
List<String> FileNames = new List<string>();
for (int i = 0; i < dirInfo.GetFiles().Length; i++)
{
FileNames.Add(dirInfo.GetFiles()[i].FullName);
}
for (int i = 0; i < FileNames.Count; i++)
{
FileInfo fileInfo = new FileInfo(FileNames[i]);
//Delete file if it is older than five minutes
if (DateTime.Now.Subtract(fileInfo.CreationTime).TotalMinutes > 1.0)
{
System.IO.File.Delete(fileInfo.FullName);
//if the file exists at the destination folder, delete it as well
if (System.IO.File.Exists(Server.MapPath("~/Home/images/") + fileInfo.Name))
{
System.IO.File.Delete(Server.MapPath("~/Home/images/") + fileInfo.Name);
}
}
else //Copy file to where it can get displayed on the report if it is less than 5 minute old
{
if (!System.IO.File.Exists(Server.MapPath("~/Home/images/") + fileInfo.Name))
{
System.IO.File.Copy(fileInfo.FullName, Server.MapPath("~/Home/images/") + fileInfo.Name);
}
}
}
}
public string GetUserDataSegment(long iUserId, long iSegmentId)
{
string ListString = string.Empty;
var userdata = new UserData();
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(ServiceURLBase);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = client.GetAsync(iUserId + "/" + iSegmentId + "/GetUserSegmentItemBySegmentIdAndUserId").Result;
if (response.IsSuccessStatusCode)
{
var data = response.Content.ReadAsStringAsync();
var product = JsonConvert.DeserializeObject<UserData>(data);
//foreach (var str in data)
//{
//ListString = str.MyList;
//if (iSegmentId == 1) //'Depot'
//{
// ListString = ("iRegionId IN (" + str.MyList + ")");
//}
//else if (iSegmentId == 2) //'BDC'
//{
//}
//else if (iSegmentId == 3) //'LPGMC'
//{
//}
//else if (iSegmentId == 4) //'Region'
//{
// ListString = ListString + (" and iRegionId IN (" + str.MyList + ")");
//}
//else if (iSegmentId == 5) //'OMC'
//{
// ListString = ListString + (" and iOMCId IN (" + str.MyList + ")");
// ListString = "";
//}
//else if (iSegmentId == 6) //'Zone'
//{
//}
//}
}
}
return ListString;
}
[System.Web.Mvc.HttpGet]
public ActionResult OutletReportListing(long lngCompanyId, string strszITSfromPersol,
string strsQuery1, string strsQuery2, string strsQuery3, string strsQuery4,
string strPicHeight, string strPicWeight, string strCompany, long iUserId, string type)
{
string Username = Convert.ToString(ConfigurationManager.AppSettings["username"]);
string Password = Convert.ToString(ConfigurationManager.AppSettings["password"]);
string Servername = Convert.ToString(ConfigurationManager.AppSettings["DSN"]);
string Databasename = Convert.ToString(ConfigurationManager.AppSettings["databasename"]);
//GetUserDataSegment(iUserId, 5).Wait();
//var myObjList = JSON.Deserialize<List<GetUserDataSegment>>(iUserId, 5);
//var objResponse1 =
// JsonConvert.DeserializeObject<List<UserData>>(iUserId, 5);
string strOMC = GetUserDataSegment(iUserId,5);
string strRegion = GetUserDataSegment(iUserId, 4);
ReportDocument reportdocument = new ReportDocument();
reportdocument.Load(Server.MapPath("~/Reports/rptNPAOutletListing.rpt"));
reportdocument.SetDatabaseLogon(Username, Password, Servername, Databasename);
reportdocument.SetParameterValue("#iCompanyId", lngCompanyId);
reportdocument.SetParameterValue("#szITSfromPersol", strszITSfromPersol);
reportdocument.SetParameterValue("#szQuery1", strsQuery1);
reportdocument.SetParameterValue("#szQuery2", strsQuery2);
reportdocument.SetParameterValue("#szQuery3", strOMC); //strOMC
reportdocument.SetParameterValue("#szQuery4", strRegion); //strRegion
reportdocument.SetParameterValue("#szPicHeight", strPicHeight);
reportdocument.SetParameterValue("#szPicWeight", strPicWeight);
reportdocument.SetParameterValue("#szCompany", strCompany);
ExportFormatType formtType = ExportFormatType.HTML40;
string ExportName = "NPAReport.html";
string ExportMimeType = "text/html";
if (type.Trim().ToLower().Equals("view"))
{
formtType = ExportFormatType.HTML40;
ExportName = "NPAReport.html";
ExportMimeType = "text/html";
}
else if (type.Trim().ToLower().Equals("pdf"))
{
formtType = ExportFormatType.PortableDocFormat;
ExportName = "NPAReport.pdf";
ExportMimeType = "application/pdf";
}
else if (type.Trim().ToLower().Equals("doc"))
{
formtType = ExportFormatType.WordForWindows;
ExportName = "NPAReport.doc";
ExportMimeType = "application/msword";
}
else if (type.Trim().ToLower().Equals("rtf"))
{
formtType = ExportFormatType.RichText;
ExportName = "NPAReport.rtf";
ExportMimeType = "application/rtf";
}
else if (type.Trim().ToLower().Equals("xls"))
{
formtType = ExportFormatType.Excel;
ExportName = "NPAReport.xls";
ExportMimeType = "application/vnd.ms-excel";
}
reportdocument.ExportToDisk(formtType, Server.MapPath("~/Reports/" + ExportName));
MoveImageFiles();
return File(Server.MapPath("~/Reports/" + ExportName), ExportMimeType);
}
}
}
As you can see, i want to generate a report file in my api project. But the first error i am getting is:
cannot convert from 'System.Threading.Tasks.Task' to 'string'
I have done a lot of research but none does not seem to work.
Any help or explanation would be appreciated. Thank you.
response.Content.ReadAsStringAsync();
Async calls return Task<T> . When you want to read the string you call .Result property and you get the string. There is also a way to make async call synchronous. When you call an async method, your method gets out of execution and your method's caller continues execution. When async call completes, then your method continues its execution right after async method. Also since you call async method from GetUserDataSegment method, it also needs to be labeled as async.