In mono 4.6.2 / linux, I'm noticing huge differences between the speed wget can download files, vs webclient.DownloadString, so I made a little test to investigate. Why is wget significantly faster than C#? From my own experiments, it's faster to swallow the overhead of downloading using wget, reading in the files manually, and finally deleting the downloaded files, than simply using .DownloadString. Am I using the HttpWebRequest incorrectly?
Update: On mono/linux, it would seem that using AutomaticDecompression makes no difference at all. I can't see any problems reported about it in mono though.
Update2: Due to a typo, I didn't notice that the native WebClient class is far faster than a simple extended class. Why does mono have a huge performance gap between a simple extended class and its parent?
class WC1 : System.Net.WebClient
{
protected override WebRequest GetWebRequest(Uri address)
{
var r = (HttpWebRequest) base.GetWebRequest(address);
r.Pipelined = true;
r.KeepAlive = true;
r.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
return r;
}
}
class WC2 : System.Net.WebClient
{
protected override WebRequest GetWebRequest(Uri address)
{
var r = (HttpWebRequest)base.GetWebRequest(address);
r.Pipelined = true;
r.KeepAlive = false;
r.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
return r;
}
}
class WC3 : System.Net.WebClient
{
protected override WebRequest GetWebRequest(Uri address)
{
var r = (HttpWebRequest)base.GetWebRequest(address);
r.Pipelined = false;
r.KeepAlive = true;
r.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
return r;
}
}
class WC4 : System.Net.WebClient
{
protected override WebRequest GetWebRequest(Uri address)
{
var r = (HttpWebRequest)base.GetWebRequest(address);
r.Pipelined = false;
r.KeepAlive = false;
r.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
return r;
}
}
class Program
{
static List<string> CreateUrls(int c)
{
var urls = new List<string>();
for (var i = 0; i < c; i++)
{
urls.Add("http://foo.com/?" + i);
}
return urls;
}
static TimeSpan Test(WebClient wc, IEnumerable<string> urls)
{
var sw = new System.Diagnostics.Stopwatch();
sw.Start();
foreach (var u in urls)
{
wc.DownloadString(u);
Console.Write(".");
}
sw.Stop();
return sw.Elapsed;
}
static void Main(string[] args)
{
var urlsPerTest = 200;
var urls = CreateUrls(urlsPerTest * 6);
var wc1 = new WC1();
var urls1 = urls.Take(urlsPerTest);
var elapsed1 = Test(wc1, urls1);
Console.WriteLine("WC1:" + elapsed1);
var wc2 = new WC2();
var urls2 = urls.Skip(urlsPerTest * 1).Take(urlsPerTest);
var elapsed2 = Test(wc2, urls2);
Console.WriteLine("WC2:" + elapsed2);
var wc3 = new WC3();
var urls3 = urls.Skip(urlsPerTest * 2).Take(urlsPerTest);
var elapsed3 = Test(wc3, urls3);
Console.WriteLine("WC3:" + elapsed3);
var wc4 = new WC4();
var urls4 = urls.Skip(urlsPerTest * 3).Take(urlsPerTest);
var elapsed4 = Test(wc4, urls4);
Console.WriteLine("WC4:" + elapsed4);
var wc5 = new WebClient();
var urls5 = urls.Skip(urlsPerTest * 4).Take(urlsPerTest);
var elapsed5 = Test(wc5, urls5);
Console.WriteLine("Webclient:" + elapsed5);
var urls6 = urls.Skip(urlsPerTest * 5).Take(urlsPerTest);
File.WriteAllLines("/tmp/foo.txt", urls6);
var sw = new Stopwatch();
sw.Start();
var p = new Process();
p.StartInfo = new ProcessStartInfo();
p.StartInfo.Arguments = "--silent -i /tmp/foo.txt";
p.StartInfo.CreateNoWindow = true;
p.StartInfo.FileName = "wget";
p.StartInfo.WorkingDirectory = "/tmp";
p.StartInfo.UseShellExecute = false;
p.Start();
p.WaitForExit();
sw.Stop();
File.Delete("/tmp/foo.txt");
Console.WriteLine("Wget:" + sw.Elapsed);
Console.ReadLine();
}
}
output
WC1:00:01:20.6518416
WC2:00:01:16.3561090
WC3:00:01:18.4278756
WC4:00:01:25.5372973
Webclient:00:01:04.6749124
Wget:00:01:03.4862053
Related
I'm trying to learn programming by myself the best I can but, seems like my code isn't as productive as it can be. I'm trying to learn by doing things that I would use on a normal occasion and I can't figure out how to properly manage it, so any information would be greatly appreciated.
I'm working on a discord bot for personal use at the moment, it works fine, the loadout time is just terrible when it comes to this part of the command. Maybe cause I'm trying to have it open, read, and close multiple databases? Or is there another explanation or method to doing this that can make it load within a faster time?
string NormalExp = "0";
string IronExp = "0";
string HCExp = "0";
string UIMExp = "0";
//Normal Account
try
{
WebRequest NormalScore = WebRequest.Create("https://secure.runescape.com/m=hiscore_oldschool/index_lite.ws?player=" + player);
WebResponse NormalResponse = NormalScore.GetResponse();
using (Stream NormalDStream = NormalResponse.GetResponseStream())
{
StreamReader NormalReader = new StreamReader(NormalDStream);
string NormalResponseFromServer = NormalReader.ReadToEnd();
var _Score = NormalResponseFromServer.Split('\n');
var _Total = _Score[0];
var _TotalGet = _Total.Split(',');
var _TotalRank = _TotalGet[0];
var _TotalLevel = _TotalGet[1];
var _TotalExp = _TotalGet[2];
NormalExp = _TotalExp;
}
NormalResponse.Close();
}
catch (Exception)
{
}
//Normal Ironman
try
{
WebRequest IronScore = WebRequest.Create("https://secure.runescape.com/m=hiscore_oldschool_ironman/index_lite.ws?player=" + player);
WebResponse IronResponse = IronScore.GetResponse();
using (Stream IronDStream = IronResponse.GetResponseStream())
{
StreamReader IronReader = new StreamReader(IronDStream);
string IronResponseFromServer = IronReader.ReadToEnd();
var _Score = IronResponseFromServer.Split('\n');
var _Total = _Score[0];
var _TotalGet = _Total.Split(',');
var _TotalRank = _TotalGet[0];
var _TotalLevel = _TotalGet[1];
var _TotalExp = _TotalGet[2];
IronExp = _TotalExp;
}
IronResponse.Close();
}
catch (Exception)
{
}
//Hardcore Ironman
try
{
WebRequest HCScore = WebRequest.Create("https://secure.runescape.com/m=hiscore_oldschool_hardcore_ironman/index_lite.ws?player=" + player);
WebResponse HCResponse = HCScore.GetResponse();
using (Stream HCDStream = HCResponse.GetResponseStream())
{
StreamReader HCReader = new StreamReader(HCDStream);
string HCResponseFromServer = HCReader.ReadToEnd();
var _Score = HCResponseFromServer.Split('\n');
var _Total = _Score[0];
var _TotalGet = _Total.Split(',');
var _TotalRank = _TotalGet[0];
var _TotalLevel = _TotalGet[1];
var _TotalExp = _TotalGet[2];
HCExp = _TotalExp;
}
HCResponse.Close();
}
catch (Exception)
{
}
//Ultimate Ironman
try
{
WebRequest UIMScore = WebRequest.Create("https://secure.runescape.com/m=hiscore_oldschool_ultimate/index_lite.ws?player=" + player);
WebResponse UIMResponse = UIMScore.GetResponse();
using (Stream UIMDStream = UIMResponse.GetResponseStream())
{
StreamReader UIMReader = new StreamReader(UIMDStream);
string UIMResponseFromServer = UIMReader.ReadToEnd();
var _Score = UIMResponseFromServer.Split('\n');
var _Total = _Score[0];
var _TotalGet = _Total.Split(',');
var _TotalRank = _TotalGet[0];
var _TotalLevel = _TotalGet[1];
var _TotalExp = _TotalGet[2];
UIMExp = _TotalExp;
}
UIMResponse.Close();
}
catch (Exception)
{
}
await ReplyAsync(
$"**Normal: ** {NormalExp}\n" +
$"**Ironman: ** {IronExp}\n" +
$"**Hardcore: ** {HCExp}\n" +
$"**UIM: ** {UIMExp}");
if (Convert.ToInt64(UIMExp) == Convert.ToInt64(NormalExp))
{
await ReplyAsync("Account is a UIM");
}
else if (Convert.ToInt64(HCExp) == Convert.ToInt64(NormalExp))
{
await ReplyAsync("Account is a HC");
}
else if (Convert.ToInt64(IronExp) == Convert.ToInt64(NormalExp) && Convert.ToInt64(IronExp) > Convert.ToInt64(UIMExp + HCExp))
{
if (Convert.ToInt32(UIMExp) > 1)
{
await ReplyAsync("Account is a ~~UIM~~ Normal Ironman");
}
else if (Convert.ToInt64(HCExp) > 1)
{
await ReplyAsync("Account is a ~~HC~~ Normal Ironman");
}
else
{
await ReplyAsync("Account is a Normal Ironman");
}
}
else
{
if (Convert.ToInt64(UIMExp) > 1 && Convert.ToInt64(IronExp) > 1)
{
await ReplyAsync("Account is a ~~UIM~~, ~~Ironman~~, normal player.");
}
else if (Convert.ToInt64(HCExp) > 1 && Convert.ToInt64(IronExp) > 1)
{
await ReplyAsync("Account is a ~~HC~~, ~~Ironman~~, normal player.");
}
else if (Convert.ToInt64(IronExp) > 1 && Convert.ToInt64(HCExp) == 0 && Convert.ToInt64(UIMExp) == 0)
{
await ReplyAsync("Account is a ~~Ironman~~ normal player.");
}
else
{
await ReplyAsync("Account is a Normal Player");
}
}
In general, sending requests is an expensive operation but you can improve it by changing your method.
Try to use HttpClient instead of WebRequest
and I suggest reading about Async/Sync operations
I'm adding request headers with the following code example, and I'm expecting to see the information I've added in the request header.
When I follow and review the request header (Telerik Fiddler 4) I can not see the information I added.
I don't know what's wrong with the code. Can you help me?
Thank you in advance.
private HttpMapTileDataSource _dataSource;
public GmHttpTileDataSourceFactory()
{
_dataSource = new
HttpMapTileDataSource("https://tile.openstreetmap.org/{zoomlevel}/{x}/{y}.png");
_dataSource.AdditionalRequestHeaders.Add("Accept-Language", "en");
_dataSource.AdditionalRequestHeaders.Add("Key", "Value");
_dataSource.AdditionalRequestHeaders.Add("blabla", "blabla");
}
Here is a semi-finished code, perhaps to solve the request header problem you encountered.
public class CustomTileDataSource : CustomMapTileDataSource
{
private string _tileUrl;
public Dictionary<string, string> AdditionalRequestHeaders = new Dictionary<string, string>();
private Dictionary<string, string> DefaultRequestHeaders = new Dictionary<string, string>();
public CustomTileDataSource(string tileUrl)
{
_tileUrl = tileUrl;
DefaultRequestHeaders.Add("Cache-Control", "max-age=0");
DefaultRequestHeaders.Add("Accept-Language", "en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7");
DefaultRequestHeaders.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3");
DefaultRequestHeaders.Add("Accept-Encoding", "gzip, deflate, br");
DefaultRequestHeaders.Add("User-Agent", "ozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.10 Safari/537.36 Edg/77.0.235.5");
BitmapRequested += BitmapRequestedHandler;
}
private async void BitmapRequestedHandler(CustomMapTileDataSource sender, MapTileBitmapRequestedEventArgs args)
{
var deferral = args.Request.GetDeferral();
try
{
using (var imgStream = await GetTileAsStreamAsync(args.X, args.Y, args.ZoomLevel))
{
var memStream = imgStream.AsRandomAccessStream();
var decoder = await Windows.Graphics.Imaging.BitmapDecoder.CreateAsync(memStream);
var pixelProvider = await decoder.GetPixelDataAsync(Windows.Graphics.Imaging.BitmapPixelFormat.Rgba8, Windows.Graphics.Imaging.BitmapAlphaMode.Straight, new Windows.Graphics.Imaging.BitmapTransform(), Windows.Graphics.Imaging.ExifOrientationMode.RespectExifOrientation, Windows.Graphics.Imaging.ColorManagementMode.ColorManageToSRgb);
var pixels = pixelProvider.DetachPixelData();
var width = decoder.OrientedPixelWidth;
var height = decoder.OrientedPixelHeight;
Parallel.For(0, height, i =>
{
for (int j = 0; j <= width - 1; j++)
{
// Alpha channel Index (RGBA)
var idx = (i * height + j) * 4 + 3;
}
});
var randomAccessStream = new InMemoryRandomAccessStream();
var outputStream = randomAccessStream.GetOutputStreamAt(0);
var writer = new DataWriter(outputStream);
writer.WriteBytes(pixels);
await writer.StoreAsync();
await writer.FlushAsync();
args.Request.PixelData = RandomAccessStreamReference.CreateFromStream(randomAccessStream);
}
}
catch
{
}
deferral.Complete();
}
private Task<MemoryStream> GetTileAsStreamAsync(int x, int y, int zoom)
{
var tcs = new TaskCompletionSource<MemoryStream>();
var quadkey = TileXYZoomToQuadKey(x, y, zoom);
string url;
url = _tileUrl.Replace("{x}", x.ToString()).Replace("{y}", y.ToString()).Replace("{zoomlevel}", zoom.ToString()).Replace("{quadkey}", quadkey);
var request = WebRequest.Create(url);
foreach (var defaultHeader in DefaultRequestHeaders)
{
request.Headers.Add(defaultHeader.Key, defaultHeader.Value);
}
if (AdditionalRequestHeaders.Count > 0)
{
foreach (var addHeader in AdditionalRequestHeaders)
{
request.Headers.Add(addHeader.Key, addHeader.Value);
}
}
request.BeginGetResponse(async a =>
{
var r = (HttpWebRequest)a.AsyncState;
HttpWebResponse response = (HttpWebResponse)r.EndGetResponse(a);
using (var s = response.GetResponseStream())
{
var ms = new MemoryStream();
await s.CopyToAsync(ms);
ms.Position = 0;
tcs.SetResult(ms);
}
}, request);
return tcs.Task;
}
private string TileXYZoomToQuadKey(int tileX, int tileY, int zoom)
{
var quadKey = new StringBuilder();
for (int i = zoom; i >= 1; i += -1)
{
char digit = '0';
int mask = 1 << (i - 1);
if ((tileX & mask) != 0)
Strings.ChrW(Strings.AscW(digit) + 1);
if ((tileY & mask) != 0)
{
Strings.ChrW(Strings.AscW(digit) + 1);
Strings.ChrW(Strings.AscW(digit) + 1);
}
quadKey.Append(digit);
}
return quadKey.ToString();
}
}
Usage
var dataSource = new CustomTileDataSource("https://tile.openstreetmap.org/{zoomlevel}/{x}/{y}.png");
dataSource.AdditionalRequestHeaders.Add("header_name", "header_value");
// other code
var mySource = new MapTileSource(dataSource);
myMap.TileSources.Add(mySource);
During the test, I also encountered the problem that HttpMapTileDataSource.AdditionalRequestHeaders does not display. I tried to use CustomMapTileDataSource to derive and rewrite the related methods so that it can work normally.
The reason for saying that it is a semi-finished product is that it does not establish a good caching mechanism, and the initial loading time is very long.
Best regards.
I have 8 jobs in my project. They start in the Application_Start event and repeat forever. Two of them are using the same class. One job every 7 seconds and the other job every 30 seconds working. But they use the same method at 1 point. Reading a date from an xml file.
If the date is older than the current date, it changes the session id and adds 20 minutes to it. The session id is constantly changing as both are trying to enter and process at the same time.
The following is my need:
1 - Enter the method.
2 - If the session is to be changed, stop the tasks other than the current task.
3 - Change session and save to xml.
4 - Restart or resume all my passive tasks.
private DateTimeOffset g_canlimacgetir = DateTimeOffset.UtcNow.AddSeconds(0);
private DateTimeOffset g_canliorangetir = DateTimeOffset.UtcNow.AddSeconds(45);
private void CanliOranlariGetir()
{
try
{
ISchedulerFactory schfack = new StdSchedulerFactory();
IScheduler scheduler = schfack.GetScheduler();
IJobDetail jobdetay = JobBuilder.Create<CanliOranlar>()
.WithIdentity("canliorangetir")
.Build();
ITrigger trigger = TriggerBuilder.Create()
.WithSimpleSchedule(s => s.WithIntervalInSeconds(7).RepeatForever()).StartAt(g_canliorangetir).Build();
scheduler.ScheduleJob(jobdetay, trigger);
scheduler.Start();
}
}
private void CanliMaclariGetir()
{
try
{
ISchedulerFactory schfack = new StdSchedulerFactory();
IScheduler scheduler = schfack.GetScheduler();
IJobDetail jobdetay = JobBuilder.Create<CanliMaclar>()
.WithIdentity("canlimacgetir")
.Build();
ITrigger trigger = TriggerBuilder.Create()
.WithSimpleSchedule(s => s.WithIntervalInSeconds(30).RepeatForever()).StartAt(g_canlimacgetir).Build();
scheduler.ScheduleJob(jobdetay, trigger);
scheduler.Start();
}
}
private Headers GetTheToken()
{
Headers h = new Headers();
HttpWebResponse response = null;
try
{
const string session_site = "";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(session_site);
Uri uri = new Uri("");
request.Method = "GET";
request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:50.0) Gecko/20100101 Firefox/50.0";
request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
request.ContentType = "text/html; charset=utf-8";
request.ContentLength = 0;
Cookie trackerID = new Cookie("trackerId", ConfigurationManager.AppSettings["TrackerID"].ToString()) { Domain = uri.Host };
DateTime tarih = DateTime.Now;
request.Timeout = 5000;
ServicePointManager.Expect100Continue = false;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
ServicePointManager.ServerCertificateValidationCallback = new
RemoteCertificateValidationCallback(delegate { return true; });
response = (HttpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
response.Close();
response.Dispose();
reader.Close();
reader.Dispose();
DateTime sesstimeout = DateTime.Now.AddSeconds(1199);
string getCookieHeader = response.Headers[HttpResponseHeader.SetCookie];
char[] ayiricilar = { '=', ',', ';' };
string[] parcalar = getCookieHeader.Split(ayiricilar);
int ses = 0, rv = 0, xt = 0, xct = 0;
if (parcalar.Length > 20)
{
h.session_timeout = sesstimeout;
for (int i = 0; i < parcalar.Length; i++)
{
if (parcalar[i] == "ASP.NET_SessionId") { h.sessionID = parcalar[i + 1]; ses = 1; }
else if (parcalar[i] == "__RequestVerificationToken") { h.request_verification = parcalar[i + 1]; rv = 1; }
else if (parcalar[i] == "XSRF-TOKEN") { h.xsrf_token = parcalar[i + 1]; xt = 1; }
else if (parcalar[i] == "XSRF-COOKIE-TOKEN") { h.xsrf_cookie_token = parcalar[i + 1]; xct = 1; }
if (ses == 1 && rv == 1 && xt == 1 && xct == 1) i = parcalar.Length;
}
}
response.Close();
response.Dispose();
XmlDocument doc = new XmlDocument();
XmlReader xmlReader = new XmlTextReader(HostingEnvironment.MapPath("~/xml/values.xml"));
doc.Load(xmlReader);
xmlReader.Close();
XmlNodeList InfoNode = doc.SelectNodes("SessionInfo/Info");
InfoNode[0].Attributes["SessionExpires"].Value = h.session_timeout.ToString();
InfoNode[0].Attributes["SessionID"].Value = h.sessionID;
InfoNode[0].Attributes["XSRF-TOKEN"].Value = h.xsrf_token;
InfoNode[0].Attributes["XSRF-COOKIE-TOKEN"].Value = h.xsrf_cookie_token;
InfoNode[0].Attributes["_requestVerification"].Value = h.request_verification.ToString();
doc.Save(HostingEnvironment.MapPath("~/xml/values.xml"));
}
return h;
}
For all jobs you can use
scheduler.PauseAll();
scheduler.ResumeAll();
But if you want to stop and start a specific job you can use this:
scheduler.PauseJob(jobdetay.Key);
scheduler.ResumeJob(jobdetay.Key);
I am developing my first windows App and I am facing some Problems while parsing an Xml,the code is as shown below
public void TimeParsing(string lat, string lon)
{
string urlbeg = "http://api.geonames.org/timezone?lat=";
string urlmid = "&lng=";
string urlend = "&username=dheeraj_kumar";
WebClient downloader = new WebClient();
Uri uri = new Uri(urlbeg + lat + urlmid + lon + urlend, UriKind.Absolute);
downloader.DownloadStringCompleted += new DownloadStringCompletedEventHandler(TimeDownloaded);
//downloader.DownloadStringCompleted += new DownloadStringCompletedEventHandler(TimeDownloaded);
downloader.DownloadStringAsync(uri);
}
private void TimeDownloaded(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Result == null || e.Error != null)
{
MessageBox.Show("Invalid");
}
else
{
XDocument document = XDocument.Parse(e.Result);
var data1 = from query in document.Descendants("geoname")
select new Country
{
CurrentTime = (string)query.Element("time"),
};
foreach (var d in data1)
{
time = d.CurrentTime;
MessageBox.Show(d.CurrentTime);
// country = d.CountryName;
}
}
}
The problem is that the Delegate TimeDownloaded is not being called. I used the same technique is parse a different URL and it was done easily but its not working in this case.Kindly Help me as I am pretty new to this field.
Thanks in advance.
Theres a few misses regarding fetching the nodes
The output is geonames/timezone/time, it's corrected below, also testable using the method DownloadStringTaskAsync instead
[TestClass]
public class UnitTest1
{
[TestMethod]
public async Task TestMethod1()
{
await TimeParsing("-33.8674869", "151.20699020000006");
}
public async Task TimeParsing(string lat, string lon)
{
var urlbeg = "http://api.geonames.org/timezone?lat=";
var urlmid = "&lng=";
var urlend = "&username=dheeraj_kumar";
var downloader = new WebClient();
var uri = new Uri(urlbeg + lat + urlmid + lon + urlend, UriKind.Absolute);
downloader.DownloadStringCompleted += TimeDownloaded;
var test = await downloader.DownloadStringTaskAsync(uri);
Console.WriteLine(test);
}
private void TimeDownloaded(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Result == null || e.Error != null)
{
Console.WriteLine("Invalid");
}
else
{
var document = XDocument.Parse(e.Result);
var data1 = from query in document.Descendants("timezone")
select new Country
{
CurrentTime = (string)query.Element("time"),
};
foreach (var d in data1)
{
Console.WriteLine(d.CurrentTime);
}
}
}
}
internal class Country
{
public string CurrentTime { get; set; }
}
}
you can use the below mentioned code.
Uri uri = new Uri(urlbeg + lat + urlmid + lon + urlend, UriKind.Absolute);
HttpWebRequest WebReq = (HttpWebRequest)WebRequest.Create(uri);
//This time, our method is GET.
WebReq.Method = "GET";
//From here on, it's all the same as above.
HttpWebResponse WebResp = (HttpWebResponse)WebReq.GetResponse();
//Now, we read the response (the string), and output it.
Stream Answer = WebResp.GetResponseStream();
StreamReader _Answer = new StreamReader(Answer);
string s = _Answer.ReadToEnd();
XDocument document = XDocument.Parse(s);
var data1 = from query in document.Descendants("geoname")
select new Country
{
CurrentTime = (string)query.Element("time"),
};
foreach (var d in data1)
{
time = d.CurrentTime;
MessageBox.Show(d.CurrentTime);
// country = d.CountryName;
}
for Windows Phone 8 you have to implement the getResponse Method.
public static System.Threading.Tasks.Task<System.Net.WebResponse> GetResponseAsync(this System.Net.WebRequest wr)
{
return Task<System.Net.WebResponse>.Factory.FromAsync(wr.BeginGetResponse, wr.EndGetResponse, null);
}
I'm using these code to download a file from the server.
The link of the server from where I need to download the file is:
http://www.mcxindia.com/sitepages/BhavCopyDateWise.aspx
var forms = new NameValueCollection();
forms["__EVENTARGUMENT"] = "";
forms["__VIEWSTATE"] = ExtractVariable(s, "__VIEWSTATE");
forms["mTbdate"] = "12/22/2011";
forms["__EVENTVALIDATION"] = __EVENTVALIDATION;
forms["mImgBtnGo"] = "?";
forms["__EVENTTARGET"] = "btnLink_Excel";
webClient.Headers.Set(HttpRequestHeader.ContentType, "application/x-www-form-urlencoded");
var responseData = webClient.UploadValues(#"http://www.mcxindia.com/sitepages/BhavCopyDateWise.aspx", "POST", forms);
System.IO.File.WriteAllBytes(#"c:\11152011.csv", responseData);
Its downloading the file of the given date in the textbox which is default in the website now.
I need to click a button called mImgBtnGo before, to download the file of the given date
in the mTbdate.
I don't know what I should do to click the button called mImgBtnGo .
What I should write here
forms["mImgBtnGo"] = "?";
using fiddler I think this is what you want:
class Program
{
static string Extract(string s, string tag)
{
var startTag = String.Format("id=\"{0}\" value=\"", tag);
var eaPos = s.IndexOf(startTag) + startTag.Length ;
var eaPosLast = s.IndexOf('"', eaPos);
return s.Substring(eaPos, eaPosLast-eaPos);
}
static void Main(string[] args)
{
WebClient webClient = new WebClient();
var firstResponse = webClient.DownloadString(#"http://www.mcxindia.com/sitepages/BhavCopyDateWise.aspx");
var forms = new NameValueCollection();
forms["__EVENTARGUMENT"] = "";
forms["__VIEWSTATE"] = Extract(firstResponse, "__VIEWSTATE");
forms["mTbdate"] = "12/22/2011";
forms["__EVENTVALIDATION"] = Extract(firstResponse, "__EVENTVALIDATION");
forms["mImgBtnGo.x"] = "10";
forms["mImgBtnGo.y"] = "10";
forms["ScriptManager1"] = "MupdPnl|mImgBtnGo";
// forms["__EVENTTARGET"] = "btnLink_Excel";
webClient.Headers.Set(HttpRequestHeader.ContentType, "application/x-www-form-urlencoded");
String secondResponse = UTF8Encoding.UTF8.GetString(
webClient.UploadValues(#"http://www.mcxindia.com/sitepages/BhavCopyDateWise.aspx", "POST", forms)
);
forms = new NameValueCollection();
forms["__EVENTARGUMENT"] = "";
forms["__VIEWSTATE"] = Extract(secondResponse, "__VIEWSTATE");
forms["mTbdate"] = "12/22/2011";
forms["__EVENTVALIDATION"] = Extract(secondResponse, "__EVENTVALIDATION");
// forms["mImgBtnGo"] = "?";
forms["__EVENTTARGET"] = "btnLink_Excel";
webClient.Headers.Set(HttpRequestHeader.ContentType, "application/x-www-form-urlencoded");
var responseData = webClient.UploadValues(#"http://www.mcxindia.com/sitepages/BhavCopyDateWise.aspx", "POST", forms);
System.IO.File.WriteAllBytes(#"c:\prj\11152011.csv", responseData);
}
}