protected void Page_Load(object sender, EventArgs e)
    {
        String identityToken;
        identityToken = Request.Params["identityToken"];

        if (identityToken == null || identityToken == "")
        {
            identityToken = "Oops! Someone forgot to tell us who they were...";
        }
        else
        {
            Token aToken = new Token(identityToken);

            FirstName.Text = aToken.Claims[ClaimTypes.GivenName];
            LastName.Text = aToken.Claims[ClaimTypes.Surname];
            City.Text = aToken.Claims[ClaimTypes.Locality];
            Country.Text = aToken.Claims[ClaimTypes.Country];
            Email.Text = aToken.Claims[ClaimTypes.Email];
            UID.Text = aToken.UniqueID;

            ResultsLiteral.Text += "<table border=\"1\"  width=\"640\"><tr><th width=\"200\">Type</th><th width=\"240\">Resource</th></tr>";

            TokenHelper tokenHelper = new TokenHelper(identityToken);

            foreach (Claim aClaim in tokenHelper.IdentityClaims)
            {
                ResultsLiteral.Text += "<tr>";
                ResultsLiteral.Text += "<td width=\"200\">" + aClaim.ClaimType + "</td>";
                ResultsLiteral.Text += "<td width=\"240\">" + aClaim.Resource.ToString() + "</td>";
                ResultsLiteral.Text += "</tr>";

            }

            ResultsLiteral.Text += "</table>";
        }
    }
Ejemplo n.º 2
0
        /// <summary>
        /// Checks if it is necessary to redirect to SharePoint for user to authenticate.
        /// </summary>
        /// <param name="httpContext">The HTTP context.</param>
        /// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param>
        /// <returns>Redirection status.</returns>
        public static RedirectionStatus CheckRedirectionStatus(HttpContextBase httpContext, out Uri redirectUrl)
        {
            if (httpContext == null)
            {
                throw new ArgumentNullException("httpContext");
            }

            redirectUrl = null;

            if (SharePointContextProvider.Current.GetSharePointContext(httpContext) != null)
            {
                return(RedirectionStatus.Ok);
            }

            const string SPHasRedirectedToSharePointKey = "SPHasRedirectedToSharePoint";

            if (!string.IsNullOrEmpty(httpContext.Request.QueryString[SPHasRedirectedToSharePointKey]))
            {
                return(RedirectionStatus.CanNotRedirect);
            }

            Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);

            if (spHostUrl == null)
            {
                return(RedirectionStatus.CanNotRedirect);
            }

            if (StringComparer.OrdinalIgnoreCase.Equals(httpContext.Request.HttpMethod, "POST"))
            {
                return(RedirectionStatus.CanNotRedirect);
            }

            Uri requestUrl = httpContext.Request.Url;

            var queryNameValueCollection = HttpUtility.ParseQueryString(requestUrl.Query);

            // Removes the values that are included in {StandardTokens}, as {StandardTokens} will be inserted at the beginning of the query string.
            queryNameValueCollection.Remove(SharePointContext.SPHostUrlKey);
            queryNameValueCollection.Remove(SharePointContext.SPAppWebUrlKey);
            queryNameValueCollection.Remove(SharePointContext.SPLanguageKey);
            queryNameValueCollection.Remove(SharePointContext.SPClientTagKey);
            queryNameValueCollection.Remove(SharePointContext.SPProductNumberKey);

            // Adds SPHasRedirectedToSharePoint=1.
            queryNameValueCollection.Add(SPHasRedirectedToSharePointKey, "1");

            UriBuilder returnUrlBuilder = new UriBuilder(requestUrl);

            returnUrlBuilder.Query = queryNameValueCollection.ToString();

            // Inserts StandardTokens.
            const string StandardTokens  = "{StandardTokens}";
            string       returnUrlString = returnUrlBuilder.Uri.AbsoluteUri;

            returnUrlString = returnUrlString.Insert(returnUrlString.IndexOf("?") + 1, StandardTokens + "&");

            // Constructs redirect url.
            string redirectUrlString = TokenHelper.GetAppContextTokenRequestUrl(spHostUrl.AbsoluteUri, Uri.EscapeDataString(returnUrlString));

            redirectUrl = new Uri(redirectUrlString, UriKind.Absolute);

            return(RedirectionStatus.ShouldRedirect);
        }
Ejemplo n.º 3
0
        protected void Page_Load(object sender, EventArgs e)
        {
            // This is the original code generated by the template.
            //var contextToken = TokenHelper.GetContextTokenFromRequest(Page.Request);
            //var hostWeb = Page.Request["SPHostUrl"];

            //using (var clientContext = TokenHelper.GetClientContextWithContextToken(hostWeb, contextToken, Request.Url.Authority))
            //{
            //    clientContext.Load(clientContext.Web, web => web.Title);
            //    clientContext.ExecuteQuery();
            //    Response.Write(clientContext.Web.Title);
            //}

            // Get app info from web.config
            string clientID = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientId"))
                                ? WebConfigurationManager.AppSettings.Get("HostedAppName")
                                : WebConfigurationManager.AppSettings.Get("ClientId");
            string clientSecret = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientSecret"))
                                ? WebConfigurationManager.AppSettings.Get("HostedAppSigningKey")
                                : WebConfigurationManager.AppSettings.Get("ClientSecret");

            // Get values from Page.Request
            string reqAuthority     = Request.Url.Authority;
            string hostWeb          = Page.Request["SPHostUrl"];
            string hostWebAuthority = (new Uri(hostWeb)).Authority;

            // Get Context Token
            string contextTokenStr = TokenHelper.GetContextTokenFromRequest(Request);
            SharePointContextToken contextToken =
                TokenHelper.ReadAndValidateContextToken(contextTokenStr, reqAuthority);

            // Read data from the Context Token
            string targetPrincipalName = contextToken.TargetPrincipalName;
            string cacheKey            = contextToken.CacheKey;
            string refreshTokenStr     = contextToken.RefreshToken;
            string realm = contextToken.Realm;

            // Create principal and client strings
            string targetPrincipal = GetFormattedPrincipal(targetPrincipalName, hostWebAuthority, realm);
            string appPrincipal    = GetFormattedPrincipal(clientID, null, realm);

            // Request an access token from ACS
            string stsUrl = TokenHelper.AcsMetadataParser.GetStsUrl(realm);
            OAuth2AccessTokenRequest oauth2Request =
                OAuth2MessageFactory.CreateAccessTokenRequestWithRefreshToken(
                    appPrincipal, clientSecret, refreshTokenStr, targetPrincipal);
            OAuth2S2SClient           client         = new OAuth2S2SClient();
            OAuth2AccessTokenResponse oauth2Response = client.Issue(stsUrl, oauth2Request) as OAuth2AccessTokenResponse;
            string accessTokenStr = oauth2Response.AccessToken;

            // Build the CSOM context with the access token
            ClientContext clientContext = TokenHelper.GetClientContextWithAccessToken(hostWeb, accessTokenStr);

            clientContext.Load(clientContext.Web, web => web.Title);
            clientContext.ExecuteQuery();

            // Dump values to the page
            DataTable dt = new DataTable();

            dt.Columns.Add("Name");
            dt.Columns.Add("Value");

            dt.Rows.Add("QueryString", Request.QueryString);
            dt.Rows.Add("clientID", clientID);
            dt.Rows.Add("clientSecret", clientSecret);
            dt.Rows.Add("hostWeb", hostWeb);
            dt.Rows.Add("contextTokenStr", contextTokenStr);
            dt.Rows.Add("contextToken", contextToken);
            dt.Rows.Add("targetPrincipalName", targetPrincipalName);
            dt.Rows.Add("cacheKey", cacheKey);
            dt.Rows.Add("refreshTokenStr", refreshTokenStr);
            dt.Rows.Add("realm", realm);
            dt.Rows.Add("targetPrincipal", targetPrincipal);
            dt.Rows.Add("appPrincipal", appPrincipal);
            dt.Rows.Add("stsUrl", stsUrl);
            dt.Rows.Add("oauth2Request", oauth2Request);
            dt.Rows.Add("client", client);
            dt.Rows.Add("oauth2Response", oauth2Response);
            dt.Rows.Add("accessTokenStr", accessTokenStr);
            dt.Rows.Add("Host Web Title", clientContext.Web.Title);

            grd.DataSource = dt;
            grd.DataBind();
        }
        public ActionResult Index(string SPHostUrl, string keyword)
        {
            Uri              hostWebUri  = new Uri(SPHostUrl);
            string           loginName   = string.Empty;
            List <Community> communities = new List <Community>();

            //Search for the Top 25 communities based on membership count
            using (var ctx = TokenHelper.GetS2SClientContextWithWindowsIdentity(hostWebUri, Request.LogonUserIdentity))
            {
                //Get the user's login Name
                User currentUser = ctx.Web.CurrentUser;
                ctx.Load(currentUser, u => u.LoginName);
                ctx.ExecuteQuery();
                loginName = currentUser.LoginName;

                //Limit search to the current site collection
                Site siteCollection = ctx.Site;
                ctx.Load(siteCollection, s => s.Url);
                ctx.ExecuteQuery();

                //Prepare the query
                KeywordQuery keywordQuery = new KeywordQuery(ctx);
                keywordQuery.QueryText = keyword + " WebTemplate=COMMUNITY +Path:" + siteCollection.Url;
                keywordQuery.SelectProperties.Add("Title");
                keywordQuery.SelectProperties.Add("Description");
                keywordQuery.SelectProperties.Add("CommunityMembersCount");
                keywordQuery.SelectProperties.Add("Path");
                keywordQuery.SortList.Add("CommunityMembersCount", SortDirection.Descending);
                keywordQuery.RowLimit = 25;

                //Execute the query
                SearchExecutor searchExecutor = new SearchExecutor(ctx);
                ClientResult <ResultTableCollection> searchResults = searchExecutor.ExecuteQuery(keywordQuery);
                ctx.ExecuteQuery();

                //Collect the results
                ResultTable resultTable = searchResults.Value.Where <ResultTable>(r => r.TableType == "RelevantResults").FirstOrDefault();
                foreach (var resultRow in resultTable.ResultRows)
                {
                    communities.Add(new Community()
                    {
                        Title           = resultRow["Title"].ToString(),
                        Description     = resultRow["Description"].ToString(),
                        Membership      = int.Parse(resultRow["CommunityMembersCount"].ToString()),
                        SiteRelativeUrl = resultRow["Path"].ToString().Substring(siteCollection.Url.Length),
                        FullUrl         = resultRow["Path"].ToString()
                    });
                }
            }

            //Determine if the current user is a member of each community
            //This is done with app-only access to read the membership lists
            string appOnlyAccessTokenString = TokenHelper.GetS2SAccessTokenWithWindowsIdentity(hostWebUri, null);

            using (ClientContext ctx = TokenHelper.GetClientContextWithAccessToken(SPHostUrl, appOnlyAccessTokenString))
            {
                //Check each community
                foreach (Community community in communities)
                {
                    List memberList = ctx.Site.OpenWeb(community.SiteRelativeUrl).Lists.GetByTitle("Community Members");
                    ctx.Load(memberList);

                    StringBuilder caml = new StringBuilder();
                    caml.Append("<View><Query><Where><Eq><FieldRef Name='Name'/><Value Type='Text'>");
                    caml.Append(loginName);
                    caml.Append("</Value></Eq></Where></Query>");
                    caml.Append("<Joins><Join Type='Inner' ListAlias='Users'><Eq><FieldRef Name='Member' RefType='Id'/>");
                    caml.Append("<FieldRef List='Users' Name='Id'/></Eq></Join></Joins>");
                    caml.Append("<ProjectedFields><Field Name='Name' Type='Lookup' List='Users' ShowField='Name'/></ProjectedFields>");
                    caml.Append("<ViewFields><FieldRef Name='Name'/></ViewFields></View>");
                    CamlQuery query = new CamlQuery();
                    query.ViewXml = caml.ToString();

                    ListItemCollection members = memberList.GetItems(query);
                    ctx.Load(members, m => m.Include(i => i["Name"]));
                    ctx.ExecuteQuery();

                    if (members.Count == 1)
                    {
                        community.CurrentUserIsMember = true;
                    }
                }
            }

            //Display communities
            ViewBag.Url         = Request.Url.AbsolutePath;
            ViewBag.SPHostUrl   = SPHostUrl;
            ViewBag.Communities = communities;
            if (keyword == null)
            {
                return(View());
            }
            else
            {
                return(PartialView());
            }
        }
 public QueryController(ILogger <QueryController> logger, Config config, ConnectionPool pool, TokenHelper tokenHelper)
 {
     this.log         = logger;
     this.config      = config;
     this.pool        = pool;
     this.tokenHelper = tokenHelper;
 }
