private HttpRequestData CreateInsertRequest(DataServiceContextData dataBeforeSaveChanges, EntityDescriptorData entityDescriptorData)
        {
            Uri insertUri;

            if (entityDescriptorData.InsertLink != null)
            {
                insertUri = entityDescriptorData.InsertLink;
            }
            else
            {
                ExceptionUtilities.CheckObjectNotNull(entityDescriptorData.ParentForInsert, "Entity descriptor data did not have insert link or parent for insert: {0}", entityDescriptorData);
                ExceptionUtilities.CheckObjectNotNull(entityDescriptorData.ParentPropertyForInsert, "Entity descriptor data did not have insert link or parent property for insert: {0}", entityDescriptorData);

                var parentDescriptor = dataBeforeSaveChanges.GetEntityDescriptorData(entityDescriptorData.ParentForInsert);
                var linkInfo         = parentDescriptor.LinkInfos.SingleOrDefault(l => l.Name == entityDescriptorData.ParentPropertyForInsert);
                if (linkInfo != null && linkInfo.NavigationLink != null)
                {
                    insertUri = linkInfo.NavigationLink;
                }
                else
                {
                    insertUri = new Uri(UriHelpers.ConcatenateUriSegments(parentDescriptor.EditLink.OriginalString, entityDescriptorData.ParentPropertyForInsert));
                }
            }

            return(new HttpRequestData()
            {
                Verb = HttpVerb.Post, Uri = insertUri
            });
        }
        private static void GetTagValues(
            object actionDescriptor,
            object request,
            out string httpMethod,
            out string host,
            out string resourceName,
            out string url,
            out string controllerName,
            out string actionName)
        {
            controllerName = actionDescriptor.GetProperty <string>("ControllerName").GetValueOrDefault()?.ToLowerInvariant();

            actionName = actionDescriptor.GetProperty <string>("ActionName").GetValueOrDefault()?.ToLowerInvariant();

            host = request.GetProperty("Host").GetProperty <string>("Value").GetValueOrDefault();

            httpMethod = request.GetProperty <string>("Method").GetValueOrDefault()?.ToUpperInvariant() ?? "UNKNOWN";

            string pathBase = request.GetProperty("PathBase").GetProperty <string>("Value").GetValueOrDefault();

            string path = request.GetProperty("Path").GetProperty <string>("Value").GetValueOrDefault();

            string queryString = request.GetProperty("QueryString").GetProperty <string>("Value").GetValueOrDefault();

            url = $"{pathBase}{path}{queryString}";

            string resourceUrl = actionDescriptor.GetProperty("AttributeRouteInfo").GetProperty <string>("Template").GetValueOrDefault() ??
                                 UriHelpers.GetRelativeUrl(new Uri($"https://{host}{url}"), tryRemoveIds: true).ToLowerInvariant();

            resourceName = $"{httpMethod} {resourceUrl}";
        }
        private void OnBeginRequest(object sender, EventArgs eventArgs)
        {
            Scope scope = null;

            try
            {
                var tracer = Tracer.Instance;

                if (!tracer.Settings.IsIntegrationEnabled(IntegrationName))
                {
                    // integration disabled
                    return;
                }

                var httpContext = (sender as HttpApplication)?.Context;

                if (httpContext == null)
                {
                    return;
                }

                HttpRequest httpRequest       = httpContext.Request;
                SpanContext propagatedContext = null;

                if (tracer.ActiveScope == null)
                {
                    try
                    {
                        // extract propagated http headers
                        var headers = httpRequest.Headers.Wrap();
                        propagatedContext = SpanContextPropagator.Instance.Extract(headers);
                    }
                    catch (Exception ex)
                    {
                        Log.Error(ex, "Error extracting propagated HTTP headers.");
                    }
                }

                string host         = httpRequest.Headers.Get("Host");
                string httpMethod   = httpRequest.HttpMethod.ToUpperInvariant();
                string url          = httpRequest.RawUrl.ToLowerInvariant();
                string path         = UriHelpers.GetRelativeUrl(httpRequest.Url, tryRemoveIds: true);
                string resourceName = $"{httpMethod} {path.ToLowerInvariant()}";

                scope = tracer.StartActive(_requestOperationName, propagatedContext);
                scope.Span.DecorateWebServerSpan(resourceName, httpMethod, host, url);

                // set analytics sample rate if enabled
                var analyticsSampleRate = tracer.Settings.GetIntegrationAnalyticsSampleRate(IntegrationName, enabledWithGlobalSetting: true);
                scope.Span.SetMetric(Tags.Analytics, analyticsSampleRate);

                httpContext.Items[_httpContextScopeKey] = scope;
            }
            catch (Exception ex)
            {
                // Dispose here, as the scope won't be in context items and won't get disposed on request end in that case...
                scope?.Dispose();
                Log.Error(ex, "Datadog ASP.NET HttpModule instrumentation error");
            }
        }
