Invalid cross-thread access from XNA GamerService - c#

I am asking the user of my app per the XNA GamerService dialog-box, if he really wants to delete a specific product.
And if he presses yes, this will take action:
private void OnMessageBoxAction(IAsyncResult ar)
{
int? selectedButton = Guide.EndShowMessageBox(ar);
switch (selectedButton)
{
case 0:
WebClient cweight = new WebClient();
cweight.Encoding = System.Text.Encoding.GetEncoding("ISO-8859-1");
cweight.Credentials = new NetworkCredential(op.username, op.userpass);
cweight.DownloadStringCompleted += new DownloadStringCompletedEventHandler(deleted);
cweight.DownloadStringAsync(new Uri("http://mydomain.com"));
break;
case 1:
Debug.WriteLine("1 pressed");
break;
default:
Debug.WriteLine("default pressed");
break;
}
}
and when the download completes, I invoke the login method:
private void deleted(object sender, DownloadStringCompletedEventArgs e)
{
Debug.WriteLine("\n[#] deleted");
if (e.Error != null)
{
Debug.WriteLine("Delete problem");
}
Debug.WriteLine("Delete successful");
login(null, null);
}
later on at login I get the invalid cross-thread access at globalprogress.Visibility = System.Windows.Visibility.Visible; and I am pretty sure, that that error would occur through the whole login method.

Handy class:
public class SmartDispatcher
{
public static void BeginInvoke(Action action)
{
if (Deployment.Current.Dispatcher.CheckAccess()
|| DesignerProperties.IsInDesignTool)
{
action();
}
else
{
Deployment.Current.Dispatcher.BeginInvoke(action);
}
}
}

Related

While pressing enter key it should display same menu