Ejemplo n.º 6
0
 private bool checkToken(string userId, string accessToken, out string code)
 => TokenHelper.checkAccessToken(tokenUrl, userId, accessToken, out code);
Ejemplo n.º 7
0
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                // Get values from Web.config.
                // NOTE: It is VERY important that you read the ReadMe document
                // so that you will have valid data in your Web.config files.
                // The values provided by this sample will not work for you!
                clientId.Value    = WebConfigurationManager.AppSettings.Get("ClientId");
                redirectUrl.Value = WebConfigurationManager.AppSettings.Get("RedirectUrl");
                Uri sharePointSiteUrl = null;

                // Retrieve data from the form or querystring.
                string siteUrl = Request.Form["siteUrl"];
                if (siteUrl == null)
                {
                    siteUrl = Request.QueryString["siteUrl"];
                }
                string code = Request.Form["code"];
                if (code == null)
                {
                    code = Request.QueryString["code"];
                }
                if (!TokenCache.IsTokenInCache(Request.Cookies) && siteUrl == null && code == null)
                {
                    //If called with no params and no cached token then render the main page
                    return;
                }

                //If siteUrl has been provided, obtain it, otherwise prompt the user
                if (siteUrl != null && siteUrl != "")
                {
                    sharePointSiteUrl = new Uri(siteUrl);
                }
                else
                {
                    //If not SharePoint Site Url in context, we need to prompt the user
                    return;
                }

                // Work with cookies and the token cache to ensure we have valid OAuth tokens.
                if (code != null && code != "")
                {
                    TokenCache.UpdateCacheWithCode(Request, Response, code, sharePointSiteUrl);
                }
                if (!TokenCache.IsTokenInCache(Request.Cookies))
                {
                    return;
                }
                else
                {
                    refreshToken     = TokenCache.GetCachedRefreshToken(Request.Cookies);
                    accessToken      = TokenHelper.GetAccessToken(refreshToken, "00000003-0000-0ff1-ce00-000000000000", sharePointSiteUrl.Authority, TokenHelper.GetRealmFromTargetUrl(sharePointSiteUrl)).AccessToken;
                    connectedSiteUrl = sharePointSiteUrl.ToString();
                    using (ClientContext context = TokenHelper.GetClientContextWithAccessToken(sharePointSiteUrl.ToString(), accessToken))
                    {
                        context.Load(context.Web);
                        context.ExecuteQuery();
                        connected = true;
                        siteTitle = context.Web.Title;
                    }
                }
            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
                Response.Write("\n" + ex.StackTrace);
                Response.End();
            }
        }
