LyncClient stuck in Sign In loop - lync-2013

I'm making "my own lync client". I've followed the several examples online about how to sign a lync client in using Ui Suppression mode. I can get the client to sign in but then it immediately loops through signing out and signing in.
What causes this?
2014-11-12 08:18:30.4381|DEBUG|LyncWpf.MainWindow|InitClient
2014-11-12 08:18:31.2021|DEBUG|LyncWpf.MainWindow|InitializeCallback
2014-11-12 08:18:31.2131|DEBUG|LyncWpf.MainWindow|StateChanged Uninitialized to Initializing
2014-11-12 08:18:31.2131|DEBUG|LyncWpf.MainWindow|StateChanged Initializing to SignedOut
2014-11-12 08:18:31.4221|DEBUG|LyncWpf.MainWindow|StateChanged SignedOut to SigningIn
2014-11-12 08:18:51.8631|DEBUG|LyncWpf.MainWindow|SigninCallback
2014-11-12 08:18:52.0151|DEBUG|LyncWpf.MainWindow|StateChanged SigningIn to SignedIn
2014-11-12 08:18:52.0211|INFO|LyncWpf.MainWindow|signed in!
2014-11-12 08:18:52.5451|DEBUG|LyncWpf.MainWindow|StateChanged SignedIn to SigningOut
2014-11-12 08:18:52.5591|DEBUG|LyncWpf.MainWindow|StateChanged SigningOut to SigningIn
2014-11-12 08:18:53.6051|DEBUG|LyncWpf.MainWindow|StateChanged SigningIn to SignedIn
2014-11-12 08:18:53.6071|INFO|LyncWpf.MainWindow|signed in!
...repeated forever
Code sample. Notice I don't call BeginSignIn again.
private void _client_StateChanged(object sender, ClientStateChangedEventArgs e)
{
this.Log().Debug("StateChanged {0} to {1}", e.OldState.ToString(), e.NewState.ToString());
switch (e.NewState)
{
case ClientState.SignedIn:
this.Log().Info("signed in!");
break;
case ClientState.SignedOut:
if (e.OldState == ClientState.Initializing)
((LyncClient) sender).BeginSignIn(null, null, null, SigninCallback, sender);
break;
}
}
private void InitClient()
{
this.Log().Debug("InitClient");
_client = LyncClient.GetClient(true);
if (_client.InSuppressedMode)
{
_client.StateChanged += _client_StateChanged;
if (_client.State == ClientState.Uninitialized)
{
Object[] asyncState = { _client };
_client.BeginInitialize(InitializeCallback, asyncState);
}
}
}
private void InitializeCallback(IAsyncResult ar)
{
this.Log().Debug("InitializeCallback");
if (ar.IsCompleted)
{
object[] asyncState = (object[])ar.AsyncState;
((LyncClient)asyncState[0]).EndInitialize(ar);
}
}
private void SigninCallback(IAsyncResult ar)
{
this.Log().Debug("SigninCallback");
if (ar.IsCompleted)
{
try
{
((LyncClient)ar.AsyncState).EndSignIn(ar);
}
catch (RequestCanceledException re)
{
this.Log().Warn("SignIn Request Cancelled {0}", re.Message);
throw;
}
}
}

I had the same problem on the second run of the application. In my case, it was because the Lync 2013 shutdown api doesn't work correctly and leaves a copy of lync in memory. When you run your app for the second time, it creates a new instance of ui suppressed mode lync and the two instances seem to fight with each to login.
I found the only way to fix this was to kill any background lync processes (i.e. has no main window handle).

Related

How can I reconnect a Photon Bolt client after it disconnects?

