Пример #1
0
        public async Task RefreshData()
        {
            var newPageData = await GetDataAsync();

            DataTable.SetColumnsAndItems(newPageData);
            RefreshState.Invoke();
        }
        private void AdjustPeriodsForNoTotalAllocationChange(int variationPointerIndex,
                                                             decimal latestPeriodAmount,
                                                             ProfilePeriod[] orderedSnapShotProfilePeriods,
                                                             ProfilePeriod[] orderedRefreshProfilePeriods,
                                                             string fundingLineId)
        {
            decimal amountAlreadyPaid            = orderedSnapShotProfilePeriods.Take(variationPointerIndex).Sum(_ => _.ProfiledValue);
            decimal amountThatShouldHaveBeenPaid = latestPeriodAmount * variationPointerIndex;

            decimal runningTotalChange = amountThatShouldHaveBeenPaid - amountAlreadyPaid;

            if (runningTotalChange < 0)
            {
                AdjustingPeriodsForOverPaymentLeavesRemainder(variationPointerIndex,
                                                              latestPeriodAmount,
                                                              orderedSnapShotProfilePeriods,
                                                              orderedRefreshProfilePeriods,
                                                              out decimal carryOver);

                if (carryOver > 0)
                {
                    RefreshState.AddCarryOver(fundingLineId, ProfilingCarryOverType.DSGReProfiling, carryOver);
                }
            }
            else if (runningTotalChange > 0)
            {
                AdjustPeriodsForUnderPayment(variationPointerIndex,
                                             latestPeriodAmount,
                                             orderedSnapShotProfilePeriods,
                                             orderedRefreshProfilePeriods);
            }
        }
Пример #3
0
 public override void OnStateChanged(IRefreshLayout refreshLayout, RefreshState oldState, RefreshState newState)
 {
     if (oldState == RefreshState.LoadFinish && newState == RefreshState.None)
     {
         refreshLayout.AutoRefresh();
         refreshLayout.SetOnMultiPurposeListener(null);
     }
 }
Пример #4
0
 public override void OnStateChanged(IRefreshLayout refreshLayout, RefreshState oldState, RefreshState newState)
 {
     mStateChanged = String.Format(Locale.China, "%s\nnew=%s\nold=%s",
                                   FORMAT.Format(new Date()),
                                   newState.Name(),
                                   oldState.Name());
     updateContent();
 }
        public void GetReferringSitesTitleDescriptionTest_InvalidRefreshState(RefreshState refreshState)
        {
            //Arrange

            //Act

            //Assert
            Assert.Throws <NotSupportedException>(() => EmptyDataViewService.GetReferringSitesDescriptionText(refreshState));
        }
        public void GetRepositoryTitleDescriptionTest_InvalidRefreshState(RefreshState refreshState, bool isRepositoryListEmpty)
        {
            //Arrange

            //Act

            //Assert
            Assert.Throws <NotSupportedException>(() => EmptyDataViewService.GetRepositoryDescriptionText(refreshState, isRepositoryListEmpty));
        }
        public void GetViewsClonesImage_InvalidRefreshState(RefreshState refreshState)
        {
            //Arrange

            //Act

            //Assert
            Assert.Throws <NotSupportedException>(() => EmptyDataViewService.GetViewsClonesImage(refreshState));
        }
        public void GetStarsImage_InvalidRefreshState(RefreshState refreshState, double totalStars)
        {
            //Arrange

            //Act

            //Assert
            Assert.Throws <NotSupportedException>(() => EmptyDataViewService.GetStarsImage(refreshState, totalStars));
        }
