How to connect to wifi using simple wifi in wpf? - c#

I am trying to connect to wifi using simplewifi. Currently, I have tried:
Wifi wifi = new Wifi();
// get list of access points
IEnumerable<AccessPoint> accessPoints = wifi.GetAccessPoints();
// for each access point from the list
foreach (AccessPoint ap in accessPoints)
{
Console.WriteLine("ap: {0}\r\n", ap.Name);
//check if SSID is desired
if (ap.Name.StartsWith("z"))
{
//verify connection to desired SSID
Console.WriteLine("connected: {0}, password needed: {1}, has profile: {2}\r\n", ap.Name, ap.IsConnected, ap.HasProfile);
if (!ap.IsConnected)
{
//connect if not connected
Console.WriteLine("\r\n{0}\r\n", ap.ToString());
Console.WriteLine("Trying to connect..\r\n");
AuthRequest authRequest = new AuthRequest(ap);
authRequest.Password = "123456789";
var x=ap.Connect(authRequest);
}
}
}
Here I am not able to pass the password if I have the password hardcoded like
var password="abc123"
How can I pass the password and connect?
Also, the connect method always returns false, even if I have to connect to a wifi with no password.

You need to set authRequest.Password = "yourpassword";
before your ap.connect(authRequest);
Add in following console.write() from https://github.com/DigiExam/simplewifi
Place at the top of your file
using SimpleWifi;
Then in your function
// Wifi object
Wifi wifi = new Wifi();
// get list of access points
IEnumerable<AccessPoint> accessPoints = wifi.GetAccessPoints();
// for each access point from list
foreach (AccessPoint ap in accessPoints){
Console.WriteLine("ap: {0}\r\n", ap.Name);
//check if SSID is desired
if (ap.Name.StartsWith("ardrone_")){
//verify connection to desired SSID
Console.WriteLine("connected: {0}, password needed: {1}, has profile: {2}\r\n", ap.Name, ap.IsConnected, ap.HasProfile);
if (!ap.IsConnected){
//connect if not connected
Console.WriteLine("\r\n{0}\r\n", ap.ToString());
Console.WriteLine("Trying to connect..\r\n");
AuthRequest authRequest = new AuthRequest(ap);
ap.Connect(authRequest);
}
}
}

Adding overwriteProfile set to "true" to parameters of the AccessPoint.Connect method solved the problem for me.
F# example:
open SimpleWifi
[<EntryPoint>]
let main argv =
let wifi = Wifi()
let accessPoint = wifi.GetAccessPoints()
|> Seq.find (fun (i:AccessPoint) -> i.Name = "Tpkl6" )
let try1 = accessPoint.Connect( AuthRequest(accessPoint, Password="12345678"), true )
let try2 = accessPoint.Connect( AuthRequest(accessPoint, Password="markvirchenko20"), true )
printfn "%b\n%b" try1 try2
0 // return an integer exit code
By the way, you asked about ispasswordvalid function in the comments:
I disconnected all internet and tried to connect, ispasswordvalid verification gives true, but while connecting it fails
ispasswordvalid doesn't actually check if the password is correct i.e matching the one set on the wifi. It simply checks if the password has a valid structure, e.g at least 8 symbols length.

Related

With access to Active Directory, can I get an object GUID for a user from an username/email address alone?