Ejemplo n.º 8
0
        protected void cmdCreateLists_Click(object sender, EventArgs e)
        {
            using (var clientContext = TokenHelper.GetS2SClientContextWithWindowsIdentity(hostWeb, Request.LogonUserIdentity)) {
                Web site = clientContext.Web;
                clientContext.Load(site);

                string listTitle = "Announcements";

                // delete list if it exists
                ExceptionHandlingScope scope = new ExceptionHandlingScope(clientContext);
                using (scope.StartScope()) {
                    using (scope.StartTry()) {
                        site.Lists.GetByTitle(listTitle).DeleteObject();
                    }
                    using (scope.StartCatch()) { }
                }

                // create and initialize ListCreationInformation object
                ListCreationInformation listInformation = new ListCreationInformation();
                listInformation.Title             = listTitle;
                listInformation.Url               = "Lists/Announcements";
                listInformation.QuickLaunchOption = QuickLaunchOptions.On;
                listInformation.TemplateType      = (int)ListTemplateType.Announcements;

                // Add ListCreationInformation to lists collection and return list object
                List list = site.Lists.Add(listInformation);

                // modify additional list properties and update
                list.OnQuickLaunch     = true;
                list.EnableAttachments = false;
                list.Update();

                // send command to server to create list
                clientContext.ExecuteQuery();


                WriteDivToPage("List created: " + list.Title);

                clientContext.Load(list);
                clientContext.ExecuteQuery();

                string urlEventReceiver = Request.Url.GetLeftPart(UriPartial.Authority) +
                                          @"/Services/AnnouncementsEventReceiver.svc";

                EventReceiverDefinitionCreationInformation erci1 = new EventReceiverDefinitionCreationInformation();
                erci1.ReceiverName   = "ItemAdding";
                erci1.EventType      = EventReceiverType.ItemAdding;
                erci1.ReceiverUrl    = urlEventReceiver;
                erci1.SequenceNumber = 1000;
                EventReceiverDefinition er1 = list.EventReceivers.Add(erci1);
                er1.Update();

                EventReceiverDefinitionCreationInformation erci2 = new EventReceiverDefinitionCreationInformation();
                erci2.ReceiverName   = "ItemUpdating";
                erci2.EventType      = EventReceiverType.ItemUpdating;
                erci2.ReceiverUrl    = urlEventReceiver;
                erci2.SequenceNumber = 1000;
                EventReceiverDefinition er2 = list.EventReceivers.Add(erci2);
                er2.Update();


                clientContext.ExecuteQuery();
                WriteDivToPage("Event receiver added at " + urlEventReceiver);

                ListItemCreationInformation lici = new ListItemCreationInformation();

                var item1 = list.AddItem(lici);
                item1["Title"]   = "SharePoint introduces new app model";
                item1["Body"]    = "<div>Developers wonder what happened to solutions.</div>";
                item1["Expires"] = DateTime.Today.AddYears(10);
                item1.Update();

                var item2 = list.AddItem(lici);
                item2["Title"]   = "All SharePoint developers must now learn JavaScript";
                item2["Body"]    = "<div>Some developers are more excited then others.</div>";
                item2["Expires"] = DateTime.Today.AddYears(1);
                item2.Update();

                var item3 = list.AddItem(lici);
                item3["Title"]   = "CSOM programming is super fun";
                item3["Body"]    = "<div>Just ask my mom.</div>";
                item3["Expires"] = DateTime.Today.AddDays(7);
                item3.Update();

                clientContext.ExecuteQuery();

                WriteDivToPage("List Item created: " + item1["Title"]);
            }
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Builds a redirect
        /// </summary>
        /// <returns></returns>
        private static string GetRedirectUrl()
        {
            string hostWebUrl = HttpContext.Current.Request["SPHostUrl"];

            return(TokenHelper.GetAppContextTokenRequestUrl(hostWebUrl, HttpContext.Current.Server.UrlEncode(HttpContext.Current.Request.Url.ToString())));
        }
Ejemplo n.º 10
0
 public Task <string> Authorize()
 {
     return(Task.Run(() => { return TokenHelper.GenerateToken(); }));
 }
        public static async Task <TokensAuthenticationModel> AddAccessToken(
            this TokensAuthenticationModel tokensAuthenticationModel, string userName, TokenHelper tokenHelper)
        {
            tokensAuthenticationModel.AccessToken = await tokenHelper.GenerateToken(userName);

            return(tokensAuthenticationModel);
        }
Ejemplo n.º 12
0
        public async Task UpdateDeviceConnectionTest()
        {
            int receivedConnectedStatusCount = 0;
            ConnectionStatusChangesHandler connectionStatusChangesHandler = null;
            string hostname = "dummy.azure-devices.net";
            string deviceId = "device1";

            ITokenCredentials GetClientCredentials(TimeSpan tokenExpiryDuration)
            {
                string token    = TokenHelper.CreateSasToken(hostname, DateTime.UtcNow.AddSeconds(tokenExpiryDuration.TotalSeconds));
                var    identity = new DeviceIdentity(hostname, deviceId);

                return(new TokenCredentials(identity, token, string.Empty, Option.None <string>(), false));
            }

            IDeviceProxy GetMockDeviceProxy()
            {
                var deviceProxyMock1 = new Mock <IDeviceProxy>();

                deviceProxyMock1.SetupGet(dp => dp.IsActive).Returns(true);
                deviceProxyMock1.Setup(dp => dp.CloseAsync(It.IsAny <Exception>()))
                .Callback(() => deviceProxyMock1.SetupGet(dp => dp.IsActive).Returns(false))
                .Returns(Task.CompletedTask);
                return(deviceProxyMock1.Object);
            }

            IClient GetMockedDeviceClient()
            {
                var deviceClient = new Mock <IClient>();

                deviceClient.SetupGet(dc => dc.IsActive).Returns(true);
                deviceClient.Setup(dc => dc.CloseAsync())
                .Callback(() => deviceClient.SetupGet(dc => dc.IsActive).Returns(false))
                .Returns(Task.FromResult(true));

                deviceClient.Setup(dc => dc.SetConnectionStatusChangedHandler(It.IsAny <ConnectionStatusChangesHandler>()))
                .Callback <ConnectionStatusChangesHandler>(c => connectionStatusChangesHandler = c);

                deviceClient.Setup(dc => dc.OpenAsync())
                .Callback(
                    () =>
                {
                    int currentCount = receivedConnectedStatusCount;
                    Assert.NotNull(connectionStatusChangesHandler);
                    connectionStatusChangesHandler.Invoke(ConnectionStatus.Connected, ConnectionStatusChangeReason.Connection_Ok);
                    Assert.Equal(receivedConnectedStatusCount, currentCount);
                })
                .Returns(Task.CompletedTask);
                return(deviceClient.Object);
            }

            ITokenProvider tokenProvider        = null;
            var            deviceClientProvider = new Mock <IClientProvider>();

            deviceClientProvider.Setup(dc => dc.Create(It.IsAny <IIdentity>(), It.IsAny <ITokenProvider>(), It.IsAny <ITransportSettings[]>(), Option.None <string>()))
            .Callback <IIdentity, ITokenProvider, ITransportSettings[], Option <string> >((s, a, t, m) => tokenProvider = a)
            .Returns(GetMockedDeviceClient);

            var metadataStore = new Mock <IMetadataStore>();

            metadataStore.Setup(m => m.GetMetadata(It.IsAny <string>())).ReturnsAsync(new ConnectionMetadata("dummyValue"));
            var messageConverterProvider = Mock.Of <IMessageConverterProvider>();

            var deviceScopeIdentitiesCache = new Mock <IDeviceScopeIdentitiesCache>();

            deviceScopeIdentitiesCache.Setup(d => d.GetAuthChain(It.Is <string>(i => i == deviceId))).ReturnsAsync(Option.Some(deviceId));

            var credentialsCache = Mock.Of <ICredentialsCache>();
            ICloudConnectionProvider cloudConnectionProvider = new CloudConnectionProvider(
                messageConverterProvider,
                1,
                deviceClientProvider.Object,
                Option.None <UpstreamProtocol>(),
                TokenProvider,
                deviceScopeIdentitiesCache.Object,
                credentialsCache,
                Mock.Of <IIdentity>(i => i.Id == $"{deviceId}/$edgeHub"),
                TimeSpan.FromMinutes(60),
                true,
                TimeSpan.FromSeconds(20),
                false,
                Option.None <IWebProxy>(),
                metadataStore.Object,
                true);

            cloudConnectionProvider.BindEdgeHub(Mock.Of <IEdgeHub>());
            var deviceConnectivityManager        = Mock.Of <IDeviceConnectivityManager>();
            IConnectionManager connectionManager = new ConnectionManager(cloudConnectionProvider, Mock.Of <ICredentialsCache>(), new IdentityProvider(hostname), deviceConnectivityManager);

            ITokenCredentials clientCredentials1 = GetClientCredentials(TimeSpan.FromSeconds(10));
            Try <ICloudProxy> cloudProxyTry1     = await connectionManager.CreateCloudConnectionAsync(clientCredentials1);

            Assert.True(cloudProxyTry1.Success);

            IDeviceProxy deviceProxy1 = GetMockDeviceProxy();
            await connectionManager.AddDeviceConnection(clientCredentials1.Identity, deviceProxy1);

            await Task.Delay(TimeSpan.FromSeconds(10));

            Assert.NotNull(tokenProvider);
            Task <string> tokenGetter = tokenProvider.GetTokenAsync(Option.None <TimeSpan>());

            Assert.False(tokenGetter.IsCompleted);

            ITokenCredentials clientCredentials2 = GetClientCredentials(TimeSpan.FromMinutes(2));
            Try <ICloudProxy> cloudProxyTry2     = await connectionManager.CreateCloudConnectionAsync(clientCredentials2);

            Assert.True(cloudProxyTry2.Success);

            IDeviceProxy deviceProxy2 = GetMockDeviceProxy();
            await connectionManager.AddDeviceConnection(clientCredentials2.Identity, deviceProxy2);

            await Task.Delay(TimeSpan.FromSeconds(3));

            Assert.False(tokenGetter.IsCompleted);

            ITokenCredentials clientCredentials3 = GetClientCredentials(TimeSpan.FromMinutes(10));
            Try <ICloudProxy> cloudProxyTry3     = await connectionManager.CreateCloudConnectionAsync(clientCredentials3);

            Assert.True(cloudProxyTry3.Success);

            IDeviceProxy deviceProxy3 = GetMockDeviceProxy();
            await connectionManager.AddDeviceConnection(clientCredentials3.Identity, deviceProxy3);

            await Task.Delay(TimeSpan.FromSeconds(23));

            Assert.True(tokenGetter.IsCompleted);
            Assert.Equal(tokenGetter.Result, clientCredentials3.Token);
        }
Ejemplo n.º 13
0
        public async Task RefreshTokenWithRetryTest()
        {
            string iothubHostName = "test.azure-devices.net";
            string deviceId       = "device1";

            ITokenCredentials GetClientCredentialsWithExpiringToken()
            {
                string token    = TokenHelper.CreateSasToken(iothubHostName, DateTime.UtcNow.AddMinutes(3));
                var    identity = new DeviceIdentity(iothubHostName, deviceId);

                return(new TokenCredentials(identity, token, string.Empty, Option.None <string>(), false));
            }

            ITokenCredentials GetClientCredentialsWithNonExpiringToken()
            {
                string token    = TokenHelper.CreateSasToken(iothubHostName, DateTime.UtcNow.AddMinutes(10));
                var    identity = new DeviceIdentity(iothubHostName, deviceId);

                return(new TokenCredentials(identity, token, string.Empty, Option.None <string>(), false));
            }

            ITokenProvider  tokenProvider  = null;
            IClientProvider clientProvider = GetMockDeviceClientProviderWithToken((s, a, t, m) => tokenProvider = a);

            var transportSettings = new ITransportSettings[] { new AmqpTransportSettings(TransportType.Amqp_Tcp_Only) };

            var receivedStatuses = new List <CloudConnectionStatus>();

            void ConnectionStatusHandler(string id, CloudConnectionStatus status) => receivedStatuses.Add(status);

            var messageConverterProvider = new MessageConverterProvider(new Dictionary <Type, IMessageConverter> {
                [typeof(TwinCollection)] = Mock.Of <IMessageConverter>()
            });

            ITokenCredentials          clientCredentialsWithExpiringToken1 = GetClientCredentialsWithExpiringToken();
            ClientTokenCloudConnection cloudConnection = await ClientTokenCloudConnection.Create(
                clientCredentialsWithExpiringToken1,
                ConnectionStatusHandler,
                transportSettings,
                messageConverterProvider,
                clientProvider,
                Mock.Of <ICloudListener>(),
                TimeSpan.FromMinutes(60),
                true,
                TimeSpan.FromSeconds(20),
                DummyProductInfo,
                Option.None <string>());

            Option <ICloudProxy> cloudProxy1 = cloudConnection.CloudProxy;

            Assert.True(cloudProxy1.HasValue);
            Assert.True(cloudProxy1.OrDefault().IsActive);

            Assert.NotNull(tokenProvider);

            // Try to refresh token but get an expiring token
            Task <string> getTokenTask = tokenProvider.GetTokenAsync(Option.None <TimeSpan>());

            Assert.False(getTokenTask.IsCompleted);

            Assert.Single(receivedStatuses);
            Assert.Equal(CloudConnectionStatus.TokenNearExpiry, receivedStatuses[0]);

            ICloudProxy cloudProxy2 = await cloudConnection.UpdateTokenAsync(clientCredentialsWithExpiringToken1);

            // Wait for the task to process
            await Task.Delay(TimeSpan.FromSeconds(5));

            Assert.False(getTokenTask.IsCompletedSuccessfully);
            Assert.Equal(cloudProxy2, cloudConnection.CloudProxy.OrDefault());
            Assert.True(cloudProxy2.IsActive);
            Assert.True(cloudProxy1.OrDefault().IsActive);
            Assert.Equal(cloudProxy1.OrDefault(), cloudProxy2);

            // Wait for 20 secs for retry to happen
            await Task.Delay(TimeSpan.FromSeconds(20));

            // Check if retry happened
            Assert.Equal(2, receivedStatuses.Count);
            Assert.Equal(CloudConnectionStatus.TokenNearExpiry, receivedStatuses[1]);

            ITokenCredentials clientCredentialsWithNonExpiringToken = GetClientCredentialsWithNonExpiringToken();
            ICloudProxy       cloudProxy3 = await cloudConnection.UpdateTokenAsync(clientCredentialsWithNonExpiringToken);

            // Wait for the task to complete
            await Task.Delay(TimeSpan.FromSeconds(5));

            Assert.True(getTokenTask.IsCompletedSuccessfully);
            Assert.Equal(cloudProxy3, cloudConnection.CloudProxy.OrDefault());
            Assert.True(cloudProxy3.IsActive);
            Assert.True(cloudProxy1.OrDefault().IsActive);
            Assert.Equal(cloudProxy1.OrDefault(), cloudProxy3);
            Assert.Equal(getTokenTask.Result, clientCredentialsWithNonExpiringToken.Token);
        }
Ejemplo n.º 14
0
 /// <summary>
 /// Whispers the specified message.
 /// </summary>
 /// <param name="message">The message.</param>
 private void Whisper(string message)
 {
     this._keyboardHelper.Whisper(this.PlayerName, TokenHelper.ReplaceToken(message, this._tradeEvent));
 }
Ejemplo n.º 15
0
 /// <summary>
 /// Thanks you.
 /// </summary>
 public void ThankYou()
 {
     this.Whisper(TokenHelper.ReplaceToken(this._settingsService.ThankYouMessage, this.Event));
 }
Ejemplo n.º 16
0
 public DropBoxControlViewModel(IInteractionInvoker interactionInvoker, IDropboxService dropboxService, TokenHelper tokenHelper, ITranslationUpdater translationUpdater, ISelectedProfileProvider profile) : base(translationUpdater, profile)
 {
     _interactionInvoker         = interactionInvoker;
     _dropboxService             = dropboxService;
     AddDropboxAccountCommand    = new DelegateCommand(AuthoriseDropboxUser);
     _accountsCollection         = new Helper.SynchronizedCollection <DropboxAccount>(new List <DropboxAccount>());
     RemoveDropboxAccountCommand = new DelegateCommand(RemoveDropboxAccount, RemoveDropboxCanExecute);
     if (tokenHelper != null)
     {
         TokenReplacer  = tokenHelper.TokenReplacerWithPlaceHolders;
         TokenViewModel = new TokenViewModel(x => CurrentProfile.DropboxSettings.SharedFolder = x, () => CurrentProfile?.DropboxSettings.SharedFolder, tokenHelper.GetTokenListForDirectory(), ReplaceTokens);
     }
 }
Ejemplo n.º 17
0
        public override void OnLoad(HttpContext context)
        {
            base.OnLoad(context);
            requestBody             = new RequestBody();
            requestBody.accessToken = context.Request["accessToken"];
            requestBody.uTo         = Convert.ToInt32(context.Request["to"]);
            requestBody.content     = context.Request["content"];

            if (requestBody.content.Length == 0 || requestBody.accessToken.Trim().Length == 0 || requestBody.uTo == 0)
            {
                SystemResponse.Output(SystemResponse.TYPE_NULLPARAMETER, out statusCode, out responseJson);
            }
            else
            {
                //验证用户
                TokenHelper    token     = new TokenHelper();
                UserTokenModel fromModel = token.getUserToken(requestBody.accessToken);
                UserTokenModel toModel   = token.getUserToken(requestBody.uTo);
                if (fromModel == null)
                {
                    SystemResponse.Output(SystemResponse.TYPE_EXPIRE, out statusCode, out responseJson);
                }
                else
                {
                    int msgstatus = 0;

                    #region 入库至本地
                    ModelAdo <MsgModel> modelAdo = new ModelAdo <MsgModel>();
                    MsgModel            msg      = new MsgModel();
                    msg.ufrom      = Convert.ToInt32(fromModel.uid);
                    msg.uto        = requestBody.uTo;
                    msg.content    = requestBody.content;
                    msg.createTime = StringHelper.ConvertDateTimeInt(DateTime.Now);
                    msg.status     = msgstatus;
                    if (modelAdo.Insert(msg) >= 1)
                    {
                        #region 百度推送
                        if (toModel != null && toModel.bpuserId.Length >= 1 && toModel.channelId.Length >= 1)
                        {
                            //获取插入本地数据
                            MsgModel msgPush = modelAdo.GetModel("ufrom=?ufrom AND uto=?uto AND createTime=?createTime AND status=0", "",
                                                                 new MySqlParameter("?ufrom", msg.ufrom),
                                                                 new MySqlParameter("?uto", msg.uto),
                                                                 new MySqlParameter("?createTime", msg.createTime));
                            if (msgPush != null)
                            {
                                try
                                {
                                    //百度配置信息
                                    string secretKey    = ConfigurationManager.AppSettings["baidu_secret_key"];
                                    string apiKey       = ConfigurationManager.AppSettings["baidu_api_key"];
                                    uint   depolyStatus = uint.Parse(ConfigurationManager.AppSettings["baidu_depoly_status"]);

                                    String    messages     = "";
                                    TimeSpan  ts           = (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0));
                                    uint      unixTime     = (uint)ts.TotalSeconds;
                                    string    messageksy   = "api";
                                    uint      message_type = 1;
                                    BaiduPush Bpush        = new BaiduPush("POST", secretKey);



                                    if (toModel.deviceType == 1)
                                    {
                                        message_type       = 1;
                                        toModel.deviceType = 4;
                                        IOSNotification notifaction = new IOSNotification();
                                        notifaction.id         = msgPush.id;
                                        notifaction.ufrom      = msgPush.ufrom;
                                        notifaction.uto        = msgPush.uto;
                                        notifaction.content    = msgPush.content.Trim();
                                        notifaction.createTime = string.Format("{0:yyyy/MM/dd HH:mm:ss}", System.DateTime.Now);
                                        notifaction.type       = msgPush.type;
                                        notifaction.status     = 1;
                                        IOSAPS aps = new IOSAPS()
                                        {
                                            alert = "收到一条新消息",
                                        };
                                        notifaction.aps = aps;
                                        messages        = notifaction.getJsonString();
                                    }
                                    else
                                    {
                                        message_type       = 0;
                                        toModel.deviceType = 3;
                                        BaiduPushNotification notifaction = new BaiduPushNotification();
                                        notifaction.title = "";
                                        //构建custom_content信息
                                        BaiduDescription bdMsg = new BaiduDescription();
                                        bdMsg.id                   = msgPush.id;
                                        bdMsg.ufrom                = msgPush.ufrom;
                                        bdMsg.uto                  = msgPush.uto;
                                        bdMsg.content              = msgPush.content;
                                        bdMsg.createTime           = string.Format("{0:yyyy/MM/dd HH:mm:ss}", System.DateTime.Now);
                                        bdMsg.type                 = msgPush.type;
                                        bdMsg.status               = 1;
                                        notifaction.description    = "收到一条新消息";
                                        notifaction.custom_content = bdMsg;
                                        messages                   = notifaction.getJsonString();
                                    }



                                    PushOptions pOpts = new PushOptions("push_msg", apiKey, toModel.bpuserId.ToString(),
                                                                        toModel.channelId.ToString(), Convert.ToUInt32(toModel.deviceType), messages, messageksy, unixTime);
                                    pOpts.message_type  = message_type;
                                    pOpts.deploy_status = depolyStatus;
                                    pOpts.push_type     = 1;
                                    string response = Bpush.PushMessage(pOpts);
                                    responseJson = response;
                                    msgstatus    = 1;

                                    //处理数据为已读
                                    if (msg.status == 0)
                                    {
                                        msgPush.status = 1;
                                        modelAdo.Update(msgPush);
                                    }

                                    //SystemResponse.Output(SystemResponse.TYPE_OK, out statusCode, out responseJson);
                                    //responseJson = strBDMsg;
                                }
                                catch (Exception ex)
                                {
                                    responseJson = ex.ToString();
                                    SystemResponse.Output(SystemResponse.TYPE_ERROR, out statusCode, out responseJson);
                                }
                            }
                            #endregion
                        }
                        else
                        {
                            SystemResponse.Output(SystemResponse.TYPE_ERROR, out statusCode, out responseJson);
                        }
                        #endregion
                    }
                }
            }
        }