Beispiel #4
0
        protected override bool CollectReceiveParametersFromRequest(HttpRequestBase request, Uri targetUrl)
        {
            if (targetUrl == null)
            {
                throw new ArgumentNullException("targetUrl");
            }

            try
            {
                LinkbackTargetUrl = UriHelpers.CreateHttpUrl(targetUrl.ToString());
            }
            catch (UriFormatException)
            {
                throw new ArgumentOutOfRangeException("targetUrl");
            }

            if (String.IsNullOrEmpty(request.Form["url"]))
            {
                throw new LinkbackReceiveException(String.Format(CultureInfo.InvariantCulture, "Url parameter for {0} not specified", Name));
            }

            LinkbackSourceUrl = UriHelpers.CreateHttpUrl(request.Form["url"]);

            Title    = HttpUtility.HtmlEncode(request.Form["title"]);
            Excerpt  = HttpUtility.HtmlEncode(request.Form["excerpt"]);
            BlogName = HttpUtility.HtmlEncode(request.Form["blog_name"]);

            return(true);
        }
Beispiel #5
0
        private void OnEndRequest(object sender, EventArgs eventArgs)
        {
            try
            {
                if (!Tracer.Instance.Settings.IsIntegrationEnabled(IntegrationId))
                {
                    // integration disabled
                    return;
                }

                if (sender is HttpApplication app &&
                    app.Context.Items[_httpContextScopeKey] is Scope scope)
                {
                    scope.Span.SetHttpStatusCode(app.Context.Response.StatusCode, isServer: true);

                    if (app.Context.Items[SharedConstants.HttpContextPropagatedResourceNameKey] is string resourceName &&
                        !string.IsNullOrEmpty(resourceName))
                    {
                        scope.Span.ResourceName = resourceName;
                    }
                    else
                    {
                        string path = UriHelpers.GetCleanUriPath(app.Request.Url);
                        scope.Span.ResourceName = $"{app.Request.HttpMethod.ToUpperInvariant()} {path.ToLowerInvariant()}";
                    }

                    scope.Dispose();
                }
        /// <summary>
        /// Gets the absolute uri for the given link href value
        /// </summary>
        /// <param name="baseUri">The context base uri</param>
        /// <param name="xmlBase">The base uri annotation from the payload</param>
        /// <param name="hrefValue">The href value for the link</param>
        /// <returns>The absolute uri for the link, or a relative uri if it cannot be determined</returns>
        internal static Uri GetAbsoluteUriForLink(Uri baseUri, XmlBaseAnnotation xmlBase, string hrefValue)
        {
            var absoluteUri = new Uri(hrefValue, UriKind.RelativeOrAbsolute);

            if (!absoluteUri.IsAbsoluteUri)
            {
                string root;
                if (xmlBase != null)
                {
                    root = xmlBase.Value;
                }
                else if (baseUri != null)
                {
                    ExceptionUtilities.Assert(baseUri.IsAbsoluteUri, "baseUri was not an absolute uri. It was: '{0}'", baseUri.OriginalString);
                    root = baseUri.AbsoluteUri;
                }
                else
                {
                    // TODO: need to be able to read xml:base from feed, cannot currently.
                    // just return a relative uri for now
                    return(absoluteUri);
                }

                absoluteUri = new Uri(UriHelpers.ConcatenateUriSegments(root, hrefValue));
            }

            return(absoluteUri);
        }
Beispiel #7
0
        /// <summary>
        /// Generates the next link for an expanded feed.
        /// </summary>
        /// <param name="containingEntity">The containing entity.</param>
        /// <param name="navigation">The expanded navigation property.</param>
        /// <param name="lastEntityValue">The last entity value.</param>
        /// <returns>
        /// The expected next link
        /// </returns>
        public string GenerateExpandedNextLink(EntityInstance containingEntity, NavigationPropertyInstance navigation, QueryStructuralValue lastEntityValue)
        {
            ExceptionUtilities.CheckArgumentNotNull(containingEntity, "containingEntity");
            ExceptionUtilities.CheckArgumentNotNull(navigation, "navigation");
            ExceptionUtilities.CheckArgumentNotNull(lastEntityValue, "lastEntityValue");

            var navigationUriString = ((ExpandedLink)navigation.Value).UriString;

            if (string.IsNullOrEmpty(navigationUriString))
            {
                navigationUriString = UriHelpers.ConcatenateUriSegments(containingEntity.EditLink, navigation.Name);
            }

            var skipTokenValues = new List <object>();

            foreach (var keyProperty in lastEntityValue.Type.Properties.Where(p => p.IsPrimaryKey))
            {
                skipTokenValues.Add(lastEntityValue.GetScalarValue(keyProperty.Name).Value);
            }

            var skiptoken = this.BuildSkipTokenFromValues(skipTokenValues);

            var nextLinkUri = new ODataUri(new UnrecognizedSegment(navigationUriString));

            nextLinkUri.SkipToken = skiptoken;

            return(this.UriToStringConverter.ConvertToString(nextLinkUri));
        }
        private static void GetTagValues(
            object request,
            out string url,
            out string httpMethod,
            out string host,
            out string resourceName)
        {
            host = request.GetProperty("Host").GetProperty <string>("Value").GetValueOrDefault();

            httpMethod = request.GetProperty <string>("Method").GetValueOrDefault()?.ToUpperInvariant() ?? "UNKNOWN";

            string pathBase = request.GetProperty("PathBase").GetProperty <string>("Value").GetValueOrDefault();

            string path = request.GetProperty("Path").GetProperty <string>("Value").GetValueOrDefault();

            string queryString = request.GetProperty("QueryString").GetProperty <string>("Value").GetValueOrDefault();

            string scheme = request.GetProperty <string>("Scheme").GetValueOrDefault()?.ToUpperInvariant() ?? "http";

            url = $"{pathBase}{path}{queryString}";

            string resourceUrl = UriHelpers.GetRelativeUrl(new Uri($"{scheme}://{host}{url}"), tryRemoveIds: true).ToLowerInvariant();

            resourceName = $"{httpMethod} {resourceUrl}";
        }
        public async Task DeleteFriendshipByUserId_ShouldDeleteFriendship_OnExistingUserId()
        {
            var client = CreateClient();

            var alice = new User("1", "alice", "*****@*****.**");
            var bob   = new User("2", "bob", "*****@*****.**");

            await CreateTestUserAsync(alice);
            await CreateTestUserAsync(bob);
            await CreateTestFriendshipAsync(alice.Id, bob.Id);

            var query = new
            {
                friendId = bob.Id
            };

            var uri = UriHelpers.BuildUri(Delete.DeleteByUserId(alice.Id), new { query = JsonConvert.SerializeObject(query) });
            await client.DeleteAsync(uri);

            var response = await client.GetAsync(uri);

            var responseStr = await response.Content.ReadAsStringAsync();

            var responseArr = JsonConvert.DeserializeObject <ArrayResponse <FriendshipDto> >(responseStr);

            Assert.True(!responseArr.Items.Any());
        }
        public async Task DeleteFriendshipByUserId_ShouldDispatchNotificationEvent_OnExistingUserId()
        {
            var client = CreateClient();

            var alice = new User("1", "alice", "*****@*****.**");
            var bob   = new User("2", "bob", "*****@*****.**");

            await CreateTestUserAsync(alice);
            await CreateTestUserAsync(bob);
            await CreateTestFriendshipAsync(alice.Id, bob.Id);

            string eventName    = null;
            string eventMessage = null;

            TestEventBusFixture.EventBus.Subscribe(nameof(NotifyUsersIntegrationEvent), (e, m) =>
            {
                eventName    = e;
                eventMessage = m;
            });
            await Task.Delay(1000);

            var uri = UriHelpers.BuildUri(Delete.DeleteByUserId(alice.Id), new { friendId = bob.Id });
            await client.DeleteAsync(uri);

            await Task.Delay(1000);

            var message = JsonConvert.DeserializeObject <NotifyUsersIntegrationEvent>(eventMessage);

            Assert.Equal(nameof(NotifyUsersIntegrationEvent), eventName);
            Assert.Equal("FriendshipDeleted", message.ClientMethod);
            Assert.True(message.UserIds.Contains(alice.Id) && message.UserIds.Contains(bob.Id));

            await Task.Delay(1000);
        }
        public async Task GetFriendshipsByUserId_ShouldReturnFriendships_OnExistingUserId()
        {
            var client = CreateClient();

            var alice = new User("1", "alice", "*****@*****.**");
            var bob   = new User("2", "bob", "*****@*****.**");
            var sam   = new User("3", "sam", "*****@*****.**");

            await CreateTestUserAsync(alice);
            await CreateTestUserAsync(bob);
            await CreateTestUserAsync(sam);
            await CreateTestFriendshipAsync(alice.Id, bob.Id);
            await CreateTestFriendshipAsync(bob.Id, sam.Id);
            await CreateTestFriendshipAsync(sam.Id, alice.Id);

            var query = new
            {
                pagination = new
                {
                    limit  = 10,
                    offset = 0
                }
            };

            var uri      = UriHelpers.BuildUri(Get.FriendshipsByUserId(alice.Id), new { query = JsonConvert.SerializeObject(query) });
            var response = await client.GetAsync(uri);

            var responseStr = await response.Content.ReadAsStringAsync();

            var responseArr = JsonConvert.DeserializeObject <ArrayResponse <FriendshipDto> >(responseStr);

            Assert.True(response.StatusCode == HttpStatusCode.OK);
            Assert.True(responseArr.Items.Count() == 2);
            Assert.True(responseArr.Total == 2);
        }
        public async Task GetFriendshipRequestsByRequesteeAndRequesterIds_ShouldReturnEmptyList_OnNonexistingRequester()
        {
            var client = CreateClient();

            var alice = new User("1", "alice", "*****@*****.**");
            var bob   = new User("2", "bob", "*****@*****.**");

            await CreateTestUserAsync(alice);
            await CreateTestUserAsync(bob);

            var friendshipRequestId = await CreateTestFriendshipRequestAsync(alice.Id, bob.Id);

            var query = new
            {
                criteria   = new { requester = "gibberish" },
                pagination = new
                {
                    limit  = 10,
                    offset = 0
                }
            };

            var uri      = UriHelpers.BuildUri(Get.FriendshipRequestsByRequesteeId(alice.Id), new { query = JsonConvert.SerializeObject(query) });
            var response = await client.GetAsync(uri);

            var responseStr = await response.Content.ReadAsStringAsync();

            var responseArr = JsonConvert.DeserializeObject <ArrayResponse <FriendshipRequestDto> >(responseStr);

            Assert.True(response.StatusCode == HttpStatusCode.OK);
            Assert.True(!responseArr.Items.Any());
            Assert.True(responseArr.Total == 0);
        }
        public async Task GetFriendshipRequests_ShouldReturnEmptyList_OnNoMatchingCriteria()
        {
            var client = CreateClient();

            var query = new
            {
                criteria   = new { id = "gibberish" },
                pagination = new
                {
                    limit  = 10,
                    offset = 0
                }
            };

            var uri      = UriHelpers.BuildUri(Get.FriendshipRequests(), new { query = JsonConvert.SerializeObject(query) });
            var response = await client.GetAsync(uri);

            var responseStr = await response.Content.ReadAsStringAsync();

            var responseArr = JsonConvert.DeserializeObject <ArrayResponse <FriendshipRequestDto> >(responseStr);

            Assert.True(response.StatusCode == HttpStatusCode.OK);
            Assert.True(!responseArr.Items.Any());
            Assert.True(responseArr.Total == 0);
        }
        internal static Uri GetEntityInsertUri(DataServiceContextData contextData, EntityDescriptorData entityDescriptorData)
        {
            Uri insertUri;

            if (entityDescriptorData.InsertLink != null)
            {
                insertUri = entityDescriptorData.InsertLink;
            }
            else
            {
                ExceptionUtilities.CheckObjectNotNull(entityDescriptorData.ParentForInsert, "Entity descriptor data did not have insert link or parent for insert: {0}", entityDescriptorData);
                ExceptionUtilities.CheckObjectNotNull(entityDescriptorData.ParentPropertyForInsert, "Entity descriptor data did not have insert link or parent property for insert: {0}", entityDescriptorData);

                var parentDescriptor = contextData.GetEntityDescriptorData(entityDescriptorData.ParentForInsert);
                var linkInfo         = parentDescriptor.LinkInfos.SingleOrDefault(l => l.Name == entityDescriptorData.ParentPropertyForInsert);

                if (linkInfo != null && linkInfo.NavigationLink != null)
                {
                    insertUri = linkInfo.NavigationLink;
                }
                else
                {
                    insertUri = new Uri(UriHelpers.ConcatenateUriSegments(parentDescriptor.EditLink.OriginalString, entityDescriptorData.ParentPropertyForInsert), UriKind.RelativeOrAbsolute);
                    if (!insertUri.IsAbsoluteUri && contextData.BaseUri != null)
                    {
                        insertUri = new Uri(contextData.BaseUri, insertUri);
                    }
                }
            }

            return(insertUri);
        }
Beispiel #15
0
    public void TestIsSubdomainOf_ReturnsFalse_WhenNotSubdomain(Uri subdomain, Uri domain)
    {
        // Act
        var isSubdomain = UriHelpers.IsSubdomainOf(subdomain, domain);

        // Assert
        Assert.False(isSubdomain);
    }
Beispiel #16
0
    public void TestIsSubdomainOf(Uri subdomain, Uri domain)
    {
        // Act
        var isSubdomain = UriHelpers.IsSubdomainOf(subdomain, domain);

        // Assert
        Assert.True(isSubdomain);
    }
Beispiel #17
0
        public void UriHelpers_CreateOrganizationUri_InputArgsMissingProtocol_ThrowsException()
        {
            var input = new InputArguments(new Dictionary <string, string>
            {
                ["host"] = "dev.azure.com"
            });

            Assert.Throws <InvalidOperationException>(() => UriHelpers.CreateOrganizationUri(input));
        }
Beispiel #18
0
        public void UriHelpers_CreateOrganizationUri_InputArgsMissingHost_ThrowsException()
        {
            var input = new InputArguments(new Dictionary <string, string>
            {
                ["protocol"] = "https"
            });

            Assert.Throws <InvalidOperationException>(() => UriHelpers.CreateOrganizationUri(input));
        }
Beispiel #19
0
        public void It_adds_slash_to_the_base_Url()
        {
            var expected    = "http://www.sample.com/";
            var request     = new FakeHttpRequest().WithUrl("http://www.sample.com");
            var httpContext = FakeHttpContext.CreateWithRequest(request);

            var result = UriHelpers.GetBaseUri(httpContext, SiteDefinition.Empty);

            Assert.Equal(expected, result.ToString());
        }
Beispiel #20
0
        public void UriHelpers_CreateOrganizationUri_NonAzureDevOpsHost_ThrowsException()
        {
            var input = new InputArguments(new Dictionary <string, string>
            {
                ["protocol"] = "https",
                ["host"]     = "example.com",
            });

            Assert.Throws <InvalidOperationException>(() => UriHelpers.CreateOrganizationUri(input));
        }
Beispiel #21
0
        public void UriHelpers_CreateOrganizationUri_VisualStudioHost_MissingOrgInHost_ThrowsException()
        {
            var input = new InputArguments(new Dictionary <string, string>
            {
                ["protocol"] = "https",
                ["host"]     = "visualstudio.com",
            });

            Assert.Throws <InvalidOperationException>(() => UriHelpers.CreateOrganizationUri(input));
        }
Beispiel #22
0
        public void UriHelpers_CreateOrganizationUri_AzureHost_OrgAlsoInUser_PrefersPathOrg()
        {
            var          expected    = new Uri("https://dev.azure.com/myorg-path");
            var          input       = new Uri("https://[email protected]/myorg-path");
            const string expectedOrg = "myorg-path";

            Uri actual = UriHelpers.CreateOrganizationUri(input, out string actualOrg);

            Assert.Equal(expected, actual);
            Assert.Equal(expectedOrg, actualOrg);
        }
Beispiel #23
0
        public void UriHelpers_CreateOrganizationUri_AzureHost_InputArgsMissingPath_HasUser_UsesUserOrg()
        {
            var          expected    = new Uri("https://dev.azure.com/myorg-user");
            var          input       = new Uri("https://[email protected]");
            const string expectedOrg = "myorg-user";

            Uri actual = UriHelpers.CreateOrganizationUri(input, out string actualOrg);

            Assert.Equal(expected, actual);
            Assert.Equal(expectedOrg, actualOrg);
        }
Beispiel #24
0
        public void UriHelpers_CreateOrganizationUri_VisualStudioHost_ReturnsCorrectUri()
        {
            var          expected    = new Uri("https://myorg.visualstudio.com");
            var          input       = new Uri("https://myorg.visualstudio.com");
            const string expectedOrg = "myorg";

            Uri actual = UriHelpers.CreateOrganizationUri(input, out string actualOrg);

            Assert.Equal(expected, actual);
            Assert.Equal(expectedOrg, actualOrg);
        }
Beispiel #25
0
        public void UriHelpers_CreateOrganizationUri_AzureHost_WithPort_ReturnsCorrectUri()
        {
            var          expected    = new Uri("https://dev.azure.com:456/myorg");
            var          input       = new Uri("https://dev.azure.com:456/myorg/myproject/_git/myrepo");
            const string expectedOrg = "myorg";

            Uri actual = UriHelpers.CreateOrganizationUri(input, out string actualOrg);

            Assert.Equal(expected, actual);
            Assert.Equal(expectedOrg, actualOrg);
        }
        public (string, string) GeneratePasswordResetEmail(string userName, string token, string completionUrl)
        {
            var url = UriHelpers.BuildUri(completionUrl, new NameValueCollection()
            {
                { "UserName", userName },
                { "Token", token }
            }).ToString();

            return("Your password reset request",
                   $@"Click <a href=""{url}"">here</a> to reset your password.");
        }
Beispiel #27
0
        public void It_uses_site_definition_scheme_when_no_http_context()
        {
            var expected       = "https://www.sample.com/";
            var siteDefinition = new SiteDefinition()
            {
                SiteUrl = new Uri(expected)
            };

            var result = UriHelpers.GetBaseUri(null, siteDefinition);

            Assert.Equal(expected, result.ToString());
        }
Beispiel #28
0
        public void UriHelpers_CreateOrganizationUri_AzureHost_WithBadPort_ThrowsException()
        {
            var expected = new Uri("https://dev.azure.com:456/myorg");
            var input    = new InputArguments(new Dictionary <string, string>
            {
                ["protocol"] = "https",
                ["host"]     = "dev.azure.com:not-a-port",
                ["path"]     = "myorg/myproject/_git/myrepo"
            });

            Assert.Throws <InvalidOperationException>(() => UriHelpers.CreateOrganizationUri(input));
        }
        public (string, string) GenerateEmailConfirmationEmail(string userName, string token)
        {
            var emailConfirmationUrl = _configuration["EmailConfirmationUrl"];
            var url = UriHelpers.BuildUri(emailConfirmationUrl, new NameValueCollection()
            {
                { "UserName", userName },
                { "Token", token }
            }).ToString();

            return("Please confirm your email",
                   $@"Thank you for registering with SecureChat. Please click <a href=""{url}"">here</a> to confirm your email address.");
        }
Beispiel #30
0
        public void It_sets_first_X_Forwarded_Proto_scheme()
        {
            var expected = "https://www.sample.com/";
            var request  = new FakeHttpRequest()
                           .WithUrl("http://www.sample.com/")
                           .WithHeader("X-Forwarded-Proto", "https, http");
            var httpContext = FakeHttpContext.CreateWithRequest(request);

            var result = UriHelpers.GetBaseUri(httpContext, SiteDefinition.Empty);

            Assert.Equal(expected, result.ToString());
        }