Пример #1
0
 public AnswerEventArgs(int number, int target, CallState state, Guid id)
 {
     TelephoneNumber = number;
     TargetTelephoneNumber = target;
     StateInCall = state;
     Id = id;
 }
 public override void OnCallStateChanged(CallState state, string incomingNumber)
 {
     if (Idle != null && state == CallState.Idle)
         Idle(this, null);
     else if (IncomingCall != null && state == CallState.Ringing)
         IncomingCall(this, incomingNumber);
 }
 public async Task<AuthorizationResult> AcquireAuthorizationAsync(Uri authorizationUri, Uri redirectUri, IDictionary<string, string> additionalHeaders, CallState callState)
 {
     returnedUriReady = new SemaphoreSlim(0);
     Authenticate(authorizationUri, redirectUri, additionalHeaders, callState);
     await returnedUriReady.WaitAsync().ConfigureAwait(false);
     return authorizationResult;
 }
        public void CallbackTest()
        {
            var counter = 0;
            Logger logger = new Logger();
            CallState state = new CallState(Guid.NewGuid());
            IMsalLogCallback callback = Substitute.For<IMsalLogCallback>();
            callback.When(x => x.Log(LogLevel.Error, Arg.Any<string>())).Do(x=>counter++);
            LoggerCallbackHandler.Callback = callback;
            logger.Error(state, new Exception("test message"));
            Assert.AreEqual(1, counter);

            callback = Substitute.For<IMsalLogCallback>();
            callback.When(x => x.Log(LogLevel.Information, Arg.Any<string>())).Do(x => counter++);
            LoggerCallbackHandler.Callback = callback;
            logger.Information(state, "test message");
            Assert.AreEqual(2, counter);

            callback = Substitute.For<IMsalLogCallback>();
            callback.When(x => x.Log(LogLevel.Verbose, Arg.Any<string>())).Do(x => counter++);
            LoggerCallbackHandler.Callback = callback;
            logger.Verbose(state, "test message");
            Assert.AreEqual(3, counter);

            callback = Substitute.For<IMsalLogCallback>();
            callback.When(x => x.Log(LogLevel.Warning, Arg.Any<string>())).Do(x => counter++);
            LoggerCallbackHandler.Callback = callback;
            logger.Warning(state, "test message");
            Assert.AreEqual(4, counter);
        }
Пример #5
0
		/// <summary>
		///	<para>Completes the operation and invokes the callback, if a callback exists.</para>
		/// </summary>
		/// <param name="wasSynchronous">
		///	<para><see langword="true"/> if the operation completed synchronously;
		///	<see langword="false"/> otherwise.</para>
		/// </param>
		public void CompleteOperation(bool wasSynchronous)
		{
			_callState = wasSynchronous ? CallState.CompletedSync : CallState.CompletedAsync;
			Thread.MemoryBarrier();
			_handle.Set();
			_callback(this);
		}
        public async Task<AuthorizationResult> AcquireAuthorizationAsync(Uri authorizationUri, Uri redirectUri, IDictionary<string, string> additionalHeaders, CallState callState)
        {
            bool ssoMode = ReferenceEquals(redirectUri, Constant.SsoPlaceHolderUri);
            
            WebAuthenticationResult webAuthenticationResult;
            WebAuthenticationOptions options = (this.useCorporateNetwork && (ssoMode || redirectUri.Scheme == Constant.MsAppScheme)) ? WebAuthenticationOptions.UseCorporateNetwork : WebAuthenticationOptions.None;

            try
            {
                if (ssoMode)
                {
                    webAuthenticationResult = await WebAuthenticationBroker.AuthenticateAsync(options, authorizationUri).AsTask().ConfigureAwait(false);
                }
                else
                { 
                    webAuthenticationResult = await WebAuthenticationBroker.AuthenticateAsync(options, authorizationUri, redirectUri).AsTask().ConfigureAwait(false);
                }
            }

            catch (Exception ex)
            {
                PlatformPlugin.Logger.Error(callState, ex);
                throw new MsalException(MsalError.AuthenticationUiFailed, ex);
            }

            AuthorizationResult result = ProcessAuthorizationResult(webAuthenticationResult, callState);

            return result;
        }
        public async Task<AuthorizationResult> AcquireAuthorizationAsync(Uri authorizationUri, Uri redirectUri, IDictionary<string, string> additionalHeaders, CallState callState)
        {
            AuthorizationResult authorizationResult = null;
            StringBuilder builder = new StringBuilder();

            if (additionalHeaders != null)
            {
                bool isFirst = true;
                foreach (var key in additionalHeaders.Keys)
                {
                    if (!isFirst)
                    {
                        builder.Append("\r\n");
                    }

                    builder.AppendFormat("{0}: {1}", key, additionalHeaders[key]);
                    isFirst = false;
                }
            }

            var sendAuthorizeRequest = new Action(
                delegate
                {
                    authorizationResult = this.Authenticate(authorizationUri, redirectUri, builder.ToString());
                });

            // If the thread is MTA, it cannot create or communicate with WebBrowser which is a COM control.
            // In this case, we have to create the browser in an STA thread via StaTaskScheduler object.
            if (Thread.CurrentThread.GetApartmentState() == ApartmentState.MTA)
            {
                using (var staTaskScheduler = new StaTaskScheduler(1))
                {
                    try
                    {
                        Task.Factory.StartNew(sendAuthorizeRequest, CancellationToken.None, TaskCreationOptions.None, staTaskScheduler).Wait();
                    }
                    catch (AggregateException ae)
                    {
                        PlatformPlugin.Logger.Error(callState, ae.InnerException);
                        // Any exception thrown as a result of running task will cause AggregateException to be thrown with 
                        // actual exception as inner.
                        Exception innerException = ae.InnerExceptions[0];

                        // In MTA case, AggregateException is two layer deep, so checking the InnerException for that.
                        if (innerException is AggregateException)
                        {
                            innerException = ((AggregateException)innerException).InnerExceptions[0];
                        }

                        throw innerException;
                    }
                }
            }
            else
            {
                sendAuthorizeRequest();
            }

            return await Task.Factory.StartNew(() => authorizationResult).ConfigureAwait(false);
        }
Пример #8
0
 public override void OnCallStateChanged(CallState state, string incomingNumber)
 {
     if (state == CallState.Ringing) {
         ShowNotification("Incommming call detected from " + incomingNumber);
         base.OnCallStateChanged (state, incomingNumber);
     }
 }
 public void BeginClientMetricsRecord(CallState callState)
 {
     if (callState != null)
     {
         metricsTimer = Stopwatch.StartNew();
     }
 }
        public virtual Uri ValidateRedirectUri(Uri redirectUri, CallState callState)
        {
            if (redirectUri == null)
            {
                throw new ArgumentNullException("redirectUri");
            }

            return redirectUri;
        }
