C# WPF how to connect a wifi with password - c#

I use Managed Wifi API library and ok to connect a "HasProfile" wifi AP like this:
WlanClient client = new WlanClient();
foreach (var item in client.Interfaces)
{
ViewModel.CurrentWlan = item;
Wlan.WlanAvailableNetwork[] networks = item.GetAvailableNetworkList(0);
foreach (Wlan.WlanAvailableNetwork network in networks)
{
var name = Helpers.GetStringForSSID(network.dot11Ssid);
ConnectionModel model = new ConnectionModel
{
DisplayName = string.Format("{0} (signal {1})", name, network.wlanSignalQuality),
IsConnected = network.flags.HasFlag(Wlan.WlanAvailableNetworkFlags.Connected),
SSID = network.dot11Ssid.SSID,
SsidString = Convert.ToBase64String(network.dot11Ssid.SSID),
ProfileName = network.profileName,
Name = name
};
if (network.flags.HasFlag(Wlan.WlanAvailableNetworkFlags.HasProfile))
{
model.XmlProfile = item.GetProfileXml(model.ProfileName);
}
if (network.flags == Wlan.WlanAvailableNetworkFlags.HasProfile)
{
model.IsRemembered = true;
}
ViewModel.Connections.Add(model);
}
}
OK now, all the availible APs are in the ViewModel.Connections.
Then I can connect one of the AP that Has Profiles:
private void OnConnect_Handler(object sender, RoutedEventArgs e)
{
Button button = sender as Button;
ConnectionModel model = button.DataContext as ConnectionModel;
ViewModel.CurrentWlan.SetProfile(Wlan.WlanProfileFlags.AllUser, model.XmlProfile, true);
ViewModel.CurrentWlan.Connect(Wlan.WlanConnectionMode.Profile, Wlan.Dot11BssType.Any, model.ProfileName);
}
and it's worked!
then I found a problem that is, such code only can connect those APs Has Profile, if I want to connect to a AP without profile(I think that means 'AP never connected'), I should use the following code:
string profileName = model.ProfileName;
string mac = "1008B1CD976F";
string key = "IsThisPasswordField?";
string profile = 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><MSM><security><authEncryption><authentication>open</authentication><encryption>WEP</encryption><useOneX>false</useOneX></authEncryption><sharedKey><keyType>networkKey</keyType><protected>false</protected><keyMaterial>{2}</keyMaterial></sharedKey><keyIndex>0</keyIndex></security></MSM></WLANProfile>",
profileName, mac, key);
ViewModel.CurrentWlan.SetProfile(Wlan.WlanProfileFlags.AllUser, profile, true);
ViewModel.CurrentWlan.Connect(Wlan.WlanConnectionMode.Profile, Wlan.Dot11BssType.Any, profileName);
But I tried serveral times always failed because:
(1) I don't know what the XML content is, why can't just input password then Connect(ssid, password)? is it because WIFI programming doesn't go like this?
(2) If must set a profile, how to input the right things such as:
string mac = "1008B1CD976F";
string key = "IsThisPasswordField?";
how to know this 'mac', and how to encrypt this key(if it's the AP's password)?
EDIT: here's the Managed Wifi API site. But there's no documentation.

First: The hex-string, you want to insert into the profile is not the mac of the accesspoint, but the hex-string of the ssid.
The profile xml is missleading here. I had the same problem, until I converted the hex-string back of a known profile. It was the ssid ;-)
You can just convert the ssid to it's hex representation by so:
string ssid = "YourSSID";
byte[] ssidBytes = Text.Encoding.Default.GetBytes(ssid);
string ssidHex = BitConverter.ToString(ssidBytes);
ssidHex = ssidHex.Replace("-", "");
Second: Because of a wrong hex-string of your ssid, your connection approach with the clear text password did not work either.
So just use the hex-representation of the ssid and you can connect with the password in clear text, as you tried before.

Related

Establish connection to wifi using ManagedNativeWifi package

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);

C# get phone from SIP address

