Windows 10 - Peerfinder in console application - c#

I want to set up a WiFiDirect connect between 2 windows 10 in a console application not in a universal app.
I set the target platform version to 10
<TargetPlatformVersion>10.0</TargetPlatformVersion>
I add the Reference to Windows.Foundation, Windows.Networking.Proximity, Windows.Networking.Sockets, Windows.Storage.Streams
In my application i check if WiFiDirect is suppartet.
if ((Windows.Networking.Proximity.PeerFinder.SupportedDiscoveryTypes & Windows.Networking.Proximity.PeerDiscoveryTypes.Browse) != Windows.Networking.Proximity.PeerDiscoveryTypes.Browse)
{
Console.WriteLine("Peer discovery using Wifi-Direct is not supported.\n");
}
This works as it should.
But when i call PeerFinder.Start() i get a exception .
HRESULT 0x80004004(E_ABORT)
This is the code calling PeerFinder.Start()
try
{
PeerFinder.AllowWiFiDirect = true;
PeerFinder.Role = PeerRole.Peer;
PeerFinder.ConnectionRequested += PeerFinder_ConnectionRequested;
PeerFinder.TriggeredConnectionStateChanged += PeerFinder_TriggeredConnectionStateChanged;
using (var discoveryDataWriter = new Windows.Storage.Streams.DataWriter(new Windows.Storage.Streams.InMemoryRandomAccessStream()))
{
discoveryDataWriter.WriteString("test12");
PeerFinder.DiscoveryData = discoveryDataWriter.DetachBuffer();
}
PeerFinder.Start();
}
catch (Exception e)
{
Console.WriteLine("start failed: " + e.Message);
}
i guess i can't use PeerFinder in a console application, are there any alternatives to establish a WiFiDirect connection for desktop applications?

Related

How to fix exception Device xxx disconnected while writing characteristic with yyy in xamarin forms?

I am creating a BLE app where I am successfully connecting to a BLE device. I am able to read the GATT characteristics as well. But when I try to do write operation I get exception
Device xxx disconnected while writing characteristic with yyy
This is my code
private async Task<string> ProcessDeviceInformationService(IService deviceInfoService)
{
try
{
await adapter.ConnectToDeviceAsync(device);
var sb = new StringBuilder("Getting information from Device Information service: \n");
var characteristics = await deviceInfoService.GetCharacteristicsAsync();
var characteristic = await deviceInfoService.GetCharacteristicAsync(Guid.Parse("00002b0f-0000-1000-8000-00805f9b34fb"));
//{
try
{
deviceInfoService.GetCharacteristicAsync(GattCharacteristicIdentifiers.DataExchange);
if (characteristic != null)
{
var sbnew = new StringBuilder("BLE Characteristics\n");
byte[] senddata = Encoding.UTF8.GetBytes(string.IsNullOrEmpty(SendMessageLabel.Text) ? "0x21" : SendMessageLabel.Text);
await Task.Delay(300);
var newbytes = await characteristic.WriteAsync(senddata);
byte[] characteristicsvalue = characteristic.Value;
var str = Encoding.UTF8.GetString(characteristicsvalue);
sbnew.AppendLine($"Characteristics found on this device: {string.Join(", ", str.ToString())}");
CharactericsLabel.Text = sbnew.ToString();
}
}
catch (Exception ex)
{
return ex.Message;
}
return CharactericsLabel.Text;
}
catch (Exception ex)
{
return ex.ToString();
}
}
After some search I found that I need to pass hexadecimal value.Even I tried sending hexadecimal value as you can see in code but it's not working. For android its working fine but for iOS it is still showing this exception.I'm using device Iphone 8 plus and OS version of Iphone is 13.5.1.The write operation works in Light Blue app which I downloaded from App store for iOS. My write type is set to default which is write with response. But it is giving exception in my xamarin app only for the iOS part. I'm using latest stable version 2.1.1 of Plugin.BLE. I have no clue how to fix this any suggestions?
I fixed this exception by getting write without response for characteristic from the peripheral side.

Creating a web server in C# UWP