I am displaying menu in the console based application using C#. I want that if user press enter key then it should display same menu. Application should not break. I am new to C#
If anyone has idea please share it. It will be helpful to me.
Below is the code.
public static void HospitalMenu()
{
string answer = "";
do
{
Console.Clear();
Console.WriteLine("=============Hospital Management System===================");
Console.WriteLine("1...............Add Patient Information");
Console.WriteLine("2...............Modify Patient Information");
Console.WriteLine("3...............Add Patient Treatment Information");
Console.WriteLine("4...............View Patient History");
Console.WriteLine("5...............Search Patient Info");
Console.WriteLine("6...............Generate Lab Report");
Console.WriteLine("7...............Generate Medical Bills");
Console.WriteLine("8...............Exit");
Console.WriteLine("Select option (between 1 to 8)");
int option = Convert.ToInt32(Console.ReadLine());
switch (option)
{
case 1:
Patient.InsertPatient();
break;
case 2:
Patient.UpdatePatient();
break;
case 3:
PatientTreatment();
break;
case 4:
ViewMenu();
break;
case 5:
SearchMenu();
break;
case 6:
LabMenu();
break;
case 7:
BillMenu();
break;
default:
Environment.Exit(0);
break;
}
Console.WriteLine("Do you want to continue ? (Enter y if yes)");
answer = Console.ReadLine();
} while (answer == "y" || answer == "Y");
}
Thanks in advance.
I'll suggest some changes in your code.
Let's create an Interface that you'll be a contract responsible to show and handle inputs
IMenuHandler.cs
public interface IMenuHandler<TInput>
{
void Show( Action stopApplicationHandler, IMenuHandler<TInput> callerMenu=null);
void HandleInput(TInput input, Action stopApplication, IMenuHandler<TInput> callerMenu);
}
Then let's create your menus.. .
As an example you'll create two, you should modify it for your needs.
MainMenu.cs
public class MainMenu:IMenuHandler<ConsoleKeyInfo>
{
public void Show(Action stopApplicationHandler, IMenuHandler<ConsoleKeyInfo> callerMenu = null)
{
Console.Clear();
Console.WriteLine("=============Hospital Management System===================");
Console.WriteLine("1...............Add Patient Information");
Console.WriteLine("2...............Modify Patient Information");
Console.WriteLine("3...............Add Patient Treatment Information");
Console.WriteLine("4...............View Patient History");
Console.WriteLine("5...............Search Patient Info");
Console.WriteLine("6...............Generate Lab Report");
Console.WriteLine("7...............Generate Medical Bills");
Console.WriteLine("8...............Exit");
Console.WriteLine("Select option (between 1 to 8)");
HandleInput(Console.ReadKey(), stopApplicationHandler, callerMenu ?? this);
}
public void HandleInput(ConsoleKeyInfo input, Action stopApplication, IMenuHandler<ConsoleKeyInfo> callerMenu)
{
switch (input.Key)
{
case ConsoleKey.D1:
new HelpMenu().Show(stopApplication, callerMenu);
break;
case ConsoleKey.D8:
stopApplication.Invoke();
break;
default:
Show(stopApplication, this);
break;
}
}
}
HelpMenu.cs
public class HelpMenu:IMenuHandler<ConsoleKeyInfo>
{
public void Show(Action stopApplicationHandler, IMenuHandler<ConsoleKeyInfo> callerMenu = null)
{
Console.Clear();
Console.WriteLine("Help Menu Example...");
Console.WriteLine("1...............Go back");
Console.WriteLine("2...............Exit");
HandleInput(Console.ReadKey(), stopApplicationHandler, callerMenu );
}
public void HandleInput(ConsoleKeyInfo input, Action stopApplication, IMenuHandler<ConsoleKeyInfo> callerMenu)
{
Console.WriteLine("Help menu handler...");
switch (input.Key)
{
case ConsoleKey.D1:
callerMenu.Show(stopApplication, this);
break;
case ConsoleKey.D2:
stopApplication.Invoke();
break;
default:
Show(stopApplication, callerMenu);
break;
}
}
}
Now we are going to create an wrapper for your application.
Application.cs
public class Application
{
public delegate void OnStopApplicationRequestHandler();
public event OnStopApplicationRequestHandler StopApplicationRequest;
private readonly CancellationTokenSource _cancellationTokenSource;
public Application(CancellationToken? cancellationToken=null, OnStopApplicationRequestHandler? stopApplicationRequestHandler=null)
{
_cancellationTokenSource = cancellationToken != null
? CancellationTokenSource.CreateLinkedTokenSource(cancellationToken.Value)
: new CancellationTokenSource();
StopApplicationRequest += stopApplicationRequestHandler ?? ConfigureDefaultStopApplicationRequestHandler();
}
private OnStopApplicationRequestHandler ConfigureDefaultStopApplicationRequestHandler()
=> () =>
{
Console.WriteLine("Stopping application...");
_cancellationTokenSource.Cancel();
};
public void Run()
{
try
{
while (!_cancellationTokenSource.Token.IsCancellationRequested)
new MainMenu().Show(Stop);
Console.WriteLine("Program has been stopped");
}
//.... You should handle other custom exceptions here
catch (Exception ex)
{
// I'll assume that you will stop your application case it hits this unhandled exception
Console.WriteLine(ex);
Stop();
}
}
private void Stop()
{
StopApplicationRequest?.Invoke();
}
}
Note that this class has an event that will be responsible to handle the application exits.
You should modify it for your needs.
Last but not least
Call your application wrapper in your Program.cs
internal class Program
{
static void Main(string[] args)
{
new Application().Run();
}
}
PS: Don't forget the correct usings....
Hope this helps

Admob banner is invisible but still clickable in Unity

