C# - Skype Auto Accept Contact Request - c#

So I'm currently working on a Skype bot thing, I wish it could automatically accept contact request so I don't have to do them manually, any idea how?
And while I was researching, I found this
ichat.AcceptAdd();
Any idea what does that do?

I don't know if I understood what you want to accomplish..
Do you want to accept contact requests automatically? Really? Do you like being target for hackers, spammers, etc? :)
Anyway, if that's what you want to do, you can subscribe to the UserAuthorizationRequestReceived event:
var events = (_ISkypeEvents_Event) _skype;
events.UserAuthorizationRequestReceived += UserAuthorizationRequestReceived;
try
{
_skype.Attach(8);
}
catch(COMException ce)
{
RaiseErrorEvent("Unable to attach to skype.", ce);
}
private void UserAuthorizationRequestReceived(SKYPE4COMLib.User puser)
{
if (do some user check here?? )
{
puser.IsAuthorized = true;
}
}
Hope this helps.

Related

Check for internet connectivity from Unity

I have a Unity project which I build for Android and iOS platforms. I want to check for internet connectivity on Desktop, Android, and iOS devices. I've read about three different solutions:
Ping something (for example Google) - I totally dislike such decision, and I've read about mistakes on Android.
Application.internetReachability - According to Unity's documentation, this function will only determine that I have a POSSIBILITY of connecting to the Internet (it doesn't guarantee a real connection).
Network.TestConnection() - If I have no Internet connection, my application fails. So this isn't correct either.
How can I determine whether I have internet connectivity from within Unity?
I don't actually believe that Network.TestConnection() is the right tool for this job. According to the documentation, it looks to me like it's meant for testing if NAT is working and your client is publicly reachable by IP, but what you want to check for is whether you have general internet connectivity.
Here is a solution that I found on Unity Answers by user pixel_fiend, which simply tests a website to see if the user has connectivity. One benefit of this code is that it uses IEnumerator for asynchronous operation, so the connectivity test won't hold up the rest of your application:
IEnumerator checkInternetConnection(Action<bool> action){
WWW www = new WWW("http://google.com");
yield return www;
if (www.error != null) {
action (false);
} else {
action (true);
}
}
void Start(){
StartCoroutine(checkInternetConnection((isConnected)=>{
// handle connection status here
}));
}
You can change the website to whatever you want, or even modify the code to return success if any one of a number of sites are reachable. AFAIK there is no way to check for true internet connectivity without trying to connect to a specific site on the internet, so "pinging" one or more websites like this is likely to be your best bet at determining connectivity.
public static IEnumerator CheckInternetConnection(Action<bool> syncResult)
{
const string echoServer = "http://google.com";
bool result;
using (var request = UnityWebRequest.Head(echoServer))
{
request.timeout = 5;
yield return request.SendWebRequest();
result = !request.isNetworkError && !request.isHttpError && request.responseCode == 200;
}
syncResult(result);
}
void Start()
{
StartCoroutine(CheckInternetConnection(isConnected =>
{
if (isConnected)
{
Debug.Log("Internet Available!");
}
else
{
Debug.Log("Internet Not Available");
}
}));
}
IEnumerator CheckInternetConnection(Action<bool> action)
{
UnityWebRequest request = new UnityWebRequest("http://google.com");
yield return request.SendWebRequest();
if (request.error != null) {
Debug.Log ("Error");
action (false);
} else{
Debug.Log ("Success");
action (true);
}
}
Since WWW has deprecated, UnityWebRequest can be used instead.
i know this is old, but maybe can help you.
public bool CheckInternetConnection(){
return !(Application.internetReachability == NetworkReachability.NotReachable)
}
Ping 8.8.8.8 instead of sending a GET
unity already provides the tool for that:
Ping
The ping operation is asynchronous and a ping object can be polled for
status using Ping.isDone. When a response is received it is in
Ping.time.
Windows Store Apps: A stream socket is used to mimic ping
functionality, it will try to open a connection to specified IP
address using port 80. For this to work correctly, InternetClient
capability must be enabled in Package.appxmanifest.
Android: ICMP sockets are used for ping operation if they're
available, otherwise Unity spawns a child process /system/bin/ping for
ping operations. To check if ICMP sockets are available, you need to
read the contents for /proc/sys/net/ipv4/ping_group_range. If ICMP
sockets are available, this file should contain an entry for 0
2147483647.
using UnityEngine;
using System.Collections.Generic;
public class PingExample : MonoBehaviour
{
bool isConnected = false;
private IEnumerator Start()
{
while(true)
{
var ping = new Ping("8.8.8.8");
yield return new WaitForSeconds(1f);
while (!ping.isDone)
{
isConnected = false;
yield return null;
}
isConnected = true;
Debug.Log(ping.time);
}
}
}
I've created an Android's library that can be used as Unity's plugin for this purpose. If anyone's interested it's available under https://github.com/rixment/awu-plugin
As for the iOS version unfortunately I don't have enough of knowledge in this area. It would be nice if someone could extend the repo to include the iOS version too.
With the latest version of Unity, WWW has become obsolete, hence you need to use WebRequest.
This is the bit of codes I'm using to check if the user is online:
private string HtmlLookUpResult_Content;
private char[] HtmlLookUpResult_Chars;
private StreamReader HtmlLookUpResult_Reader;
private bool HtmlLookUpResult_isSuccess;
private HttpWebRequest HtmlLookUpResult_Request;
private HttpWebResponse HtmlLookUpResult_Response;
public bool CheckIfOnline()
{
HtmlLookUpResult_Content = UniversalEnum.String_Empty;
HtmlLookUpResult_Request = (HttpWebRequest)WebRequest.Create(UniversalEnum.WebHtml_isOnline);
HtmlLookUpResult_Request.Timeout = 5000;
try
{
using (HtmlLookUpResult_Response = (HttpWebResponse)HtmlLookUpResult_Request.GetResponse())
{
HtmlLookUpResult_isSuccess = (int)HtmlLookUpResult_Response.StatusCode < 299 && (int)HtmlLookUpResult_Response.StatusCode >= 200;
if (HtmlLookUpResult_isSuccess)
{
using (HtmlLookUpResult_Reader = new StreamReader(HtmlLookUpResult_Response.GetResponseStream()))
{
HtmlLookUpResult_Chars = new char[1];
HtmlLookUpResult_Reader.Read(HtmlLookUpResult_Chars, 0, 1);
HtmlLookUpResult_Content += HtmlLookUpResult_Chars[0];
}
}
}
}
catch
{
HtmlLookUpResult_Content = UniversalEnum.String_Empty;
}
if (HtmlLookUpResult_Content != UniversalEnum.String_Empty)
{
return true;
}
else
{
return false;
}
}
If you would like to know if the user is just online, you can get the result just from the boolean HtmlLookUpResult_isSuccess in the code. But, in reality, you most likely want to confirm the user has also access to your server or whatever remote system you use in your project, right? Which is what the remaining of the code does.
In case you wonder what UniversalEnum is, in my code, it's a separate non-Monobehavior script that contains all persistent variables (like strings and hashes) I'm planning on reusing in my project. For short:
UniversalEnum.String_Empty = "";
UniversalEnum.WebHtml_isOnline = "http://www.ENTER_YOUR_WEBSITE_HERE.com/games-latestnews/isOnline.html"
That isOnline.html file is, as you can see, a file in the folder "games-latestnews" in the HTML_content of my hosted website and it contains only [1] as it content. It has no header, no actual content and is pretty much like a .txt file set online. I'm using this method also because I can add new news to my game by just adding new HTML page in that folder. I'm also surrounding the content check with a Try{} so that if ANYTHING fails, it returns the Catch{} value and then by comparing if the content (a string) is an empty string or contain anything, we know if the user is both online and if he/she has access to your website.
On good example of why you would want to check that the user has both access to the net AND to your website is if the user is using a limited network such as what you might find at a school. If a school decided to ban your website due to whatever reason, just looking up if the connection is possible will return a false positive since it wouldn't access the actual webpage anyway.
You can check network connection using this code
if(Application.internetReachability == NetworkReachability.NotReachable){
Debug.Log("Error. Check internet connection!");
}