Ejemplo n.º 18
0
        public static ClientContext GetAppOnlyContext(string url)
        {
            if (String.IsNullOrEmpty(url))
            {
                throw new ArgumentNullException("url");
            }
            if (TokenHelper.IsHighTrustApp())
            {
                return(TokenHelper.GetS2SClientContextWithWindowsIdentity(new Uri(url), null));
            }
            // TODO: Test app only context code with ACS in O365.
            var fullUri        = new Uri(url);
            var appOnlyContext = TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, fullUri.Authority, TokenHelper.GetRealmFromTargetUrl(fullUri));

            return(TokenHelper.GetClientContextWithAccessToken(url, appOnlyContext.AccessToken));
        }
Ejemplo n.º 19
0
        public StampUserControlViewModel(IInteractionInvoker interactionInvoker, IFontHelper fontHelper, TokenHelper tokenHelper,
                                         ITranslationUpdater translationUpdater, ISelectedProfileProvider profile, ITokenViewModelFactory tokenViewModelFactory, IDispatcher dispatcher)
            : base(translationUpdater, profile, dispatcher)
        {
            _interactionInvoker = interactionInvoker;
            _fontHelper         = fontHelper;

            if (CurrentProfile != null)
            {
                UpdateFontButtonText(CurrentProfile.Stamping);
            }

            translationUpdater.RegisterAndSetTranslation(tf =>
            {
                _tokenReplacer = tokenHelper.TokenReplacerWithPlaceHolders;
                var tokens     = tokenHelper.GetTokenListForStamp();
                SetTokenViewModels(tokenViewModelFactory, tokens);
            });
        }
        protected override void OnLoad(EventArgs e)
        {
            bool hasManageWebPerms = false;

            //get SharePoint context
            var spContext = Util.ContextUtil.Current;

            using (var clientContext = TokenHelper.GetClientContextWithContextToken(spContext.ContextDetails.AppWebUrl, spContext.ContextDetails.ContextTokenString, Request.Url.Authority))
            {
                //check if the user has ManageWeb permissions from app web
                BasePermissions perms = new BasePermissions();
                perms.Set(PermissionKind.ManageWeb);
                ClientResult <bool> result = clientContext.Web.DoesUserHavePermissions(perms);
                clientContext.ExecuteQuery();
                hasManageWebPerms = result.Value;
            }

            //define initial script
            string script = @"
            function chromeLoaded() {
                $('body').show();
            }
            //function callback to render chrome after SP.UI.Controls.js loads
            function renderSPChrome() {
                //Get the host site logo url from the SPHostLogoUrl parameter
                var hostlogourl = decodeURIComponent(getQueryStringParameter('SPHostLogoUrl'));

                var links = [{
                    'linkUrl': 'mailto:[email protected]',
                    'displayName': 'Contact us'
                }];
                ";

            //add link to settings if the current user has ManageWeb permissions
            if (hasManageWebPerms)
            {
                script += @"links.push({
                        'linkUrl': '" + spContext.ContextDetails.AppWebUrl + @"/SSConfig',
                        'displayName': 'Settings'
                    });";
            }

            //add remainder of script
            script += @"
                //Set the chrome options for launching Help, Account, and Contact pages
                var options = {
                    'appIconUrl': hostlogourl,
                    'appTitle': document.title,
                    'settingsLinks': links,
                    'onCssLoaded': 'chromeLoaded()'
                };

                //Load the Chrome Control in the divSPChrome element of the page
                var chromeNavigation = new SP.UI.Controls.Navigation('divSPChrome', options);
                chromeNavigation.setVisible(true);

            }";

            //register script in page
            Page.ClientScript.RegisterClientScriptBlock(typeof(BasePage), "BasePageScript", script, true);

            //call base onload
            base.OnLoad(e);
        }