Пример #11
0
 public CallHistoryInfo(DialInfo caller, DialInfo callee, bool isIncoming, CallState callState, string reasonOfState)
 {
     Date = DateTime.Now;
     PhoneLine = caller;
     OtherParty = callee;
     IsIncoming = isIncoming;
     CallState = callState;
     ReasonOfState = reasonOfState;
 }
Пример #12
0
 public CallHandler(SIPApp app, Preferences settings, MultimediaHandler mediaHandler, int localAudioPort, int localVideoPort)
 {
     _app = app;
     _settings = settings;
     _mediaHandler = mediaHandler;
     _localAudioPort = localAudioPort;
     _localVideoPort = localVideoPort;
     CallState = CallState.Inactive;
 }
Пример #13
0
 public CallInfo()
 {
     this.CallIndex = -1;
     this.Dir = CallDir.unknown;
     this.Status = CallState.unknown;
     this.CallMode = CallMode.unknownn;
     this.IsMultipartyConferenceCall = false;
     this.Number = this.EntryInPhonebook = "-1";
     this.NumberType = CallNumberType.unknown;
 }
        internal static async Task<UserRealmDiscoveryResponse> CreateByDiscoveryAsync(string userRealmUri, string userName, CallState callState)
        {
            string userRealmEndpoint = userRealmUri;
            userRealmEndpoint += (userName + "?api-version=1.0");

            PlatformPlugin.Logger.Information(callState, string.Format("Sending user realm discovery request to '{0}'", userRealmEndpoint));

            var client = new MsalHttpClient(userRealmEndpoint, callState) { Client = { Accept = "application/json" } };
            return await client.GetResponseAsync<UserRealmDiscoveryResponse>(ClientMetricsEndpointType.UserRealmDiscovery).ConfigureAwait(false);
        }
 public void Authenticate(Uri authorizationUri, Uri redirectUri, IDictionary<string, string> additionalHeaders, CallState callState)
 {
     try
     {
         this.parameters.CallerViewController.PresentViewController(new AuthenticationAgentUINavigationController(authorizationUri.AbsoluteUri, redirectUri.OriginalString, additionalHeaders, CallbackMethod), false, null);
     }
     catch (Exception ex)
     {
         PlatformPlugin.Logger.Error(callState, ex);
         throw new MsalException(MsalError.AuthenticationUiFailed, ex);
     }
 }
        /// <summary>
        /// Parse a parameter from FreeSWITCH
        /// </summary>
        /// <param name="name">Parameter name as defined by FS</param>
        /// <param name="value">Parameter value</param>
        /// <returns>
        /// true if parsed sucessfully; otherwise false.
        /// </returns>
        public override bool ParseParameter(string name, string value)
        {
            switch (name)
            {
                case "original-channel-call-state":
                    OriginalChannelCallState = Enumm.Parse<CallState>(value);
                    break;
                default:
                    return base.ParseParameter(name, value);
            }

            return true;
        }
        public Dictionary<string, string> GetPreviousRequestRecord(CallState callState)
        {
            Dictionary<string, string> parameters;
            if (callState != null)
            {
                parameters = GetClientMetricsParameters();
            }
            else
            {
                parameters = new Dictionary<string, string>();
            }

            return parameters;
        }
Пример #18
0
        /// <summary>
        /// Parse a parameter from FreeSWITCH
        /// </summary>
        /// <param name="name">Parameter name as defined by FS</param>
        /// <param name="value">Parameter value</param>
        /// <returns>
        /// true if parsed sucessfully; otherwise false.
        /// </returns>
        public override bool ParseParameter(string name, string value)
        {
            switch (name)
            {
            case "original-channel-call-state":
                OriginalChannelCallState = Enumm.Parse <CallState>(value);
                break;

            default:
                return(base.ParseParameter(name, value));
            }

            return(true);
        }
Пример #19
0
        public IWaveProvider Call(IWaveIn waveIn)
        {
            Reset();
            var sampleRate = waveIn.WaveFormat.SampleRate;

            state                      = CallState.WaitForAnswer;
            toneDetector               = new BiFSKDetector(sampleRate, Channel2Freq);
            toneDetector.DetectTone   += ToneDetected;
            toneGenerator              = new ToneGenerator(sampleRate, Channel1Freq);
            ansamDetector              = new ANSamDetector(sampleRate);
            ansamDetector.DetectANSam += ANSamDetected;
            waveIn.DataAvailable      += WaveInDataAvailable;
            return(toneGenerator);
        }
Пример #20
0
        public static T CreateResponse <T>(HttpResponse response, CallState callState, bool addCorrelationId)
        {
            if (response.StatusCode != HttpStatusCode.OK)
            {
                CreateErrorResponse(response, callState);
            }

            if (addCorrelationId)
            {
                VerifyCorrelationIdHeaderInReponse(response.Headers, callState);
            }

            return(JsonHelper.DeserializeFromJson <T>(response.Body));
        }
Пример #21
0
        internal override void HandleResourceEvent(EventContext eventcontext)
        {
            CallState oldState = State;

            // Raise resource events before CallStateChanged event
            base.HandleResourceEvent(eventcontext);

            CallState newState = State;

            if (oldState != newState)
            {
                m_callStateChanged?.Invoke(this, new CallStateChangedEventArgs(oldState, State));
            }
        }
Пример #22
0
        public static bool FalseCall(Vector3 position, string calloutName)
        {
            if (Vector3.Distance(Game.LocalPlayer.Character.Position, position) < 30f && callState == CallState.Start)
            {
                callState = CallState.Middle;
                calloutName.DisplayNotification("Caller hung up, investigate the area");
            }
            if (Vector3.Distance(Game.LocalPlayer.Character.Position, position) < 10f && callState == CallState.Middle)
            {
                callState = CallState.Wait;
                GameFiber.StartNew(delegate
                {
                    GameFiber.Sleep(Fiskey111Common.Rand.RandomNumber(9000));
                    GameFiber.Sleep(Fiskey111Common.Rand.RandomNumber(4000, 9000));
                    GameFiber.Sleep(Fiskey111Common.Rand.RandomNumber(4000, 9000));
                    GameFiber.Sleep(Fiskey111Common.Rand.RandomNumber(4000, 9000));
                    calloutName.DisplayNotification("Update: Call possibly false\nInvestigate the area");
                });
            }
            if (callState == CallState.Wait && !_wait)
            {
                _wait = true;
                if (Fiskey111Common.Rand.RandomNumber(1, 10) == 1)
                {
                    _p = new Ped(position);
                    if (Fiskey111Common.Rand.RandomNumber(1, 4) == 1)
                    {
                        Weapon g = new Weapon("WEAPON_PISTOL", position, 100);
                        g.GiveTo(_p);
                    }
                    _p.KeepTasks = true;
                    _p.Tasks.FightAgainst(Game.LocalPlayer.Character, -1);
                    callState = CallState.End;
                }
                else
                {
                    GameFiber.Sleep(Fiskey111Common.Rand.RandomNumber(3000, 9000));
                    calloutName.DisplayNotification("Call determined to be a false report");
                    return(true);
                }
            }
            if (callState == CallState.End && (_p.IsDead || Functions.IsPedArrested(_p)))
            {
                return(true);
            }

            GameFiber.Yield();
            return(false);
        }