I am writing a web server as a Universal Windows Platform app in C#. Here is my code so far:
sealed partial class App : Application
{
int port = 8000;
/// <summary>
/// Initializes the singleton application object. This is the first line of authored code
/// executed, and as such is the logical equivalent of main() or WinMain().
/// </summary>
public App()
{
StartServer();
}
private void StartServer()
{
StreamSocketListener listener = new StreamSocketListener();
listener.BindServiceNameAsync(port.ToString());
Debug.WriteLine("Bound to port: " + port.ToString());
listener.ConnectionReceived += async (s, e) =>
{
Debug.WriteLine("Got connection");
using (IInputStream input = e.Socket.InputStream)
{
var buffer = new Windows.Storage.Streams.Buffer(2);
await input.ReadAsync(buffer, buffer.Capacity, InputStreamOptions.Partial);
}
using (IOutputStream output = e.Socket.OutputStream)
{
using (Stream response = output.AsStreamForWrite())
{
response.Write(Encoding.ASCII.GetBytes("Hello, World!"), 0, 1);
}
}
};
}
}
I tried connecting to the server using this address:
http://127.0.0.1:8000/C:/pathtohtmlfile/htmlfile.html
However, the connection times out. I am not sure if it is a problem with the C# code or with something else.
Raymond Zuo's solution really works. But the main thing not to forget are capabilities in Packages.appxmanifest. In order to run the server in Private networks one should add:
<Capability Name="privateNetworkClientServer" />
And in order to run the server in Public network:
<Capability Name="internetClientServer" />
If you want to host a server in uwp app, be sure these things:
your device which run this code (Device A) and device which your web browser run (Device B) must at a same LAN. And you cannot use the browser in Device A to access your service.
use WIFI to access your service.
your app must be at the state of running.
you should write a method to get ip address, but not 127.0.0.1:
public static string FindIPAddress()
{
List<string> ipAddresses = new List<string>();
var hostnames = NetworkInformation.GetHostNames();
foreach (var hn in hostnames)
{
//IanaInterfaceType == 71 => Wifi
//IanaInterfaceType == 6 => Ethernet (Emulator)
if (hn.IPInformation != null &&
(hn.IPInformation.NetworkAdapter.IanaInterfaceType == 71
|| hn.IPInformation.NetworkAdapter.IanaInterfaceType == 6))
{
string ipAddress = hn.DisplayName;
ipAddresses.Add(ipAddress);
}
}
if (ipAddresses.Count < 1)
{
return null;
}
else if (ipAddresses.Count == 1)
{
return ipAddresses[0];
}
else
{
return ipAddresses[ipAddresses.Count - 1];
}
}
It is possible to host a web service on phone/tablet.
It is possible to host a web service in a Window Universal App. I followed the example from http://www.dzhang.com/blog/2012/09/18/a-simple-in-process-http-server-for-windows-8-metro-apps , also followed the three first steps from Raymond Zuo's solution and finally I also put the firewall down. Unfortunately, I was not able to run on localhost even though I followed the answers from here Cannot connect to localhost in windows store application . I am currently doing java http requests to the Universal Platform App. Definitely, server and client seem to be required to run on different hosts.

can not create activex object using C#