Ejemplo n.º 21
0
 public TokenHintPanelViewModel(ITranslationUpdater translationUpdater, TokenHelper tokenHelper, ShowUserGuideCommand userGuideCommand) : base(translationUpdater)
 {
     TokenHelper      = tokenHelper;
     UserGuideCommand = userGuideCommand;
     userGuideCommand.Init(HelpTopic.Tokens);
 }
Ejemplo n.º 22
0
        public async Task GetMultipleCloudProxiesTest()
        {
            // Arrange
            string  edgeDeviceId             = "edgeDevice";
            string  module1Id                = "module1";
            string  token                    = TokenHelper.CreateSasToken(IotHubHostName);
            var     module1Credentials       = new TokenCredentials(new ModuleIdentity(IotHubHostName, edgeDeviceId, module1Id), token, DummyProductInfo, true);
            IClient client1                  = GetDeviceClient();
            IClient client2                  = GetDeviceClient();
            var     messageConverterProvider = Mock.Of <IMessageConverterProvider>();
            var     deviceClientProvider     = new Mock <IClientProvider>();

            deviceClientProvider.SetupSequence(d => d.Create(It.IsAny <IIdentity>(), It.IsAny <ITokenProvider>(), It.IsAny <Client.ITransportSettings[]>()))
            .Returns(client1)
            .Returns(client2);

            ICredentialsCache credentialsCache = new CredentialsCache(new NullCredentialsCache());
            await credentialsCache.Add(module1Credentials);

            var cloudConnectionProvider = new CloudConnectionProvider(
                messageConverterProvider,
                1,
                deviceClientProvider.Object,
                Option.None <UpstreamProtocol>(),
                Mock.Of <ITokenProvider>(),
                Mock.Of <IDeviceScopeIdentitiesCache>(),
                credentialsCache,
                new ModuleIdentity(IotHubHostName, edgeDeviceId, "$edgeHub"),
                TimeSpan.FromMinutes(60),
                true,
                TimeSpan.FromSeconds(20));

            cloudConnectionProvider.BindEdgeHub(Mock.Of <IEdgeHub>());
            IConnectionManager connectionManager = new ConnectionManager(cloudConnectionProvider, credentialsCache, GetIdentityProvider());

            // Act
            Task <Option <ICloudProxy> > getCloudProxyTask1 = connectionManager.GetCloudConnection(module1Credentials.Identity.Id);
            Task <Option <ICloudProxy> > getCloudProxyTask2 = connectionManager.GetCloudConnection(module1Credentials.Identity.Id);
            Task <Option <ICloudProxy> > getCloudProxyTask3 = connectionManager.GetCloudConnection(module1Credentials.Identity.Id);
            Task <Option <ICloudProxy> > getCloudProxyTask4 = connectionManager.GetCloudConnection(module1Credentials.Identity.Id);

            Option <ICloudProxy>[] cloudProxies = await Task.WhenAll(getCloudProxyTask1, getCloudProxyTask2, getCloudProxyTask3, getCloudProxyTask4);

            // Assert
            Assert.True(cloudProxies[0].HasValue);
            Assert.True(cloudProxies[1].HasValue);
            Assert.True(cloudProxies[2].HasValue);
            Assert.True(cloudProxies[3].HasValue);
            Assert.Equal(cloudProxies[0].OrDefault(), cloudProxies[1].OrDefault());
            Assert.Equal(cloudProxies[0].OrDefault(), cloudProxies[2].OrDefault());
            Assert.Equal(cloudProxies[0].OrDefault(), cloudProxies[3].OrDefault());

            // Act
            await cloudProxies[0].OrDefault().CloseAsync();
            Option <ICloudProxy> newCloudProxyTask1 = await connectionManager.GetCloudConnection(module1Credentials.Identity.Id);

            // Assert
            Assert.True(newCloudProxyTask1.HasValue);
            Assert.NotEqual(newCloudProxyTask1.OrDefault(), cloudProxies[0].OrDefault());
            Mock.Get(client1).Verify(cp => cp.CloseAsync(), Times.Once);
            Mock.Get(client2).Verify(cp => cp.CloseAsync(), Times.Never);
        }
 /// <summary>
 /// Returns an app only ClientContext object
 /// </summary>
 /// <param name="siteUrl">Site for which the ClientContext object will be instantiated</param>
 /// <param name="appId">Application ID which is requesting the ClientContext object</param>
 /// <param name="appSecret">Application secret of the Application which is requesting the ClientContext object</param>
 /// <returns>ClientContext to be used by CSOM code</returns>
 public ClientContext GetAppOnlyAuthenticatedContext(string siteUrl, string appId, string appSecret)
 {
     return(GetAppOnlyAuthenticatedContext(siteUrl, TokenHelper.GetRealmFromTargetUrl(new Uri(siteUrl)), appId, appSecret));
 }
        public override void ExecuteCmdlet()
        {
            base.ExecuteCmdlet();

            var fileInfo = new System.IO.FileInfo(FilePath);
            var site     = this.ClientContext.Site;
            var web      = this.ClientContext.Web;

            this.ClientContext.Load(site, ccsu => ccsu.ServerRelativeUrl, cssu => cssu.UserCustomActions);
            this.ClientContext.Load(web, ccwu => ccwu.ServerRelativeUrl, ccwu => ccwu.UserCustomActions);
            this.ClientContext.ExecuteQueryRetry();

            var siteurl = TokenHelper.EnsureTrailingSlash(site.ServerRelativeUrl);
            var weburl  = TokenHelper.EnsureTrailingSlash(web.ServerRelativeUrl);



            var actions = JsonConvert.DeserializeObject <SPCustomAction>(System.IO.File.ReadAllText(fileInfo.FullName));

            if (actions.Site != null)
            {
                if (actions.Site.scriptblocks != null && actions.Site.scriptblocks.Any())
                {
                    actions.Site.scriptblocks.ForEach(cab =>
                    {
                        var htmlblock = cab.htmlblock.Replace("~SiteCollection/", siteurl);
                        htmlblock     = htmlblock.Replace("~Site/", weburl);

                        site.AddOrUpdateCustomActionLinkBlock(cab.name, htmlblock, cab.sequence);
                    });
                }
                if (actions.Site.scriptlinks != null && actions.Site.scriptlinks.Any())
                {
                    actions.Site.scriptlinks.ForEach(cab =>
                    {
                        site.AddOrUpdateCustomActionLink(cab.name, cab.linkurl, cab.sequence);
                    });
                }
            }

            if (actions.Web != null)
            {
                if (actions.Web.scriptblocks != null && actions.Web.scriptblocks.Any())
                {
                    actions.Web.scriptblocks.ForEach(cab =>
                    {
                        var htmlblock = cab.htmlblock.Replace("~SiteCollection/", siteurl);
                        htmlblock     = htmlblock.Replace("~Site/", weburl);

                        web.AddOrUpdateCustomActionLinkBlock(cab.name, htmlblock, cab.sequence);
                    });
                }
                if (actions.Web.scriptlinks != null && actions.Web.scriptlinks.Any())
                {
                    actions.Web.scriptlinks.ForEach(cab =>
                    {
                        web.AddOrUpdateCustomActionLink(cab.name, cab.linkurl, cab.sequence);
                    });
                }
            }
        }