Пример #23
0
        public SessionScriptBase(RbrResult pInitResult, ISession pSession, ScriptInfo pScriptInfo)
        {
            session    = pSession;
            scriptInfo = pScriptInfo;

            promptManager = new PromptManager(scriptInfo);
            leg1Length    = 0;
            cardLength    = scriptInfo.PinLength;
            neverUsed     = false;

            startingBalance     = currentBalance = decimal.Zero;
            currentBonusBalance = 0;
            serialNumber        = string.Empty;
            callState           = CallState.Initializing;
        }
 public override void OnCallStateChanged(CallState state, string incomingNumber)
 {
     base.OnCallStateChanged(state, incomingNumber);
       switch(state) {
       case CallState.Ringing:
       case CallState.Offhook:
     // stop media player
     PortaPodderApp.Context.StopService(new Intent(PortaPodderApp.Context, typeof(EpisodePlayer)));
     break;
       case CallState.Idle:
       default:
     // intentionally do nothing
     break;
       }
 }
        public void TestInstanceDiscovery_WhenMultipleSimultaneousCallsWithTheSameAuthority_ShouldMakeOnlyOneRequest()
        {
            for (int i = 0; i < 2; i++) // Prepare 2 mock responses
            {
                HttpMessageHandlerFactory.AddMockHandler(MockHelpers.CreateInstanceDiscoveryMockHandler("https://login.windows.net/common/discovery/instance"));
            }

            CallState callState = new CallState(Guid.NewGuid());
            string    host      = "login.windows.net";

            Task.WaitAll( // Simulate several simultaneous calls
                InstanceDiscovery.GetMetadataEntry(new Uri($"https://{host}/tenant"), true, callState),
                InstanceDiscovery.GetMetadataEntry(new Uri($"https://{host}/tenant"), true, callState));
            Assert.AreEqual(1, HttpMessageHandlerFactory.MockHandlersCount()); // 1 mock response is consumed, 1 remaining
        }
        private static async Task <HttpResponse> ExecuteWithRetry(Uri endpoint, Dictionary <string, string> headers,
                                                                  Dictionary <string, string> bodyParameters, HttpMethod method,
                                                                  CallState callstate, bool retry = true)
        {
            bool         isRetryable = false;
            HttpResponse response    = null;

            try
            {
                response = await Execute(endpoint, headers, bodyParameters, method);

                if (response.StatusCode == HttpStatusCode.OK)
                {
                    return(response);
                }

                PlatformPlugin.Logger.Error(callstate,
                                            string.Format(CultureInfo.InvariantCulture,
                                                          "Response status code does not indicate success: {0} ({1}).",
                                                          (int)response.StatusCode, response.StatusCode));

                if ((response.StatusCode.Equals(HttpStatusCode.InternalServerError)) ||
                    (response.StatusCode).Equals(HttpStatusCode.GatewayTimeout) ||
                    (response.StatusCode).Equals(HttpStatusCode.ServiceUnavailable))
                {
                    isRetryable = true;
                }
            }
            catch (TaskCanceledException exception)
            {
                PlatformPlugin.Logger.Error(callstate, exception);
                isRetryable = true;
            }

            if (isRetryable)
            {
                if (retry)
                {
                    PlatformPlugin.Logger.Information(callstate, "Retrying one more time..");
                    return(await ExecuteWithRetry(endpoint, headers, bodyParameters, method, callstate, false));
                }

                PlatformPlugin.Logger.Information(callstate, "Request retry failed.");
                throw new RetryableRequestException();
            }

            return(response);
        }
Пример #27
0
        /// <summary>
        /// Parse a delimited string of key-value pairs in to a dictionary.
        /// </summary>
        /// <param name="input">Delimited string of key-value pairs</param>
        /// <param name="delimiter">Character used as a delimiter between key-value pairs</param>
        /// <param name="urlDecode">True to perform URL decoding of both the keys and values</param>
        /// <param name="lowercaseKeys">True to make all resulting keys lower-case</param>
        /// <param name="callState">call state to pass correlation id and logger instance</param>
        /// <param name="strict">Throw <see cref="ArgumentException"/> when the input string contains a malformed key-value pair</param>
        /// <exception cref="ArgumentException">Thrown if <paramref name="strict"/> is true and a malformed key-value pair is present in <paramref name="input"/></exception>
        /// <returns>Dictionary of string key-value pairs</returns>
        private static Dictionary <string, string> ParseKeyValueList(string input, char delimiter, bool urlDecode, bool lowercaseKeys,
                                                                     CallState callState, bool strict)
        {
            var response = new Dictionary <string, string>();

            List <string> queryPairs = SplitWithQuotes(input, delimiter);

            foreach (string queryPair in queryPairs)
            {
                List <string> pair = SplitWithQuotes(queryPair, '=');

                if (pair.Count == 2 && !string.IsNullOrWhiteSpace(pair[0]) && !string.IsNullOrWhiteSpace(pair[1]))
                {
                    string key   = pair[0];
                    string value = pair[1];

                    // Url decoding is needed for parsing OAuth response, but not for parsing WWW-Authenticate header in 401 challenge
                    if (urlDecode)
                    {
                        key   = UrlDecode(key);
                        value = UrlDecode(value);
                    }

                    if (lowercaseKeys)
                    {
                        key = key.Trim().ToLowerInvariant();
                    }

                    value = value.Trim().Trim(new[] { '\"' }).Trim();

                    if (response.ContainsKey(key) && callState != null)
                    {
                        var msg = string.Format(CultureInfo.CurrentCulture,
                                                "Key/value pair list contains redundant key '{0}'.", key);
                        callState.Logger.Warning(callState, msg);
                        callState.Logger.WarningPii(callState, msg);
                    }

                    response[key] = value;
                }
                else if (strict && pair.Count > 2)
                {
                    throw new ArgumentException(nameof(input));
                }
            }

            return(response);
        }