I am using LyncClient library to create a widget and when a call comes in externally the remote participant sometimes comes up as 'sip:emailaddress#domain' if the contact is in the users outlook contacts.
Wondering if there is a way or library that allows me to open up the contact card for that email address and then get phone numbers if there are any.
Been pulling at my hair for a while now and can't figure it out. Any tips or experiences (good and bad) would be great! Let me know if you guys need more information.
I made a program that gets the phone address out of a SIP URL.
a SIP Url is basically in this format(Without quotes): "sip:username#domain"
try
{
LyncClient lyncClient = LyncClient.GetClient();
Contact contact;
List<object> endPoints = new List<object>();
Dictionary<string, string> phoneNumbers = new Dictionary<string, string>();
contact = lyncClient.ContactManager.GetContactByUri("sip:myusername#domain.com"); //PASS THE SIP ADDRESS HERE
var telephoneNumber = (List<object>)contact.GetContactInformation(ContactInformationType.ContactEndpoints);
//var contactName = contact.GetContactInformation(ContactInformationType.DisplayName).ToString();
//var availability = contact.GetContactInformation(ContactInformationType.Activity).ToString();
//foreach (object endPoint in telephoneNumber)
//{
//Console.WriteLine(((ContactEndpoint)endPoint).DisplayName + " " + ((ContactEndpoint)endPoint).Type.ToString());
//}
endPoints = telephoneNumber.Where<object>(N => ((ContactEndpoint)N).Type == ContactEndpointType.HomePhone || ((ContactEndpoint)N).Type == ContactEndpointType.MobilePhone || ((ContactEndpoint)N).Type == ContactEndpointType.OtherPhone || ((ContactEndpoint)N).Type == ContactEndpointType.WorkPhone).ToList<object>();
foreach (var endPoint in endPoints)
{
//Console.WriteLine(((ContactEndpoint)test).DisplayName.ToString());
string numberType = Regex.Replace(((ContactEndpoint)endPoint).Type.ToString(), #"Phone", "");
//string number = Regex.Replace(((ContactEndpoint)endPoint).DisplayName.ToString(), #"[^0-9]", "");
string number = "";
//Numbers only with dashes
if (Regex.IsMatch(((ContactEndpoint)endPoint).DisplayName.ToString(), #"^\d{3}-\d{3}-\d{4}$"))
{
number = ((ContactEndpoint)endPoint).DisplayName.ToString();
try
{
phoneNumbers.Add(numberType, number);
}
catch
{
}
}
//Console.WriteLine(numberType + " " + number);
}
foreach (var entry in phoneNumbers)
{
//entry.Key is the PhoneType
//entry.Value is the Phone Number
}
}
catch (Exception ex)
{
MessageBox.Show("An error occurred: " + ex.Message);
}
I don't think that this is the email address.
SIP URI's has the same format as an email address: sip:username#sipdomain, so maybe Lync is just sending the peer sip address.
In this case you just have to grab the sub-string between "sip:" and "#" to get the caller id.
Another problem is that there are multiple ways for SIP to send the caller id. Maybe you should look for Asserted/Preferred identity (and Lync just extracts it from the SIP "Contact" header).

Disable User in MultiBio 800-H Device using zk api (zkemkeeper / Interop.zkemkeeper)

I am developing an Access Control and able to disable user in other zk Devices. using below code but not only in zk 800-H device method returns true but cards is working and unlocking door.
In other device if I disable the user, swipe card device shows me user is disabled which is fine..
zkemkeeper.CZKEM zkApi = new zkemkeeper.CZKEM();//intialize api...
var bIsConnected = zkApi.Connect_Net("xxx.xxx.xxx.xxx", 4370);// connecting api and tested the device is connected.
if (bIsConnected)
{
zkApi.RegEvent(1, 65535);
return true;
}
//in zk api for enable disable user
//in below method 1 is iMachineNumber, "1001" is UserId In machine and fasle is for enable/disable user.
var result = zkApi.SSR_EnableUser(1, "1001" , false);//no error and return true for indicate success.
if (result)
{
MessageBox.Show("User Disabled Successfull");
}
There is a known issue in this device as I faced the same issue and contacted the support.
team.
Simply delete the record if you want to disable it.
Using C#, just do this (obviously you need the employeeId)
objCZKEM = new CZKEM();
string _Name = "", _Password = "";
int _Privilefe = 0;
bool _Enabled = false;
var t = objCZKEM.SSR_GetUserInfo(1, "2524", out _Name, out _Password, out _Privilefe, out _Enabled);
t = objCZKEM.SSR_SetUserInfo(1, "2524", _Name, _Password, _Privilefe, false);

Retrieve Lync contact from a phone number in an UCMA application

I have a C# managed Application that runs on a Lync 2013 Server and uses MSPL. I route every call from MSPL to the application and handle it there. Lync to Lync calls work fine and their to Header is in the form sip:user#domain.com. But when a call from outside the network (non-lync like mobile phone etc.) to the workphone of a Lyncuser is started, the Uri is like sip:+12341234#domain.com;user=phone (sip:[workphone]#domain). Passing this string to the Presence Retrieval function does not work.
var sips = new string[] { phone }; // The "To" number
presenceService.BeginPresenceQuery(sips, categories, null, null, null);
This always returns an empty result. How can I first retrieve the user associated with the phone number to get its presence?
I solved it this way:
public static UserObject FindContactBySip(string sip)
{
return UserList.FirstOrDefault(u => u.HasSip(sip));
}
private static void InitFindUsersInAD()
{
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
var user = new UserPrincipal(ctx);
user.Name = "*";
var searcher = new PrincipalSearcher(user);
var result = searcher.FindAll();
var sipList = new List<string>();
UserList = new List<UserObject>();
foreach (var res in result)
{
var underlying = (DirectoryEntry)res.GetUnderlyingObject();
string email = string.Empty, phone = string.Empty, policies = string.Empty;
foreach (var keyval in underlying.Properties.Values)
{
var kv = keyval as System.DirectoryServices.PropertyValueCollection;
if (kv != null && kv.Value is string)
{
if (kv.PropertyName.Equals("msRTCSIP-PrimaryUserAddress"))
{
email = (kv.Value ?? string.Empty).ToString();
}
else if (kv.PropertyName.Equals("msRTCSIP-Line"))
{
phone = (kv.Value ?? string.Empty).ToString();
}
else if (kv.PropertyName.Equals("msRTCSIP-UserPolicies"))
{
policies = (kv.Value ?? string.Empty).ToString();
}
}
}
if (!string.IsNullOrEmpty(phone) && !string.IsNullOrEmpty(email))
{
var userobj = new UserObject(email, phone, policies);
UserList.Add(userobj);
}
}
}
First I initialize the UserList (List // Custom class) from the AD. Then I call FindContactBySip and check if the provided SIP equals the Email or Phone of the User.
I have found two other ways to solve your problem.
In MSPL you can:
toContactCardInfo = QueryCategory(toUserUri, 0, "contactCard", 0);
Which gives you:
<contactCard xmlns=""http://schemas.microsoft.com/2006/09/sip/contactcard"" >
<identity >
<name >
<displayName >
Lync User</displayName>
</name>
<email >
lync.user#xxx.com</email>
</identity>
</contactCard>
You can turn the email address into a sip address. This only works if your lync setup uses email address for sip addresses.
The other method is to use 'P-Asserted-Identity' sip header to determine who the phone call is being routed to/from. The only problem is that it doesn't show up in the inital invites (as that would be for the From side anyway), but in the 180 ringing response from the Lync Client.
P-Asserted-Identity: <sip:lync.user#xxx.com>, <tel:+123456789;ext=12345>
So if you wait for the 180 ringing response then I would recommand that you use P-Asserted-Identity method and you don't even need to escape out of MSPL for it!

Google Analytics API in C# -Execution of request failed: https://www.google.com/analytics/feeds/accounts/default

i want to access Google analytic data and i got samples from Google data API SDK. but these coding does not working and throws exception
Execution of request failed: https://www.google.com/analytics/feeds/accounts/default
so i found the reason for this is Google updated it's to v3.0. i searched updated coding for the C#, but i couldn't find solution for this.
i have same problem as this, but with C#.
Exception thrown when using GData .NET Analytics API
i tried coding with doing changes as follows as it says in Google developer - https://developers.google.com/analytics/resources/articles/gdata-migration-guide#appendix_a
string userName = this.Username.Text;
string passWord = this.Password.Text;
AnalyticsService service = new AnalyticsService("AnalyticsSampleApp");
service.setUserCredentials(userName, passWord);
string googleAccountWebId = "AIXXXXXXXXXXXXXXXXXXXXXXXXXXX";
string profileFeedUrl = "https://www.googleapis.com/analytics/v2.4/data?key=" + googleAccountWebId;
DataQuery query2 = new DataQuery(profileFeedUrl);
query2.Ids = "12345678";
query2.Metrics = "ga:visits";
query2.Sort = "ga:visits";
query2.GAStartDate = DateTime.Now.AddMonths(-1).AddDays(-2).ToString("2011-08-01");
query2.GAEndDate = DateTime.Now.ToString("2013-09-01");
query2.StartIndex = 1;
DataFeed data = service.Query(query2);
foreach (DataEntry entry in data.Entries)
{
string st=entry.Metrics[0].Value;
}
but even i change this it throws exception in
DataFeed data = service.Query(query2);
this line. exception is as follows:
Execution of request failed: https://www.googleapis.com/analytics/v2.4/data?key=AIXXXXXXXXXXXXXXXXXXXXXX-8&start-index=1&end-date=2013-09-01&ids=12345678&metrics=ga:visits&sort=ga:visits&start-date=2011-08-01
i'm using following DLL
Google.GData.Analytics.dll
Google.GData.Client.dll
Google.GData.Extensions.dll
My Questions :
how can i correct this error?
how can i access Google analytic data? is this correct? or else what is the way to doing it??
for a example i want to get available ProfileId and their values. (Title and Page views)
Analytics Account:
I am assuming you have an analytics account already if you don't then create one, and sign up your domain here:
http://www.google.com/intl/en/analytics/
To get your API Key do this:
Follow the instructions on https://developers.google.com/analytics/resources/articles/gdata-migration-guide (Create a Project in the Google APIs Console) to generate your key Once you have it set it as part of the querystring to request to Google Analytics service, in this case:
YourAPIkEStringabcdefghijklmno
To get the profileId (Ids on the code) you should do this:
Log into your analytics account, select the desired domain on your list (blue link) click on the administrator button and on the profiles tab find the profile
configuration subtab, right there you will find the profile id in this case the eight characters long id:
12345678
Here you have some C# code to help you getting the number of visits for that Id:
public string VisitsNumber()
{
string visits = string.Empty;
string username = "youremailuser#domain.com";
string pass = "yourpassword";
string gkey = "?key=YourAPIkEYYourAPIkEYYourAPIkEYYourAPIkE";
string dataFeedUrl = "https://www.google.com/analytics/feeds/data" + gkey;
string accountFeedUrl = "https://www.googleapis.com/analytics/v2.4/management/accounts" + gkey;
AnalyticsService service = new AnalyticsService("WebApp");
service.setUserCredentials(username, pass);
DataQuery query1 = new DataQuery(dataFeedUrl);
query1.Ids = "ga:12345678";
query1.Metrics = "ga:visits";
query1.Sort = "ga:visits";
//You were setting 2013-09-01 and thats an invalid date because it hasn't been reached yet, be sure you set valid dates
//For start date is better to place an aprox date when you registered the domain on Google Analytics for example January 2nd 2012, for an end date the actual date is enough, no need to go further
query1.GAStartDate = new DateTime(2012, 1, 2).ToString("yyyy-MM-dd");
query1.GAEndDate = DateTime.Now.ToString("yyyy-MM-dd");
query1.StartIndex = 1;
DataFeed dataFeedVisits = service.Query(query1);
foreach (DataEntry entry in dataFeedVisits.Entries)
{
string st = entry.Title.Text;
string ss = entry.Metrics[0].Value;
visits = ss;
}
return visits;
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Response.Write("Visits:" + this.VisitsNumber());
}
}
Since the 2.4 API is not so flexible anymore, I have another post here hacking it to get the profile Id:
Getting an specific ProfileId from registered Accounts using GData .NET Analytics API 2.4 if you need to convert the code to C# you can use the Telerik converter: http://converter.telerik.com/
I think this suffice to use the 2.4 API. If you need extra help let me know.

Categories