Using the Lync 2013 SDK in a multithreaded application

I want to use the Lync 2013 SDK in a WPF application to query contact availability, although I’m seeing some strange behaviour. I suspect this is because of the way I am calling it from many threads at a time, although not sure of the best approach to resolve this.
I have a custom UserControl for displaying contact information for people within our company. I load a collection of these controls into a single form based on a search query. Each contact control will load detailed information about the contact on creation, using the ThreadPool to apply some throttling. All information up until this point is coming from AD, which has been working well.
Now I want to show the contact availability status of each contact. I have put together this code, which has been modified from another post.
private LyncClient _lyncClient;
private ContactSubscription _contactSubscription;
private void GetContactAvailability(string sip)
{
if (!String.IsNullOrEmpty(sip))
{
_lyncClient = LyncClient.GetClient();
if (_lyncClient.State == ClientState.SignedIn)
{
_lyncClient.ContactManager.BeginSearch(
sip,
SearchProviders.Default,
SearchFields.EmailAddresses,
SearchOptions.ContactsOnly,
1,
BeginSearchCallback,
new object[] {_lyncClient.ContactManager, sip});
}
}
}
private void BeginSearchCallback(IAsyncResult r)
{
var asyncState = (object[]) r.AsyncState;
var cm = (ContactManager) asyncState[0];
var results = cm.EndSearch(r);
if (results.AllResults.Count > 0)
{
Debug.WriteLine(results.Contacts.Count);
Microsoft.Lync.Model.Contact contact = results.Contacts[0];
UpdateLyncStatus(contact);
_contactSubscription = cm.CreateSubscription();
_contactSubscription.AddContact(contact);
contact.ContactInformationChanged += contact_ContactInformationChanged;
ContactInformationType[] contactInformationTypes = {ContactInformationType.Availability};
_contactSubscription.Subscribe(ContactSubscriptionRefreshRate.High, contactInformationTypes);
}
}
private void contact_ContactInformationChanged(object sender, ContactInformationChangedEventArgs e)
{
var contact = (Microsoft.Lync.Model.Contact) sender;
UpdateLyncStatus(contact);
}
private void UpdateLyncStatus(Microsoft.Lync.Model.Contact contact)
{
if ((_lyncClient != null) && (_lyncClient.State == ClientState.SignedIn))
{
UpdateLyncStatus((ContactAvailability) contact.GetContactInformation(ContactInformationType.Availability));
}
}
If my search form returns only a single result, then this code seems to work every time to successfully return the availability status for a single contact control. If I do a more generic search, such as “John” (which returns 50+ results), only a few (if any) of the contacts show the availability status. The code doesn’t generate any exceptions, it just doesn’t work.
If I repeat the search for “John” again, then all of the contacts will show an availability status. I suspect these statuses are cached from the previous Lync search, which is great, but how do I get them to show in the first search?
Is there a better way to use the Lync SDK in a multithreaded application?