I'm trying to make a Photon Bolt game that connects two devices. The problem is that the Client tends to get disconnected a lot, an it doesn't reconnect automatically. I've tried using methods like ReconnectAndRejoin, but it seems like it only works in PUN. Right now I'm using this custom solution, without success:
[BoltGlobalBehaviour(BoltNetworkModes.Client)]
public class InitialiseGameClient : Photon.Bolt.GlobalEventListener
{
private bool disconnected;
public void Update(){
if(disconnected){
Reconnect();
}
}
public override void Disconnected(BoltConnection connection)
{
disconnected = true;
}
public void Reconnect(){
BoltLauncher.StartClient();
PlayerPrefs.DeleteAll();
if (BoltNetwork.IsRunning && BoltNetwork.IsClient)
{
foreach (var session in BoltNetwork.SessionList)
{
UdpSession udpSession = session.Value as UdpSession;
if (udpSession.Source != UdpSessionSource.Photon)
continue;
PhotonSession photonSession = udpSession as PhotonSession;
string sessionDescription = String.Format("{0} / {1} ({2})",
photonSession.Source, photonSession.HostName, photonSession.Id);
RoomProtocolToken token = photonSession.GetProtocolToken() as RoomProtocolToken;
if (token != null)
{
sessionDescription += String.Format(" :: {0}", token.ArbitraryData);
}
else
{
object value_t = -1;
object value_m = -1;
if (photonSession.Properties.ContainsKey("t"))
{
value_t = photonSession.Properties["t"];
}
if (photonSession.Properties.ContainsKey("m"))
{
value_m = photonSession.Properties["m"];
}
sessionDescription += String.Format(" :: {0}/{1}", value_t, value_m);
}
ServerConnectToken connectToken = new ServerConnectToken
{
data = "ConnectTokenData"
};
Debug.Log((int)photonSession.Properties["t"]);
var propertyID = PlayerPrefs.GetInt("PropertyID", 2);;
if((int)photonSession.Properties["t"] == propertyID){
BoltMatchmaking.JoinSession(photonSession, connectToken);
disconnected = false;
}
}
}
}
}
With this method I'm trying to use the same code used to connect the the client for the first time in the reconnect function, and keep trying until the client manages to connect. However it seems that the code never executes, even if the disconnect function gets triggered (the reconnect doesn't). Is there any Bolt integrated function that helps with reconnecting? Thanks in advance.
You need to shutdown bolt, then try reconnecting. Even if you don't get the below exception, it's just an example and you should shutdown and do BoltLauncher.StartClient() etc.
BoltException: Bolt is already running, you must call BoltLauncher.Shutdown() before starting a new instance of Bolt.

How to get Fiddler or Charles to capture traffic from Unity 2018 IL2CPP apps

