Establish connection to wifi using ManagedNativeWifi package - c#

Nice framework... but I am trying to establish a connection to an available network. I have connected manually, and made a snapshot of the XML. Then removed the connection.
I am able to find the network,
I pass in the SSID I want to connect to (yes, it is found..). I also pass the profileSecurity to use... but not really sure what to put there. From my XML I tried bot AES as well as WPA2PSK. But, SetProfile always returns false. And not sure how to extract an error message about what went wrong. That would be nice.
As the profile fails, the ConnectNetwork also fails, but that would be expected I think.
Any pointer would be nice. And a bit more documentation on these points would make the tool a lot better.
// get the network to connect to
var availableNetwork = NativeWifi.EnumerateAvailableNetworks()
.FirstOrDefault(x => x.Ssid.ToString() == ssid);
if (availableNetwork is null)
return;
var profile = NativeWifi.EnumerateProfiles().FirstOrDefault(x => x.Name == ssid);
if (profile is null)
{
// build XML
string profileName = ssid;
string mac = StringToHex(profileName);
string profileXml = string.Format("<?xml version=\"1.0\"?><WLANProfile xmlns = \"http://www.microsoft.com/networking/WLAN/profile/v1\"><name>{0}</name><SSIDConfig><SSID><hex>{1}</hex><name>{0}</name></SSID></SSIDConfig><connectionType>ESS</connectionType><connectionMode>auto</connectionMode><MSM><security><authEncryption><authentication>WPA2PSK</authentication><encryption>AES</encryption><useOneX>false</useOneX></authEncryption><sharedKey><keyType>passPhrase</keyType><protected>true</protected><keyMaterial>... key removed for security...</keyMaterial></sharedKey></security></MSM><MacRandomization xmlns=\"http://www.microsoft.com/networking/WLAN/profile/v3\"><enableRandomization>false</enableRandomization><randomizationSeed>153878511</randomizationSeed></MacRandomization></WLANProfile>", ssid, mac);
// create a profile
var profileResult = NativeWifi.SetProfile(availableNetwork.Interface.Id, ProfileType.AllUser, profileXml, encryption, true);
}
else
{
//todo: log here
}
var wasConnected = NativeWifi.ConnectNetwork(availableNetwork.Interface.Id, ssid, availableNetwork.BssType);

Related

Updating MetaData on Connected account fails

I am using stripe connect(destination payment) with the help of stripe.net library from Jaymedavis.
The problem that I am facing is that I am not able to retrieve the destination payment ID to update the metadata in the connected account. The following line returns a null preventing me from updating meta data on the connected account. But the strange thing is that when I log in to the dashboard the destination payment ID exists. I am not sure why I am not able to retreive it in code.
Is the charge creation asynchronous?. I am not sure. Stripe's connect documentation does not help either. The following line returns a null. My code is down below. Seeking help.
String deschargeID = result.Transfer.DestinationPayment;
Here is the code that I am using
var service = new StripeChargeService(ZambreroSecretKey);
var result = (Stripe.StripeCharge) null;
try {
result = service.Create(newCharge);
if (result.Paid) {
//get the chargeID on the newgen account and update the metadata.
//Returns null even though it exists in the dashboard
String deschargeID = result.Transfer.DestinationPayment;
var chargeService = new StripeChargeService(newgenSecretKey);
StripeCharge charge = chargeService.Get(deschargeID);
charge.Metadata = myDict;
Response.Redirect("PgeCustSuccess.aspx?OrderID=" + OrderID);
}
} catch (StripeException stripeException) {
Debug.WriteLine(stripeException.Message);
stripe.Text = stripeException.Message;
}
The charge object's transfer attribute is not expanded by default, meaning it's just a string with the ID of the transfer object ("tr_..."), not a full transfer object.
According to Stripe.net's documentation, you can expand the transfer attribute by adding this line:
service.ExpandTransfer = True
before sending the charge creation request.

VMWare API disconnect USB-Passthrough

