Kindly see the UWP code snippet below tried on Windows 10 desktop using Visual Studio 2017 community edition.
The code implements Custom IVpnPlugin module. When system's VPN configuration is selected to this app and connect is done, the application's task gets triggered and VPN plugin's "Connect()" method gets invoked.
However, following code steps face exception while executing StartWithMainTransport(…).
("The operation was cancelled by user") on Visual Studio.
On the system's VPN settings following error is seen - "remote access service ip configuration is unusable"
I think I am passing correctly v4 and v6 address to the channel->StartWithMainTransport(…) API which are bound to my m/c network I/f. What other validations may have caused this issue. I do not want to configure certificates etc for the VpnChannel as I plan to implement encapsulate and decapsulate myself in VpnPlugin.
// Sample Plugin's connect implementation
void TunnelPlugin::Connect(Windows::Networking::Vpn::VpnChannel^ channel)
{
this->dSock = ref new DatagramSocket();
channel->AssociateTransport(this->dSock, nullptr); // No difference even if this statement is moved after ConnectAsync().
Platform::String^ svcName = "22111";
auto result = create_task(dSock->BindServiceNameAsync(svcName));
result.get();
// Connect to the destination tunnel address on UDP socket.
HostName^ remoteTunnelIP = ref new HostName("192.168.1.137");
Platform::String^ remoteTunnelPort = "22112";
result = create_task(this->dSock->ConnectAsync(remoteTunnelIP, remoteTunnelPort));
result.get();
VpnChannelConfiguration^ chanCfg = channel->Configuration;
// IP destinations to be routed via VPN
VpnRouteAssignment^ routeScope = ref new VpnRouteAssignment();
routeScope->Ipv4InclusionRoutes->Append(ref new VpnRoute(ref new HostName("192.168.1.111"), 32));
Vector<HostName^>^ localV4Addrs = ref new Vector<HostName^>;
localV4Addrs->Append(ref new HostName("192.168.1.133")); // Local host name to be bound.
Vector<HostName^>^ localV6Addrs = ref new Vector<HostName^>;
localV6Addrs->Append(ref new HostName("fc00::44fd:d3ed:b02a:a05e"));
Vector<HostName^>^ dnsServers = ref new Vector<HostName^>;
dnsServers->Append(ref new HostName("1.1.1.1"));
VpnDomainNameInfo^ dnsInfo = ref new VpnDomainNameInfo(".", VpnDomainNameType::Suffix, dnsServers, ref new Vector<HostName^>);
VpnDomainNameAssignment^ dnsAssignment = ref new VpnDomainNameAssignment;
dnsAssignment->DomainNameList->Append(dnsInfo);
try
{
// Throws exception here.
channel->StartWithMainTransport(localV4Addrs->GetView(), localV6Addrs->GetView(), nullptr, routeScope, dnsAssignment, 1400, 1412, false, this->dSock);
}
catch (Exception^ exc)
{
auto type = exc->GetType();
Platform::String^ str = exc->ToString();
}
}
Related
I've been trying to connect to a specific wifi through code, but with no succcess.
This is what i've come up with:
public void ConnectToWifi(string ssid, string password)
{
WifiManager wifiManager = (WifiManager)Android.App.Application.Context.GetSystemService(Context.WifiService);
if (!wifiManager.IsWifiEnabled)
{
wifiManager.SetWifiEnabled(true);
}
string formattedSsid = $"\"{ssid}\"";
string formattedPassword = $"\"{password}\"";
WifiConfiguration wifiConfig = new WifiConfiguration
{
Ssid = formattedSsid,
PreSharedKey = formattedPassword
};
var addNetwork = wifiManager.AddNetwork(wifiConfig);
WifiConfiguration network = wifiManager.ConfiguredNetworks.FirstOrDefault(n => n.Ssid == ssid);
if (network == null)
{
Console.WriteLine($"Cannot connect to network: {ssid}");
return;
}
wifiManager.Disconnect();
bool enableNetwork = wifiManager.EnableNetwork(network.NetworkId, true);
}
I've added permissions.
When testing it does turn the wifi on atleast, so i know it works until that point. What seems not to be working is the AddNetwork part.
I appreciate any help i can get!
You are missing one key method - reconnect(). You can read more about it in the WifiManager's docs here
The important part of the documentation is:
Reconnect to the currently active access point, if we are currently disconnected.
So, what you need to do it after you have disconnected and enabled your new network, call in the end this and you will be good to go:
wifiManager.Disconnect();
wifiManager.EnableNetwork(network.NetworkId, true);
wifiManager.Reconnect(); // This is the missing method
NB: Keep in mind that most of the WifiManager's code that you are using is being obsolete starting Android 10. So, if you want to target Android 10, then you will need to write an additional code for the connectivity for devices with Android 10+.
I know how to launch a windows application using the filepath to launch it and that works (working example below). I am writing tests and they work too but my question is this: If the application is running already, how do I create my "session" (often called "driver") for the currently running application?
I have read this article that explains how you would connect a new session to Cortana which is already running. It's a great example but my app is an exe that has been launched and is not part of windows and I'm getting the error "Could not find any recognizable digits.".
What am I doing wrong?
WORKING CODE THAT LAUNCHES THE APP AND CREATES THE "session":
private const string WindowsApplicationDriverUrl = "http://127.0.0.1:4723";
protected static WindowsDriver<RemoteWebElement> session;
public static void Setup(TestContext context)
{
// Launch app and populate session
if (session == null)
{
// Create a new sessio
DesiredCapabilities appCapabilities = new DesiredCapabilities();
appCapabilities.SetCapability("app", filepath /*The exeecutable's filepath on c drive*/);
//LaunchWPF app and wpf session
session = new WindowsDriver<RemoteWebElement>(new Uri(WindowsApplicationDriverUrl), appCapabilities);
session.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(10);
}
}
PROBLEM CODE :
[TestMethod()]
public void Common_CreateSession_ForAlreadyRunningmyApp()
{
string WindowsApplicationDriverUrl = "http://127.0.0.1:4723";
IntPtr myAppTopLevelWindowHandle = new IntPtr();
foreach (Process clsProcess in Process.GetProcesses())
{
if (clsProcess.ProcessName.Contains("MyApp.Client.Shell"))
{
myAppTopLevelWindowHandle = clsProcess.Handle;
}
}
DesiredCapabilities appCapabilities = new DesiredCapabilities();
appCapabilities.SetCapability("appTopLevelWindow", myAppTopLevelWindowHandle);
//Create session for app that's already running (THIS LINE FAILS, ERROR: : 'Could not find any recognizable digits.')
session = new WindowsDriver<RemoteWebElement>(new Uri(WindowsApplicationDriverUrl), appCapabilities);
session.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(10);
}
}
There's now an answer on github here. You can see on github I have made 3 tweaks to the answer given by moonkey124, 2 of them were obvious (my aplication name and a little sleep command), 1 of them was to adapt the answer to a WPF application under test...
I had some code that uses PNRP to discover peers on network. Everything works fine since Windows 10 update 1803.
public void Init()
{
try
{
_ServiceUrl = Dns.GetHostAddresses(Dns.GetHostName()).Where(address => address.AddressFamily == AddressFamily.InterNetwork).Select(address => _Address = address).Select(address => $"net.tcp://{address}:{Port}/SiemensVR").FirstOrDefault();
if (string.IsNullOrEmpty(_ServiceUrl)) return;
_LocalProxy = new PeerProxy(_EventAggregator, this);
_Host = new ServiceHost(_LocalProxy, new Uri(_ServiceUrl));
var binding = new NetTcpBinding();
binding.Security.Mode = SecurityMode.None;
_Host.AddServiceEndpoint(typeof(IPeerContract), binding, new Uri(_ServiceUrl));
_Host.Open();
_PeerName = new PeerName(PEER_NAME_ID, PeerNameType.Unsecured);
_PeerNameRegistration = new PeerNameRegistration(_PeerName, Port) { Cloud = Cloud.AllLinkLocal };
_PeerNameRegistration.Comment = _UserId.ToString();
_PeerNameRegistration.Start();
ResolvePeers();
}
finally { }
}
private async void ResolvePeers()
{
var resolver = new PeerNameResolver();
resolver.ResolveProgressChanged += OnResolveProgressChanged;
resolver.ResolveCompleted += (s, e) =>
{
Console.WriteLine("Completed");
};
resolver.ResolveAsync(_PeerName, this);
await Task.Delay(1000);
resolver.ResolveAsyncCancel(this);
}
Does MS have replace PNRP by something ?
I already tested to activate pnrp services, reinstall teredo tunneling and more.
Microsoft has deprecated and is in the process of removing PNRP.
You're out of luck, since its service and client APIs are being removed completely.
See https://learn.microsoft.com/en-us/windows/deployment/planning/windows-10-deprecated-features
Having the same issue here... Let me know if you find any resolution.
Previously, our application works fine, but on 1803 it doesn't work anymore. I can see the cloud start to synchronize and then each peer just ends up going to status alone.
Same issue, I found a Microsoft note to set the following services to Automatic Delayed Start:
Computer Browser (Browser) <- Set to Automatic, not delayed start
Function Discovery Provider Host (FDPHost)
Function Discovery Resource Publication (FDResPub)
Network Connections (NetMan)
UPnP Device Host (UPnPHost)
Peer Name Resolution Protocol (PNRPSvc)
Peer Networking Grouping (P2PSvc)
Peer Networking Identity Manager (P2PIMSvc)
But it didn't resolve the issue.
Any progress in resolving this?
I am trying to customize some lists for SharePoint Online and since I am new to the subject I do not know how to connect to the service.
When I use NAPA and from the cloud use the option "Edit in Visual Studio", I am prompted for credentials automatically when the project opens.
However, when I start from bottom-up, i.e. open a new project in Visual Studio, add all necessary dlls, this part of code throws an error (it is an authentication issue):
ClientContext context = new ClientContext("https://MYURL.sharepoint.com/n/");
context.ExecuteQuery();
I am using Microsoft.SharePoint.Client;
The error message:
An unhandled exception of type 'System.Net.WebException' occurred in Microsoft.SharePoint.Client.dll
Additional information: The remote server returned an error: (403) Forbidden.
I think I am missing part of the code which is responsible for authentication and which in case of NAPA app is hard-coded.
How can I authenticate to SharePoint Online? (it is enough if my code runs just once, it's not an app, I don't want to package it and publish)
I am guessing it has something to do with http://msdn.microsoft.com/en-us/library/microsoft.visualstudio.sharepoint.remote.authentication.aspx, but that's as far as I got.
How to authenticate against SharePoint Online using the managed CSOM
The CSOM for SharePoint 2013 introduces the SharePointOnlineCredentials class that allows to perform an active authentication to SharePoint Online.
Example
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter the URL of the SharePoint Online site:");
string webUrl = Console.ReadLine();
Console.WriteLine("Enter your user name (format: username#tenant.onmicrosoft.com)");
string userName = Console.ReadLine();
Console.WriteLine("Enter your password.");
SecureString password = GetPasswordFromConsoleInput();
using (var context = new ClientContext(webUrl))
{
context.Credentials = new SharePointOnlineCredentials(userName,password);
context.Load(context.Web, w => w.Title);
context.ExecuteQuery();
Console.WriteLine("Your site title is: " + context.Web.Title);
}
}
private static SecureString GetPasswordFromConsoleInput()
{
ConsoleKeyInfo info;
//Get the user's password as a SecureString
SecureString securePassword = new SecureString();
do
{
info = Console.ReadKey(true);
if (info.Key != ConsoleKey.Enter)
{
securePassword.AppendChar(info.KeyChar);
}
}
while (info.Key != ConsoleKey.Enter);
return securePassword;
}
}
Im creating a simple WCF service for receiving crash reports.
The service will run self-hosted as a console program and must run without any installation of certificates.
Security-wise i need to ensure that the data send by the client is only send to our server and that the data is not intercepted. From the server point of view i would also like to ensure that the connecting client is using a specific certificate (embedded in the client assembly) to discourage abuse of the service.
I have created a single self-signed certificate and plan to embed the .cer (containing the public part of the certificate) in the client assembly and embed the PFX containing the certificate with the private key into the service host program assembly. (I was led to believe by this that i could use a single certificate).
My problem is that no matter how is setup this up i get the following error:
"An error occurred while making the HTTP request to https://localhost:8080/errorservice. This could be due to the fact that the server certificate is not configured properly with HTTP.SYS in the HTTPS case. This could also be caused by a mismatch of the security binding between the client and the server."
There shouldnt be a mismatch between the bindings, as they are created using the same code:
public static BasicHttpBinding CreateStreamingBinding() {
BasicHttpBinding streamBinding = new BasicHttpBinding();
streamBinding.TransferMode = TransferMode.StreamedRequest;
streamBinding.MaxReceivedMessageSize = long.MaxValue;
streamBinding.Security = new BasicHttpSecurity
{
Transport = new HttpTransportSecurity
{
ClientCredentialType = HttpClientCredentialType.None,
ProxyCredentialType =HttpProxyCredentialType.None
},
Mode = BasicHttpSecurityMode.Transport,
};
streamBinding.MaxBufferSize = int.MaxValue;
streamBinding.MessageEncoding = WSMessageEncoding.Mtom;
streamBinding.SendTimeout = new TimeSpan( 1, 0, 0, 0, 0 );
streamBinding.ReceiveTimeout = new TimeSpan( 1, 0, 0, 0, 0 );
return streamBinding;
}
On the client the code to create service is setup like this (the certificate location is just for testing):
protected ErrorReportingServiceClient CreateClient() {
X509Certificate2 cert = new X509Certificate2( #"C:\certs\reporting.cer" );
EndpointAddress endpointAddress = new EndpointAddress( new Uri( ReportingServiceUri ));
ErrorReportingServiceClient client = new ErrorReportingServiceClient( CreateStreamingBinding(), endpointAddress );
client.ClientCredentials.ServiceCertificate.DefaultCertificate = cert;
client.ClientCredentials.ServiceCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.None;
client.ClientCredentials.ClientCertificate.Certificate = cert;
return client;
}
On the service side the setup is as follows:
X509Certificate2 cert = new X509Certificate2( #"C:\certs\reporting.pfx", <password>);
BasicHttpBinding basicHttpBinding = CreateStreamingBinding();
host.Credentials.ClientCertificate.Certificate = cert;
host.Credentials.ClientCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.None;
host.Credentials.ServiceCertificate.Certificate = cert;
host.AddServiceEndpoint( contractType, basicHttpBinding, baseAddress );
Any help on how to setup this correctly would be greatly appreciated.
The question was answered on the MSDN forums:
http://social.msdn.microsoft.com/Forums/en-US/wcf/thread/14f44296-5e3d-4df5-8cc4-a185415852b7