Ejemplo n.º 25
0
        public static void ProcessQueueMessage([QueueTrigger("siteprovisioningqueue")] ActionRequest actionRequest, TextWriter log)
        {
            try
            {
                //   Updatehelper.UpdateDashboard("Request receiveded.");

                Log.AddlogToTable(actionRequest, State.Provisioning);

                if (actionRequest.IsSiteCollection)
                {
                    CreateSiteCollection(actionRequest);
                    Updatehelper.UpdateProgressView("Provisioning", actionRequest);
                }
                else
                {
                    CreateSite(actionRequest);
                    Updatehelper.UpdateProgressView("Create site", actionRequest);
                }

                Log.AddlogToTable(actionRequest, State.Created);
                Console.WriteLine(actionRequest.Url + "/" + actionRequest.Name, actionRequest.Name, actionRequest.User);
                //var mail = new NotificationMail();
                //mail.SendMailNotification(actionRequest.Url + "/" + actionRequest.Name, actionRequest.Name, actionRequest.User);
                Updatehelper.UpdateProgressView("Done", actionRequest);
            }
            catch (Exception ex)
            {
                Log.AddlogToTable(actionRequest, State.Failed);
                Updatehelper.UpdateProgressView("Failed", actionRequest);

                Console.WriteLine(ex.ToString(), "Failed creating site: " + actionRequest.Url + "/" + actionRequest.Name,
                                  actionRequest.User);

                //var mail = new NotificationMail();
                //mail.SendMailNotification(ex.ToString(), "Failed creating site: " + actionRequest.Url + "/" + actionRequest.Name, actionRequest.User);

                if (actionRequest.IsSiteCollection)
                {
                    var tenantAdminUri = new Uri($"https://{actionRequest.TenantName}-admin.sharepoint.com");
                    var realm          = TokenHelper.GetRealmFromTargetUrl(tenantAdminUri);
                    var token          =
                        TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, tenantAdminUri.Authority,
                                                          realm).AccessToken;
                    using (var ctx = TokenHelper.GetClientContextWithAccessToken(tenantAdminUri.ToString(), token))
                    {
                        var manager = new SiteCollectionManager(actionRequest, ctx);
                        manager.TryDeleteSiteCollection();
                    }
                }
                else
                {
                    var tenantAdminUri = new Uri(actionRequest.Url);
                    var realm          = TokenHelper.GetRealmFromTargetUrl(tenantAdminUri);
                    var token          =
                        TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, tenantAdminUri.Authority,
                                                          realm).AccessToken;
                    using (var ctx = TokenHelper.GetClientContextWithAccessToken(tenantAdminUri.ToString(), token))
                    {
                        var manager = new SiteManager(actionRequest, ctx);
                        manager.TryDeleteSite();
                    }
                }
            }
        }