Пример #28
0
        private static Activity GenerateActivity(string text, CallState callState)
        {
            var thisParticipant = callState.Participants.Single(t => t.Originator);

            return(new Activity
            {
                ChannelId = "directline",
                Conversation = new ConversationAccount(id: callState.Conversation.ConversationId),
                From = new ChannelAccount(id: thisParticipant.Identity, name: thisParticipant.DisplayName),
                Id = callState.Conversation.ConversationId + "|" + (int.Parse(callState.Watermark) + 1).ToString("D7"),
                Locale = thisParticipant.LanguageId,
                Text = text,
                Type = ActivityTypes.Message,
                ServiceUrl = ConfigurationManager.AppSettings["Microsoft.Bot.Builder.Calling.CallbackUrl"]
            });
        }
Пример #29
0
        public Channel CallTo(string dst)
        {
            try
            {
                agent     = pbx.Channels.Originate(dst, null, null, null, null, appName, "", "1111", 20, null, null, null, null);
                callState = CallState.CONNECTIING;
                chronometer.CallToStart();
                //bridge.Channels.Add(agent.Id); //no debería hacerlo cuando es calltosuccess?
            }
            catch (Exception ex)
            {
                throw new Exception("Error llamando a:  " + dst, ex);
            }

            return(agent);
        }
Пример #30
0
        private string ConvertState(CallState state)
        {
            switch (state)
            {
            case CallState.ACTIVE: return("Active");

            case CallState.ALERTING:
            case CallState.CONNECTING: return("Calling");

            case CallState.INCOMING: return("Incoming");

            case CallState.HOLDING: return("Holding");

            default: return("Ended");
            }
        }
Пример #31
0
 private void UpdateComponent()
 {
     this.friendNumber             = -1;
     this.friendName               = string.Empty;
     this.friendStatusMessage      = string.Empty;
     this.latestFriendMessage      = null;
     this.latestFriendAction       = null;
     this.latestFriendActivityDate = ZeroDateTime;
     this.friendTypingStatus       = false;
     this.callState = CallState.None;
     this.displayName.DoubleClick          += this.OnFriendInfoDoubleClick;
     this.displayStatusMessage.DoubleClick += this.OnFriendInfoDoubleClick;
     this.startCall.PictureClick           += this.OnStartCallClick;
     this.endCall.PictureClick             += this.OnEndCallClick;
     this.removeEntry.PictureClick         += this.OnRemoveEntryClick;
     this.UpdateControl();
 }
Пример #32
0
        private static void CallStatusUpdated(CallState state)
        {
            switch (state)
            {
            case CallState.Ringing:
                LedSdkAbstraction.FlashLighting(currentSdk, 0, 0, 100, 120000, 200);
                break;

            case CallState.Connected:
                LedSdkAbstraction.PulseLighting(currentSdk, 100, 0, 0, 0, 800);     //duration == 0 is infinite for Logitech.
                break;

            case CallState.NoUpdate:
                SetLEDToCurrentStatus(LyncStatusWatcher.UserStatus);
                break;
            }
        }
        public void PiiLogCallbackTest()
        {
            var logger = new Logger();
            var state  = new CallState(Guid.NewGuid());

            var obsoleteCallback = new TestObsoleteAdalLogCallback();

            LoggerCallbackHandler.Callback = obsoleteCallback;

            LoggerCallbackHandler.LogCallback = InitLogCallback();

            LoggerCallbackHandler.PiiLoggingEnabled = true;

            logger.ErrorPii(state, new Exception(Message));
            Assert.AreEqual(1, _piiErrorLogCount);
            Assert.AreEqual(0, _piiWarningLogCount);
            Assert.AreEqual(0, _piiInfoLogCount);
            Assert.AreEqual(0, _piiVerboseLogCount);

            logger.InformationPii(state, Message);
            Assert.AreEqual(1, _piiErrorLogCount);
            Assert.AreEqual(0, _piiWarningLogCount);
            Assert.AreEqual(1, _piiInfoLogCount);
            Assert.AreEqual(0, _piiVerboseLogCount);

            logger.VerbosePii(state, Message);
            Assert.AreEqual(1, _piiErrorLogCount);
            Assert.AreEqual(0, _piiWarningLogCount);
            Assert.AreEqual(1, _piiInfoLogCount);
            Assert.AreEqual(1, _piiVerboseLogCount);

            logger.WarningPii(state, Message);
            Assert.AreEqual(1, _piiErrorLogCount);
            Assert.AreEqual(1, _piiWarningLogCount);
            Assert.AreEqual(1, _piiInfoLogCount);
            Assert.AreEqual(1, _piiVerboseLogCount);

            // make sure no calls to Log with containsPii = false
            Assert.AreEqual(0, _errorLogCount);
            Assert.AreEqual(0, _warningLogCount);
            Assert.AreEqual(0, _infoLogCount);
            Assert.AreEqual(0, _verboseLogCount);

            // make sure no calls were done to ObsoleteAdalLogCallback
            Assert.AreEqual(0, obsoleteCallback.AllCallsCount);
        }
Пример #34
0
        public static void CreateErrorResponse(HttpResponse response, CallState callState)
        {
            MsalServiceException serviceEx;

            try
            {
                TokenResponse tokenResponse = JsonHelper.DeserializeFromJson <TokenResponse>(response.Body);
                serviceEx = new MsalServiceException(tokenResponse.Error, tokenResponse.ErrorDescription);
            }
            catch (SerializationException)
            {
                serviceEx = new MsalServiceException(MsalError.Unknown, response.Body);
            }

            PlatformPlugin.Logger.Error(callState, serviceEx);
            throw serviceEx;
        }
 public void Authenticate(Uri authorizationUri, Uri redirectUri, CallState callState)
 {
     try
     {
         safariViewController          = new SFSafariViewController(new NSUrl(authorizationUri.AbsoluteUri), false);
         safariViewController.Delegate = this;
         this.parameters.CallerViewController.InvokeOnMainThread(() =>
         {
             this.parameters.CallerViewController.PresentViewController(safariViewController, false, null);
         });
     }
     catch (Exception ex)
     {
         PlatformPlugin.Logger.Error(callState, ex);
         throw new MsalException(MsalError.AuthenticationUiFailed, ex);
     }
 }
 public void EndClientMetricsRecord(string endpoint, CallState callState)
 {
     if (callState != null && metricsTimer != null)
     {
         metricsTimer.Stop();
         lastResponseTime = metricsTimer.ElapsedMilliseconds;
         lastCorrelationId = callState.CorrelationId;
         lastEndpoint = endpoint;
         lock (PendingClientMetricsLock)
         {
             if (pendingClientMetrics == null)
             {
                 pendingClientMetrics = this;
             }
         }
     }
 }
