how to fix Webexception unhandle - c#

i want to make console c# program to download and execute a program.exe file from web.
so i get a "Webexception unhandle" error when i run this program.can any one help me. thanks
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Diagnostics;
using System.IO;
namespace Downloader{
class Program
{
static void Main(string[] args)
{
Uri uri = new Uri("http://www.pendrivelinux.com/downloads/Universal-USB-Installer/Universal-USB-Installer-1.9.5.1.exe");
string filename = #"C:\bootable.exe";
using (var wc = new WebClient())
{
wc.Credentials = CredentialCache.DefaultCredentials;
wc.Headers.Add(HttpRequestHeader.UserAgent, "anything");
wc.DownloadFile(uri, filename);
}
}
}
}
can any one help me.

I'm guessing your WebException occurs on the last line (please in future include that in your question - we can't really help you based on guesswork).
wc.DownloadFile(uri, filename);
From the documentation on this method call, it will throw a WebException if one of the following is true:
The URI formed by combining BaseAddress and address is invalid.
filename is null or Empty.
The file does not exist.
An error occurred while downloading data.
We can rule out #2 immediately, as you've set that. To find out which of these situations you've got, try looking at the exception's message property (or the message property of the inner exception if there is one).

Related

Azure function cannot find blob during blob trigger

There is an Azure function that is triggered when HTML files are placed into Azure blob storage.The function opens the HTML file, and transforms it into JSON. There is a small percentage of triggered files (less than 1%), that result in the following exception:
Microsoft.WindowsAzure.Storage.StorageException
There does happen to be a second function triggered by the placement of the blob that changes the files content type, but I am not sure if this is effecting the first function's ability to also open the file.
What can be done to allow the Azure functions to correctly process the HTML files without throwing this type of exception?
Exception properties:
Message: Exception while executing function: [Function name here] The condition specified using HTTP conditional header(s) is not met.
Exception type: Microsoft.WindowsAzure.Storage.StorageException
Failed method: HtmlAgilityPack.HtmlDocument.Load
Exception type: Microsoft.WindowsAzure.Storage.StorageException
Function 1 (supporting methods, class, and namespace omitted for brevity):
using System;
using System.Collections.Generic;
using System.IO;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Host;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using HtmlAgilityPack;
using System.Threading.Tasks;
[FunctionName("Function name")]
public static async Task Run([BlobTrigger("container-name/html/{name}", Connection = "ConnectionString")]Stream myBlob, ILogger log, Binder binder)
{
var doc = new HtmlDocument();
doc.Load(myBlob);
var form = doc.DocumentNode.SelectSingleNode("//form");
var elements = form.SelectNodes("//input");
CustomType MyObject = BuildObject(elements);
var attributes = new Attribute[]
{
new BlobAttribute("container-name/json/" + MyObject.ID + ".json"),
new StorageAccountAttribute("ConnectionString")
};
using (var writer = await binder.BindAsync<TextWriter>(attributes))
{
writer.Write(BuildJSON(MyObject));
}
}
Function 2 same trigger but in a different function and it's own .cs file. Class and namespace omitted for brevity:
using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Host;
using Microsoft.Extensions.Logging;
using Microsoft.WindowsAzure.Storage.Blob;
[FunctionName("Function name")]
public static async Task Run([BlobTrigger("container-name/html/{name}", Connection = "ConnectionString")]ICloudBlob myBlob)
{
if (myBlob.Properties.ContentType == "text/html; charset=utf-8")
return;
myBlob.Properties.ContentType = "text/html; charset=utf-8";
await myBlob.SetPropertiesAsync();
}
I think your error should appear like this: Funtion1 retrieves the blob, and then function2's operation on the blob causes the change of Etag. Then function1 tries to load the retrieved blob, but finds that the Etag has changed, so it returns to you abnormal.
If the resource is accessed or changed by multiple apps, please have a try to make sure the orginal files are not changed. Otherwise the Etag of the blob will be changed automatically.
Azure Storage blob use 'strong Etag validation'. the content of the two resource representations must be byte-for-byte identical and that all other entity fields (such as Content-Language) are also unchanged.
Please refer to this:https://www.microsoftpressstore.com/articles/article.aspx?p=2224058&seqNum=12

Synaptics SDK can't find device

I'm attempting to grab a device handle on the Synaptics Touchpad using the Synaptics SDK, specifically using methods in the SYNCTRLLib.
However, the SYNCTRL method failed to find it, returning -1.
Syn.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SYNCOMLib;
using SYNCTRLLib;
namespace TP_Test1
{
class Syn
{
SynAPICtrl SynTP_API = new SynAPICtrl();
SynDeviceCtrl SynTP_Dev = new SynDeviceCtrl();
SynPacketCtrl SynTP_Pack = new SynPacketCtrl();
int DeviceHandle;
//Constructor
public Syn ()
{
SynTP_API.Initialize();
SynTP_API.Activate();
//DeviceHandle == -1 ? Can't find device?
DeviceHandle = SynTP_API.FindDevice(new SynConnectionType(), new SynDeviceType(), 0);
//Below line causing Unhandled Exception
SynTP_Dev.Select(DeviceHandle);
SynTP_Dev.Activate();
SynTP_Dev.OnPacket += SynTP_Dev_OnPacket;
}
public void SynTP_Dev_OnPacket()
{
Console.WriteLine(SynTP_Pack.FingerState);
Console.WriteLine(SynTP_Pack.X);
Console.WriteLine(SynTP_Pack.Y);
}
}
}
Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SYNCOMLib;
using SYNCTRLLib;
namespace TP_Test1
{
class Program
{
static void Main(string[] args)
{
Syn mySyn = new Syn();
mySyn.SynTP_Dev_OnPacket();
}
}
}
I see that you are using the C# wrappers for Synaptics SDK. Even though CPP code might be not trivial to you, you might want to take a look at the file Samples/ComTest.cpp. It contains some example logic in order to find devices, more specifically at lines 66-76:
// Find a device, preferentially a TouchPad or Styk.
ISynDevice *pDevice = 0;
long lHandle = -1;
if ((pAPI->FindDevice(SE_ConnectionAny, SE_DeviceTouchPad, &lHandle) &&
pAPI->FindDevice(SE_ConnectionAny, SE_DeviceStyk, &lHandle) &&
pAPI->FindDevice(SE_ConnectionAny, SE_DeviceAny, &lHandle)) ||
pAPI->CreateDevice(lHandle, &pDevice))
{
printf("Unable to find a Synaptics Device.\n");
exit(-1);
}
Also, make sure you have registered the dlls. According to the ReadSynSDK.txt file:
For certain purposes it may be necessary to register the dlls
that are provided with the SDK. This can be done with the windows regsvr32
utility.