I'm working on an app that displays a banner depending on the scene. I use Show and Hide to control this behavior.
It works perfectly the first time that the banner is shown, but the second (after being hidden) the banner does not appear. However, the banner zone still clickable and it performs as expected.
I'm using the last release of the AdMob plugin for unity (v3.15.1) and I have not been able of finding any solution to the problem.
This is my code:
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using GoogleMobileAds;
using GoogleMobileAds.Api;
public class AdsManager //Ads information: https://developers.google.com/admob/unity (see left menu fo detailed info of each ad type)
{
public static AdsManager instance;
public BannerView bannerAd;
public InterstitialAd interstitialAd;
public RewardBasedVideoAd rewardedVideoAd;
#if UNITY_EDITOR
private static String appId = "unused";
private static String bannerAdId = "unused";
private static String interistitialAdId = "unused";
private static String rewardedVideAdId = "TBD";
#elif UNITY_ANDROID
private static String appId = "ca-app-pub-6685658831663319~7807395346";
private static String bannerAdId = "ca-app-pub-3940256099942544/6300978111"; //"ca-app-pub-6685658831663319/9607562172";
private static String interistitialAdId = "ca-app-pub-3940256099942544/1033173712"; //"ca-app-pub-6685658831663319/4875778545";
private static String rewardedVideAdId = "ca-app-pub-3940256099942544/5224354917"; //"ca-app-pub-6685658831663319/2971919290";
#elif UNITY_IOS
private static String appId = "ca-app-pub-6685658831663319~7807395346";
private static String bannerAdId = "ca-app-pub-6685658831663319/9607562172";
private static String interistitialAdId = "ca-app-pub-6685658831663319/4875778545";
private static String rewardedVideAdId = "ca-app-pub-6685658831663319/2971919290";
#else
private static String appId = "unexpected_platform";
private static String bannerAdId = "unexpected_platform";
private static String interistitialAdId = "unexpected_platform";
private static String rewardedVideAdId = "unexpected_platform";
#endif
public enum TypeOfAd
{
Banner,
Interestitial,
RewardedVideo
}
public AdsManager()
{
Debug.Log("Initializing a new AdsManager.");
if (instance == null)
{
instance = this;
Setup();
Debug.Log("AdsManager initialization successful.");
}
else
{
Debug.Log("AdsManager already exists. New initialization unsuccessful.");
}
}
private void Setup()
{
// Initialize the Google Mobile Ads SDK.
MobileAds.Initialize(appId);
this.bannerAd = new BannerView(bannerAdId, AdSize.SmartBanner, AdPosition.Bottom); //Info to chang banner size: https://developers.google.com/admob/unity/banner#banner_sizes
SetupBannerEventHandlers();
this.interstitialAd = new InterstitialAd(interistitialAdId);
SetupInterstitialEventHandlers();
this.rewardedVideoAd = RewardBasedVideoAd.Instance;
SetupRewardedVideoAdsEventHandlers();
//Load firsts ads
instance.LoadAd(TypeOfAd.Interestitial);
instance.LoadAd(TypeOfAd.Banner);
}
private void SetupBannerEventHandlers()
{
this.bannerAd.OnAdLoaded += HandlerOnBannerAdLoaded;
this.bannerAd.OnAdFailedToLoad += HandlrOnBannerAdFailedToLoad;
this.bannerAd.OnAdOpening += HandlerOnBannerAdOpening;
this.bannerAd.OnAdClosed += HandlerOnBannerAdClosed;
this.bannerAd.OnAdLeavingApplication += HandlerOnBannerAdLeavingApplication;
}
private void SetupInterstitialEventHandlers()
{
this.interstitialAd.OnAdLoaded += HandlerOnInterstitialAdLoaded;
this.interstitialAd.OnAdFailedToLoad += HandlerOnInterstitialAdFailedToLoad;
this.interstitialAd.OnAdOpening += HandlerOnInterstitialAdOpening;
this.interstitialAd.OnAdClosed += HandlerOnInterstitialAdClosed;
this.interstitialAd.OnAdLeavingApplication += HandlerOnInterstitialAdLeavingApplication;
}
private void SetupRewardedVideoAdsEventHandlers()
{
this.rewardedVideoAd.OnAdLoaded += HandlerRewardVideoAdLoaded;
this.rewardedVideoAd.OnAdFailedToLoad += HandlerRewardVideoAdFailedToLoad;
this.rewardedVideoAd.OnAdOpening += HandlerRewardVideoAdOpening;
this.rewardedVideoAd.OnAdStarted += HandlerRewardVideoAdStarted;
this.rewardedVideoAd.OnAdRewarded += HandlerRewardVideoAdRewarded;
this.rewardedVideoAd.OnAdClosed += HandlerRewardVideoAdClosed;
this.rewardedVideoAd.OnAdLeavingApplication += HandlerRewardVideoAdLeftApplication;
}
public void LoadAd(TypeOfAd typeOfAd)
{
if (DataManager.instance.showAds)
switch (typeOfAd)
{
case TypeOfAd.Banner:
Debug.Log("Loading Banner ad");
this.bannerAd.LoadAd(new AdRequest.Builder().Build()); //After loading it, it will be automatically displayed
break;
case TypeOfAd.Interestitial:
Debug.Log("Loading Interestitial ad");
if (!this.interstitialAd.IsLoaded())
this.interstitialAd.LoadAd(new AdRequest.Builder().Build());
break;
case TypeOfAd.RewardedVideo:
Debug.Log("Loading RewardedVideo ad");
if (!this.rewardedVideoAd.IsLoaded())
this.rewardedVideoAd.LoadAd(new AdRequest.Builder().Build(), rewardedVideAdId);
break;
}
}
public bool ShowAd(TypeOfAd typeOfAd)
{
if (DataManager.instance.showAds)
switch (typeOfAd)
{
case TypeOfAd.Banner:
Debug.Log("Showing Banner ad");
this.bannerAd.Show(); //No avaliable check to know if the ad has been loaded...
return true; //...so maybe the return is true but the ad is not being displayed because it was not loaded before.
case TypeOfAd.Interestitial:
Debug.Log("Showing Interestitial ad");
if (this.interstitialAd.IsLoaded())
{
this.interstitialAd.Show();
return true;
}
else
{
Debug.LogWarning("Trying to show InterstitialAd but it is not loaded");
//TBD: Automaitcally load?
}
break;
case TypeOfAd.RewardedVideo:
Debug.Log("Showing RewardedVideo ad");
if (this.rewardedVideoAd.IsLoaded())
{
this.rewardedVideoAd.Show();
return true;
} else {
Debug.LogWarning("Trying to show RewardedBasedVideoAd but it is not loaded");
//TBD: Automaitcally load?
}
break;
}
return false;
}
public void QuitAd(TypeOfAd typeOfAd)
{
switch (typeOfAd)
{
case TypeOfAd.Banner:
Debug.Log("Quiting Banner ad");
bannerAd.Hide();
break;
case TypeOfAd.Interestitial:
Debug.Log("Quiting Interestitial ad");
Debug.LogError("QuitAd Interestitial Not Implemented");
break;
case TypeOfAd.RewardedVideo:
Debug.Log("Quiting RewardedVideo ad");
Debug.LogError("QuitAd RewardedVideo Not Implemented");
break;
}
}
//BANNER EVENT HANDLERS
public void HandlerOnBannerAdLoaded(object sender, EventArgs args) { } // Called when an ad request has successfully loaded.
public void HandlrOnBannerAdFailedToLoad(object sender, AdFailedToLoadEventArgs args) { Debug.LogWarning("Banner failed to load: " + args.Message); LoadAd(TypeOfAd.Banner); } // Called when an ad request failed to load.
public void HandlerOnBannerAdOpening(object sender, EventArgs args) { } // Called when an ad is clicked.
public void HandlerOnBannerAdClosed(object sender, EventArgs args) { } // Called when the user returned from the app after an ad click.
public void HandlerOnBannerAdLeavingApplication(object sender, EventArgs args) { } // Called when the ad click caused the user to leave the application.
//INTERSTITIAL EVENT HANDLERS
public void HandlerOnInterstitialAdLoaded(object sender, EventArgs args) { } // Called when an ad request has successfully loaded.
public void HandlerOnInterstitialAdFailedToLoad(object sender, AdFailedToLoadEventArgs args) { Debug.LogWarning("Interstitial failed to load: " + args.Message); LoadAd(TypeOfAd.Interestitial); } // Called when an ad request failed to load.
public void HandlerOnInterstitialAdOpening(object sender, EventArgs args) { } // Called when an ad is shown.
public void HandlerOnInterstitialAdClosed(object sender, EventArgs args) { } // Called when the ad is closed.
public void HandlerOnInterstitialAdLeavingApplication(object sender, EventArgs args) { } // Called when the ad click caused the user to leave the application.
//REWARDED VIDEO AD EVENT HANDLERS
public void HandlerRewardVideoAdLoaded(object sender, EventArgs args) { } // Called when an ad request has successfully loaded.
public void HandlerRewardVideoAdFailedToLoad(object sender, AdFailedToLoadEventArgs args) { Debug.LogWarning("RewardedVideo failed to load: " + args.Message); LoadAd(TypeOfAd.RewardedVideo); } // Called when an ad request failed to load.
public void HandlerRewardVideoAdOpening(object sender, EventArgs args) { } // Called when an ad is shown.
public void HandlerRewardVideoAdStarted(object sender, EventArgs args) { } // Called when the ad starts to play.
public void HandlerRewardVideoAdRewarded(object sender, Reward args) { Debug.Log("Rewarded video ad completed. Reward info: " + args.Amount + " of " + args.Type); } // Called when the user should be rewarded for watching a video.
public void HandlerRewardVideoAdClosed(object sender, EventArgs args) { } // Called when the ad is closed.
public void HandlerRewardVideoAdLeftApplication(object sender, EventArgs args) { } // Called when the ad click caused the user to leave the application.
}
To show the ads I'm simply calling the method ShowAd and to hide them I'm calling the method QuitAd. I think that both perform as expected because they work the first time they are called and because in the scenes where the HideAd is called the "banner area" is not clickable but when te ShowAd method is called you can click on the invisible banner.
Thank you for any help!
In my case canvas for some reason overlapped banner, i just unchecked "Render Over native UI" in PlayerSettings -> Resolution and Presentation and now it works fine.
I solved the problem by destroying the banner in the QuitAd method:
public void QuitAd(TypeOfAd typeOfAd)
{
switch (typeOfAd)
{
case TypeOfAd.Banner:
Debug.Log("Quiting Banner ad");
bannerAd.Destroy();
break;
case TypeOfAd.Interestitial:
Debug.Log("Quiting Interestitial ad");
Debug.LogError("QuitAd Interestitial Not Implemented");
break;
case TypeOfAd.RewardedVideo:
Debug.Log("Quiting RewardedVideo ad");
Debug.LogError("QuitAd RewardedVideo Not Implemented");
break;
}
}
And then I've modified the ShowAd method loading the banner before showing it:
public bool ShowAd(TypeOfAd typeOfAd)
{
if (DataManager.instance.showAds)
switch (typeOfAd)
{
case TypeOfAd.Banner:
Debug.Log("Showing Banner ad");
LoadAd(TypeOfAd.Banner); //Every time the banner is asked to be shown it will try to load before being shown.
this.bannerAd.Show(); //Will be show after loading
return true;
case TypeOfAd.Interestitial:
Debug.Log("Showing Interestitial ad");
if (this.interstitialAd.IsLoaded())
{
this.interstitialAd.Show();
return true;
}
else
{
Debug.LogWarning("Trying to show InterstitialAd but it is not loaded");
//TBD: Automaitcally load?
}
break;
case TypeOfAd.RewardedVideo:
Debug.Log("Showing RewardedVideo ad");
if (this.rewardedVideoAd.IsLoaded())
{
this.rewardedVideoAd.Show();
return true;
} else {
Debug.LogWarning("Trying to show RewardedBasedVideoAd but it is not loaded");
//TBD: Automaitcally load?
}
break;
}
return false;
}
However, I do not know if this is a proper solution because a new load request will be done every time a banner has to be shown (after a scene where it is not shown).
Additionally, this "solution" is only a different approach for the same objective, not a fix for the original approach.
So if anyone knows why the original code is not working I would appreciate a lot the sharing of this knowledge.