Пример #37
0
    void AsyncCallCallback(IAsyncResult result)
    {
        CallState       cs        = (CallState)result.AsyncState;
        Response        data      = cs.client.EndGetUserRoles(result);
        List <string[]> claimData = new List <string[]>();

        foreach (var val in data.Values)
        {
            claimData.Add(new string[1] {
                val
            });
        }
        string[][] retVal = claimData.ToArray();
        TypedAsyncResult <string[][]> queryResult = (TypedAsyncResult <string[][]>)cs.result;

        queryResult.Complete(retVal, false);
    }
Пример #38
0
 public void OnCallCompleted(CallState pLastCallState)
 {
     lock (padlock) {
         if (pLastCallState == CallState.Started)
         {
             currentOpen--;
         }
         if (pLastCallState == CallState.Connecting)
         {
             currentConnecting--;
         }
         if (pLastCallState == CallState.Connected)
         {
             currentConnected--;
         }
     }
 }
Пример #39
0
        public DTypeDesc /*!*/ PeekType(int i)
        {
            if (TypeArgCount >= i)
            {
                // peeks the value:
                return(Types[TypesTop - i]);
            }
            else
            {
                // warning (can invoke user code => we have to save and restore callstate):
                CallState call_state = SaveCallState();
                PhpException.MissingTypeArgument(i, CalleeName);
                RestoreCallState(call_state);

                return(DTypeDesc.ObjectTypeDesc);
            }
        }
        public void ObsoleteAdalLogCallbackTest()
        {
            var logger = new Logger();
            var state  = new CallState(Guid.NewGuid());

            var obsoleteCallback = new TestObsoleteAdalLogCallback();

            LoggerCallbackHandler.Callback = obsoleteCallback;

            LoggerCallbackHandler.LogCallback = null;

            LoggerCallbackHandler.PiiLoggingEnabled = true;

            logger.ErrorPii(state, new Exception(Message));
            logger.InformationPii(state, Message);
            logger.VerbosePii(state, Message);
            logger.WarningPii(state, Message);

            // make sure no Pii are logged with ObsoleteAdalLogCallback
            Assert.AreEqual(0, obsoleteCallback.AllCallsCount);

            logger.Error(state, new Exception(Message));
            Assert.AreEqual(1, obsoleteCallback.ErrorLogCount);
            Assert.AreEqual(0, obsoleteCallback.WarningLogCount);
            Assert.AreEqual(0, obsoleteCallback.InfoLogCount);
            Assert.AreEqual(0, obsoleteCallback.VerboseLogCount);

            logger.Information(state, Message);
            Assert.AreEqual(1, obsoleteCallback.ErrorLogCount);
            Assert.AreEqual(0, obsoleteCallback.WarningLogCount);
            Assert.AreEqual(1, obsoleteCallback.InfoLogCount);
            Assert.AreEqual(0, obsoleteCallback.VerboseLogCount);

            logger.Verbose(state, Message);
            Assert.AreEqual(1, obsoleteCallback.ErrorLogCount);
            Assert.AreEqual(0, obsoleteCallback.WarningLogCount);
            Assert.AreEqual(1, obsoleteCallback.InfoLogCount);
            Assert.AreEqual(1, obsoleteCallback.VerboseLogCount);

            logger.Warning(state, Message);
            Assert.AreEqual(1, obsoleteCallback.ErrorLogCount);
            Assert.AreEqual(1, obsoleteCallback.WarningLogCount);
            Assert.AreEqual(1, obsoleteCallback.InfoLogCount);
            Assert.AreEqual(1, obsoleteCallback.VerboseLogCount);
        }
Пример #41
0
        public void GetUserCallsByCallStatePerMonth(IUser user, CallState callState)
        {
            var userCalls = Calls
                            .Where(x => User.Equals(user) && x.GetStarted().Date >= DateTime.Now.AddMonths(-1).Date&& x.GetCallState().Equals(callState));

            if (userCalls.Count() == 0)
            {
                Console.WriteLine($"No {callState} calls");
            }
            else
            {
                Console.WriteLine($"{callState} calls");
                foreach (var item in userCalls.OrderBy(x => x.GetStarted()))
                {
                    Console.WriteLine($"{item}\n");
                }
            }
        }
Пример #42
0
        public object PeekValueUnchecked(int i)
        {
            PhpRuntimeChain php_chain;

            // caller may have pushed a reference even if a formal argument is not reference => dereference it:
            object result = PhpVariable.Dereference(Items[Top - i]);

            // caller may have pushed a runtime chain => evaluate it:
            if ((php_chain = result as PhpRuntimeChain) != null)
            {
                // call state has to be stored since chain can call arbitrary user code:
                CallState call_state = SaveCallState();
                result = php_chain.GetValue(Context);
                RestoreCallState(call_state);
            }

            return(result);
        }
        public void NullCallbackTest()
        {
            var logger = new Logger();
            var state  = new CallState(Guid.NewGuid());

            LoggerCallbackHandler.Callback    = null;
            LoggerCallbackHandler.LogCallback = null;

            logger.Error(state, new Exception(Message));
            logger.Information(state, Message);
            logger.Verbose(state, Message);
            logger.Warning(state, Message);

            logger.ErrorPii(state, new Exception(Message));
            logger.InformationPii(state, Message);
            logger.VerbosePii(state, Message);
            logger.WarningPii(state, Message);
        }
Пример #44
0
        private void CallStateChangedHandler(object sender, VoIPEventArgs <CallState> e)
        {
            CallState callState = e.Item;

            _log.Debug("State change to " + callState.ToString());
            if (callState == CallState.InCall)
            {
                CallAnswered();
            }
            else if (callState == CallState.Completed)
            {
                CallEnded();
            }
            else
            {
                _log.Debug("Unhandled call state " + callState.ToString());
            }
        }