Пример #9
0
        public void onPullEvent(PullToRefreshBase <V> refreshView, RefreshState ev, PullMode direction)
        {
            int?soundResIdObj = mSoundMap[ev];

            if (null != soundResIdObj)
            {
                playSound(soundResIdObj.Value);
            }
        }
        public void GetReferringSitesDescriptionText_ValidRefreshState(RefreshState refreshState, string expectedResult)
        {
            //Arrange
            string actualResult;

            //Act
            actualResult = EmptyDataViewService.GetReferringSitesDescriptionText(refreshState);

            //Assert
            Assert.AreEqual(expectedResult, actualResult);
        }
        public void GetRepositoresTitleTextTest_ValidRefreshState(RefreshState refreshState, bool isRepositoryListEmpty, string expectedResult)
        {
            //Arrange
            string actualResult;

            //Act
            actualResult = EmptyDataViewService.GetRepositoryTitleText(refreshState, isRepositoryListEmpty);

            //Assert
            Assert.AreEqual(expectedResult, actualResult);
        }
        public void GetStarsImage_ValidRefreshState(RefreshState refreshState, double totalStars, string expectedResult)
        {
            //Arrange
            string actualResult;

            //Act
            actualResult = EmptyDataViewService.GetStarsImage(refreshState, totalStars);

            //Assert
            Assert.AreEqual(expectedResult, actualResult);
        }
        public void GetViewsClonesImage_ValidRefreshState(RefreshState refreshState, string expectedResult)
        {
            //Arrange
            string actualResult;

            //Act
            actualResult = EmptyDataViewService.GetViewsClonesImage(refreshState);

            //Assert
            Assert.AreEqual(expectedResult, actualResult);
        }
Пример #14
0
        void ResetRefreshing()
        {
            var movedDistance              = _refreshIcon.Geometry.Y - _initialIconGeometryY;
            var currentIconGeometryY       = _refreshIcon.Geometry.Y;
            var _refreshIconResetAnimation = new Animation(v => _refreshIcon.Move(_refreshIcon.Geometry.X, currentIconGeometryY - (int)v), 0, movedDistance, Easing.Linear);

            _refreshIconResetAnimation.Commit(this, "RefreshIconReset", length: _animationLength);

            _refreshState             = RefreshState.Idle;
            _refreshIcon.PullDistance = 0;
            _refreshIcon.IsRunning    = false;
        }
        public void PerformRefresh(IEnumerable<SvnClientAction> sccRefreshItems)
        {
            Debug.Assert(RequiresForcedRefresh(), "Refreshing a project that manages itself");

            RefreshState state = new RefreshState(_context, ProjectHierarchy, VsProject, ProjectDirectory);

            if (state.VsProject == null || state.ProjectDirectory == null)
                return; // Can't fix it

            VSDOCUMENTPRIORITY[] prio = new VSDOCUMENTPRIORITY[1];
            IVsHierarchy hierarchy = null;

            foreach (SvnClientAction action in sccRefreshItems)
            {
                if (!action.AddOrRemove)
                    continue; // Not for me

                SvnItem item = state.Cache[action.FullPath];
                if (!item.IsBelowPath(ProjectDirectory))
                    return;

                int found;
                uint id;

                // Check the real project here instead of our cache to keep the update initiative
                // at the project. Checking our cache might be unsafe, as we get file add and remove
                // events from the project while we are updating
                if (!ErrorHandler.Succeeded(VsProject.IsDocumentInProject(item.FullPath, out found, prio, out id)))
                    continue;

                bool bFound = (found != 0);

                if (!bFound)
                {
                    if (hierarchy == null)
                        hierarchy = VsProject as IVsHierarchy;

                    // We need this additional check to find directories in Websites
                    if (hierarchy != null &&
                        ErrorHandler.Succeeded(hierarchy.ParseCanonicalName(item.FullPath, out id)))
                    {
                        bFound = (id != VSConstants.VSITEMID_NIL) && (id != VSConstants.VSITEMID_ROOT);
                    }
                }
                if (bFound == item.Exists)
                    continue; //

                if (!bFound)
                    state.AddItem(item);
                else
                    state.RemoveItem(item, id);
            }
        }
Пример #16
0
        void BeginRefreshing(bool isPulledRefresh)
        {
            var currentIconGeometryY       = _refreshIcon.Geometry.Y;
            var contentDistanceDiff        = _maximumDistance - currentIconGeometryY;
            var _refreshIconBeginAnimation = new Animation(v => _refreshIcon.Move(_refreshIcon.Geometry.X, currentIconGeometryY + (int)v), 0, contentDistanceDiff, Easing.Linear);

            _refreshIconBeginAnimation.Commit(this, "RefreshIconBegin", length: _animationLength);

            _refreshState          = RefreshState.Loading;
            _isRefreshing          = true;
            _refreshIcon.IsRunning = true;
            Refreshing?.Invoke(this, EventArgs.Empty);
        }
