HTTPWebRequest.GetResponse() throws connection failure exception - c#

I'm trying to create a simple application that does a HTTP
request/response on a button click. Here's the entire code which I got
from a reference book:
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Net;
namespace emulator2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public void button1_Click(object sender, EventArgs e)
{
Uri l_Uri = new Uri("http://www.testing.com");
HttpWebRequest l_WebReq = (HttpWebRequest)WebRequest.Create(l_Uri);
HttpWebResponse l_WebResponse =
(HttpWebResponse)l_WebReq.GetResponse();
Stream l_responseStream = l_WebResponse.GetResponseStream();
StreamReader l_SReader = new StreamReader(l_responseStream);
string resultstring = l_SReader.ReadToEnd();
Console.WriteLine(resultstring);
}
}
}
The thing that puzzles me is that when I shift the entire chunk of code
to a Windows Application, it works fine. But when I use it on a Device
Application, it just throws me an error. Here are the details of the
error:
System.Net.WebException was unhandled Message="Could not establish
connection to network." StackTrace: at
System.Net.HttpWebRequest.finishGetResponse() at
System.Net.HttpWebRequest.GetResponse() at
emulator2.Form1.button1_Click() at
System.Windows.Forms.Control.OnClick() at
System.Windows.Forms.Button.OnClick() at
System.Windows.Forms.ButtonBase.WnProc() at
System.Windows.Forms.Control._InternalWnProc() at
Microsoft.AGL.Forms.EVL.EnterMainLoop() at
System.Windows.Forms.Application.Run() at emulator2.Program.Main()
The error points at this line:
HttpWebResponse l_WebResponse = (HttpWebResponse)l_WebReq.GetResponse();
Does anyone have any idea on how to solve this? I need to get this
solved real quick..so any help given is greatly appreciated! Thanks!

My guess is that the emulator doesn't have proper network connectivity. It can be a pain (and hit-and-miss in my experience) getting networking up and running on the old Windows Mobile emulators. (It's easy in Windows Phone 7.)
Load up Internet Explorer and see if that can make a connection to the same URL...
Additionally, you're not disposing of any of your resources (and if this code is really in a reference book exactly as you wrote it, that's a significant black mark against the book). For example, you should be disposing of the web response:
using (HttpWebResponse response = ...)
{
}
Likewise I would personally dispose of the response stream and the stream reader, just on general principle. I suspect that when the response is disposed, the stream will be too - but it makes sense to dispose of all streams etc unless you know you need to leave them undisposed.

If you're running in the emulator you'll ned to "cradle" the emulator and then create a partnership with ActiveSync (Win XP) or Windows Mobile Device Center (Vista or 7).
This will allow the emulator to share the network connection with the PC. You also need to do this even if you want to connect from the emulator to the PC.
As Jon mentions, in WP7 you don't need to make a connection in this way, the WP7 emulator automatically shares the network connection of the host PC.
Use IE Mobile (on the emulator) to check that the device can connect to the site.
Edit
To cradle the emulator, in VS2008 select "Device Emulator Manager" from the Tools menu. Select the emulator that's running, right click and select "Cradle".
Mobile Device Center should start automatically and ask if you want to create a partnership, just as if you'd connected a real device.

Related

System.Windows.Forms - RemoteWebDriver -> Access is denied