I am deploying a C# application on client machine. The Application need to access code from another program, so it can scrap text from the screen of another application. It is running fine on the development machine but on the client machine it is throwing an error "ActiveX Component cannot create Object" this is where i am getting the error from!
private ExtraSession objExtraSession;
private ExtraSessions objExtraSessions;
private ExtraScreen objExtraScreen;
private ExtraArea objExtraArea;
private ExtraSystem objExtraSystem;
protected void sessionInitializer()
{
try
{
objExtraSystem = (ExtraSystem) Microsoft.VisualBasic.Interaction.CreateObject("Extra.system");
if (objExtraSystem == null)
{
MessageBox.Show("Could not create system");
return;
}
objExtraSessions = objExtraSystem.Sessions;
if (objExtraSessions == null)
{
MessageBox.Show("Could not create sessions");
return;
}
if (!System.IO.File.Exists("C:\\Users\\" + userid + "\\Documents\\Attachmate\\EXTRA!\\Sessions\\SAS.edp"))
{
MessageBox.Show("File does not exist");
return;
}
objExtraSession = (ExtraSession) Microsoft.VisualBasic.Interaction.GetObject("C:\\Users\\"+ userid + "\\Documents\\Attachmate\\EXTRA!\\Sessions\\SAS.edp");
if (objExtraSession == null)
{
MessageBox.Show("Could not create session");
return;
}
if (objExtraSession.Visible == 0)
{
objExtraSession.Visible = 1;
}
objExtraScreen = objExtraSession.Screen;
}
catch (Exception ex)
{
MessageBox.Show(ex.StackTrace, "Failed to initialize Attachmate sessions");
}
}
The error is generated from objExtraSession = (ExtraSession) Microsoft.VisualBasic.Interaction.GetObject("C:\Users\"+ userid + "\Documents\Attachmate\EXTRA!\Sessions\SAS.edp");
Am I missing some step. Please help me out. Thanks in advance.
The most likely explanation is that your development machine has the ActiveX control installed, but the client machine does not. Read the deployment documentation for the control and do what is says is required to deploy to the client machine.
Thanks for all your responses... The method GetObject was creating an object whose activex component was not registered... I resolved by finding the corresponding *.ocx file and calling Regsvr32 on the file this resolved the problem...

No sound TAPI in Windows 7

I try to write a auto answer machin with TAPI in C#.NET.
I using tapi3_dev sample to work.this sample work in windows XP but in windows 7, everything is normal(no error or exception) but no sound playback just i can record the audio;
please help me.
my code::
case TAPI3Lib.ADDRESS_EVENT.AE_RINGING: this.PlayVoice(CallInfo);
...
private void PlayVoice(TAPI3Lib.ITCallInfo iTCallInfo)
{
try
{
//the supported file extensions are .avi and .wav. http://msdn.microsoft.com/en-us/library/ms730457.aspx
TAPI3Lib.ITBasicCallControl2 iTBasicCallControl2 = (TAPI3Lib.ITBasicCallControl2)iTCallInfo;
this.selectedTerminal = iTBasicCallControl2.RequestTerminal(TAPI3Lib.TapiConstants.CLSID_String_FilePlaybackTerminal, TAPI3Lib.TapiConstants.TAPIMEDIATYPE_AUDIO, TAPI3Lib.TERMINAL_DIRECTION.TD_CAPTURE);
TAPI3Lib.ITMediaPlayback iTMediaPlayback = (TAPI3Lib.ITMediaPlayback)this.selectedTerminal;
object[] playList = new object[1];
playList[0] = #"C:\ModemLog\7533f717-6cc5-41d5-9845-6983cff85e4b.avi";
//playList[0] = #"C:\Users\Abedi\Desktop\Anghezi.wav";
//playList[0] = #"C:\ProgramData\Venta\VentaFax & Voice 6\Service\greet1.wav";
iTMediaPlayback.PlayList = playList;
iTBasicCallControl2.SelectTerminalOnCall(this.selectedTerminal);
this.iTMediaControl = (TAPI3Lib.ITMediaControl)this.selectedTerminal;
if (iTCallInfo.CallState == TAPI3Lib.CALL_STATE.CS_OFFERING)
iTBasicCallControl2.Answer();
this.iTMediaControl.Start();
(selectedTerminal as TAPI3Lib.ITBasicAudioTerminal).Volume = 0;
}
catch (Exception exception)
{
this.Log(exception.Message, "Exception in PlayVoice");
this.WriteLine(exception.Message);
this.buttonDisconnect_Click(null, EventArgs.Empty);
}
}
Is your code running in a windows service? There is a known issue with audio control from a windows service under windows 7. Currently, I cannot find a work-around other than launcing a windows application to intergate with tapi.

Remote Desktop Connection with MSTSCLib

I'm trying to code a Remote Desktop Application using C# .NET.
I followed some examples (listed below) and created a Windows Form, added references to MSTSLib, added Microsoft Terminal Service Control to the Form and code the following behavior:
namespace RDConnector
{
public partial class Form1 : Form
{
const string server = "55.55.55.555";
const string userNameBase = "username";
const string passwordBase = "password";
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
rdClient.Server = server;
rdClient.UserName = userNameBase;
/*IMsTscNonScriptable secured = (IMsTscNonScriptable)rdClient.GetOcx();
secured.ClearTextPassword = passwordBase;*/
rdClient.AdvancedSettings8.DisplayConnectionBar = true;
rdClient.AdvancedSettings8.ClearTextPassword = passwordBase;
rdClient.AdvancedSettings8.EncryptionEnabled = -1;
//// Start connection
rdClient.Connect();
MessageBox.Show("Connection Status + " + rdClient.Connected.ToString());
}
catch (Exception Ex)
{
MessageBox.Show("Exception ocurred: " + Ex.Message);
}
}
}
}
However, it isn't working, the Connection status after calling rdClient.Connect() is 2 (0 before calling it), but nothing happens. I also ran the Example 1 and it doesn't work.
I'm using Windows 7 - 64 bit and Visual Studio C# Express. Visual Express Edition doesn't have a X64 compiler, Could be the problem related with that?
I'll really appreciate your help.
Examples:
http://www.codeproject.com/KB/cs/RemoteDesktop_CSharpNET.aspx
Running COM component controls on multiple threads
I found the problem at last. When you want to choose COM Components, just select "Microsoft RDP Client Control - version x". I choose the 8 version that works perfectly for me.

Categories

Resources