Пример #45
0
        void setConnected(string pDestIPAddress)
        {
            cdr.Leg2Start();
            var _result = sessionHandler.CallConnect(session.Id,
                                                     session.AccessNumber,
                                                     session.OrigIPAddress,
                                                     pDestIPAddress,
                                                     LegIn.CustomerAcctId,
                                                     LegIn.CustomerRouteId,
                                                     legOutOptions[outboundAttempt - 1].CarrierAcctId,
                                                     legOutOptions[outboundAttempt - 1].CarrierBaseRouteId,
                                                     cdr.Leg1Length);

            if (_result)
            {
                callState = sessionHandler.OnConnected(legOutOptions[outboundAttempt - 1].CarrierAcctId, LegIn.CustomerAcctId);
            }
        }
Пример #46
0
 public override void OnCallStateChanged([GeneratedEnum] CallState state, string incomingNumber)
 {
     if (state == CallState.Offhook)
     {
         if (_Recorder != null)
         {
             _Recorder.RecStart();
         }
     }
     else if (state == CallState.Idle)
     {
         if (_Recorder != null)
         {
             _Recorder.RecStop(incomingNumber);
             _Recorder.Dispose();
         }
     }
 }
Пример #47
0
        private async Task OnIncomingCallReceived(IncomingCallEvent incomingCallEvent)
        {
            System.Diagnostics.Trace.TraceInformation(DateTime.Now + " CallReceived " + incomingCallEvent.IncomingCall.Id);

            var client = new DirectLineClient(directLineSecret);

            var    conversation = client.Conversations.StartConversation();
            string watermark    = null;
            var    callState    = new CallState(incomingCallEvent.IncomingCall.Participants, conversation, watermark);

            await Task.Delay(1000);

            List <ActionBase> actionList = await GetActionListOnIncomingCall(client, callState);

            incomingCallEvent.ResultingWorkflow.Actions          = actionList;
            this.callStateMap[incomingCallEvent.IncomingCall.Id] = callState;

            //return Task.FromResult(true);
        }