C# - SignalR How can I remove my event handler

I am a C# newbie trying to implement SignalR in my Xamarin IOS app.
My code is quite simple:
_connection = new Microsoft.AspNet.SignalR.Client.Hubs.HubConnection (Common.signalRAddress);
feedHub = _connection.CreateHubProxy ("feedHub");
_connection.Received += data => { OnReceiveData (data); };
_connection.Start ();
my question is how can I remove my delegate?
Is it enough to write?
_connection.Received -= data => { OnReceiveData (data); };
Any help would be really appreciated.
You're using a hub, why not use the built in on/off for method invocations?
aka:
var doSomething = feeHub.On<int>("doSomething", val => {
// Do something with int val
});
Then to remove it you can do:
doSomething.Dispose();
If you truly want to listen to ALL data that flows through the hub then using Received is the correct approach and #Dracanus' answer will work.
I might be wrong, but if you do that it won't actually unsubscribe the event.
It didn't in a little test app I wrote anyways.
Instead create a function such as
void Connection_Recieved(string obj)
{
}
and do connection.Recieved += Connection_Recieved;
and connection.Recieved -= Connection_Recieved;
I don't think anonymous event functions are the way to go here :)
I am assuming, looking at your code sample you could just do,
connection.Recieved += OnReceiveData;
connection.Recieved -= OnReceiveData;

C# read/write mifare nfc tag

I've searched a lot but I'm not able to find some C# simple sdk that lets me write and read in a nfc mifare 1k classic tags.
Could you give me some help please?
Thanks a lot.
Just check my library for ACR122u readers. It also supports insert/discard events. It is so simple to use it. Basically you create a class and register two events to that class. Afterwards, call the Watch function. It watches the changes on your device.
//Initializing
NFCReader NFC = new NFCReader();
//Inserted Event
NFC.CardInserted += new NFCReader.CardEventHandler(...Some function);
//Ejected Event
NFC.CardEjected += new NFCReader.CardEventHandler(... Some function);
//Enabling Event Watching
NFC.Watch();
If any change occurs, it calls the related event. You handle what you want to do there.
public void Card_Inserted()
{
try
{
if (NFC.Connect())
{
//Do stuff like NFC.GetCardUID(); ...
}
else
{
//Give error message about connection...
}
}
catch (Exception ex)
{
//Something went wrong
}
}
public void Card_Ejected()
{
//Do stuff...
NFC.Disconnect();
}
See the related repo and links for more information.
Medium introduction tutorial:
https://medium.com/#hakbas/nfcreader-a-very-simple-nfc-library-for-c-that-supports-insert-and-discard-events-93db29f79b5
Github address:
https://github.com/h4kbas/NfcReader

Detect Office Communicator Audio Call