Пример #17
0
        /// <summary>
        /// Initializes a new instance of the RefreshLayout class.
        /// </summary>
        /// <param name="parent"></param>
        public RefreshLayout(EvasObject parent) : base(parent)
        {
            MinimumHeight  = _minimumSize;
            _refreshState  = RefreshState.Idle;
            _refreshIcon   = new RefreshIcon(parent);
            _contentLayout = new Box(parent);
            _refreshIcon.Show();
            _contentLayout.Show();

            _gestureLayer = new GestureLayer(parent);
            _gestureLayer.Attach(_contentLayout);
            _gestureLayer.SetMomentumCallback(GestureLayer.GestureState.Move, OnMoved);
            _gestureLayer.SetMomentumCallback(GestureLayer.GestureState.End, OnEnded);
            _gestureLayer.SetMomentumCallback(GestureLayer.GestureState.Abort, OnEnded);

            this.PackEnd(_contentLayout);
            this.PackEnd(_refreshIcon);

            SetLayoutCallback(OnLayoutUpdate);
        }
Пример #18
0
        void OnMoved(GestureLayer.MomentumData moment)
        {
            if (_refreshState == RefreshState.Idle && _isRefreshEnabled)
            {
                var isEdge = IsEdgeScrolling?.Invoke() ?? true;
                if (isEdge)
                {
                    _refreshState          = RefreshState.Drag;
                    _refreshIcon.IsPulling = true;
                }
            }

            if (_refreshState == RefreshState.Drag)
            {
                var dy = moment.Y2 - moment.Y1;
                if (dy < 0)
                {
                    return;
                }
                MoveLayout(dy);
            }
        }
Пример #19
0
        public void Refresh(RefreshState state, int dataValue = 0)
        {
            if (Error())
            {
                return;
            }

            if (m_ESVData.m_DataCount == 0)
            {
                return;
            }

            if (state == RefreshState.All)
            {
                RefereshAll();
            }

            if (state == RefreshState.Single)
            {
                RefreshTarget(dataValue);
            }
        }
Пример #20
0
        /// <summary>
        /// Initializes a new instance of the RefreshLayout class.
        /// </summary>
        public RefreshLayout()
        {
            _overlayArea = new View
            {
                WidthSpecification  = LayoutParamPolicies.MatchParent,
                HeightSpecification = LayoutParamPolicies.MatchParent,
            };
            Add(_overlayArea);

            _refreshIcon = new RefreshIcon
            {
                Opacity = 0
            };
            _overlayArea.Add(_refreshIcon);

            _panGestureDetector = new PanGestureDetector();
            _panGestureDetector.Attach(this);
            _panGestureDetector.Detected += OnDetected;

            LayoutUpdated += OnLayout;

            _refreshState = RefreshState.Idle;
        }