I am using VMWare Workstation (v11) to run a Virtual Machine for testing.
Now I'd like to pragmatically add and remove USB-devices attached to the system.
using VMware.Vim; I can connect to the server and query it. I can also remove devices like CD-Drives and other things. But I can't disconnect any USB-Passthrough-Device. I either get : "Invalid Config" or "Unknown Error" (most likely due to the lib being interopt and not transporting all information)
My current code:
using VMware.Vim;
var dongle = devs.SingleOrDefault(i => i.DeviceInfo.Summary.Contains("Silicon"));
if (dongle != null) {
var usbDongle = (dongle as VirtualUSB);
usbDongle.Connected = false;
var spec = new VirtualMachineConfigSpec() {
DeviceChange = new[] {
new VirtualDeviceConfigSpec() {
Device = dongle,
Operation = VirtualDeviceConfigSpecOperation.remove,
}
}
};
vm.ReconfigVM(spec);
Neither Operation = "remove" or "edit" has any effect. I'm always getting some kind of error...
I appreciate any ideas!
Regards,
Corelgott

Doing cryptography on Windows Phone

I have made some code that allows me to do cryptography in c# - using primarily AesManaged() and SHA256Managed() in System.Security.Cryptography.
The use case is that the tool needs to be able to pull off an encrypted piece of data, decrypt it, display it to the user, allow for editing and encrypt again before sending it back again.
I would like to be able to do similar on Windows Phone, but it seems that the namespace is not available on the phone.
So what are my options now? Will it be available on Windows Phone 10? It seems that doing crypto-stuff would be a relatively common task in a phone app?
Edit: added information about what the app should do
What are you trying to do with the cryptography?
Because if you just need to store some user credentials, best way is using the PasswordVault
MSDN reference here https://msdn.microsoft.com/en-us/library/windows/apps/xaml/windows.security.credentials.passwordvault.aspx
I've made an example of this here
http://depblog.weblogs.us/2014/11/20/migrating-from-sl8-0-protectdata-to-rt8-1-passwordvault/
Added some example code on how to add and remove entries from the Vault ( more details on the blog post )
public async Task AddAccount(Account accountToAdd)
{
//Reinitialize the vault to see if the given account is already available
await this.InitializeSettingsService();
Account accountFromVault = this.Accounts.FirstOrDefault(item => item.UserName.Equals(accountToAdd.UserName, StringComparison.OrdinalIgnoreCase));
if(accountFromVault == null)
_vault.Add(new PasswordCredential(Constants.VAULTRESOURCENAME, accountToAdd.UserName, accountToAdd.Password));
if (accountFromVault != null && !accountFromVault.Password.Equals(accountToAdd.Password, StringComparison.Ordinal))
{
_vault.Remove(new PasswordCredential(Constants.VAULTRESOURCENAME, accountFromVault.UserName, accountFromVault.Password));
_vault.Add(new PasswordCredential(Constants.VAULTRESOURCENAME, accountToAdd.UserName, accountToAdd.Password));
}
Account accountFromMemory = this.Accounts.FirstOrDefault(item => item.UserName.Equals(accountToAdd.UserName, StringComparison.OrdinalIgnoreCase));
if (accountFromMemory != null)
{
if (!accountFromMemory.Password.Equals(accountToAdd.Password, StringComparison.OrdinalIgnoreCase))
{
this.Accounts.Remove(accountFromMemory);
this.Accounts.Add(accountToAdd);
}
}
else
this.Accounts.Add(accountToAdd);
}
public async Task RemoveAccount(Account accountToRemove)
{
//Reinitialize the vault to see if the given account is already available
await this.InitializeSettingsService();
Account accountFromVault = this.Accounts.FirstOrDefault(item => item.UserName.Equals(accountToRemove.UserName, StringComparison.OrdinalIgnoreCase));
if (accountFromVault != null)
_vault.Remove(new PasswordCredential(Constants.VAULTRESOURCENAME, accountToRemove.UserName, accountToRemove.Password));
Account accountFromMemory = this.Accounts.FirstOrDefault(item => item.UserName.Equals(accountToRemove.UserName, StringComparison.OrdinalIgnoreCase));
if (accountFromMemory != null)
this.Accounts.Remove(accountFromMemory);
}
As #WDS noted, the tools for doing cryptography is located in Windows.Security.Cryptography namespace - available on #WP8 .
So I rewrote my hash-implementation like this:
public IBuffer ComputeHash(string value)
{
IBuffer buffUtf8Msg = CryptographicBuffer.ConvertStringToBinary(value, BinaryStringEncoding.Utf8);
var objAlgProv = HashAlgorithmProvider.OpenAlgorithm("SHA256");
var strAlgNameUsed = objAlgProv.AlgorithmName;
var buffHash = objAlgProv.HashData(buffUtf8Msg);
if (buffHash.Length != objAlgProv.HashLength)
{
throw new Exception("There was an error creating the hash");
}
return buffHash;
}
Examples of how to do encryption and decryption can be found here:
https://msdn.microsoft.com/en-us/library/windows/apps/windows.security.cryptography.core.cryptographicengine.aspx

Set server address dynamically in ideablade for second time?

I have this problem that in my program I set dynamically server address and try to connect to my database and it works fine if the address that I provided was correct, if not it doesn't connect and that's normal. After that I would like to change this address, but even though I change it in code and try to connect with my database again, it stills remembers old configuration and still doesn't connect. What should I do to change it?
I set my configuration like this:
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
foreach (XmlElement element in xmlDoc.DocumentElement)
{
if (element.Name.Equals("ideablade.configuration"))
{
foreach (XmlNode ele in element.ChildNodes)
{
if (ele.Name == "objectServer")
{
var node = ele;
node.Attributes["remoteBaseURL"].Value = remoteBaseURL;
node.Attributes["serverPort"].Value = serverPort;
node.Attributes["serviceName"].Value = serviceName;
}
}
}
}
xmlDoc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
ConfigurationManager.RefreshSection("ideablade.configuration");
and I try to connect to my databse like this
if (BeczkaModel!= null)
{
BeczkaModel.Disconnect();
BeczkaModel= null;
}
IdeaBladeConfig.Instance.ObjectServer.RemoteBaseUrl = remoteBaseURL;
IdeaBladeConfig.Instance.ObjectServer.ServerPort = (int)double.Parse(serverPort);
IdeaBladeConfig.Instance.ObjectServer.ServiceName = serviceName;
IdeaBladeConfig.Instance.ObjectServer.ClientSettings.IsDistributed=true;
BeczkaModel= new BeczkaContainer();
BeczkaModel.AuthorizedThreadId = null;
BeczkaModel.Connect();
Data source key extensions and/or a custom IDataSourceKeyResolver are the way to handle different database connections. It's important to realize that the EntityManager.Connect call is not connecting to a specific data source; it's actually connecting to a specific EntityService. The way to connect to differing EntityService URLs is to use a ServiceKey. More info here: http://drc.ideablade.com/devforce-2012/bin/view/Documentation/connect-to-multiple-entityservers.
You will be able to determine which database to connect to by implementing a custom DataSourceKeyResolver.
You will find additional information at http://drc.ideablade.com/devforce-2012/bin/view/Documentation/data-sources and a sample at http://drc.ideablade.com/devforce-2012/bin/view/Documentation/code-sample-custom-datasourcekeyresolver.
To clarify sbellini's post, there are two ways to dynamically determine the database connection. The first and easier approach is to use Data Source Extensions. This is useful if you have a static list of database connections and want to select among the list at runtime. The second approach is to implement an IDataSourceKeyResolver. This allows you to determine the connection string entirely at runtime.
http://drc.ideablade.com/devforce-2012/bin/view/Documentation/data-sources
http://drc.ideablade.com/devforce-2012/bin/view/Documentation/code-sample-data-source-extensions
http://drc.ideablade.com/devforce-2012/bin/view/Documentation/code-sample-custom-datasourcekeyresolver

How to access WinRM in C#

I'd like to create a small application that can collect system information (Win32_blablabla) using WinRM as opposed to WMI. How can i do that from C#?
The main goal is to use WS-Man (WinRm) as opposed to DCOM (WMI).
I guess the easiest way would be to use WSMAN automation. Reference wsmauto.dll from windwos\system32 in your project:
then, code below should work for you. API description is here: msdn: WinRM C++ API
IWSMan wsman = new WSManClass();
IWSManConnectionOptions options = (IWSManConnectionOptions)wsman.CreateConnectionOptions();
if (options != null)
{
try
{
// options.UserName = ???;
// options.Password = ???;
IWSManSession session = (IWSManSession)wsman.CreateSession("http://<your_server_name>/wsman", 0, options);
if (session != null)
{
try
{
// retrieve the Win32_Service xml representation
var reply = session.Get("http://schemas.microsoft.com/wbem/wsman/1/wmi/root/cimv2/Win32_Service?Name=winmgmt", 0);
// parse xml and dump service name and description
var doc = new XmlDocument();
doc.LoadXml(reply);
foreach (var elementName in new string[] { "p:Caption", "p:Description" })
{
var node = doc.GetElementsByTagName(elementName)[0];
if (node != null) Console.WriteLine(node.InnerText);
}
}
finally
{
Marshal.ReleaseComObject(session);
}
}
}
finally
{
Marshal.ReleaseComObject(options);
}
}
hope this helps, regards
I've got an article that describes an easy way to run Powershell through WinRM from .NET at http://getthinktank.com/2015/06/22/naos-winrm-windows-remote-management-through-net/.
The code is in a single file if you want to just copy it and it's also a NuGet package that includes the reference to System.Management.Automation.
It auto manages trusted hosts, can run script blocks, and also send files (which isn't really supported but I created a work around). The returns are always the raw objects from Powershell.
// this is the entrypoint to interact with the system (interfaced for testing).
var machineManager = new MachineManager(
"10.0.0.1",
"Administrator",
MachineManager.ConvertStringToSecureString("xxx"),
true);
// will perform a user initiated reboot.
machineManager.Reboot();
// can run random script blocks WITH parameters.
var fileObjects = machineManager.RunScript(
"{ param($path) ls $path }",
new[] { #"C:\PathToList" });
// can transfer files to the remote server (over WinRM's protocol!).
var localFilePath = #"D:\Temp\BigFileLocal.nupkg";
var fileBytes = File.ReadAllBytes(localFilePath);
var remoteFilePath = #"D:\Temp\BigFileRemote.nupkg";
machineManager.SendFile(remoteFilePath, fileBytes);
Hope this helps, I've been using this for a while with my automated deployments. Please leave comments if you find issues.
I would like to note that this shows an interop error by default in Visual Studio 2010.
c.f. http://blogs.msdn.com/b/mshneer/archive/2009/12/07/interop-type-xxx-cannot-be-embedded-use-the-applicable-interface-instead.aspx
There appear to be two ways to solve this. This first is documented in the article listed above and appears to be the correct way to handle the problem. The pertinent changes for this example is:
WSMan wsManObject = new WSMan();
This is in lieu of IWSMan wsman = new WSManClass(); which will throw the error.
The second resolution is to go to the VS2010—>Solution Explorer—>Solution—>Project—>References and select WSManAutomation. Right click or hit Alt-Enter to access the properties. Change the value of the "Embed Interop Types" property of the wsmauto reference.

Categories