What im trying to do is a functionality that will advice users that make
audio calls in office communicator over a wireless connection to use a
wired connection instead.
i have been looking around but have not been able to find the info im searching for
Im looking for a way to detect if Office Communicator is in an Audio call.
is there an easy way to do this?
I don't think you'll be able to get exactly what you need with Communicator, but you can get close. (you could probably get even closer, or all the way there, if you were to upgrade to Lync).
You'll need to use the Automation API - documentation here, download here.
First thing to try is catching the users status changes:
MessengerClass _communicator;
public Form1()
{
InitializeComponent();
_communicator = new MessengerClass();
_communicator.OnMyStatusChange += new DMessengerEvents_OnMyStatusChangeEventHandler(_communicator_OnMyStatusChange);
}
void _communicator_OnMyStatusChange(int hr, MISTATUS mMyStatus)
{
AddText(string.Format("My Status changed to '{0}'", mMyStatus));
}
You're looking for a status of MISTATUS_ON_THE_PHONE
The downside of this is that certain statuses will override the MISTATUS_ON_THE_PHONE status. e.g. if the user is set to "Online", and then makes or receives a call, the status will change to MISTATUS_ON_THE_PHONE. But if their status is set to "Do not Disturb" and they make or receive a call, the status will NOT change to MISTATUS_ON_THE_PHONE.
You can maybe work around this a bit by examining the call as it is created. Catching a new conversation window being created is fairly straightforward:
_communicator = new MessengerClass();
_communicator.OnIMWindowCreated += new DMessengerEvents_OnIMWindowCreatedEventHandler(_communicator_OnIMWindowCreated);
Problem is, this will fire for IM and AV conversations, and also for incoming conversations as well as outgoing. There is no way to directly detect whether the call is an outgoing audio call.
You can also catch the "Contact Added" event, this will give you some info about which recipients get added to the conversation, and when. It's possible that the order in which this happens will give you some info as to whether its outgoing or incoming, and you could look for "tel:" uri's being added to tell you if the call is to a phone (although this won't help for communicator to communicator calls)
_communicator.OnIMWindowContactAdded += new DMessengerEvents_OnIMWindowContactAddedEventHandler(_communicator_OnIMWindowContactAdded);
The best thing to do is to have a play around with the events, and see what happens under which circumstances. This code should get you up and running with that.
MessengerClass _communicator;
public Form1()
{
InitializeComponent();
_communicator = new MessengerClass();
_communicator.OnIMWindowCreated += new DMessengerEvents_OnIMWindowCreatedEventHandler(_communicator_OnIMWindowCreated);
_communicator.OnIMWindowDestroyed += new DMessengerEvents_OnIMWindowDestroyedEventHandler(_communicator_OnIMWindowDestroyed);
_communicator.OnIMWindowContactAdded += new DMessengerEvents_OnIMWindowContactAddedEventHandler(_communicator_OnIMWindowContactAdded);
_communicator.OnIMWindowContactRemoved += new DMessengerEvents_OnIMWindowContactRemovedEventHandler(_communicator_OnIMWindowContactRemoved);
_communicator.OnMyStatusChange += new DMessengerEvents_OnMyStatusChangeEventHandler(_communicator_OnMyStatusChange);
}
void _communicator_OnMyStatusChange(int hr, MISTATUS mMyStatus)
{
AddText(string.Format("My Status changed to '{0}'", mMyStatus));
}
void _communicator_OnIMWindowContactRemoved(object pContact, object pIMWindow)
{
AddText(string.Format("{0} - Participant removed - '{1}'", ((IMessengerConversationWndAdvanced)pIMWindow).HWND, ((IMessengerContactAdvanced)pContact).SigninName));
}
void _communicator_OnIMWindowContactAdded(object pContact, object pIMWindow)
{
AddText(string.Format("{0} - Participant added - '{1}'", ((IMessengerConversationWndAdvanced)pIMWindow).HWND, ((IMessengerContactAdvanced)pContact).SigninName));
}
void _communicator_OnIMWindowDestroyed(object pIMWindow)
{
AddText(string.Format("{0} Conversation Closed, duration = {1}", ((IMessengerConversationWndAdvanced)pIMWindow).HWND, (DateTime.Now - _start).ToString()));
}
void _communicator_OnIMWindowCreated(object pIMWindow)
{
try
{
AddText(string.Format("{0} Conversation Created", ((IMessengerConversationWndAdvanced)pIMWindow).HWND));
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private delegate void AddTextDelegate(string text);
private void AddText(string text)
{
if (textBox1.InvokeRequired)
{
textBox1.Invoke(new AddTextDelegate(AddText), text);
return;
}
textBox1.Text += text + "\r\n";
}
By the way, don't forget to accept this as the answer using the "tick", if you feel that it helped :)

Categories

Resources