Пример #21
0
        public ETClient(NameValueCollection parameters = null, RefreshState refreshState = null)
        {
            var builder = new ConfigurationBuilder()
                          .SetBasePath(Directory.GetCurrentDirectory())
                          .AddJsonFile("appsettings.json");

            var config = builder.Build();

            // Get configuration file and set variables
            configSection = (FuelSDKConfigurationSection)config.GetSection("FuelSDK").Get <FuelSDKConfigurationSection>();

            if (parameters != null)
            {
                if (parameters.AllKeys.Contains("appSignature"))
                {
                    configSection.AppSignature = parameters["appSignature"];
                }
                if (parameters.AllKeys.Contains("clientId"))
                {
                    configSection.ClientId = parameters["clientId"];
                }
                if (parameters.AllKeys.Contains("clientSecret"))
                {
                    configSection.ClientSecret = parameters["clientSecret"];
                }
                if (parameters.AllKeys.Contains("soapEndPoint"))
                {
                    configSection.SoapEndPoint = parameters["soapEndPoint"]; //https://webservice.s4.exacttarget.com/Service.asmx
                }
                if (parameters.AllKeys.Contains("authEndPoint"))
                {
                    configSection.AuthenticationEndPoint = parameters["authEndPoint"]; //https://auth-qa.exacttargetapis.com/v1/requestToken?legacy=1
                }
            }

            if (string.IsNullOrEmpty(configSection.ClientId) || string.IsNullOrEmpty(configSection.ClientSecret))
            {
                throw new Exception("clientId or clientSecret is null: Must be provided in config file or passed when instantiating ETClient");
            }

            // If JWT URL Parameter Used
            var organizationFind = false;

            if (refreshState != null)
            {
                RefreshKey     = refreshState.RefreshKey;
                EnterpriseId   = refreshState.EnterpriseId;
                OrganizationId = refreshState.OrganizationId;
                Stack          = refreshState.Stack;
                RefreshToken();
            }
            else if (parameters != null && parameters.AllKeys.Contains("jwt") && !string.IsNullOrEmpty(parameters["jwt"]))
            {
                if (string.IsNullOrEmpty(configSection.AppSignature))
                {
                    throw new Exception("Unable to utilize JWT for SSO without appSignature: Must be provided in config file or passed when instantiating ETClient");
                }
                var encodedJWT = parameters["jwt"].ToString().Trim();
                var decodedJWT = DecodeJWT(encodedJWT, configSection.AppSignature);
                var parsedJWT  = JObject.Parse(decodedJWT);
                AuthToken           = parsedJWT["request"]["user"]["oauthToken"].Value <string>().Trim();
                AuthTokenExpiration = DateTime.Now.AddSeconds(int.Parse(parsedJWT["request"]["user"]["expiresIn"].Value <string>().Trim()));
                InternalAuthToken   = parsedJWT["request"]["user"]["internalOauthToken"].Value <string>().Trim();
                RefreshKey          = parsedJWT["request"]["user"]["refreshToken"].Value <string>().Trim();
                Jwt = parsedJWT;
                var orgPart = parsedJWT["request"]["organization"];
                if (orgPart != null)
                {
                    EnterpriseId   = orgPart["enterpriseId"].Value <string>().Trim();
                    OrganizationId = orgPart["id"].Value <string>().Trim();
                    Stack          = orgPart["stackKey"].Value <string>().Trim();
                }
            }
            else
            {
                RefreshToken();
                organizationFind = true;
            }

            // Find the appropriate endpoint for the acccount
            var grSingleEndpoint = new ETEndpoint {
                AuthStub = this, Type = "soap"
            }.Get();

            if (grSingleEndpoint.Status && grSingleEndpoint.Results.Length == 1)
            {
                configSection.SoapEndPoint = ((ETEndpoint)grSingleEndpoint.Results[0]).URL;
            }
            else
            {
                throw new Exception("Unable to determine stack using /platform/v1/endpoints: " + grSingleEndpoint.Message);
            }

            // Create the SOAP binding for call with Oauth.
            SoapClient = new SoapClient(GetSoapBinding(), new EndpointAddress(new Uri(configSection.SoapEndPoint)));
            SoapClient.ClientCredentials.UserName.UserName = "******";
            SoapClient.ClientCredentials.UserName.Password = "******";

            // Find Organization Information
            if (organizationFind)
            {
                using (var scope = new OperationContextScope(SoapClient.InnerChannel))
                {
                    // Add oAuth token to SOAP header.
                    XNamespace ns           = "http://exacttarget.com";
                    var        oauthElement = new XElement(ns + "oAuthToken", InternalAuthToken);
                    var        xmlHeader    = MessageHeader.CreateHeader("oAuth", "http://exacttarget.com", oauthElement);
                    OperationContext.Current.OutgoingMessageHeaders.Add(xmlHeader);

                    var httpRequest = new System.ServiceModel.Channels.HttpRequestMessageProperty();
                    OperationContext.Current.OutgoingMessageProperties.Add(System.ServiceModel.Channels.HttpRequestMessageProperty.Name, httpRequest);
                    httpRequest.Headers.Add(HttpRequestHeader.UserAgent, ETClient.SDKVersion);

                    var req = new RetrieveRequest {
                        ObjectType = "BusinessUnit", Properties = new[] { "ID", "Client.EnterpriseID" }
                    };
                    var req1 = new RetrieveRequest1(req);
                    var r    = SoapClient.RetrieveAsync(req1).Result;

                    if (r.OverallStatus == "OK" && r.Results.Length > 0)
                    {
                        EnterpriseId   = r.Results[0].Client.EnterpriseID.ToString();
                        OrganizationId = r.Results[0].ID.ToString();
                        Stack          = GetStackFromSoapEndPoint(new Uri(configSection.SoapEndPoint));
                    }
                }
            }
        }