Background
I've been experimenting with active directory access in C# to find out how to connect/validate credentials in various ways. At the bottom of this answer I've included some code snippets to give an idea of what I've done, maybe this can be built upon to fulfill my aim.
Main Aim
If I have valid credentials for connecting to an Active Directory, can I take an string representing a username/email address (assuming it exists in the userPrincipalName or similar field), and get back the objectGUID?
Or do I need to take other things into account like: the permissions those credentials have to search other users; knowledge of the structure of different ADs; if userPrincipalName is the correct field to search?
Code Snippets (experimental beginnings, not fully functional for my aim)
var credentials = new NetworkCredential(username, password, hostname);
var serverId = new LdapDirectoryIdentifier(hostname);
var connection = new LdapConnection(serverId, credentials);
try
{
connection.Bind();
}
catch (Exception e)
{
//error
Console.WriteLine(e);
connection.Dispose();
return;
}
//success
var dirEntry = new DirectoryEntry(string.Format("LDAP://{0}/{1}", hostname, baseDn), username, password);
var searcher = new DirectorySearcher(dirEntry)
{
Filter = "(&(&(objectClass=user)(objectClass=person)))"
};
var resultCollection = searcher.FindAll();
searcher.Dispose();
You're on the right track with DirectorySeacher. You just need a proper query, and a few other tweaks.
Modify the Filter so you find what you're looking for.
a. If you have the email address:
(&(objectClass=user)(objectClass=person)(mail=email#example.com))
Or, (&(objectClass=user)(objectClass=person)(proxyAddresses=smtp:email#example.com)) (this will match against secondary email addresses too)
b. If you have a username, it depends which username you have.
User Principal Name: (&(objectClass=user)(objectClass=person)(userPrincipalName=username#example.com))
What is normally called the "username", which is often formatted like DOMAIN\username: (&(objectClass=user)(objectClass=person)(sAMAccountName=myusername))
Use DirectorySeacher.PropertiesToLoad. If you don't, it will retrieve every attribute that has a value, which is just wasted network traffic.
You don't need to dispose the DirectorySearcher, but you do need to dispose resultCollection since the documentation says you can end up with a memory leak if you leave it up to garbage collection.
So, assuming you have the userPrincipalName, you would have something like this:
var userToLookFor = "username#example.com";
var dirEntry = new DirectoryEntry(string.Format("LDAP://{0}/{1}", hostname, baseDn), username, password);
var searcher = new DirectorySearcher(dirEntry)
{
Filter = $"(&(objectClass=user)(objectClass=person)(userPrincipalName={userToLookFor}))",
SizeLimit = 1 //we're only looking for one account
};
searcher.PropertiesToLoad.Add("objectGuid");
using (var resultCollection = searcher.FindAll())
{
if (resultCollection.Count == 1)
{
var userGuid = new Guid((byte[]) resultCollection[0].Properties["objectGuid"][0]);
}
else
{
//the account was not found - do something else
}
}

Perform SNMP walk using SharpSnmpLib BulkWalk method

I am trying to retrieve the MAC address of a device that connects to the network. My goal is to perform a WALK and then search the results by the port number that triggered the event.
I first grab the port information via a GetRequestMessage (Success). Then I TRY to perform a walk to get the MAC Address table. I do not get any errors or exceptions, but I also do not get any results.
Where am I going wrong?
// Capture IPAddress
string ipAddress = e.Sender.Address.ToString();
// Capture the port
string port = e.Message.Scope.Pdu.Variables[0].Data.ToString();
// Setup Authentication with password from App.Config
var auth = new SHA1AuthenticationProvider(new OctetString(_Password));
// Setup Privacy with Phrase from App.Config
var priv = new DESPrivacyProvider(new OctetString(_Phrase), auth);
// Setup username from App.Config
OctetString userName = new OctetString(_Username);
// Create IPEndPoint
IPEndPoint iPEndPoint = new IPEndPoint(IPAddress.Parse(ipAddress), 161);
// Create discovery
Discovery discovery = Messenger.GetNextDiscovery(SnmpType.GetRequestPdu);
// Create report
ReportMessage report = discovery.GetResponse(60000, iPEndPoint);
// Setup OID variables to get port information
List<Variable> variables = new List<Variable>
{
// Port Description
new Variable(new ObjectIdentifier($"1.3.6.1.2.1.31.1.1.1.18.{ port }")),
// Port PVID
new Variable(new ObjectIdentifier($"1.3.6.1.2.1.17.7.1.4.5.1.1.{ port }")),
// Voice VLAN
new Variable(new ObjectIdentifier($"1.3.6.1.4.1.674.10895.5000.2.6132.1.1.1.2.13.1.28.{ port }")),
};
// Create SNMP request
GetRequestMessage request = new GetRequestMessage(VersionCode.V3, Messenger.NextMessageId, Messenger.NextRequestId, userName, variables, priv, Messenger.MaxMessageSize, report);
// Send request and get reply
ISnmpMessage reply = request.GetResponse(60000, iPEndPoint);
// Request failed
if (reply.Pdu().ErrorStatus.ToInt32() != 0) // != ErrorCode.NoError
{
throw ErrorException.Create(
"error in response",
IPAddress.Parse(ipAddress),
reply);
}
// Store reply information
string Port_Description = reply.Scope.Pdu.Variables[0].Data.ToString(),
Port_Pvid = reply.Scope.Pdu.Variables[1].Data.ToString(),
Port_VLAN = reply.Scope.Pdu.Variables[2].Data.ToString();
// Create BulkWalk Discovery
// TODO: Do I need to do this or can I reuse the original discovery??
Discovery BULKWALK_discovery = Messenger.GetNextDiscovery(SnmpType.GetRequestPdu);
// Create BulkWalk report
// TODO: Do I need to do this or can I reuse the original report??
ReportMessage BULKWALK_report = BULKWALK_discovery.GetResponse(60000, iPEndPoint);
// Variable to store the results of the WALK
var BULKWALK_results = new List<Variable>();
// Perform the walk and return the count of results. Community name from App.Config
var BULKWALK_results_count = Messenger.BulkWalk(VersionCode.V3, iPEndPoint, new OctetString(_CommunityName), OctetString.Empty, new ObjectIdentifier($"1.3.6.1.2.1.17.7.1.2.2.1.2"), BULKWALK_results, 60000, 10, WalkMode.WithinSubtree, priv, BULKWALK_report);
Debugger.Break();
EDIT
Also, I am using this resource as guidance.
So I found the issue, which was two fold.
The first was when instantiating the Discovery for the BulkWalk, it needs to be as follows:
Discovery discovery = Messenger.GetNextDiscovery(SnmpType.GetBulkRequestPdu);
The key part being getting the SnmpType correct (my code above is SnmpType.GetRequestPdu and not SnmpType.GetBulkRequestPdu). The tutorial does not mention that the SnmpType is different.
Second, when passing parameters into the Messenger.BulkWalk() method I was passing in the community name and not the user name. The source code remarks for the BulkWalk method does say community name but it should be the user.
I did as Lex Li suggested and complied/ran the snmpwalk sample to verify that there were no issues. After that was a success, I went back and reviewed the source code for that sample and found the two issues.

How to connect my unity project to mysql server on ec2 instance

I am trying to get data from my MySQL server to my Unity project. I tried to get the data like so:
public string awsurl = "ec2-174-129-82-141.compute-1.amazonaws.com/connect_to_server.php";
IEnumerator GetScores()
{
print("get scores start");
WWW aws_get = new WWW(awsurl);
yield return aws_get;
print("getscore here");
if (aws_get.error != null)
{
print("There was an error getting aws: " + aws_get.error);
}
else
{
print(aws_get.text); // this is a GUIText that will display the scores in game.
}
}
I have a php script on my server to handle the interaction because I am having trouble using the MySqlConnection library for my unity project.
Here is my php script:
$address = "localhost"
$dbusername = "root";
$dbpassword = "root";
$db_name = "watshoes";
$db_conn = new mysqli($address, $dbusername, $dbpassword, $db_name);
if(isset($_POST['username'])) $username = $_POST['username'];
if(isset($_POST['user_id'])) $user_id = $_POST['user_id'];
if(isset($password)) $password =$_POST['password'];
$stmt = $db_conn->prepare("SELECT image FROM ImageText");
// "s" means the database expects a string
$stmt->bind_param("s", $user_id);
if($stmt->execute())
{
/* bind result variables */
$stmt->bind_result($image);
/* fetch value */
$stmt->fetch();
echo $image;
}
else
{
echo "query failed";
}
$stmt->close();
$db_conn->close();
But every time I run the code I get this error:There was an error getting aws: Failed to connect to ec2-174-129-82-141.compute-1.amazonaws.com port 80: Timed out
Thanks for looking at the code and please let me know if there is anything else I can do to help.
You have to add a rule to open the port 80 using security groups (Inbound tab)
How your rule should look:
By default the port 80 is close in EC2 AWS instances.
And the URL is malformed in Unity
Add http:// to your server URL
In editor will work ok without http:// but it will fail in android.

Get Indentifier of Android of iOS device (C#)

I have written a function that should give me an Identifier for iOS devices... But now I have to do the same for Android...
Is there an Id witch is on both devices?
Actually im using the AdvertisingIdentifier.
private static string GetIdentifier()
{
if (ASIdentifierManager.SharedManager.IsAdvertisingTrackingEnabled)
{
return ASIdentifierManager.SharedManager.AdvertisingIdentifier.ToString();
}
return null;
}
Since I don't know which ID do you want exactly, I wrote three block of code as follow:
//get unique number through TelephonyManager
//use this method, we need to add android.permission.READ_PHONE_STATE permission
var telephonymanager = this.GetSystemService(Context.TelephonyService) as TelephonyManager;
var imsid = telephonymanager.SubscriberId;
System.Diagnostics.Debug.WriteLine("imsid: " + imsid);
//get mac address through WifiManager
//use this method, we need to add android.permission.ACCESS_WIFI_STATE permission
var wifimanager = this.GetSystemService(Context.WifiService) as WifiManager;
var info = wifimanager.ConnectionInfo;
var macaddress = info.MacAddress;
System.Diagnostics.Debug.WriteLine("mac address: " + macaddress);
//get Android_ID use Android Provider
var deviceid = Android.Provider.Settings.Secure.GetString(this.ContentResolver,
Android.Provider.Settings.Secure.AndroidId);
System.Diagnostics.Debug.WriteLine("device id: " + deviceid);
First one is to get the IMEI, MEID, ESN and IMSI of the phone, which is unique to that piece of hardware. Second one is to get mac address of the device and the last one is to get device id.
All of them can be used to identify the device, you can choose the right one for your scenario. By the way, for the permissions which are needed, I've commented in the code block.

Is there a way to check if a printing process was successful?

I have an application where I need to print a ticket. Each ticket must be unique. The application is windows forms and written entirely in c#. For our application we're using Samsung ML- 2525 laser monochromatic printers.
The flow is basically the following, the operator picks a product/ticket (which is unique) and then it presses a button that does 2 things:
Connects to a database and updates the product as used
Prints the ticket (this is done using System.Drawing and GDI+)
For some reason, every once in a while, the image that needs to be printed is not sent to the printer. It's a rare case, but it happens.
I tried to connect to the printer using Win32_Printer ( http://msdn.microsoft.com/en-us/library/Aa394363 ) but I can't get to get the current printer's state (online, offline, low toner, paper jam, etc). I can only check if the printer exists and that the paper size is installed correctly. I tried code similar to the following but it didn't work
private string MonitorPrintJobWmi()
{
var jobMessage = String.Empty;
var scope = new ManagementScope(ManagementPath.DefaultPath);
scope.Connect();
var selectQuery = new SelectQuery { QueryString = #"select * from Win32_PrintJob" };
var objSearcher = new ManagementObjectSearcher(scope, selectQuery);
var objCollection = objSearcher.Get();
foreach (var job in objCollection)
{
if (job != null)
{
jobMessage += String.Format("{0} \r\n", job["Name"].ToString());
jobMessage += String.Format("{0} \r\n", job["JobId"].ToString());
_jobId = Convert.ToInt32(job["JobId"]);
jobMessage += String.Format("{0} \r\n", job["JobStatus"].ToString());
jobMessage += String.Format("{0} \r\n", job["Status"].ToString());
}
}
return jobMessage;
}
I tried to get an API for the printer but I couldn't get a hold of it. By the way, the printer's software do indicate different errors in the windows toolbar.
My question is if anyone can lead me in the right direction as to how to connect to a printer and check if printing was successful.
Also, it would be helpful if someone know of some other specific printer in which I may accomplish this ie, changing hardware.
Thanks,
To get a list of print queues on the local machine, try PrintServer's GetPrintQueues method.
Once you have an instance of the PrintQueue object associated with the relevant printer, you can use it to access the printer's status (IsOffline, IsPaperOut, etc.). Also, you can use it to get a list of the jobs in the given queue (GetPrintJobInfoCollection) which then will allow you to get job-specific status information (IsInError, IsCompleted, IsBlocked, etc.).
Hope this helps!
After try to print your PrintDocument (System.Drawing.Printing), try to check status of printjobs.
First step: Initialize your printDocument.
Second step: Get your printer Name From System.Drawing.Printing.PrinterSettings.InstalledPrinters.Cast<string>();
And copy it into your printerDocument.PrinterSettings.PrinterName
Third step: Try to print and dispose.
printerDocument.Print();
printerDocument.Dispose();
Last step: Run the check in a Task (do NOT block UI thread).
Task.Run(()=>{
if (!IsPrinterOk(printerDocument.PrinterSettings.PrinterName,checkTimeInMillisec))
{
// failed printing, do something...
}
});
Here is the implementation:
private bool IsPrinterOk(string name,int checkTimeInMillisec)
{
System.Collections.IList value = null;
do
{
//checkTimeInMillisec should be between 2000 and 5000
System.Threading.Thread.Sleep(checkTimeInMillisec);
// or use Timer with Threading.Monitor instead of thread sleep
using (System.Management.ManagementObjectSearcher searcher = new System.Management.ManagementObjectSearcher("SELECT * FROM Win32_PrintJob WHERE Name like '%" + name + "%'"))
{
value = null;
if (searcher.Get().Count == 0) // Number of pending document.
return true; // return because we haven't got any pending document.
else
{
foreach (System.Management.ManagementObject printer in searcher.Get())
{
value = printer.Properties.Cast<System.Management.PropertyData>().Where(p => p.Name.Equals("Status")).Select(p => p.Value).ToList();
break;
}
}
}
}
while (value.Contains("Printing") || value.Contains("UNKNOWN") || value.Contains("OK"));
return value.Contains("Error") ? false : true;
}
Good luck.

Categories

Resources