We have a problem with my team for several weeks.
We currently have a test in MSTest v1 and Selenium 3.11 that is dedicated to upload a photo when filling out a profile.
In local works perfectly (hehehe), but in remote (RemoteWebdriver) the server of Build & Releases (VSTS) throws an error just in the step where I interact with this window, of the Access Denied type.
It is not really Selenium who acts there, but the System.Windows.Forms library and the SendWait method of the SendKeys class that gives the error when it is launched remotely.
Screenshot of the element in question >>> UploadFile
Example code:
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Windows.Forms;
using OpenQA.Selenium;
using System.IO;
//...
public class EditarFotoUsuarioAdministrador
{
public static void Execute(IWebDriver driver, string foto)
{
driver.FindElement(By.XPath("//button[#id='upload']")).Click();
System.Threading.Thread.Sleep(2000);
SendKeys.SendWait(Directory.GetCurrentDirectory() + foto);
SendKeys.SendWait(#"{Enter}");
System.Threading.Thread.Sleep(2000);
driver.FindElement(By.XPath("//button[#id='save']")).Click();
System.Threading.Thread.Sleep(500);
}
}
As I said, this in local works perfectly, but when it runs on the remote server, the whole test goes well until it reaches the SendKeys line:
AccessIsDenied
Hopefully someone has an answer, thank you very much !!
The agent need to be running as interactive mode.
I've fixed it using AutoIT3.
Loading the nuget and using its methods to send the path of the file, you can perfectly interact with any pop-up browser window.
And best of all, the remote server does it too.
Thank you very much to all !
AutoIT3 or AutoItX.Dotnet ?
can you please send the code snippet. i used below code
` AutoItX.WinActivate("Open");
AutoItX.ControlGetFocus("Open");
AutoItX.Send(file);
System.Threading.Thread.Sleep(2000);
AutoItX.ControlClick("Open", " ", "Button1");`
It works fine in local but not in remote

Trying to connect to an USB Zebra printer from a Windows Mobile emulator via the Zebra SDK in C#

I have a Zebra GK420t printer plugged in via USB to a PC.
The PC is running MS Visual Studio.
I have created a new Project -> Other Languages -> Visual C# -> Smart Device -> Windows Mobile 6 Professional project.
I have created a class:
using System;
using System.Collections.Generic;
using System.Text;
using ZSDK_API.Comm;
using ZSDK_API.ApiException;
namespace Zebra2
{
class CTest
{
static void Main(string[] args)
{
try
{
// Instantiate connection for ZPL USB port with a given port name.
ZebraPrinterConnection thePrinterConn = new UsbPrinterConnection("USB001:");
// "LPT" is the default prefix for most Windows CE/Mobile USB ports
// Open the connection - physical connection is established here.
thePrinterConn.Open();
// This example prints "This is a ZPL test." near the top of the label.
String zplData = "^XA^FO20,20^A0N,25,25^FDThis is a ZPL test.^FS^XZ";
// Send the data to printer as a byte array.
thePrinterConn.Write(Encoding.Default.GetBytes(zplData));
// Close the connection to release resources.
thePrinterConn.Close();
}
catch (ZebraPrinterConnectionException e)
{
// Handle communications error here.
Console.Write(e.StackTrace);
}
}
}
}
In Visual, I added a Reference for the ZSDK_API.dll successfully.
When I try to add a reference for the ZebraUsb.dll, I get the error message:
A reference to 'ZebraUsb.dll' couldn't be added.
If I build the code without the reference for this dll, the build is successful.
But at runtime, an exception is raised on the line where the Open() method is invoked.
The error message is:
An unhandled exception of type ZSDK_API.ApiException.ZebraGeneralException' occurred in ZSDK_API.dll.
Additional information: Can't find PInvoke DLL 'ZebraUsb.dll'.
Second problem:
I'm not sure what argument I should give to the UsbPrinterConnection constructor.
On the PC, the port for the printer is USB001.
I'm not sure how it's being seen from the emulator.
The printer can also be seen as a share via \\PC\printer.
Can you help me?
Best regards.
For all USB printers on Windows PC you normally have to add the printers USB driver first. This driver can be a USB Serial one or something special. Such drivers do not exist for Windows Mobile.
The Zebra GK420t is a desktop barcode label printer and not designed to be used from Windows Mobile.
You may install the printer on your Windows PC and share it over the network, either using Windows Printer Sharing or TCP/IP printer services (LPR). Then you might write an application that sends print commands over the network to this shared connection.
Zebra also offers a range of portable printers and a Windows Mobile SDK. These may match your needs more than the GK420t.

How to restart Cordova WP8 app?

I have a WP8 Cordova app that has one page locally and then it redirects to a server for further functionality. Both pages have the cordova JS API's available and things work well.
Except that when I want to go to the local start page again. Any anchors to it (pointing to x-wmapp0:www/index.html) do not work on the HTML side.
In addition, any tricks with plugins and invocations of CordovaBrowser.Navigate() result in UnauthorizedAccessException errors.
The fallback has been for me to try to go back in browser history like this:
window.history.go(-window.history.length + 1);
But this doesn't do anything if I spend any time in the remote pages at all. So this isn't applicable either!
Is there a decent way to get to the starting page? With help from C# or otherwise?
So the UnauthorizedAccessException stuff came from thread issues. (The VS Express for WP can sometimes hide the details of an exception pretty well.)
This is a complete plugin that performs the redirection with neatest elegance available.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using WPCordovaClassLib.Cordova;
using WPCordovaClassLib.Cordova.Commands;
namespace Cordova.Extension.Commands
{
public class Jumper : BaseCommand
{
/** Instruct the browser component to go to beginning. */
public void goHome(string unused)
{
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
var webview = WebViewHandler.getInstance().webView;
webview.CordovaBrowser.Navigate(webview.StartPageUri);
});
}
}
}
The WebViewHandler is a singleton for sharing the Cordova WebView to plugins, described in another SO answer (thanks #MikeBryant!).

32Feet.Net connecting to Bluetooth speakers

So I am trying to connect a bluetooth speakers from a script. I am using 32feet.net and I have successfully found the device but it doesn't work when I try to pair and connect to it.
This is the code im using to pair to device, this always fails not sure why:
private static void connected(BluetoothDeviceInfo[] dev)
{
// dev[foundIndex];
bool paired=false;
paired = BluetoothSecurity.PairRequest(dev[foundIndex].DeviceAddress, "1166");
if (paired)
Console.WriteLine("Passed, Device is connected.");
else
Console.WriteLine("Failed....");
}
Here is the code called after connected to actually connect to the device: bc is my bluetooth client var.
bc.BeginConnect(devInfo[foundIndex].DeviceAddress, BluetoothService.SerialPort, new AsyncCallback(Connect), devInfo[foundIndex]);
private static void Connect(IAsyncResult result)
{
if (result.IsCompleted)
{
Console.Write("Connected... ");
}
}
Any help would be appreciated. I am new to 32feet.net so i dont know much about this, i tried following code online to get where im at.
Try BluetoothDeviceInfo.SetServiceState. That will ask Windows to connect to the audio service on the device -- hopefully that'll do the job.
See https://32feet.codeplex.com/wikipage?title=Connecting%20to%20Bluetooth%20Services
Sometimes we don’t want our application to itself send data to/from a remote service but we want instead the local operating system to do so. This is the case for keyboard/mouse/etc with HID, networking with DUN/NAP/PAN/etc, Headset/Handsfree etc.
and then
The short answer in this case is to use BluetoothDeviceInfo.SetServiceState. This is the API equivalent to manually checking the respective checkbox on the “Services” tab of the Device dialog in Bluetooth Control panel.
Also, in these days of Secure Simple Pairing, using PairRequest is fine only if all peer devices will use old style PIN code authentication, otherwise instantiate a BluetoothWin32Authentication and then do the connect (here indirectly via SetServiceState) and handle the authentication in the authentication callback.

Mount Network Drive with WMI

Trying to write a WMI class function to mount a network drive on any computer (remote or local) using the credentials of the logged in computer.
This is a class for a larger project that I wrote for help desk staff to do first line fixes on remote PC's. The tech types in the the machine name or ip address and the app connects to it and allows to tech to click a couple of buttons and fix some basic items without having to remote(VNC) into the PC.
I've read all over the internet that it is much easier ways than WMI, but due to the remote nature of the app I would rather not use local API calls, nor do I want to worry about uploading script and executing it though a process start. Also other functions are already in WMI so I'd like to keep the code base the same.
The basic idea is to mount H: to //fileserver.example.com/$username
NetFixer is already in production use so I'm trying to keep my code nice and neat
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Management;
namespace WMIcontrols
{
public class Remote
{
public string target;
//Some code skipped here for simplicity sake...
public bool MountNetDrive(string DriveLetter, string MountLocation)
{
try
{
//Mount the network drive
return true;
}
catch
{
//Mount Failed
return false;
}
}
}
}
This is not using WMI but will accomplish what you want and is very simple
System.Diagnostics.Process.Start("cmd", "/c net use x: \\fileserver.example.com /user:Username Password");

Categories

Resources