Ejemplo n.º 26
0
        public static IWebHost Seed(this IWebHost webHost)
        {
            using (var scope = webHost.Services.CreateScope())
            {
                using (var context = scope.ServiceProvider.GetRequiredService <PridDbContext>())
                {
                    try
                    {
                        Console.Write(" \n ... ----- -------- [Seeding data] -------- ----- ... \n");
                        if (context.Users.Count() == 0)
                        {
                            context.Users.AddRange(
                                new User {
                                Id = 1, Pseudo = "ben", Password = TokenHelper.GetPasswordHash("ben"), LastName = "Penelle", FirstName = "Benoît", Email = "*****@*****.**"
                            },
                                new User {
                                Id = 2, Pseudo = "bruno", Password = TokenHelper.GetPasswordHash("bruno"), LastName = "Lacroix", FirstName = "Bruno", Email = "*****@*****.**"
                            },
                                new User {
                                Id = 3, Pseudo = "admin", Password = TokenHelper.GetPasswordHash("admin"), LastName = "Administrator", FirstName = "Administrator", Email = "*****@*****.**", Role = Role.Admin
                            },
                                new User {
                                Id = 4, Pseudo = "boris", Password = TokenHelper.GetPasswordHash("boris"), LastName = "Verhaegen", FirstName = "Boris", Email = "*****@*****.**", Role = Role.Admin
                            },
                                new User {
                                Id = 5, Pseudo = "alain", Password = TokenHelper.GetPasswordHash("alain"), LastName = "Silovy", FirstName = "Alain", Email = "*****@*****.**"
                            }
                                );
                            context.SaveChanges();
                        }
                        if (context.Posts.Count() == 0)
                        {
                            context.Posts.AddRange(
                                new Post()
                            {
                                Id        = 1,
                                Title     = "What does 'initialization' exactly mean?",
                                Body      = @"My csapp book says that if global and static variables are initialized, than they are contained in .data section in ELF relocatable object file.
So my question is that if some `foo.c` code contains 
```
int a;
int main()
{
    a = 3;
}`
```
and `example.c` contains,
```
int b = 3;
int main()
{
...
}
```
is it only `b` that considered to be initialized? In other words, does initialization mean declaration and definition in same line?",
                                AuthorId  = 1,
                                Timestamp = new DateTime(2019, 11, 15, 8, 30, 0)
                            },
                                new Post()
                            {
                                Id        = 2,
                                Body      = @"It means exactly what it says. Initialized static storage duration objects will have their init values set before the main function is called. Not initialized will be zeroed. The second part of the statement is actually implementation dependant,  and implementation has the full freedom of the way it will be archived. 
When you declare the variable without the keyword `extern`  you always define it as well",
                                ParentId  = 1,
                                AuthorId  = 2,
                                Timestamp = new DateTime(2019, 11, 15, 8, 31, 0)
                            },
                                new Post()
                            {
                                Id        = 3,
                                Body      = @"Both are considered initialized
------------------------------------
They get [zero initialized][1] or constant initalized (in short: if the right hand side is a compile time constant expression).
> If permitted, Constant initialization takes place first (see Constant
> initialization for the list of those situations). In practice,
> constant initialization is usually performed at compile time, and
> pre-calculated object representations are stored as part of the
> program image. If the compiler doesn't do that, it still has to
> guarantee that this initialization happens before any dynamic
> initialization.
> 
> For all other non-local static and thread-local variables, Zero
> initialization takes place. In practice, variables that are going to
> be zero-initialized are placed in the .bss segment of the program
> image, which occupies no space on disk, and is zeroed out by the OS
> when loading the program.
To sum up, if the implementation cannot constant initialize it, then it must first zero initialize and then initialize it before any dynamic initialization happends.
  [1]: https://en.cppreference.com/w/cpp/language/zero_initialization
",
                                ParentId  = 1,
                                AuthorId  = 3,
                                Timestamp = new DateTime(2019, 11, 15, 8, 32, 0)
                            },
                                new Post()
                            {
                                Id        = 4,
                                Title     = "How do I escape characters in an Angular date pipe?",
                                Body      = @"I have an Angular date variable `today` that I'm using the [date pipe][1] on, like so:
    {{today | date:'LLLL d'}}
> February 13
However, I would like to make it appear like this:
> 13 days so far in February
When I try a naive approach to this, I get this result:
    {{today | date:'d days so far in LLLL'}}
> 13 13PM201818 18o fPMr in February
This is because, for instance `d` refers to the day.
How can I escape these characters in an Angular date pipe? I tried `\d` and such, but the result did not change with the added backslashes.
  [1]: https://angular.io/api/common/DatePipe",
                                AuthorId  = 1,
                                Timestamp = new DateTime(2019, 11, 15, 8, 33, 0)
                            },
                                new Post()
                            {
                                Id        = 5,
                                Body      = @"How about this:
    {{today | date:'d \'days so far in\' LLLL'}}
Anything inside single quotes is ignored. Just don't forget to escape them.",
                                ParentId  = 4,
                                AuthorId  = 1,
                                Timestamp = new DateTime(2019, 11, 15, 8, 34, 0)
                            },
                                new Post()
                            {
                                Id        = 6,
                                Body      = @"Then only other alternative to stringing multiple pipes together as suggested by RichMcCluskey would be to create a custom pipe that calls through to momentjs format with the passed in date. Then you could use the same syntax including escape sequence that momentjs supports.
Something like this could work, it is not an exhaustive solution in that it does not deal with localization at all and there is no error handling code or tests.
    import { Inject, Pipe, PipeTransform } from '@angular/core';
    @Pipe({ name: 'momentDate', pure: true })
    export class MomentDatePipe implements PipeTransform {
        transform(value: any, pattern: string): string {
            if (!value)
                return '';
            return moment(value).format(pattern);
        }
    }
And then the calling code:
    {{today | momentDate:'d [days so far in] LLLL'}}
For all the format specifiers see the [documentation for format][1]. 
Keep in mind you do have to import `momentjs` either as an import statement, have it imported in your cli config file, or reference the library from the root HTML page (like index.html).
  [1]: http://momentjs.com/docs/#/displaying/format/",
                                ParentId  = 4,
                                AuthorId  = 3,
                                Timestamp = new DateTime(2019, 11, 15, 8, 35, 0)
                            },
                                new Post()
                            {
                                Id        = 7,
                                Body      = @"As far as I know this is not possible with the Angular date pipe at the time of this answer. One alternative is to use multiple date pipes like so:
    {{today | date:'d'}} days so far in {{today | date:'LLLL'}}
EDIT:
After posting this I tried @Gh0sT 's solution and it worked, so I guess there is a way to use one date pipe.",
                                ParentId  = 4,
                                AuthorId  = 2,
                                Timestamp = new DateTime(2019, 11, 15, 8, 36, 0)
                            },
                                new Post()
                            {
                                Id        = 8,
                                Title     = "Q1",
                                Body      = "Q1",
                                AuthorId  = 5,
                                Timestamp = new DateTime(2019, 11, 22, 8, 0, 0)
                            },
                                new Post()
                            {
                                Id        = 9,
                                Body      = "R1",
                                ParentId  = 8,
                                AuthorId  = 1,
                                Timestamp = new DateTime(2019, 11, 22, 8, 5, 0)
                            },
                                new Post()
                            {
                                Id        = 10,
                                Body      = "R2",
                                ParentId  = 8,
                                AuthorId  = 2,
                                Timestamp = new DateTime(2019, 11, 22, 8, 3, 0)
                            },
                                new Post()
                            {
                                Id        = 11,
                                Body      = "R3",
                                ParentId  = 8,
                                AuthorId  = 3,
                                Timestamp = new DateTime(2019, 11, 22, 8, 4, 0)
                            },
                                new Post()
                            {
                                Id        = 12,
                                Title     = "Q2",
                                Body      = "Q2",
                                AuthorId  = 4,
                                Timestamp = new DateTime(2019, 11, 22, 9, 0, 0)
                            },
                                new Post()
                            {
                                Id        = 13,
                                Body      = "R4",
                                ParentId  = 12,
                                AuthorId  = 5,
                                Timestamp = new DateTime(2019, 11, 22, 9, 1, 0)
                            },
                                new Post()
                            {
                                Id        = 14,
                                Title     = "Q3",
                                Body      = "Q3",
                                AuthorId  = 1,
                                Timestamp = new DateTime(2019, 11, 22, 10, 0, 0)
                            },
                                new Post()
                            {
                                Id        = 15,
                                Body      = "R5",
                                ParentId  = 14,
                                AuthorId  = 5,
                                Timestamp = new DateTime(2019, 11, 22, 10, 2, 0)
                            },
                                new Post()
                            {
                                Id        = 16,
                                Body      = "R6",
                                ParentId  = 14,
                                AuthorId  = 3,
                                Timestamp = new DateTime(2019, 11, 22, 10, 2, 0)
                            },
                                new Post()
                            {
                                Id        = 17,
                                Title     = "Q4",
                                Body      = "Q4",
                                AuthorId  = 2,
                                Timestamp = new DateTime(2019, 11, 22, 11, 0, 0)
                            },
                                new Post()
                            {
                                Id        = 18,
                                Body      = "R7",
                                ParentId  = 17,
                                AuthorId  = 3,
                                Timestamp = new DateTime(2019, 11, 22, 10, 2, 0)
                            },
                                new Post()
                            {
                                Id        = 19,
                                Title     = "Q5",
                                Body      = "Q8",
                                AuthorId  = 4,
                                Timestamp = new DateTime(2019, 11, 22, 11, 0, 0)
                            },
                                new Post()
                            {
                                Id        = 20,
                                Body      = "R8",
                                ParentId  = 19,
                                AuthorId  = 3,
                                Timestamp = new DateTime(2019, 11, 22, 10, 2, 0)
                            }
                                );
                            context.SaveChanges();
                            var post4 = context.Posts.Find(4);
                            post4.AcceptedAnswerId = 5;
                            context.SaveChanges();
                        }
                        if (context.Comments.Count() == 0)
                        {
                            context.Comments.AddRange(
                                new Comment()
                            {
                                Id        = 1,
                                Body      = @"Global ""uninitialized"" variables typically end up in a ""bss"" segment, which will be initialized to zero.",
                                AuthorId  = 1,
                                PostId    = 1,
                                Timestamp = new DateTime(2019, 11, 15, 8, 40, 0)
                            },
                                new Comment()
                            {
                                Id        = 2,
                                Body      = @"[stackoverflow.com/questions/1169858/…]() This might help",
                                AuthorId  = 2,
                                PostId    = 1,
                                Timestamp = new DateTime(2019, 11, 15, 8, 41, 0)
                            },
                                new Comment()
                            {
                                Id        = 3,
                                Body      = @"Verified that this works! Pretty cool",
                                AuthorId  = 2,
                                PostId    = 6,
                                Timestamp = new DateTime(2019, 11, 15, 8, 42, 0)
                            },
                                new Comment()
                            {
                                Id        = 4,
                                Body      = @"For me it works with double quotes. `{{today | date:""d \'days so far in\' LLLL""}}`",
                                AuthorId  = 3,
                                PostId    = 7,
                                Timestamp = new DateTime(2019, 11, 15, 8, 43, 0)
                            },
                                new Comment()
                            {
                                Id        = 5,
                                Body      = @"This does not provide an answer to the question. Once you have sufficient reputation you will be able to comment on any post; instead, provide answers that don't require clarification from the asker.",
                                AuthorId  = 2,
                                PostId    = 6,
                                Timestamp = new DateTime(2019, 11, 15, 8, 44, 0)
                            },
                                new Comment()
                            {
                                Id        = 6,
                                Body      = @"Duplicate of [xxx](yyy). Please stop!",
                                AuthorId  = 1,
                                PostId    = 6,
                                Timestamp = new DateTime(2019, 11, 15, 8, 45, 0)
                            }
                                );
                            context.SaveChanges();
                        }
                        if (context.Votes.Count() == 0)
                        {
                            context.Votes.AddRange(
                                new Vote()
                            {
                                UpDown = 1, AuthorId = 5, PostId = 1
                            },
                                new Vote()
                            {
                                UpDown = -1, AuthorId = 3, PostId = 2
                            },
                                new Vote()
                            {
                                UpDown = -1, AuthorId = 2, PostId = 1
                            },
                                new Vote()
                            {
                                UpDown = -1, AuthorId = 3, PostId = 1
                            },
                                new Vote()
                            {
                                UpDown = 1, AuthorId = 2, PostId = 3
                            },
                                new Vote()
                            {
                                UpDown = 1, AuthorId = 5, PostId = 5
                            },
                                new Vote()
                            {
                                UpDown = -1, AuthorId = 3, PostId = 5
                            },
                                new Vote()
                            {
                                UpDown = 1, AuthorId = 4, PostId = 7
                            },
                                new Vote()
                            {
                                UpDown = -1, AuthorId = 4, PostId = 8
                            },
                                new Vote()
                            {
                                UpDown = -1, AuthorId = 1, PostId = 8
                            },
                                new Vote()
                            {
                                UpDown = 1, AuthorId = 4, PostId = 9
                            },
                                new Vote()
                            {
                                UpDown = -1, AuthorId = 2, PostId = 9
                            },
                                new Vote()
                            {
                                UpDown = 1, AuthorId = 1, PostId = 11
                            },
                                new Vote()
                            {
                                UpDown = 1, AuthorId = 2, PostId = 11
                            },
                                new Vote()
                            {
                                UpDown = 1, AuthorId = 1, PostId = 12
                            },
                                new Vote()
                            {
                                UpDown = 1, AuthorId = 2, PostId = 12
                            },
                                new Vote()
                            {
                                UpDown = 1, AuthorId = 3, PostId = 12
                            },
                                new Vote()
                            {
                                UpDown = -1, AuthorId = 1, PostId = 13
                            },
                                new Vote()
                            {
                                UpDown = -1, AuthorId = 2, PostId = 14
                            },
                                new Vote()
                            {
                                UpDown = -1, AuthorId = 2, PostId = 15
                            },
                                new Vote()
                            {
                                UpDown = -1, AuthorId = 4, PostId = 16
                            },
                                new Vote()
                            {
                                UpDown = 1, AuthorId = 1, PostId = 18
                            }
                                );
                            context.SaveChanges();
                        }
                        if (context.Tags.Count() == 0)
                        {
                            context.Tags.AddRange(
                                new Tag()
                            {
                                Id = 1, Name = "angular"
                            },
                                new Tag()
                            {
                                Id = 2, Name = "typescript"
                            },
                                new Tag()
                            {
                                Id = 3, Name = "csharp"
                            },
                                new Tag()
                            {
                                Id = 4, Name = "EntityFramework Core"
                            },
                                new Tag()
                            {
                                Id = 5, Name = "dotnet core"
                            },
                                new Tag()
                            {
                                Id = 6, Name = "mysql"
                            }
                                );
                            context.SaveChanges();
                        }
                        if (context.PostTags.Count() == 0)
                        {
                            context.PostTags.AddRange(
                                new PostTag()
                            {
                                PostId = 1, TagId = 1
                            },
                                new PostTag()
                            {
                                PostId = 1, TagId = 3
                            },
                                new PostTag()
                            {
                                PostId = 4, TagId = 2
                            }
                                );
                            context.SaveChanges();
                        }
                        Console.WriteLine("\n ... ----- -------- [Seeding data]  : [OK] -------- ----- ... \n");
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.ToString());
                    }
                }
            }
            return(webHost);
        }
Ejemplo n.º 27
0
        private static void CreateSiteCollection(ActionRequest actionRequest)
        {
            string siteCollectionUrl;

            var tenantAdminUri = new Uri($"https://{actionRequest.TenantName}-admin.sharepoint.com");
            var realm          = TokenHelper.GetRealmFromTargetUrl(tenantAdminUri);
            var token          = TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, tenantAdminUri.Authority, realm).AccessToken;

            using (var ctx = TokenHelper.GetClientContextWithAccessToken(tenantAdminUri.ToString(), token))
            {
                var manager = new SiteCollectionManager(actionRequest, ctx);
                siteCollectionUrl = manager.CreateSiteCollection();
            }

            var newWebUri = new Uri(siteCollectionUrl);

            token = TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, newWebUri.Authority, TokenHelper.GetRealmFromTargetUrl(newWebUri)).AccessToken;
            using (var ctx = TokenHelper.GetClientContextWithAccessToken(siteCollectionUrl, token))
            {
                var pwd      = ConfigurationManager.AppSettings["SharePointOnlineCredentials.Password"];
                var username = ConfigurationManager.AppSettings["SharePointOnlineCredentials.Username"];

                using (var secureString = new SecureString())
                {
                    foreach (var chr in pwd.ToCharArray())
                    {
                        secureString.AppendChar(chr);
                    }
                    secureString.MakeReadOnly();

                    ctx.Credentials    = new SharePointOnlineCredentials(username, secureString);
                    ctx.RequestTimeout = Timeout.Infinite;

                    var manager = new SiteCollectionManager(actionRequest, ctx);
                    manager.ApplyCustomTemplateToSite();
                }
            }
        }