Пример #48
0
        private void OnCall(Core lc, Call lcall, CallState state, string message)
        {
            try
            {
                if (state == CallState.End || state == CallState.Error)
                {
                    LastCall = null;
                }
                if ((state == CallState.IncomingReceived || state == CallState.OutgoingInit) && LastCall != null)
                {
                    linphoneCore.TerminateCall(LastCall);
                    LastCall = null;
                }

                if ((state == CallState.IncomingReceived || state == CallState.OutgoingInit) && LastCall == null)
                {
                    LastCall = lcall;
                }

                CallPCL call = new CallPCL
                {
                    UsernameCaller = lcall.RemoteAddress.Username
                };
                CallParams param = linphoneCore.CreateCallParams(lcall);

                lock (LinphoneListeners)
                {
                    for (int i = 0; i < LinphoneListeners.Count; i++)
                    {
                        try
                        {
                            var listener = LinphoneListeners[i];
                            listener.OnCall(new CallArgs(call, (int)state, message, param.VideoEnabled));
                        }
                        catch (Exception ex)
                        {
                            Log("error with listenner, OnCall");
                        }
                    }
                }
            }
            catch (Exception ex) { }
        }
        public async Task <AuthorizationResult> AcquireAuthorizationAsync(Uri authorizationUri, Uri redirectUri,
                                                                          CallState callState)
        {
            AuthorizationResult authorizationResult = null;

            var sendAuthorizeRequest = new Action(
                delegate { authorizationResult = this.Authenticate(authorizationUri, redirectUri); });

            // If the thread is MTA, it cannot create or communicate with WebBrowser which is a COM control.
            // In this case, we have to create the browser in an STA thread via StaTaskScheduler object.
            if (Thread.CurrentThread.GetApartmentState() == ApartmentState.MTA)
            {
                using (var staTaskScheduler = new StaTaskScheduler(1))
                {
                    try
                    {
                        Task.Factory.StartNew(sendAuthorizeRequest, CancellationToken.None, TaskCreationOptions.None,
                                              staTaskScheduler).Wait();
                    }
                    catch (AggregateException ae)
                    {
                        PlatformPlugin.Logger.Error(callState, ae.InnerException);
                        // Any exception thrown as a result of running task will cause AggregateException to be thrown with
                        // actual exception as inner.
                        Exception innerException = ae.InnerExceptions[0];

                        // In MTA case, AggregateException is two layer deep, so checking the InnerException for that.
                        if (innerException is AggregateException)
                        {
                            innerException = ((AggregateException)innerException).InnerExceptions[0];
                        }

                        throw innerException;
                    }
                }
            }
            else
            {
                sendAuthorizeRequest();
            }

            return(await Task.Factory.StartNew(() => authorizationResult).ConfigureAwait(false));
        }
        public static async Task<WsTrustResponse> SendRequestAsync(WsTrustAddress wsTrustAddress, UserCredential credential, CallState callState)
        {
            HttpClientWrapper request = new HttpClientWrapper(wsTrustAddress.Uri.AbsoluteUri, callState);
            request.ContentType = "application/soap+xml";
            if (credential.UserAuthType == UserAuthType.IntegratedAuth)
            {
                SetKerberosOption(request);
            }

            StringBuilder messageBuilder = BuildMessage(DefaultAppliesTo, wsTrustAddress, credential);
            WsTrustResponse wstResponse;

            try
            {
                request.BodyParameters = new StringRequestParameters(messageBuilder);
                IHttpWebResponse response = await request.GetResponseAsync().ConfigureAwait(false);
                wstResponse = WsTrustResponse.CreateFromResponse(response.ResponseStream, wsTrustAddress.Version);
            }
            catch (WebException ex)
            {
                PlatformPlugin.Logger.Error(callState, ex);
                string errorMessage;

                try
                {
                    XDocument responseDocument = WsTrustResponse.ReadDocumentFromResponse(ex.Response.GetResponseStream());
                    errorMessage = WsTrustResponse.ReadErrorResponse(responseDocument, callState);
                }
                catch (MsalException)
                {
                    errorMessage = "See inner exception for detail.";
                }

                throw new MsalServiceException(
                    MsalError.FederatedServiceReturnedError,
                    string.Format(MsalErrorMessage.FederatedServiceReturnedErrorTemplate, wsTrustAddress.Uri, errorMessage),
                    null,
                    ex);
            }

            return wstResponse;
        }
        public async Task UpdateFromTemplateAsync(CallState callState)
        {
            if (!this.updatedFromTemplate)
            {
                var authorityUri = new Uri(this.Authority);
                string host = authorityUri.Authority;
                string path = authorityUri.AbsolutePath.Substring(1);
                string tenant = path.Substring(0, path.IndexOf("/", StringComparison.Ordinal));

                AuthenticatorTemplate matchingTemplate = await AuthenticatorTemplateList.FindMatchingItemAsync(this.ValidateAuthority, host, tenant, callState).ConfigureAwait(false);

                this.AuthorizationUri = matchingTemplate.AuthorizeEndpoint.Replace("{tenant}", tenant);
                this.DeviceCodeUri = matchingTemplate.DeviceCodeEndpoint.Replace("{tenant}", tenant);
                this.TokenUri = matchingTemplate.TokenEndpoint.Replace("{tenant}", tenant);
                this.UserRealmUri = CanonicalizeUri(matchingTemplate.UserRealmEndpoint);
                this.IsTenantless = IsTenantLess(this.Authority);
                this.SelfSignedJwtAudience = matchingTemplate.Issuer.Replace("{tenant}", tenant);
                this.updatedFromTemplate = true;
            }
        }
        public static Dictionary<string, string> ParseKeyValueList(string input, char delimiter, bool urlDecode, bool lowercaseKeys,
            CallState callState)
        {
            var response = new Dictionary<string, string>();

            List<string> queryPairs = SplitWithQuotes(input, delimiter);

            foreach (string queryPair in queryPairs)
            {
                List<string> pair = SplitWithQuotes(queryPair, '=');

                if (pair.Count == 2 && !string.IsNullOrWhiteSpace(pair[0]) && !string.IsNullOrWhiteSpace(pair[1]))
                {
                    string key = pair[0];
                    string value = pair[1];

                    // Url decoding is needed for parsing OAuth response, but not for parsing WWW-Authenticate header in 401 challenge
                    if (urlDecode)
                    {
                        key = UrlDecode(key);
                        value = UrlDecode(value);
                    }

                    if (lowercaseKeys)
                    {
                        key = key.Trim().ToLower();
                    }

                    value = value.Trim().Trim(new[] { '\"' }).Trim();

                    if (response.ContainsKey(key) && callState != null)
                    {
                        PlatformPlugin.Logger.Warning(callState, string.Format(CultureInfo.InvariantCulture,"Key/value pair list contains redundant key '{0}'.", key));
                    }

                    response[key] = value;
                }
            }

            return response;
        }
        private static AuthorizationResult ProcessAuthorizationResult(WebAuthenticationResult webAuthenticationResult, CallState callState)
        {
            AuthorizationResult result;
            switch (webAuthenticationResult.ResponseStatus)
            {
                case WebAuthenticationStatus.Success:
                    result = new AuthorizationResult(AuthorizationStatus.Success, webAuthenticationResult.ResponseData);
                    break;
                case WebAuthenticationStatus.ErrorHttp:
                    result = new AuthorizationResult(AuthorizationStatus.ErrorHttp, webAuthenticationResult.ResponseErrorDetail.ToString(CultureInfo.InvariantCulture));
                    break;
                case WebAuthenticationStatus.UserCancel:
                    result = new AuthorizationResult(AuthorizationStatus.UserCancel, null);
                    break;
                default:
                    result = new AuthorizationResult(AuthorizationStatus.UnknownError, null);
                    break;
            }

            return result;
        }
        public async Task<AuthorizationResult> AcquireAuthorizationAsync(Uri authorizationUri, Uri redirectUri, IDictionary<string, string> additionalHeaders, CallState callState)
        {
            returnedUriReady = new SemaphoreSlim(0);

            try
            {
                var agentIntent = new Intent(this.parameters.CallerActivity, typeof(AuthenticationAgentActivity));
                agentIntent.PutExtra("Url", authorizationUri.AbsoluteUri);
                agentIntent.PutExtra("Callback", redirectUri.AbsoluteUri);
                AuthenticationAgentActivity.AdditionalHeaders = additionalHeaders;

                this.parameters.CallerActivity.StartActivityForResult(agentIntent, 0);
            }
            catch (Exception ex)
            {
                PlatformPlugin.Logger.Error(callState, ex);
                throw new MsalException(MsalError.AuthenticationUiFailed, ex);
            }

            await returnedUriReady.WaitAsync().ConfigureAwait(false);
            return authorizationResult;
        }
        public async Task VerifyAnotherHostByInstanceDiscoveryAsync(string host, string tenant, CallState callState)
        {
            string instanceDiscoveryEndpoint = this.InstanceDiscoveryEndpoint;
            instanceDiscoveryEndpoint += ("?api-version=1.0&authorization_endpoint=" + AuthorizeEndpointTemplate);
            instanceDiscoveryEndpoint = instanceDiscoveryEndpoint.Replace("{host}", host);
            instanceDiscoveryEndpoint = instanceDiscoveryEndpoint.Replace("{tenant}", tenant);

            try
            {
                var client = new MsalHttpClient(instanceDiscoveryEndpoint, callState);
                InstanceDiscoveryResponse discoveryResponse = await client.GetResponseAsync<InstanceDiscoveryResponse>(ClientMetricsEndpointType.InstanceDiscovery).ConfigureAwait(false);

                if (discoveryResponse.TenantDiscoveryEndpoint == null)
                {
                    throw new MsalException(MsalError.AuthorityNotInValidList);
                }
            }
            catch (MsalServiceException ex)
            {
                PlatformPlugin.Logger.Error(callState, ex);
                throw new MsalException((ex.ErrorCode == "invalid_instance") ? MsalError.AuthorityNotInValidList : MsalError.AuthorityValidationFailed, ex);
            }
        }
        public static string ReadErrorResponse(XDocument responseDocument, CallState callState)
        {
            string errorMessage = null;

            try
            {
                XElement body = responseDocument.Descendants(XmlNamespace.SoapEnvelope + "Body").FirstOrDefault();

                if (body != null)
                {
                    XElement fault = body.Elements(XmlNamespace.SoapEnvelope + "Fault").FirstOrDefault();
                    if (fault != null)
                    {
                        XElement reason = fault.Elements(XmlNamespace.SoapEnvelope + "Reason").FirstOrDefault();
                        if (reason != null)
                        {
                            XElement text = reason.Elements(XmlNamespace.SoapEnvelope + "Text").FirstOrDefault();
                            if (text != null)
                            {
                                using (var reader = text.CreateReader())
                                {
                                    reader.MoveToContent();
                                    errorMessage = reader.ReadInnerXml();
                                }
                            }
                        }
                    }
                }
            }
            catch (XmlException ex)
            {
                PlatformPlugin.Logger.Error(callState, ex);
                throw new MsalException(MsalError.ParsingWsTrustResponseFailed, ex);
            }

            return errorMessage;
        }
        internal static async Task<XDocument> FetchMexAsync(string federationMetadataUrl, CallState callState)
        {
            XDocument mexDocument;
            try
            {
                HttpClientWrapper request = new HttpClientWrapper(federationMetadataUrl, callState);
                using (var response = await request.GetResponseAsync().ConfigureAwait(false))
                {
                    mexDocument = XDocument.Load(response.ResponseStream, LoadOptions.None);
                }
            }
            catch (WebException ex)
            {
                PlatformPlugin.Logger.Error(callState, ex);
                throw new MsalServiceException(MsalError.AccessingWsMetadataExchangeFailed, ex);
            }
            catch (XmlException ex)
            {
                PlatformPlugin.Logger.Error(callState, ex);
                throw new MsalException(MsalError.ParsingWsMetadataExchangeFailed, ex);
            }

            return mexDocument;
        }