Audio file not played on the call but on local system - Skype for Business (C#)

I have found some code HERE and modified the same to call a phone number using skype, play an audio file and then disconnect. However, there are two issues in this code.
Audio file which is being played can be heard on the local system
but NOT in the phone call (the person receiving the call is not able to hear the audio played).
The call is not getting disconnected after audio file finishes
playing.
using Microsoft.Lync.Model;
using Microsoft.Lync.Model.Conversation;
using Microsoft.Lync.Model.Conversation.AudioVideo;
using Microsoft.Lync.Model.Device;
using Microsoft.Lync.Model.Extensibility;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Windows.Forms;
namespace LyncTest
{
public partial class frmCaller : Form
{
public frmCaller()
{
InitializeComponent();
}
private void btnCall_Click(object sender, EventArgs e)
{
//if this client is in UISuppressionMode...
if (client.InSuppressedMode && client.State == ClientState.Uninitialized)
{
//...need to initialize it
try
{
client.BeginInitialize(this.ClientInitialized, null);
}
catch (LyncClientException lyncClientException)
{
Console.WriteLine(lyncClientException);
}
catch (SystemException systemException)
{
if (LyncModelExceptionHelper.IsLyncException(systemException))
{
// Log the exception thrown by the Lync Model API.
Console.WriteLine("Error: " + systemException);
}
else
{
// Rethrow the SystemException which did not come from the Lync Model API.
throw;
}
}
}
else //not in UI Suppression, so the client was already initialized
{
//sign-in or contact selection
SignInToLync();
}
SendLyncCall("+6512345678", "Hello, I am calling regarding a pending change request");
}
LyncClient client = LyncClient.GetClient();
private void SignInToLync()
{
try
{
client.BeginSignIn("abc#contoso.com", "abc#contoso.com", "Pass#word99", HandleEndSignIn, null);
}
catch (LyncClientException lyncClientException)
{
Console.WriteLine(lyncClientException);
}
catch (SystemException systemException)
{
if (LyncModelExceptionHelper.IsLyncException(systemException))
{
// Log the exception thrown by the Lync Model API.
Console.WriteLine("Error: " + systemException);
}
else
{
// Rethrow the SystemException which did not come from the Lync Model API.
throw;
}
}
}
Automation _automation = LyncClient.GetAutomation();
ConversationWindow globalConv = null;
public void SendLyncCall(string numberToCall, string textToSpeech)
{
var targetContactUris = new List<string> { numberToCall }; //"tel:+4900000000"
_automation.BeginStartConversation(AutomationModalities.Audio, targetContactUris, null, StartConversationCallback, null);
while (this.globalConv == null)
{
Thread.Sleep(1);
}
if (globalConv != null)
{
//client.DeviceManager.EndPlayAudioFile(
// client.DeviceManager.BeginPlayAudioFile(#"C:\Temp\voice.wav", AudioPlayBackModes.AlertAndCommunication, false, AudioPlayed, null)
// );
}
}
private void StartConversationCallback(IAsyncResult asyncop)
{
// this is called once the dialing completes..
if (asyncop.IsCompleted == true)
{
ConversationWindow newConversationWindow = _automation.EndStartConversation(asyncop);
globalConv = newConversationWindow;
AVModality avModality = newConversationWindow.Conversation.Modalities[ModalityTypes.AudioVideo] as AVModality;
avModality.ModalityStateChanged += ConversationModalityStateChangedCallback;
}
}
/// <summary>
/// Called when the client in done initializing.
/// </summary>
/// <param name="result"></param>
private void ClientInitialized(IAsyncResult result)
{
//registers for conversation related events
//these events will occur when new conversations are created (incoming/outgoing) and removed
//client.ConversationManager.ConversationAdded += ConversationManager_ConversationAdded;
//client.ConversationManager.ConversationRemoved += ConversationManager_ConversationRemoved;
}
private void ConversationModalityStateChangedCallback(object sender, ModalityStateChangedEventArgs e)
{
AVModality avModality = sender as AVModality;
if (avModality != null)
{
switch (e.NewState)
{
case ModalityState.Disconnected:
avModality.ModalityStateChanged -= ConversationModalityStateChangedCallback;
break;
case ModalityState.Connected:
avModality.ModalityStateChanged -= ConversationModalityStateChangedCallback;
//foreach (char c in "SOS")
//{
// avModality.AudioChannel.BeginSendDtmf(c.ToString(), null, null);
// System.Threading.Thread.Sleep(500);
//}
client.DeviceManager.EndPlayAudioFile(client.DeviceManager.BeginPlayAudioFile(#"C:\Temp\voice.wav",
AudioPlayBackModes.Communication, false, AudioPlayed, null));
break;
case ModalityState.Invalid:
break;
case ModalityState.Notified:
break;
}
}
}
private void AudioPlayed(IAsyncResult audioPlayed)
{
if(audioPlayed.IsCompleted == true)
{
client.ConversationManager.Conversations[0].End();
}
}
private void HandleEndSignIn(IAsyncResult ar)
{
try
{
client.EndSignIn(ar);
}
catch (Exception e)
{
Console.Out.WriteLine(e);
}
}
private void frmCaller_FormClosing(object sender, FormClosingEventArgs e)
{
GC.Collect();
}
}
}
Any help would be appreciated. Thank you.
It was confirmed by Microsoft that this is not possible using client side code. I need to use UCMA and develop a server side solution for the same.

how to understand who wanted the result of a method

I have two methods alphaClicked() and betaClicked() and for them to work we need to be connected to a service in the net so I have another method named connect() so in both classes we need to be connected first so we check if we are connected then if we are not then we call connect() method then we get the result of the connection in ActionConnectionResultReceived so if we connected successfully I want to call alphaClicked() if alpha was the one requesting the connect() and call betaClicked() if betaClicked() was the one requesting the connect() method what is the best way to do that?
To summarize this is the issue :
alpha and beta need to connect but connect result doesn't comes back immediately , so we get it via ActionConnectionResultReceived so , how to get who called the connect was it alpha or beta
private void alphaClicked()
{
if(GooglePlayConnection.State == GPConnectionState.STATE_CONNECTED) {
//do something
}
else
{
Connect();
}
}
private void betaClicked()
{
if(GooglePlayConnection.State == GPConnectionState.STATE_CONNECTED) {
//do something else
}
else
{
Connect();
}
}
private void ActionConnectionResultReceived(GooglePlayConnectionResult result)
{
if (result.IsSuccess)
{
Debug.Log("Connected!");
//if alpha requested call alpha if beta requested call beta
//how to do this?
}
else
{
Debug.Log("Cnnection failed with code: " + result.code.ToString());
}
}
private void Connect()
{
GooglePlayConnection.Instance.Connect();
}
Without Async or event handler, and provided you only call one connect per time, you could introduce a variable which stores the last caller:
string gCaller = "";
private void Connect(string caller){
gCaller = caller;
//something else
}
And then use it like this:
private void alphaClicked()
{
if(GooglePlayConnection.State == GPConnectionState.STATE_CONNECTED) {
//do something
}
else
{
Connect("alpha");
}
}
private void betaClicked()
{
if(GooglePlayConnection.State == GPConnectionState.STATE_CONNECTED) {
//do something else
}
else
{
Connect("beta");
}
}
Then when you need the last one who creates the connection, you use the info in gCaller.
private void ActionConnectionResultReceived(GooglePlayConnectionResult result)
{
if (result.IsSuccess)
{
Debug.Log("Connected!");
switch (gCaller){
case "alpha":
alphaClicked();
break;
case "beta":
betaClicked();
break;
default:
break;
}
}
else
{
Debug.Log("Cnnection failed with code: " + result.code.ToString());
}
}
But the best way would be to create async or event handler for Connected events. Take a look on this MSDN article.

How identify that form is consuming a Data Service

I have a C# WinForms application with using of WCF Data Services and I can't find a way to know if the application is doing a process to a web service. I have tried to implement IClientMessageInspector, etc. but it seems that it doesn't work.
Is there any other way to catch when a Windows Form app is consuming a web service? The purpose is to display a "running process" icon when the communication to a service is opened and then hide it when it's close.
Thanks.
you should add event in place where you calling WcfService methods and then listen to this event in UI layer. With custom event argument in this event, you should provide more info for consuming UI layer like enum values Connected, TransferStarted, TransferEnded, Closed,...
I think there are two main possible cases:
Wcf communication take place synchronous - you are calling some wrapper methods of object which handles connection/requests/responses with wcf service - in this case i think its trivial, you make UI actions before every call of wrapper for example
try
{
WcfEx.IwcfS5ExtensionClient client = new IwcfS5ExtensionClient("MyEndpointConfigurationName");
client.Open();
if (client.State == CommunicationState.Opened)
{
//change UI to Connected
}
else
{
//change ui to Connection Error
}
Application.DoEvents();
//Change UI to Transfering data
Application.DoEvents();
client.DoWork();
//change UI to transfer done
Application.DoEvents();
client.Close();
//change ui to Closed
}
catch (Exception e)
{
//change ui to Comunication error
}
Second is if wcf communication is async
-i will add more sofisticated sample later today
EDIT: Example with async work and notifying form
using System;
using System.ComponentModel;
using System.Threading;
using WcfEx;
public class MyForm : Form
{
public MyForm()
{
WcfHandler WcfConnection = new WcfHandler();
WcfConnection.ProgressChanged += WcfConnectionOnProgressChanged;
}
private delegate void WcfConnectionOnProgressChangedDelegate(object Sender, WcfHandler.ProgressChangedEventArgs EventArgs);
private void WcfConnectionOnProgressChanged(object Sender, WcfHandler.ProgressChangedEventArgs EventArgs)
{
//multi thread synchronization check
if (this.InvokeRequired)
{
object[] Parameters = new object[2];
Parameters[0] = Sender;
Parameters[1] = EventArgs;
this.Invoke(new WcfConnectionOnProgressChangedDelegate(WcfConnectionOnProgressChanged), Parameters);
}
else
{
if (EventArgs == null)
return;
switch (EventArgs.StateValue)
{
case WcfHandler.ProgressChangedEventArgs.State.Started:
{
this.Text = "Starting connection...";
break;
}
case WcfHandler.ProgressChangedEventArgs.State.Processing:
{
this.Text = "Downloading updates...";
break;
}
case WcfHandler.ProgressChangedEventArgs.State.Finished:
{
this.Text = EventArgs.Succes ? "Update completed" : "Update failed";
break;
}
}
Application.DoEvents();
}
}
public class WcfHandler
{
public class ProgressChangedEventArgs : EventArgs
{
public enum State : int
{
Started,
Processing,
Finished
};
public bool Succes { get; set; }
public State StateValue { get; set; }
}
public delegate void ProgressChangedEventHandler(object sender, ProgressChangedEventArgs EventArgs);
public event ProgressChangedEventHandler ProgressChanged;
protected virtual void OnProgressChanged(ProgressChangedEventArgs e)
{
if (ProgressChanged != null)
{
ProgressChanged(this, e);
}
}
public void StartChecking()
{
BackgroundWorker bWorker = new BackgroundWorker();
bWorker.DoWork += CheckStatesAsync;
bWorker.RunWorkerCompleted += BWorkerOnRunWorkerCompleted;
bWorker.RunWorkerAsync();
}
private void CheckStatesAsync(object sender, DoWorkEventArgs e)
{
while (true)
{
WcfEx.IwcfS5ExtensionClient client = new IwcfS5ExtensionClient("MyWcfBindingConfig");
ProgressChangedEventArgs Controller = new ProgressChangedEventArgs();
Controller.StateValue = ProgressChangedEventArgs.State.Started;
Controller.Succes = true;
this.OnProgressChanged(Controller);
try
{
client.Open();
Controller.StateValue = ProgressChangedEventArgs.State.Processing;
Controller.Succes = true;
this.OnProgressChanged(Controller);
//do some work
}
catch (Exception)
{
this.OnProgressChanged(new ProgressChangedEventArgs()
{
StateValue = ProgressChangedEventArgs.State.Finished,
Succes = false
});
}
Thread.Sleep(8000);
}
}
private void BWorkerOnRunWorkerCompleted(object Sender, RunWorkerCompletedEventArgs RunWorkerCompletedEventArgs)
{
ProgressChangedEventArgs Controller = new ProgressChangedEventArgs();
Controller.StateValue = ProgressChangedEventArgs.State.Finished;
Controller.Succes = true;
this.OnProgressChanged(Controller);
}
}

Categories

Resources