Ejemplo n.º 28
0
 /// <summary>
 /// Used to create context to location provided as URL
 /// </summary>
 /// <param name="spContext"></param>
 /// <param name="url"></param>
 /// <returns></returns>
 private ClientContext CreateAppOnlyClientContextForUrl(SharePointContext spContext, string url)
 {
     return(TokenHelper.GetClientContextWithAccessToken(url, spContext.AppOnlyAccessTokenForSPHost));
 }
Ejemplo n.º 29
0
        /// <summary>
        /// Grabs the build number of the environment that we're testing
        /// </summary>
        /// <returns>Build number of the environment that's being tested</returns>
        private string GetBuildNumber()
        {
            string build = "";

            try
            {
                AuthenticationManager am = new AuthenticationManager();
                if (testConfiguration.TestAuthentication.AppOnly)
                {
                    string realm = TokenHelper.GetRealmFromTargetUrl(new Uri(testConfiguration.TestSiteUrl));

                    ClientContext ctx = null;

                    if (new Uri(testConfiguration.TestSiteUrl).DnsSafeHost.Contains("spoppe.com"))
                    {
                        ctx = am.GetAppOnlyAuthenticatedContext(testConfiguration.TestSiteUrl, realm, testConfiguration.TestAuthentication.AppId, testConfiguration.TestAuthentication.AppSecret, acsHostUrl: "windows-ppe.net", globalEndPointPrefix: "login");
                    }
                    else
                    {
                        ctx = am.GetAppOnlyAuthenticatedContext(testConfiguration.TestSiteUrl, realm, testConfiguration.TestAuthentication.AppId, testConfiguration.TestAuthentication.AppSecret);
                    }

                    using (ctx)
                    {
                        ctx.Load(ctx.Web, w => w.Title);
                        ctx.ExecuteQueryRetry();
                        build = ctx.ServerLibraryVersion.ToString();
                    }
                }
                else
                {
                    if (!String.IsNullOrEmpty(testConfiguration.TestAuthentication.CredentialManagerLabel))
                    {
                        System.Net.ICredentials credentials = null;

                        if (testConfiguration.TestAuthentication.Type == TestAuthenticationType.OnPremises)
                        {
                            var tempCred = CredentialManager.GetCredential(testConfiguration.TestAuthentication.CredentialManagerLabel);
                            if (tempCred.UserName.IndexOf("\\") > 0)
                            {
                                string[] userParts = tempCred.UserName.Split('\\');
                                credentials = new System.Net.NetworkCredential(userParts[1], tempCred.SecurePassword, userParts[0]);
                            }
                            else
                            {
                                throw new ArgumentException(String.Format("Username {0} stored in credential manager value {1} needs to be formatted as domain\\user", tempCred.UserName, testConfiguration.TestAuthentication.CredentialManagerLabel));
                            }
                        }
                        else
                        {
                            credentials = CredentialManager.GetSharePointOnlineCredential(testConfiguration.TestAuthentication.CredentialManagerLabel);
                        }

                        using (ClientContext ctx = new ClientContext(testConfiguration.TestSiteUrl))
                        {
                            ctx.Credentials = credentials;
                            ctx.Load(ctx.Web, w => w.Title);
                            ctx.ExecuteQueryRetry();
                            build = ctx.ServerLibraryVersion.ToString();
                        }
                    }
                    else
                    {
                        if (testConfiguration.TestAuthentication.Type == TestAuthenticationType.Online)
                        {
                            using (ClientContext ctx = am.GetSharePointOnlineAuthenticatedContextTenant(testConfiguration.TestSiteUrl, testConfiguration.TestAuthentication.User, testConfiguration.TestAuthentication.Password))
                            {
                                ctx.Load(ctx.Web, w => w.Title);
                                ctx.ExecuteQueryRetry();
                                build = ctx.ServerLibraryVersion.ToString();
                            }
                        }
                        else
                        {
                            using (ClientContext ctx = am.GetNetworkCredentialAuthenticatedContext(testConfiguration.TestSiteUrl, testConfiguration.TestAuthentication.User, testConfiguration.TestAuthentication.Password, testConfiguration.TestAuthentication.Domain))
                            {
                                ctx.Load(ctx.Web, w => w.Title);
                                ctx.ExecuteQueryRetry();
                                build = ctx.ServerLibraryVersion.ToString();
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("ERROR: Most likely something is wrong with the provided credentials (username+pwd, appid+secret, credential manager setting) causing the below error:");
                Console.WriteLine(ex.ToString());
                //throw;
            }

            return(build);
        }
Ejemplo n.º 30
0
        public DocumentTabViewModel(DocumentTabTranslation translation, IInteractionInvoker interactionInvoker, IFontHelper fontHelper, TokenHelper tokenHelper)
        {
            _interactionInvoker = interactionInvoker;
            _fontHelper         = fontHelper;
            Translation         = translation;

            TokenReplacer = tokenHelper.TokenReplacerWithPlaceHolders;

            TitleViewModel = new TokenViewModel(
                s => CurrentProfile.TitleTemplate = s,
                () => CurrentProfile?.TitleTemplate,
                tokenHelper.GetTokenListForTitle());

            AuthorViewModel = new TokenViewModel(
                s => CurrentProfile.AuthorTemplate = s,
                () => CurrentProfile?.AuthorTemplate,
                tokenHelper.GetTokenListForAuthor());

            SubjectViewModel = new TokenViewModel(s => CurrentProfile.SubjectTemplate = s, () => CurrentProfile?.SubjectTemplate, tokenHelper.GetTokenListForSubjectAndKeyword());
            KeywordViewModel = new TokenViewModel(s => CurrentProfile.KeywordTemplate = s, () => CurrentProfile?.KeywordTemplate, tokenHelper.GetTokenListForSubjectAndKeyword());
        }
Ejemplo n.º 31
0
 /// <summary>
 /// Determines if the specified access token is valid.
 /// It considers an access token as not valid if it is null, or it has expired.
 /// </summary>
 /// <param name="accessToken">The access token to verify.</param>
 /// <returns>True if the access token is valid.</returns>
 protected static bool IsAccessTokenValid(Tuple <string, long> accessToken)
 {
     return(accessToken != null &&
            !string.IsNullOrEmpty(accessToken.Item1) &&
            accessToken.Item2 > TokenHelper.EpochTimeNow());
 }