Пример #58
0
		internal void RestoreCallState(CallState old)
		{
			TypeArgCount = old.TypeCount;
			ArgCount = old.ArgCount;
			Callback = old.Callback;
			CalleeName = old.CalleeName;
			Variables = old.Variables;
			NamingContext = old.NamingContext;
			AllowProtectedCall = old.AllowProtectedCall;
            LateStaticBindType = old.LateStaticBindType;
		}
Пример #59
0
        private void call_CallStateChanged(object sender, VoIPEventArgs<CallState> e)
        {
            callstate = e.Item;

                if (e.Item == CallState.Ringing)
                {
                    m_TimeStart = DateTime.Now.TimeOfDay;
                    m_StartTimeOutCounter = true;
                    m_MediaUtility.Start(MediaUtility.ePhoneCallSoundType.Ring);
                }

                else if (e.Item == CallState.InCall)
                {
                    try
                    {
                        m_StartTimeOutCounter = false;
                        m_MediaUtility.Stop();
                        recorder.StartStreaming();
                        //recorder.IsStreaming = true;
                    }
                    catch (Ozeki.Common.Exceptions.MediaException me)
                    {

                        if (CallState_Changed != null)
                        {
                            AudioId = Guid.Empty;
                            CallState_Changed(this, new CallStateChangedArgs()
                            {
                                PhoneCallState = CallState.Rejected
                            });
                        }
                        if (call != null)
                            call.HangUp();

                        //softPhone.UnregisterPhoneLine(phoneLine);
                        softPhone.Close();
                        this.WireDownCallEvents();
                        call = null;

                        m_MediaUtility.Start(MediaUtility.ePhoneCallSoundType.HangUp);
                        MessageBox.Show("Your mic or speaker is not working. Please change your mic or speaker in the Phone Settings.", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return;
                    }
                }

                else if (e.Item == CallState.Completed)
                {
                    try
                    {
                        recorder.StopStreaming();
                        //recorder.IsStreaming = false;

                        EndCall();

                        if (m_RingTimeOut)
                            return;

                        this.WireDownCallEvents();
                        call = null;
                        recorder.Dispose();
                        recorder = null;
                        CommonApplicationData commonData = new CommonApplicationData("BrightVision", "BrightSales", true);
                        string fileNameTmp = String.Format(@"{0}\tmpwav\{1}_.wav", commonData.ApplicationFolderPath, AudioId);
                        string fileNameCache = String.Format(@"{0}\cachewav\{1}_.wav", commonData.ApplicationFolderPath, AudioId);
                        File.Copy(fileNameTmp, fileNameCache);

                        m_MediaUtility.Start(MediaUtility.ePhoneCallSoundType.HangUp);

                    }
                    catch
                    {
                        //softPhone.UnregisterPhoneLine(phoneLine);
                        softPhone.Close();
                        this.WireDownCallEvents();
                        call = null;
                    }
                }

                else if (e.Item == CallState.Cancelled)
                {
                    AudioId = Guid.Empty;
                    EndCall();
                    if (m_RingTimeOut)
                        return;

                    m_StartTimeOutCounter = false;
                    //softPhone.UnregisterPhoneLine(phoneLine);

                    this.WireDownCallEvents();
                    call = null;
                    m_MediaUtility.Start(MediaUtility.ePhoneCallSoundType.HangUp);
                }

                else if (e.Item == CallState.Rejected)
                {
                    AudioId = Guid.Empty;
                    EndCall();
                    m_StartTimeOutCounter = false;
                    //softPhone.UnregisterPhoneLine(phoneLine);

                    this.WireDownCallEvents();
                    call = null;
                    m_MediaUtility.Start(MediaUtility.ePhoneCallSoundType.HangUp);
                }

                else if (e.Item == CallState.Busy || e.Item == CallState.Error)
                {
                    AudioId = Guid.Empty;
                    EndCall();
                    m_RingTimeOut = true;
                    m_StartTimeOutCounter = false;
                    m_MediaUtility.Start(MediaUtility.ePhoneCallSoundType.Busy);
                    //softPhone.UnregisterPhoneLine(phoneLine);
                    softPhone.Close();
                    call.HangUp();
                    call = null;
                    //MessageBox.Show("Error encountered. Please check the format of the number you are calling.", "Bright Sales", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    //this.WireDownCallEvents();
                    //call = null;
                }

                if (CallState_Changed != null)
                {
                    CallState_Changed(this, new CallStateChangedArgs()
                    {
                        PhoneCallState = e.Item,
                        AudioId = AudioId
                    });
                }
        }
Пример #60
0
        /// <summary>
        /// Displays call state information for the given call.
        /// </summary>
        /// <param name="callInfo">The call object.</param>
        /// <param name="callState">The state of the call.</param>
        public void CallStateInfo(PhoneCallInfo callInfo, CallState callState)
        {
            if (InvokeRequired)
            {
                BeginInvoke((Action<MainForm, PhoneCallInfo, CallState>)((t, c, c1) => t.CallStateInfo(c, c1)), this, callInfo, callState);
                return;
            }

            PhoneCallInfo selectedCall = SelectedCall;
            if (selectedCall == null)
                return;

            if (!selectedCall.Equals(callInfo))
                return;

            switch (callState)
            {
                case CallState.InCall:
                    btnHold.Text = "Hold";
                    btnHold.Enabled = true;
                    videoViewerRemote.Start();
                    break;
                case CallState.LocalHeld:
                    btnHold.Text = "Unhold";
                    break;
                case CallState.RemoteHeld:
                    btnHold.Text = "Holded";
                    btnHold.Enabled = false;
                    break;
                case CallState.Completed:
                    softphoneEngine.StopCamera(callInfo);
                    videoViewerLocal.Stop();
                    videoViewerRemote.Stop();
                    StopRecord();
                    break;
            }

            tbPhoneStatus.Text = "Call " + callInfo.Dial + " is " + callState + ".";
        }