My code (intended for searching for steam market items using an API call) is supposed to read the response from an API call into my program and this works great, however, when the API call fails I want to display a separate error message letting the user know that something has gone wrong but currently it will simply crash the code.
An example of a successful API call is:
https://steamcommunity.com/market/priceoverview/?currency=2&appid=730&market_hash_name=Glock-18%20%7C%20Steel%20Disruption%20%28Minimal%20Wear%29
This results in the following;
{"success":true,"lowest_price":"\u00a31.39","volume":"22","median_price":"\u00a31.40"}
So far this works perfectly fine, the problem arises when an incorrect link is used, like this:
https://steamcommunity.com/market/priceoverview/?currency=2&appid=730&market_hash_name=this-skin-does-not-exist
This results in an error like so;
{"success":false}
I want to know when this happens so I can display a message to the user however in my code's current state it simply crashes when this is returned. Here's my current code:
webpage = "https://steamcommunity.com/market/priceoverview/?currency=2&appid=730&market_hash_name=" + Model.category + Model.weapon + " | " + Model.skin + " (" + Model.wear + ")";
System.Net.WebClient wc = new System.Net.WebClient();
byte[] raw = wc.DownloadData(webpage);
string webData = System.Text.Encoding.UTF8.GetString(raw);
if (webData.Substring(11, 1) == "t")
{
int lowestPos = webData.IndexOf("\"lowest_price\":\"");
int volumePos = webData.IndexOf("\",\"volume\":\"");
int medianPos = webData.IndexOf("\",\"median_price\":\"");
int endPos = webData.IndexOf("\"}");
Model.lowestPrice = webData.Substring(lowestPos + 16, volumePos - lowestPos - 16);
if (Model.lowestPrice.IndexOf("\\u00a3") != -1)
{
Model.lowestPrice = "£" + Model.lowestPrice.Substring(6);
}
Model.medianPrice = webData.Substring(medianPos + 18, endPos - medianPos - 18);
if (Model.medianPrice.IndexOf("\\u00a3") != -1)
{
Model.medianPrice = "£" + Model.medianPrice.Substring(6);
}
Model.volume = webData.Substring(volumePos + 12, medianPos - volumePos - 12);
}
else
{
Console.WriteLine("An error has occurred, please enter a correct skin");
}
The error occurs at byte[] raw = wc.DownloadData(webpage);
Any help would be appreciated :)
Webclient is deprecated and you should consider using HttpClient if possible. Webclient throws an exception. So you should wrap your code inside a try/catch block to catch the exception and react accordingly:
try
{
System.Net.WebClient wc = new System.Net.WebClient();
byte[] raw = wc.DownloadData(webpage);
string webData = System.Text.Encoding.UTF8.GetString(raw);
}
catch(System.Net.WebException e)
{
//handle the error here
}
Related
For a couple of days, I have puzzled about how to do this in the best way possible. I created a form application like so:
I gave the name "WiFi Hacker" for giggles. But my question is, why does Visual Studio give me this error after a couple minutes using the program?
Additional information: Type 'NativeWifi.Wlan+WlanReasonCode' cannot be marshaled as an unmanaged structure; no meaningful size or offset can be computed.
I am using NativeWifi for my program, and the code for logging networks is as follows:
WlanClient client = new WlanClient();
private void wifilister()
{
foreach (WlanClient.WlanInterface wI in client.Interfaces)
{
foreach (Wlan.WlanAvailableNetwork network in wI.GetAvailableNetworkList(0))
{
Wlan.Dot11Ssid ssid = network.dot11Ssid;
string networkName = Encoding.ASCII.GetString(ssid.SSID, 0, (int)ssid.SSIDLength);
if (wifis.Contains(networkName) == false)
{
//Name
ListViewItem item = new ListViewItem(networkName);
wifis.Add(networkName);
listBox1.Items.Add(networkName);
//Encryption Type
item.SubItems.Add(network.dot11DefaultCipherAlgorithm.ToString());
wifis.Add(network.dot11DefaultCipherAlgorithm.ToString());
//Signal
item.SubItems.Add(network.wlanSignalQuality + "%");
wifis.Add(network.wlanSignalQuality + "%");
//Logged Time
item.SubItems.Add(DateTime.Now.ToString("T"));
wifis.Add(DateTime.Now.ToString("T"));
listView1.Items.Add(item);
label2.Text = "Networks: " + (wifis.Count / 4).ToString();
}
if (checkBox2.Checked)
{
label1.Text = track;
if (Encoding.ASCII.GetString(ssid.SSID, 0, (int)ssid.SSIDLength) == track)
{
label1.Text += " " + network.wlanSignalQuality + "%";
}
}
}
}
I got most of this off a tutorial from YouTube, but after it logs more than about 40 different networks in the List, it seems to give that weird error about
'NativeWifi.Wlan+WlanReasonCode'.
This annoyed me, is there a way around it?
I have a page there is a button that generates a Link like this.
private string GenerateLINK(string NameID)
{
string NameID= ds.Tables[0].Rows[0]["FName"] + " " + ds.Tables[0].Rows[0]["LName"];
string sQS = ID+ "|" + ClientName;
var xCrypto = new CryptoServer();
string Vector= null;
string sEncrypted = null;
xCrypto.Encrypt3DES(sQS, ref sEncrypted, ref Vector);
string sURL = sEncrypted + "#######" + Vector;
sURL = Server.UrlEncode(sURL);
sURL = "https://www.Page.aspx?s=" + sURL;
return sURL;
}
This then gets sent to a user who clicks on it and goes to a page.
Now the issue is I take the link like this and DCode it.
private void DecryptQuerystring()
{
var sQS = Request.QueryString["s"];
sQS = Server.UrlDecode(sQS);
var idelim = sQS.IndexOf("###X####", StringComparison.Ordinal);
var sIv = sQS.Substring(idelim + 8);
sQS = sQS.Substring(0, idelim);
var xCrypto = new ICECrypto.CryptoServer();
sQS = xCrypto.Decrypt3DES(sQS, sIv);
string sID = sQS.Substring(0, sQS.IndexOf("|"));
studentID = sID;
Name = sQS.Substring(sQS.IndexOf("|") + 1);
Welcome.InnerText = "Welcome " + sQS.Substring(sQS.IndexOf("|") + 1);
}
The Problem is when the User gets there and if he puts in any word in the link it breaks the whole page showing the Server Error. I want user to NOT to be able to Edit the Link insert any thing in it. Any clue? Thanks in advance!
This is funny but I am answering my own question maybe someone else could use it.
So where I am doing the Decryption of the QueryString() i put in the word
Try {
// Do the Decryption here
}
Catch(Exception ex) {
// if any thing goes wrong in that Try it will hit here and then i will show error 404
}
I'm having a problem with this query below. I'm connecting to OrientDB using the C# driver and running the query in my c# code. All this code is in a loop and the queries in the try block works for a number of iterations and afterwards fails throwing a FormatException. At the point it fails I copy out the query and run it in the orientDB web interface and it returns the expect records so I'm sure it's not the input. So I'm so confused as to why it succeeds sometimes and fails at other times even when the input string is correct. Has anyone encountered a similar problem? Someone please help.
string origin = route[i].Trim();
string destination = route[i + 1].Trim();
List<ODocument> document = new List<ODocument>();
try
{
document = database.Query("select from (traverse out_Connects from " + origin + ") where in = " + destination);
//document = database.Query("select from Connects where (out = " + origin + " and in = " + destination + ")");
}
catch (Exception e)
{
//document = database.Query("select from Connects where (out = " + origin + " and in = " + destination + ")");
}
I am scraping the content of web pages heavily in a multi-thread environment. I need a reliable downloader component that is tolerable to temporary server failures, connection drops, etc. Below is what my code looks like.
Now, I am having a weird situation over and over: It all starts perfectly. 10 threads pull data concurrently for about 10 minutes. After that time I start getting WebException with timeouts right after I call the GetResponse method of my request object. Taking a break (getting a thread to sleep) doesn't help. It only helps when I stop the application and start it over until the next 10 minutes pass and the problem comes back again.
What I tried already and nothing has helped:
to close/dispose the response object explicitly and via the "using" statement
to call request.Abort everywhere it could have helped
to manipulate timeouts at ServicePointManager/ServicePoint and WebRequest level (extend / shorten the timeout interval)
to manipulate the KeepAlive property
to call to CloseConnectionGroup
to manipulate the number the threads that run simultaneously
Nothing helps! So it seems like it's a bug or at least very poorly documented behavior. I've seen a lot of question regarding this in Google and on Stackoverflow, but non of them is fully answered. Basically people suggest one of the things from the list above. I tried all of them.
public TResource DownloadResource(Uri uri)
{
for (var resourceReadingAttempt = 0; resourceReadingAttempt <= MaxTries; resourceReadingAttempt++)
{
var request = (HttpWebRequest)WebRequest.Create(uri);
HttpWebResponse response = null;
for (var downloadAttempt = 0; downloadAttempt <= MaxTries; downloadAttempt++)
{
if (downloadAttempt > 0)
{
var sleepFor = TimeSpan.FromSeconds(4 << downloadAttempt) + TimeSpan.FromMilliseconds(new Random(DateTime.Now.Millisecond).Next(1000));
Trace.WriteLine("Retry #" + downloadAttempt + " in " + sleepFor + ".");
Thread.Sleep(sleepFor);
}
Trace.WriteLine("Trying to get a resource by URL: " + uri);
var watch = Stopwatch.StartNew();
try
{
response = (HttpWebResponse)request.GetResponse();
break;
}
catch (WebException exception)
{
request.Abort();
Trace.WriteLine("Failed to get a resource by the URL: " + uri + " after " + watch.Elapsed + ". " + exception.Message);
if (exception.Status == WebExceptionStatus.Timeout)
{
//Trace.WriteLine("Closing " + request.ServicePoint.CurrentConnections + " current connections.");
//request.ServicePoint.CloseConnectionGroup(request.ConnectionGroupName);
//request.Abort();
continue;
}
else
{
using (var failure = exception.Response as HttpWebResponse)
{
Int32 code;
try { code = failure != null ? (Int32)failure.StatusCode : 500; }
catch { code = 500; }
if (code >= 500 && code < 600)
{
if (failure != null) failure.Close();
continue;
}
else
{
Trace.TraceError(exception.ToString());
throw;
}
}
}
}
}
if (response == null) throw new ApplicationException("Unable to get a resource from URL \"" + uri + "\".");
try
{
// response disposal is required to eliminate problems with timeouts
// more about the problem: http://stackoverflow.com/questions/5827030/httpwebrequest-times-out-on-second-call
// http://social.msdn.microsoft.com/Forums/en/netfxnetcom/thread/a2014f3d-122b-4cd6-a886-d619d7e3140e
TResource resource;
using (var stream = response.GetResponseStream())
{
try
{
resource = this.reader.ReadFromStream(stream);
}
catch (IOException exception)
{
Trace.TraceError("Unable to read the resource stream: " + exception.ToString());
continue;
}
}
return resource;
}
finally
{
// recycle as much as you can
if (response != null)
{
response.Close();
(response as IDisposable).Dispose();
response = null;
}
if (request != null)
{
//Trace.WriteLine("closing connection group: " + request.ConnectionGroupName);
//request.ServicePoint.CloseConnectionGroup(request.ConnectionGroupName);
request.Abort();
request = null;
}
}
}
throw new ApplicationException("Resource was not able to be acquired after several attempts.");
}
i have same problem i have search a lot on internet , i got 1 solution, fix the number of thread at a time .you have to control the number of thread at a time, i have started to use 2-3 thread at a time.
also use this ServicePointManager.DefaultConnectionLimit = 200;
this will really help you.
I trying to capture packets using SharpPcap library.
I'm able to return the packets details but I'm having problem to get what the message content inside the packet.
the packet using .Data to return the message and when I use it it is returning (System.Byte[]).
here is the library website:
http://www.codeproject.com/KB/IP/sharppcap.aspx
here is my code:
string packetData;
private void packetCapturingThreadMethod()
{
Packet packet = null;
int countOfPacketCaptures = 0;
while ((packet = device.GetNextPacket()) != null)
{
packet = device.GetNextPacket();
if (packet is TCPPacket)
{
TCPPacket tcp = (TCPPacket)packet;
myPacket tempPacket = new myPacket();
tempPacket.packetType = "TCP";
tempPacket.sourceAddress = Convert.ToString(tcp.SourceAddress);
tempPacket.destinationAddress = Convert.ToString(tcp.DestinationAddress);
tempPacket.sourcePort = Convert.ToString(tcp.SourcePort);
tempPacket.destinationPort = Convert.ToString(tcp.DestinationPort);
tempPacket.packetMessage = Convert.ToString(tcp.Data);
packetsList.Add(tempPacket);
packetData =
"Type= TCP" +
" Source Address = "+ Convert.ToString(tcp.SourceAddress)+
" Destination Address =" +Convert.ToString(tcp.DestinationAddress)+
" SourcePort =" + Convert.ToString(tcp.SourcePort)+
" SourcePort =" +Convert.ToString(tcp.DestinationPort)+
" Messeage =" + Convert.ToString(tcp.Data);
txtpackets.Invoke(new UpdatetxtpacketsCallback(this.Updatetxtpackets),
new object[] { packetData });
string[] row = { packetsList[countOfPacketCaptures].packetType, packetsList[countOfPacketCaptures].sourceAddress, packetsList[countOfPacketCaptures].destinationAddress, packetsList[countOfPacketCaptures].sourcePort, packetsList[countOfPacketCaptures].destinationPort, packetsList[countOfPacketCaptures].packetMessage };
try { //dgwPacketInfo.Rows.Add(row); countOfPacketCaptures++;
//lblCapturesLabels.Text = Convert.ToString(countOfPacketCaptures);
}
catch (Exception e) { }
}
else if (packet is UDPPacket)
{
UDPPacket udp = (UDPPacket)packet;
myPacket tempPacket = new myPacket();
tempPacket.packetType = "UDP";
tempPacket.sourceAddress = Convert.ToString(udp.SourceAddress);
tempPacket.destinationAddress = Convert.ToString(udp.DestinationAddress);
tempPacket.sourcePort = Convert.ToString(udp.SourcePort);
tempPacket.destinationPort = Convert.ToString(udp.DestinationPort);
tempPacket.packetMessage = udp.Data.ToArray() + "\n";
packetsList.Add(tempPacket);
packetData =
"Type= UDP" +
" Source Address = "+ Convert.ToString(udp.SourceAddress)+
" Destination Address =" +Convert.ToString(udp.DestinationAddress)+
" SourcePort =" + Convert.ToString(udp.SourcePort)+
" SourcePort =" +Convert.ToString(udp.DestinationPort)+
" Messeage =" + udp.Data.ToArray() + "\n";
string[] row = { packetsList[countOfPacketCaptures].packetType, packetsList[countOfPacketCaptures].sourceAddress, packetsList[countOfPacketCaptures].destinationAddress, packetsList[countOfPacketCaptures].sourcePort, packetsList[countOfPacketCaptures].destinationPort, packetsList[countOfPacketCaptures].packetMessage };
try {
//dgwPacketInfo.Rows.Add(row);
//countOfPacketCaptures++;
//lblCapturesLabels.Text = Convert.ToString(countOfPacketCaptures);
txtpackets.Invoke(new UpdatetxtpacketsCallback(this.Updatetxtpackets),
new object[] { packetData });
}
catch (Exception e) { }
}
}
}
I found the answer...
Data is a byte array so I need to use bit converter and instead of using:
Convert.ToString(tcp.Data);
I should use:
BitConverter.ToString(tcp.Data)
The parser isn't that complex...
I looked at the Packet.Net code (which is the parse for SharpPcap) and all of the fields are stored in commonly used formats.
The IP Addresses are stored in System.Net.IPAddress format so you can just call .ToString on them to get a text string that properly includes the dot marks.
The port numbers are stored as ushort which can be printed the same as any other integer.
The only part that needs to be interpreted in its binary form is the Data field because that changes based on what protocol is being used on the next layer up. SharpPcap/Packet.Net does most of the work for you already and fields are stored in the most convenient or identical forms to those found in the protocol specification. Just use intellisense to check the field's type and if it's not one you're familiar with (such as System.Net.IPAddress or System.NetworkInformation.PhysicalAddress (For MAC addresses)) just google it.