Пример #22
0
        public void ChangeVisualState(RefreshState state, bool useTransitions)
        {
            switch (state)
            {
                case RefreshState.Pulling:
                    {
                        CurrentState = RefreshState.Pulling;
                        StateDescription.Text = PullDownText;
                        GoToState("Pulling", useTransitions);
                    }
                    break;
                case RefreshState.ReleasePulling:
                    {
                        if (CurrentState == RefreshState.Pulling)
                        {
                            CurrentState = RefreshState.ReleasePulling;
                            StateDescription.Text = ReleaseText;
                            GoToState("ReleasePulling", useTransitions);
                        }
                    }
                    break;
                case RefreshState.RefreshDoing:
                    {
                        CurrentState = RefreshState.RefreshDoing;
                        StateDescription.Text = DoRefreshText;
                        GoToState("RefreshDoing", useTransitions);
                    }
                    break;
                case RefreshState.RefreshCompleted:
                    {
                        if (CurrentState == RefreshState.RefreshDoing)
                        {
                            CurrentState = RefreshState.RefreshCompleted;
                            StateDescription.Text = RefreshedText;
                            GoToState("RefreshCompleted", useTransitions);
                        }
                    }
                    break;

            }
        }
Пример #23
0
 /// <summary>
 /// Set the Sounds to be played when a Pull Event happens. You specify which
 /// sound plays for which events by calling this method multiple times for
 /// each event.
 ///
 /// If you've already set a sound for a certain event, and add another sound
 /// for that event, only the new sound will be played.
 /// </summary>
 /// <param name="event"> - The event for which the sound will be played. </param>
 /// <param name="resId"> - Resource Id of the sound file to be played (e.g.
 ///            <var>R.raw.pull_sound</var>) </param>
 public virtual void addSoundEvent(RefreshState ev, int resId)
 {
     mSoundMap[ev] = resId;
 }
        public void PerformRefresh(IEnumerable <SvnClientAction> sccRefreshItems)
        {
            Debug.Assert(WebLikeFileHandling, "Refreshing a project that manages itself");

            RefreshState state = new RefreshState(_context, ProjectHierarchy, VsProject, ProjectDirectory);

            if (state.VsProject == null || state.ProjectDirectory == null)
            {
                return; // Can't fix it
            }
            VSDOCUMENTPRIORITY[] prio      = new VSDOCUMENTPRIORITY[1];
            IVsHierarchy         hierarchy = null;

            foreach (SvnClientAction action in sccRefreshItems)
            {
                if (!action.AddOrRemove)
                {
                    continue; // Not for me
                }
                SvnItem item = state.Cache[action.FullPath];
                if (!item.IsBelowPath(ProjectDirectory))
                {
                    return;
                }

                int  found;
                uint id;

                // Check the real project here instead of our cache to keep the update initiative
                // at the project. Checking our cache might be unsafe, as we get file add and remove
                // events from the project while we are updating
                if (!VSErr.Succeeded(VsProject.IsDocumentInProject(item.FullPath, out found, prio, out id)))
                {
                    continue;
                }

                bool bFound = (found != 0);

                if (!bFound)
                {
                    if (hierarchy == null)
                    {
                        hierarchy = VsProject as IVsHierarchy;
                    }

                    // We need this additional check to find directories in Websites
                    if (hierarchy != null &&
                        VSErr.Succeeded(hierarchy.ParseCanonicalName(item.FullPath, out id)))
                    {
                        bFound = (id != VSItemId.Nil) && (id != VSItemId.Root);

                        // Perform an extra validation step to avoid issue #700
                        string foundName;
                        if (bFound &&
                            VSErr.Succeeded(VsProject.GetMkDocument(id, out foundName)))
                        {
                            foundName = SharpSvn.SvnTools.GetNormalizedFullPath(foundName);
                            bFound    = String.Equals(item.FullPath, foundName, StringComparison.OrdinalIgnoreCase);
                        }
                    }
                }
                if (bFound == item.Exists)
                {
                    continue; //
                }
                if (!bFound)
                {
                    state.AddItem(item);
                }
                else
                {
                    state.RemoveItem(item, id);
                }
            }
        }
        protected override void MakeAdjustmentsFromProfileVariationPointer(ProfileVariationPointer variationPointer)
        {
            PublishedProvider previousSnapshot = VariationContext.GetPublishedProviderOriginalSnapShot(ProviderId);

            if (previousSnapshot == null)
            {
                return;
            }

            string fundingLineId = variationPointer.FundingLineId;

            FundingLine latestFundingLine = RefreshState.FundingLines?
                                            .SingleOrDefault(_ => _.FundingLineCode == fundingLineId);
            FundingLine previousFundingLine = previousSnapshot.Current?.FundingLines?
                                              .SingleOrDefault(_ => _.FundingLineCode == fundingLineId);

            if (latestFundingLine == null || previousFundingLine == null)
            {
                RecordErrors($"Did not locate all funding lines for variation pointer with fundingLineId {fundingLineId}");

                return;
            }

            if (latestFundingLine.Value == null && previousFundingLine.Value == null)
            {
                return;
            }

            ProfilePeriod[] orderedRefreshProfilePeriods = new YearMonthOrderedProfilePeriods(latestFundingLine)
                                                           .ToArray();
            ProfilePeriod[] orderedSnapShotProfilePeriods = new YearMonthOrderedProfilePeriods(previousFundingLine)
                                                            .ToArray();

            int variationPointerIndex = GetProfilePeriodIndexForVariationPoint(variationPointer, orderedRefreshProfilePeriods);

            decimal previousFundingLineValuePaid = orderedSnapShotProfilePeriods.Take(variationPointerIndex).Sum(_ => _.ProfiledValue);
            decimal latestFundingLineValuePaid   = orderedRefreshProfilePeriods.Take(variationPointerIndex).Sum(_ => _.ProfiledValue);
            decimal latestFundingLineValue       = latestFundingLine.Value.GetValueOrDefault();

            decimal fundingChange      = latestFundingLineValuePaid - previousFundingLineValuePaid;
            decimal latestPeriodAmount = (int)(latestFundingLineValue / orderedRefreshProfilePeriods.Length);

            AdjustPeriodsForFundingAlreadyReleased(variationPointerIndex,
                                                   orderedSnapShotProfilePeriods,
                                                   orderedRefreshProfilePeriods);

            if (fundingChange < 0)
            {
                if (AdjustingPeriodsForOverPaymentLeavesRemainder(variationPointerIndex,
                                                                  latestPeriodAmount,
                                                                  orderedSnapShotProfilePeriods,
                                                                  orderedRefreshProfilePeriods,
                                                                  out decimal remainingOverPayment))
                {
                    if (remainingOverPayment > 0)
                    {
                        RefreshState.AddCarryOver(fundingLineId, ProfilingCarryOverType.DSGReProfiling, remainingOverPayment);
                    }
                }
            }
            else if (fundingChange > 0)
            {
                AdjustPeriodsForUnderPayment(variationPointerIndex,
                                             latestPeriodAmount,
                                             orderedSnapShotProfilePeriods,
                                             orderedRefreshProfilePeriods);
            }
            else
            {
                AdjustPeriodsForNoTotalAllocationChange(variationPointerIndex,
                                                        latestPeriodAmount,
                                                        orderedSnapShotProfilePeriods,
                                                        orderedRefreshProfilePeriods,
                                                        fundingLineId);
            }
        }