I have built apps with Unity 5 and with Unity 2017, and am able to use Fiddler or Charles to capture network traffic successfully. However, When I build a Unity 2018 app using IL2CPP (the other apps were built with .Net), the app works (successfully sending network traffic), but the app seems to somehow bypass the Fiddler (or Charles) proxy. That is, Fiddler and Charles are unable to show the network traffic from the Unity 2018 IL2CPP app, even though it can show traffic from Unity 5 and Unity 2017 apps.
Note that everything works with Unity 5 and Unity 2017, and, that the SSL settings, etc. have been setup previously. Also, I have used the Fiddler "WinConfig" to EnableLoopback for the Unity 2018 app.
My question is: What do I need to do to get a Unity 2018 IL2CPP app to show traffic in Fiddler or Charles?
Update:
Here is some sample code that shows that HttpClient requests don't go through the proxy, but other (Unity) webrequests do go through the proxy:
public class RequestTest : MonoBehaviour
{
public UnityEngine.UI.Text text;
void Update()
{
if (Input.GetKeyUp(KeyCode.P))
{
StartCoroutine(yieldPing());
}
if (Input.GetKeyUp(KeyCode.O))
{
asyncPing();
}
}
private IEnumerator yieldPing()
{
Debug.Log("This request shows up in Fiddler");
text.text = "UWR in Coroutine";
using (UnityWebRequest uwr = UnityWebRequest.Get("https://www.google.com/"))
{
yield return uwr.SendWebRequest();
}
}
private async void asyncPing()
{
await awaitPing();
}
private async System.Threading.Tasks.Task<bool> awaitPing()
{
Debug.Log("This request also shows up in Fiddler");
UnityWebRequest uwr = UnityWebRequest.Get("https://www.google.com/");
text.text = "UWR in async await";
uwr.SendWebRequest().completed += delegate
{
uwr.Dispose();
};
Debug.Log("This request does NOT show up in Fiddler???");
text.text += "\nHttpClient in async await";
using (System.Net.Http.HttpClient httpClient = new System.Net.Http.HttpClient())
{
using (System.Net.Http.HttpRequestMessage httpRequest = new System.Net.Http.HttpRequestMessage())
{
httpRequest.RequestUri = new System.Uri("http://www.youtube.com/");
httpRequest.Method = System.Net.Http.HttpMethod.Get;
using (System.Net.Http.HttpResponseMessage httpResponse = await httpClient.SendAsync(httpRequest, System.Net.Http.HttpCompletionOption.ResponseHeadersRead))
{
var responseCode = (int)httpResponse.StatusCode;
// We will get a 304 if the content has not been modified
// If there is new, good content, then we will get a 200
return (responseCode == 200);
}
}
}
}
}
Here are the Unity Player Settings:
Unity has acknowledged that this is a problem:
https://fogbugz.unity3d.com/default.asp?1222589_u6qsndet3umnp50u
https://issuetracker.unity3d.com/issues/httpclient-ignores-windows-proxy
It appears that during the "IL2CPP" code generation process, the generated code changes the HttpClient to not use the local proxy.
The code below was copied from here, and seems to overcome the Unity IL2CPP bug:
// might be overly complicated, there is an option to wrap the existing proxy here...
class myWebProxy : System.Net.IWebProxy
{
private System.Net.IWebProxy wrappedProxy;
private System.Net.ICredentials creds;
private void init()
{
wrappedProxy = null;
creds = CredentialCache.DefaultCredentials;
}
public myWebProxy()
{
init();
}
public myWebProxy(System.Net.IWebProxy theWrappedProxy)
{
init();
wrappedProxy = theWrappedProxy;
}
public System.Net.ICredentials Credentials
{
get
{
if (wrappedProxy != null)
{
return wrappedProxy.Credentials;
}
else
{
return creds;
}
}
set
{
if (wrappedProxy != null)
{
wrappedProxy.Credentials = value;
}
else
{
creds = value;
}
}
}
public Uri GetProxy(Uri destination)
{
if (wrappedProxy != null /* todo or Uri == certain Uri */)
{
return wrappedProxy.GetProxy(destination);
}
else
{
// hardcoded proxy here..
return new Uri("http://seeplusplus:8080");
}
}
public bool IsBypassed(Uri host)
{
if (wrappedProxy != null)
{
return wrappedProxy.IsBypassed(host);
}
else
{
return false;
}
}
}
// in your code use your new proxy
HttpClientHandler aHandler = new HttpClientHandler();
// use your proxy!
aHandler.Proxy = new myWebProxy();
HttpClient client = new HttpClient(aHandler);

Stopping a Windows Service in the event of a critical error

I have a Windows Service which basically wraps a task:
public partial class Service : ServiceBase
{
private Task task;
private CancellationTokenSource cancelToken;
public Service()
{
InitializeComponent();
this.task = null;
this.cancelToken = null;
}
protected override void OnStart(string[] args)
{
var svc = new MyServiceTask();
this.cancelToken = new CancellationTokenSource();
this.task = svc.RunAsync(cancelToken.Token);
this.task.ContinueWith(t => this.OnUnhandledException(t.Exception), TaskContinuationOptions.OnlyOnFaulted);
}
protected override void OnStop()
{
if (this.task != null)
{
this.cancelToken.Cancel();
this.task.Wait();
}
}
private void OnUnhandledException(Exception ex)
{
this.EventLog.WriteEntry(string.Format("Unhandled exception: {0}", ex), EventLogEntryType.Error);
this.task = null;
this.Stop();
}
}
As you can see, the service can catch unhandled exceptions. If this happens, the exception is logged and the service is stopped. This has the effect of writing two messages to the event log - one error stating there was an unhandled exception, and another stating that the service was successfully stopped.
This may sound minor, but I'm hoping to be able to suppress the 'successfully stopped' message. I find it misleading - it suggests that the service stopping was a normal occurrence. Is there another way I can force the service to stop itself without this message being logged?

Facebook webview called twice in Android app