Can't get Request.QueryString or similar methods to work

To my shame, because I can barely C#, I cannot manage to read the parameters from the URL.
I run a C# cgi executable on my IIS 7 as an application. The url that calls the executable is as below:
https://server/cgi/showEmail/showEmail.exe?email=john#gmail.com
The code starts as below:
using System;
using System.Web; // <---- isn't this for Request.QueryString ?
using System.Web.UI;
using System.Collections;
using System.Collections.Specialized;
using System.Data.SqlClient;
class showEmail
{
static void Main(string[] args)
{
Console.WriteLine("\r\n\r\n");
Console.WriteLine("<h1>Test</h1>");
try
{
Now, if I use the code below, the program compiles, but gives this a null exception when executed in the browser:
string email = HttpContext.Current.Request.QueryString["email"];
System.NullReferenceException: Object reference not set to an instance of an object. at showEmail.Main(String[] args)
and if I use this code below, the fun stops already at the compiler, who gives a "current context" exception:
string email = Request.QueryString["email"];
error CS0103: The name 'Request' does not exist in the current context
...
Am I missing something elementary that is required for the executable to see the url parameters?
Edit: I have looked through sof and many other places, but so far have not been able to connect the dots on this issue.
HttpContext.Current.Request is not available in console appliaction.
Use args parameter to receive query string parameter, like I am doing below.
for (int i = 0; i < args.Length; i++)
{
Console.WriteLine("parameter[{0}] is [{1}]", i, args[i]);
}
You might need to use below code to extract parameters from url received in args.
var url=args[0];
var queryString = url.Substring(url.IndexOf('?')).Split('#')[0]
System.Web.HttpUtility.ParseQueryString(queryString)
This is how I got it to work finally, please keep in mind this is not professionally validated code, more of try and try and try...
using System;
using System.Data;
using System.Configuration;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string email = Request.QueryString["email"] ?? "null";
if (email != "null") {

CSharp - IMAP Connection TCP error

I wanted to access over IMAP to my gmail account bsed on this example:
http://code.msdn.microsoft.com/windowsdesktop/Simple-IMAP-CLIENT-b249d2e6
When I start to debug the code, I get always an error at the codeline:
tcpc = new System.Net.Sockets.TcpClient("imap.gmail.com", 993);
It gives me the error:
"The requested service provider could not be loaded or initialized"
My search on Internet give me as result, that I need to repair the Window Socket.
But, when I run directkly the compiled .exe file, then I don't get this error at all.
This makes no sense to me.
Does anybody have an idea, whats wrong here?
The code looks like:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
namespace IMAP
{
class Program
{
static System.Net.Sockets.TcpClient tcpc = null;
static System.Net.Security.SslStream ssl = null;
static string username, password;
static void Main(string[] args)
{
username = "(username)";
password = "(password)";
SSLAuthenticate = "imap.gmail.com";
try
{
tcpc = new System.Net.Sockets.TcpClient("imap.gmail.com", 993);
ssl = new System.Net.Security.SslStream(tcpc.GetStream());
ssl.AuthenticateAsClient("imap.gmail.com");
...
I am thankful for any help.

C# The name 'client' does not exist in the current context // Identifier expected // Expected class, delegate, enum, interface, or struct

Im extremely noob in C#. Could you please help me?
I get the following errors:
The name 'client' does not exist in the current context
Identifier expected
Expected class, delegate, enum, interface, or struct
Could you please write me the code that could work properly. I really appreciate your help in advance.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using (WebClient client = new WebClient ());
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
client.DownloadFile("http://yoursite.com/page.html", #"C:\localfile.html");
}
}
}
You've got this:
using (WebClient client = new WebClient ());
in the list of using directives when you really meant it to be a using statement in the method:
static void Main(string[] args)
{
using (WebClient client = new WebClient())
{
client.DownloadFile("http://yoursite.com/page.html",
#"C:\localfile.html");
}
}
Basically the using keyword has two different meanings in C#:
using directives import namespaces and allow type aliases. For example:
using System; // Imports the System namespace
using Cons = System.Console; // Creates an alias for the System.Console type
using statements allow a resource to be easily wrapped in a try/finally block to dispose of the resource at the end of the statement:
using (SomeResource resource = new SomeResource(...))
{
// Use the resource here; it will be disposed of automatically at the
// end of the block.
}

Categories