Пример #26
0
        public ETClient(NameValueCollection parameters = null, RefreshState refreshState = null)
        {
            // Get configuration file and set variables
            configSection = (FuelSDKConfigurationSection)ConfigurationManager.GetSection("fuelSDK");
            configSection = (configSection != null ? (FuelSDKConfigurationSection)configSection.Clone() : new FuelSDKConfigurationSection());
            configSection = configSection
                            .WithDefaultAuthEndpoint(DefaultEndpoints.Auth)
                            .WithDefaultRestEndpoint(DefaultEndpoints.Rest);
            if (parameters != null)
            {
                if (parameters.AllKeys.Contains("appSignature"))
                {
                    configSection.AppSignature = parameters["appSignature"];
                }
                if (parameters.AllKeys.Contains("clientId"))
                {
                    configSection.ClientId = parameters["clientId"];
                }
                if (parameters.AllKeys.Contains("clientSecret"))
                {
                    configSection.ClientSecret = parameters["clientSecret"];
                }
                if (parameters.AllKeys.Contains("soapEndPoint"))
                {
                    configSection.SoapEndPoint = parameters["soapEndPoint"];
                }
                if (parameters.AllKeys.Contains("authEndPoint"))
                {
                    configSection.AuthenticationEndPoint = parameters["authEndPoint"];
                }
                if (parameters.AllKeys.Contains("restEndPoint"))
                {
                    configSection.RestEndPoint = parameters["restEndPoint"];
                }
            }

            if (string.IsNullOrEmpty(configSection.ClientId) || string.IsNullOrEmpty(configSection.ClientSecret))
            {
                throw new Exception("clientId or clientSecret is null: Must be provided in config file or passed when instantiating ETClient");
            }

            // If JWT URL Parameter Used
            var organizationFind = false;

            if (refreshState != null)
            {
                RefreshKey     = refreshState.RefreshKey;
                EnterpriseId   = refreshState.EnterpriseId;
                OrganizationId = refreshState.OrganizationId;
                Stack          = refreshState.Stack;
                RefreshToken();
            }
            else if (parameters != null && parameters.AllKeys.Contains("jwt") && !string.IsNullOrEmpty(parameters["jwt"]))
            {
                if (string.IsNullOrEmpty(configSection.AppSignature))
                {
                    throw new Exception("Unable to utilize JWT for SSO without appSignature: Must be provided in config file or passed when instantiating ETClient");
                }
                var encodedJWT = parameters["jwt"].ToString().Trim();
                var decodedJWT = DecodeJWT(encodedJWT, configSection.AppSignature);
                var parsedJWT  = JObject.Parse(decodedJWT);
                AuthToken           = parsedJWT["request"]["user"]["oauthToken"].Value <string>().Trim();
                AuthTokenExpiration = DateTime.Now.AddSeconds(int.Parse(parsedJWT["request"]["user"]["expiresIn"].Value <string>().Trim()));
                InternalAuthToken   = parsedJWT["request"]["user"]["internalOauthToken"].Value <string>().Trim();
                RefreshKey          = parsedJWT["request"]["user"]["refreshToken"].Value <string>().Trim();
                Jwt = parsedJWT;
                var orgPart = parsedJWT["request"]["organization"];
                if (orgPart != null)
                {
                    EnterpriseId   = orgPart["enterpriseId"].Value <string>().Trim();
                    OrganizationId = orgPart["id"].Value <string>().Trim();
                    Stack          = orgPart["stackKey"].Value <string>().Trim();
                }
            }
            else
            {
                RefreshToken();
                organizationFind = true;
            }

            FetchSoapEndpoint();

            // Create the SOAP binding for call with Oauth.
            SoapClient = new SoapClient(GetSoapBinding(), new EndpointAddress(new Uri(configSection.SoapEndPoint)));
            SoapClient.ClientCredentials.UserName.UserName = "******";
            SoapClient.ClientCredentials.UserName.Password = "******";

            // Find Organization Information
            if (organizationFind)
            {
                using (var scope = new OperationContextScope(SoapClient.InnerChannel))
                {
                    // Add oAuth token to SOAP header.
                    XNamespace ns           = "http://exacttarget.com";
                    var        oauthElement = new XElement(ns + "oAuthToken", InternalAuthToken);
                    var        xmlHeader    = MessageHeader.CreateHeader("oAuth", "http://exacttarget.com", oauthElement);
                    OperationContext.Current.OutgoingMessageHeaders.Add(xmlHeader);

                    var httpRequest = new System.ServiceModel.Channels.HttpRequestMessageProperty();
                    OperationContext.Current.OutgoingMessageProperties.Add(System.ServiceModel.Channels.HttpRequestMessageProperty.Name, httpRequest);
                    httpRequest.Headers.Add(HttpRequestHeader.UserAgent, ETClient.SDKVersion);

                    string      requestID;
                    APIObject[] results;
                    var         r = SoapClient.Retrieve(new RetrieveRequest {
                        ObjectType = "BusinessUnit", Properties = new[] { "ID", "Client.EnterpriseID" }
                    }, out requestID, out results);
                    if (r == "OK" && results.Length > 0)
                    {
                        EnterpriseId   = results[0].Client.EnterpriseID.ToString();
                        OrganizationId = results[0].ID.ToString();
                    }
                }
            }
        }
 public RefreshStateMessage(RefreshState refresh)
 {
     this.Refresh = refresh;
 }