I'm testing my app on a device where the Facebook application is not installed.
So when I'm logging with Facebook, a webview is opened.
The strange this is that when I've inserted my username and password, after pressing ok a webview is reopened and I've to insert the username and password again and I can login.
What could be ?
authButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
authButton.setVisibility(View.GONE);
logoutButton.setVisibility(View.VISIBLE);
// start Facebook Login
Session.openActiveSession(Login.this, true, new Session.StatusCallback() {
// callback when session changes state
SharedPreferences.Editor edit = pref.edit();
#Override
public void call(Session session, SessionState state,
Exception exception) {
if (session.isOpened()) {
accesstoken = session.getAccessToken();
edit.putString("fbtoken", accesstoken);
if (session.getExpirationDate()!= null)
edit.putLong("com.facebook.sdk.AccessTokenExpires", session.getExpirationDate().getTime());
Log.d("FACEBOOK", "LOGGED IN");
}
});
List<String> permissions = session.getPermissions();
if (!isSubsetOf(PERMISSIONS, permissions)) {
Session.NewPermissionsRequest newPermissionsRequest = new Session.NewPermissionsRequest(
Login.this, PERMISSIONS);
session.requestNewReadPermissions(newPermissionsRequest);
return;
}
// make request to the /me API
Request.newMeRequest(session, new GraphUserCallback() {
#Override
public void onCompleted(GraphUser user, Response response) {
Log.d("FACEBOOK", "onCompleted");
Log.d("",""+user);
try {
name=user.getName();
email=user.getProperty("email").toString();
location=(user.getLocation().getProperty("name").toString());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.d("ID", user.getId());
}
}).executeAsync();
}
}
});
}
});
I've had the same problem on iOS so this problem could be linked.
I solved it by removing the delegate after I received the first response.
So it may be applicable in your exemple like this:
Session.openActiveSession(Login.this, true, new Session.StatusCallback() {
// callback when session changes state
if (logoutButton.getVisibility() == View.VISIBLE) {
// Its visible so we end the callback
return;
}
SharedPreferences.Editor edit = pref.edit();
My guess is that you're saving the access token into the shared pref,
and it needs some time to be saved on disk if you don't force it.
You should add
edit.putLong("com.facebook.sdk.AccessTokenExpires", ...);
edit.commit(); // <- this line
so you are sure that for the next call it will be available

Write to Event Log - The source was not found, but some or all event logs could not be searched. Inaccessible logs: Security."

I'am trying to write some messages to Windows Event log.
The (security) exception will be thrown when calling function "SourceExists()".
private bool CheckIfEventLogSourceExits()
{
try
{
if (!EventLog.SourceExists(this.BaseEventLog))
{
return false;
}
return true;
}
catch (System.Security.SecurityException)
{
return false;
}
}
All answers to this question are explaining how you can MANUALLY resolve issue.
Like here: Stackoverflow Thread. Solution would be changing some registry keys
But you can't expect that everyone who consumes your application is aware of these changes.
So my question is, how can we solve this issue programmatically?
Below my code:
try
{
string sLog = "Application";
if (CheckIfEventLogSourceExits())
{
EventLog.CreateEventSource(this.BaseEventLog, sLog);
}
EventLog.WriteEntry(this.BaseEventLog, message, eventLogEntryType);
}
catch (Exception ex)
{
ex.Source = "WriteToEventLog";
throw ex;
}
I know it's too late for this posting, but the answer, I found from similar experience, is that the service you're running under doesn't have administrative rights to the machine and, thus, can't write to the logs.
It's easy enough to figure out if an app is being run under admin rights. You can add something like this to your code with a message box advising the user to run "admin".
private void GetServicePermissionLevel()
{
bool bAdmin = false;
try {
SecurityIdentifier sidAdmin = new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null);
AppDomain myDomain = Thread.GetDomain();
myDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);
WindowsPrincipal myPrincipal = (WindowsPrincipal)Thread.CurrentPrincipal;
if (myPrincipal.IsInRole(sidAdmin)) {
bAdmin = true;
} else {
bAdmin = false;
}
} catch (Exception ex) {
throw new Exception("Error in GetServicePermissionlevel(): " + ex.Message + " - " + ex.StackTrace);
} finally {
_ServiceRunAsAdmin = bAdmin;
}
}