//Take the screenshots from the browser protected void TakeScreenshots(ExecutionOptions options, IUserConfig userConfig) { _logger.LogDebug("Starting the screenshot mode"); var parallelOptions = new ParallelOptions() { MaxDegreeOfParallelism = userConfig.NumberOfThreads <= 0 ? 10 : userConfig.NumberOfThreads }; var browser = _browserFactory.GetBrowserFromConfig(userConfig); Parallel.ForEach(userConfig.Urls, parallelOptions, (url) => { _logger.LogInformation($"Screenshoting: '{url}'"); foreach (var width in userConfig.ScreenWidth) { var argument = new ScriptArguments() { ScreenWidth = width, UrlName = url.Key, Url = UriUtils.CombineUriToString(userConfig.Domain, url.Value), TargetPath = GetTargetPath(userConfig, url.Key, width) }; browser.ErrorDataReceived += (sender, args) => { _logger.LogError(EventIds.BrowserErrorMessage, $"BROWSER ERROR : {args.Response}"); }; browser.OutputDataReceived += (sender, args) => { _logger.LogInformation(EventIds.BrowserErrorMessage, $"BROWSER : {args.Response}"); }; browser.ExecuteScript(userConfig.ScriptFileFullPath, argument); } }); }
public bool SendBinaryMessage(string text, string SMSC) { bool result; if (text == null) { result = false; } else { string dstSipUri = base.ToUri; string SMSCPhoneNumber; string dstPhoneNumber; if ((SMSCPhoneNumber = UriUtils.GetValidPhoneNumber(SMSC)) != null && (dstPhoneNumber = UriUtils.GetValidPhoneNumber(dstSipUri)) != null) { base.ToUri = SMSC; this.session.addHeader("Content-Type", "application/vnd.3gpp.sms"); this.session.addHeader("Content-Transfer-Encoding", "binary"); this.session.addHeader("Contact", string.Format("<{0};transport=udp>", this.fromUri)); RPMessage rpMessage = SMSEncoder.encodeSubmit(++MyMessageSession.SMS_MR, SMSCPhoneNumber, dstPhoneNumber, text); bool ret = this.session.send(rpMessage.getPayload()); rpMessage.Dispose(); if (MyMessageSession.SMS_MR >= 255) { MyMessageSession.SMS_MR = 0; } result = ret; } else { MyMessageSession.LOG.Error(string.Format("SMSC={0} or RemoteUri={1} is invalid", SMSC, dstSipUri)); result = this.SendTextMessage(text); } } return(result); }
/// <summary> /// Returns a hash set of operation imports (actions and functions) in the given resource. /// </summary> /// <param name="resource">The resource in question.</param> /// <param name="model">The edm model to resolve operation imports.</param> /// <param name="metadataDocumentUri">The metadata document uri.</param> /// <returns>The hash set of operation imports (actions and functions) in the given resource.</returns> private static HashSet <IEdmOperation> GetOperationsInEntry(ODataResourceBase resource, IEdmModel model, Uri metadataDocumentUri) { Debug.Assert(resource != null, "resource != null"); Debug.Assert(model != null, "model != null"); Debug.Assert(metadataDocumentUri != null && metadataDocumentUri.IsAbsoluteUri, "metadataDocumentUri != null && metadataDocumentUri.IsAbsoluteUri"); HashSet <IEdmOperation> edmOperationImportsInEntry = new HashSet <IEdmOperation>(EqualityComparer <IEdmOperation> .Default); IEnumerable <ODataOperation> operations = ODataUtilsInternal.ConcatEnumerables((IEnumerable <ODataOperation>)resource.NonComputedActions, (IEnumerable <ODataOperation>)resource.NonComputedFunctions); if (operations != null) { foreach (ODataOperation operation in operations) { Debug.Assert(operation.Metadata != null, "operation.Metadata != null"); string operationMetadataString = UriUtils.UriToString(operation.Metadata); Debug.Assert( ODataJsonLightUtils.IsMetadataReferenceProperty(operationMetadataString), "ODataJsonLightUtils.IsMetadataReferenceProperty(operationMetadataString)"); Debug.Assert( operationMetadataString[0] == ODataConstants.ContextUriFragmentIndicator || metadataDocumentUri.IsBaseOf(operation.Metadata), "operationMetadataString[0] == JsonLightConstants.ContextUriFragmentIndicator || metadataDocumentUri.IsBaseOf(operation.Metadata)"); string fullyQualifiedOperationName = ODataJsonLightUtils.GetUriFragmentFromMetadataReferencePropertyName(metadataDocumentUri, operationMetadataString); IEnumerable <IEdmOperation> edmOperations = model.ResolveOperations(fullyQualifiedOperationName); if (edmOperations != null) { foreach (IEdmOperation edmOperation in edmOperations) { edmOperationImportsInEntry.Add(edmOperation); } } } } return(edmOperationImportsInEntry); }
static ThemeManager() { themes = new Dictionary <Platform, ResourceDictionary>() { { Platform.Android, new ResourceDictionary() { Source = UriUtils.GetAbsolute("Themes/Platforms/AndroidStyle.xaml") } }, { Platform.iOS, new ResourceDictionary() { Source = UriUtils.GetAbsolute("Themes/Platforms/iOSStyle.xaml") } }, { Platform.Window, new ResourceDictionary() { Source = UriUtils.GetAbsolute("Themes/Platforms/WindowStyle.xaml") } } }; }
/// <summary> /// Resolves a type. /// </summary> /// <param name="typeName">The type name.</param> /// <param name="clientCustomTypeResolver">The function of client cuetom type resolver.</param> /// <param name="throwIfMetadataConflict">Whether to throw if a type specified in the ContextUri is not found in metadata.</param> /// <returns>The resolved Edm type.</returns> private ODataPayloadKind ResolveType(string typeName, Func <IEdmType, string, IEdmType> clientCustomTypeResolver, bool throwIfMetadataConflict) { string typeNameToResolve = EdmLibraryExtensions.GetCollectionItemTypeName(typeName) ?? typeName; bool isCollection = typeNameToResolve != typeName; EdmTypeKind typeKind; IEdmType resolvedType = MetadataUtils.ResolveTypeNameForRead(this.model, /*expectedType*/ null, typeNameToResolve, clientCustomTypeResolver, out typeKind); if (resolvedType == null && !throwIfMetadataConflict) { string namespaceName; string name; TypeUtils.ParseQualifiedTypeName(typeName, out namespaceName, out name, out isCollection); resolvedType = new EdmUntypedStructuredType(namespaceName, name); } if (resolvedType == null || resolvedType.TypeKind != EdmTypeKind.Primitive && resolvedType.TypeKind != EdmTypeKind.Enum && resolvedType.TypeKind != EdmTypeKind.Complex && resolvedType.TypeKind != EdmTypeKind.Entity && resolvedType.TypeKind != EdmTypeKind.TypeDefinition && resolvedType.TypeKind != EdmTypeKind.Untyped) { throw new ODataException(ODataErrorStrings.ODataJsonLightContextUriParser_InvalidEntitySetNameOrTypeName(UriUtils.UriToString(this.parseResult.ContextUri), typeName)); } if (resolvedType.TypeKind == EdmTypeKind.Entity || resolvedType.TypeKind == EdmTypeKind.Complex) { this.parseResult.EdmType = resolvedType; return(isCollection ? ODataPayloadKind.ResourceSet : ODataPayloadKind.Resource); } // For structured collection ,the EdmType is element type. for primitive collection, it is collection type resolvedType = isCollection ? EdmLibraryExtensions.GetCollectionType(resolvedType.ToTypeReference(true /*nullable*/)) : resolvedType; this.parseResult.EdmType = resolvedType; return(isCollection ? ODataPayloadKind.Collection : ODataPayloadKind.Property); }
/// <summary> /// Applies the model and validates the context URI against it. /// </summary> /// <param name="expectedPayloadKind">The payload kind we expect the context URI to conform to.</param> /// <param name="clientCustomTypeResolver">The function of client custom type resolver.</param> /// <param name="throwIfMetadataConflict">Whether to throw if a type specified in the ContextUri is not found in metadata.</param> private void ParseContextUri(ODataPayloadKind expectedPayloadKind, Func <IEdmType, string, IEdmType> clientCustomTypeResolver, bool throwIfMetadataConflict) { bool isUndeclared; ODataPayloadKind detectedPayloadKind = this.ParseContextUriFragment(this.parseResult.Fragment, clientCustomTypeResolver, throwIfMetadataConflict, out isUndeclared); // unsupported payload kind indicates that this is during payload kind detection, so we should not fail. bool detectedPayloadKindMatchesExpectation = detectedPayloadKind == expectedPayloadKind || expectedPayloadKind == ODataPayloadKind.Unsupported; IEdmType parseType = this.parseResult.EdmType; if (parseType != null && parseType.TypeKind == EdmTypeKind.Untyped) { if (string.Equals(parseType.FullTypeName(), ODataConstants.ContextUriFragmentUntyped, StringComparison.Ordinal)) { // Anything matches the built-in Edm.Untyped this.parseResult.DetectedPayloadKinds = new[] { ODataPayloadKind.ResourceSet, ODataPayloadKind.Property, ODataPayloadKind.Collection, ODataPayloadKind.Resource }; detectedPayloadKindMatchesExpectation = true; } else if (expectedPayloadKind == ODataPayloadKind.Property || expectedPayloadKind == ODataPayloadKind.Resource) { // If we created an untyped type because the name was not resolved it can match any single value this.parseResult.DetectedPayloadKinds = new[] { ODataPayloadKind.Property, ODataPayloadKind.Resource }; detectedPayloadKindMatchesExpectation = true; } } else if (parseType != null && parseType.TypeKind == EdmTypeKind.Collection && ((IEdmCollectionType)parseType).ElementType.TypeKind() == EdmTypeKind.Untyped) { this.parseResult.DetectedPayloadKinds = new[] { ODataPayloadKind.ResourceSet, ODataPayloadKind.Property, ODataPayloadKind.Collection }; if (expectedPayloadKind == ODataPayloadKind.ResourceSet || expectedPayloadKind == ODataPayloadKind.Property || expectedPayloadKind == ODataPayloadKind.Collection) { detectedPayloadKindMatchesExpectation = true; } } else if (detectedPayloadKind == ODataPayloadKind.ResourceSet && parseType.IsODataComplexTypeKind()) { this.parseResult.DetectedPayloadKinds = new[] { ODataPayloadKind.ResourceSet, ODataPayloadKind.Property, ODataPayloadKind.Collection }; if (expectedPayloadKind == ODataPayloadKind.Property || expectedPayloadKind == ODataPayloadKind.Collection) { detectedPayloadKindMatchesExpectation = true; } } else if (detectedPayloadKind == ODataPayloadKind.Resource && parseType.IsODataComplexTypeKind()) { this.parseResult.DetectedPayloadKinds = new[] { ODataPayloadKind.Resource, ODataPayloadKind.Property }; if (expectedPayloadKind == ODataPayloadKind.Property) { detectedPayloadKindMatchesExpectation = true; } } else if (detectedPayloadKind == ODataPayloadKind.Collection) { // If the detected payload kind is 'collection' it can always also be treated as a property. this.parseResult.DetectedPayloadKinds = new[] { ODataPayloadKind.Collection, ODataPayloadKind.Property }; if (expectedPayloadKind == ODataPayloadKind.Property) { detectedPayloadKindMatchesExpectation = true; } } else if (detectedPayloadKind == ODataPayloadKind.Resource) { this.parseResult.DetectedPayloadKinds = new[] { ODataPayloadKind.Resource, ODataPayloadKind.Delta }; if (expectedPayloadKind == ODataPayloadKind.Delta) { this.parseResult.DeltaKind = ODataDeltaKind.Resource; detectedPayloadKindMatchesExpectation = true; } } else if (detectedPayloadKind == ODataPayloadKind.Property && isUndeclared && (expectedPayloadKind == ODataPayloadKind.Resource || expectedPayloadKind == ODataPayloadKind.ResourceSet)) { // for undeclared, we don't know whether it is a resource/resource set or not. this.parseResult.DetectedPayloadKinds = new[] { expectedPayloadKind, ODataPayloadKind.Property }; detectedPayloadKindMatchesExpectation = true; } else { this.parseResult.DetectedPayloadKinds = new[] { detectedPayloadKind }; } // If the expected and detected payload kinds don't match and we are not running payload kind detection // right now (payloadKind == ODataPayloadKind.Unsupported) and we did not detect a collection kind for // an expected property kind (which is allowed), fail. if (!detectedPayloadKindMatchesExpectation) { throw new ODataException(ODataErrorStrings.ODataJsonLightContextUriParser_ContextUriDoesNotMatchExpectedPayloadKind(UriUtils.UriToString(this.parseResult.ContextUri), expectedPayloadKind.ToString())); } // NOTE: we interpret an empty select query option to mean that nothing should be projected // (whereas a missing select query option means everything should be projected). string selectQueryOption = this.parseResult.SelectQueryOption; if (selectQueryOption != null) { if (detectedPayloadKind != ODataPayloadKind.ResourceSet && detectedPayloadKind != ODataPayloadKind.Resource && detectedPayloadKind != ODataPayloadKind.Delta) { throw new ODataException(ODataErrorStrings.ODataJsonLightContextUriParser_InvalidPayloadKindWithSelectQueryOption(expectedPayloadKind.ToString())); } } }
public void UriInvariantInsensitiveIsBaseOf_ShouldIgnoreStuffAfterFinalSlash() { UriUtils.UriInvariantInsensitiveIsBaseOf(new Uri("http://www.example.com/OData.svc"), new Uri("http://www.example.com/One/Two")).Should().BeTrue(); }
public void UriInvariantInsensitiveIsBaseOf_ShouldBeCaseInsensitive() { UriUtils.UriInvariantInsensitiveIsBaseOf(new Uri("HTTP://WwW.ExAmPlE.cOm/OnE/"), new Uri("http://www.example.com/One/")).Should().BeTrue(); }
public void UriInvariantInsensitiveIsBaseOf_RelativeFirstUrlIsNotAllowed() { Action method = () => UriUtils.UriInvariantInsensitiveIsBaseOf(new Uri("/One/", UriKind.Relative), new Uri("http://www.example.com/One/Two")); method.ShouldThrow <InvalidOperationException>(); }
public static string ThumbnailPath(System.Uri uri) { string large_path = Gnome.Thumbnail.PathForUri(UriUtils.UriToStringEscaped(uri), Gnome.ThumbnailSize.Large); return(large_path); }
protected bool BeValidHttpUrlWhenSet <TDto>(TDto dto, string value) => !(!string.IsNullOrWhiteSpace(value) && !UriUtils.IsValidHttpUrl(value));
internal Participant(String sipUri, confStatus status) { this.sipUri = sipUri; this.status = status; this.displayName = UriUtils.GetDisplayName(this.sipUri); }
public void UriInvariantInsensitiveIsBaseOf_DifferentBaseShouldReturnFalse() { var result = UriUtils.UriInvariantInsensitiveIsBaseOf(new Uri("http://www.example.com/OData.svc/"), new Uri("http://www.example.com/One/Two")); Assert.False(result); }
public void UriInvariantInsensitiveIsBaseOf_ShouldIgnoreStuffAfterFinalSlash() { var result = UriUtils.UriInvariantInsensitiveIsBaseOf(new Uri("http://www.example.com/OData.svc"), new Uri("http://www.example.com/One/Two")); Assert.True(result); }
public void UriInvariantInsensitiveIsBaseOf_ShouldBeCaseInsensitive() { var result = UriUtils.UriInvariantInsensitiveIsBaseOf(new Uri("HTTP://WwW.ExAmPlE.cOm/OnE/"), new Uri("http://www.example.com/One/")); Assert.True(result); }
internal static bool TryUriStringToPrimitive(string text, IEdmTypeReference targetType, out object targetValue, out string reason) { Debug.Assert(text != null, "text != null"); Debug.Assert(targetType != null, "targetType != null"); reason = null; if (targetType.IsNullable) { if (text == ExpressionConstants.KeywordNull) { targetValue = null; return(true); } } IEdmPrimitiveTypeReference primitiveTargetType = targetType.AsPrimitiveOrNull(); if (primitiveTargetType == null) { targetValue = null; return(false); } EdmPrimitiveTypeKind targetTypeKind = primitiveTargetType.PrimitiveKind(); byte[] byteArrayValue; bool binaryResult = TryUriStringToByteArray(text, out byteArrayValue); if (targetTypeKind == EdmPrimitiveTypeKind.Binary) { targetValue = (object)byteArrayValue; return(binaryResult); } else if (binaryResult) { string keyValue = Encoding.UTF8.GetString(byteArrayValue, 0, byteArrayValue.Length); return(TryUriStringToPrimitive(keyValue, targetType, out targetValue)); } else if (targetTypeKind == EdmPrimitiveTypeKind.Guid) { Guid guidValue; bool result = UriUtils.TryUriStringToGuid(text, out guidValue); targetValue = guidValue; return(result); } else if (targetTypeKind == EdmPrimitiveTypeKind.DateTimeOffset) { DateTimeOffset dateTimeOffsetValue; bool result = UriUtils.TryUriStringToDateTimeOffset(text, out dateTimeOffsetValue); targetValue = dateTimeOffsetValue; return(result); } else if (targetTypeKind == EdmPrimitiveTypeKind.Duration) { TimeSpan timespanValue; bool result = TryUriStringToDuration(text, out timespanValue); targetValue = timespanValue; return(result); } else if (targetTypeKind == EdmPrimitiveTypeKind.Geography) { Geography geographyValue; bool result = TryUriStringToGeography(text, out geographyValue, out reason); targetValue = geographyValue; return(result); } else if (targetTypeKind == EdmPrimitiveTypeKind.Geometry) { Geometry geometryValue; bool result = TryUriStringToGeometry(text, out geometryValue, out reason); targetValue = geometryValue; return(result); } bool quoted = targetTypeKind == EdmPrimitiveTypeKind.String; if (quoted != IsUriValueQuoted(text)) { targetValue = null; return(false); } if (quoted) { text = RemoveQuotes(text); } try { switch (targetTypeKind) { case EdmPrimitiveTypeKind.String: targetValue = text; break; case EdmPrimitiveTypeKind.Boolean: targetValue = XmlConvert.ToBoolean(text); break; case EdmPrimitiveTypeKind.Byte: targetValue = XmlConvert.ToByte(text); break; case EdmPrimitiveTypeKind.SByte: targetValue = XmlConvert.ToSByte(text); break; case EdmPrimitiveTypeKind.Int16: targetValue = XmlConvert.ToInt16(text); break; case EdmPrimitiveTypeKind.Int32: targetValue = XmlConvert.ToInt32(text); break; case EdmPrimitiveTypeKind.Int64: TryRemoveLiteralSuffix(ExpressionConstants.LiteralSuffixInt64, ref text); targetValue = XmlConvert.ToInt64(text); break; case EdmPrimitiveTypeKind.Single: TryRemoveLiteralSuffix(ExpressionConstants.LiteralSuffixSingle, ref text); targetValue = XmlConvert.ToSingle(text); break; case EdmPrimitiveTypeKind.Double: TryRemoveLiteralSuffix(ExpressionConstants.LiteralSuffixDouble, ref text); targetValue = XmlConvert.ToDouble(text); break; case EdmPrimitiveTypeKind.Decimal: TryRemoveLiteralSuffix(ExpressionConstants.LiteralSuffixDecimal, ref text); try { targetValue = XmlConvert.ToDecimal(text); } catch (FormatException) { // we need to support exponential format for decimals since we used to support them in V1 decimal result; if (Decimal.TryParse(text, NumberStyles.Float, NumberFormatInfo.InvariantInfo, out result)) { targetValue = result; } else { targetValue = default(Decimal); return(false); } } break; default: throw new ODataException(ODataErrorStrings.General_InternalError(InternalErrorCodes.UriPrimitiveTypeParser_TryUriStringToPrimitive)); } return(true); } catch (FormatException) { targetValue = null; return(false); } catch (OverflowException) { targetValue = null; return(false); } }
public static Gdk.Pixbuf Create(string path) { return(Create(UriUtils.PathToFileUri(path))); }
protected HistoryItem(MediaType mediaType, string remoteParty) : this() { this.mediaType = mediaType; this.remoteParty = UriUtils.GetUserName(remoteParty); }
public static string ThumbnailPath(string path) { return(ThumbnailPath(UriUtils.PathToFileUri(path))); }
protected HistoryItem(MediaType mediaType, string remoteParty, long id) : this() { this.mediaType = mediaType; this.remoteParty = UriUtils.GetUserName(remoteParty); this.sipSessionId = id; }
public void UriInvariantInsensitiveIsBaseOf_IdenticalUrisShouldReturnTrue() { UriUtils.UriInvariantInsensitiveIsBaseOf(new Uri("http://www.example.com/One/"), new Uri("http://www.example.com/One/")).Should().BeTrue(); }
/// <summary> /// Returns list of segments in the specified path (eg: /abc/pqr -> abc, pqr). /// </summary> /// <param name="fullUri">The full URI of the request.</param> /// <param name="serviceBaseUri">The service base URI for the request.</param> /// <returns>List of unescaped segments.</returns> internal ICollection <string> ParsePathIntoSegments(Uri fullUri, Uri serviceBaseUri) { if (serviceBaseUri == null) { Debug.Assert(!fullUri.IsAbsoluteUri, "fullUri must be relative Uri"); serviceBaseUri = UriUtils.CreateMockAbsoluteUri(); fullUri = UriUtils.CreateMockAbsoluteUri(fullUri); } if (!UriUtils.UriInvariantInsensitiveIsBaseOf(serviceBaseUri, fullUri)) { throw new ODataException(Strings.UriQueryPathParser_RequestUriDoesNotHaveTheCorrectBaseUri(fullUri, serviceBaseUri)); } try { Uri uri = fullUri; int numberOfSegmentsToSkip = 0; // Skip over the base URI segments #if !ORCAS // need to calculate the number of segments to skip in the full // uri (so that we can skip over http://blah.com/basePath for example, // get only the odata specific parts of the path). // // because of differences in system.uri between portable lib and // the desktop library, we need to handle this differently. // in this case we get the number of segments to skip as simply // then number of tokens in the serviceBaseUri split on slash, with // length - 1 since its a zero based array. numberOfSegmentsToSkip = serviceBaseUri.AbsolutePath.Split('/').Length - 1; string[] uriSegments = uri.AbsolutePath.Split('/'); #else numberOfSegmentsToSkip = serviceBaseUri.Segments.Length; string[] uriSegments = uri.Segments; #endif List <string> segments = new List <string>(); for (int i = numberOfSegmentsToSkip; i < uriSegments.Length; i++) { string segment = uriSegments[i]; if (segment.Length != 0 && segment != "/") { if (segment[segment.Length - 1] == '/') { segment = segment.Substring(0, segment.Length - 1); } if (segments.Count == this.maxSegments) { throw new ODataException(Strings.UriQueryPathParser_TooManySegments); } segments.Add(Uri.UnescapeDataString(segment)); } } return(segments.ToArray()); } #if !ORCAS catch (FormatException uriFormatException) #else catch (UriFormatException uriFormatException) #endif { throw new ODataException(Strings.UriQueryPathParser_SyntaxError, uriFormatException); } }
public void UriInvariantInsensitiveIsBaseOf_ShouldIgnoreHostAndSchemeAndPort() { UriUtils.UriInvariantInsensitiveIsBaseOf(new Uri("https://different.org:1234/One/"), new Uri("http://www.example.com:4567/One/Two")).Should().BeTrue(); }
/// <summary> /// Returns list of segments in the specified path (eg: /abc/pqr -> abc, pqr). /// </summary> /// <param name="fullUri">The full URI of the request.</param> /// <param name="serviceBaseUri">The service base URI for the request.</param> /// <returns>List of unescaped segments.</returns> public virtual ICollection <string> ParsePathIntoSegments(Uri fullUri, Uri serviceBaseUri) { if (serviceBaseUri == null) { Debug.Assert(!fullUri.IsAbsoluteUri, "fullUri must be relative Uri"); serviceBaseUri = UriUtils.CreateMockAbsoluteUri(); fullUri = UriUtils.CreateMockAbsoluteUri(fullUri); } if (!UriUtils.UriInvariantInsensitiveIsBaseOf(serviceBaseUri, fullUri)) { throw new ODataException(Strings.UriQueryPathParser_RequestUriDoesNotHaveTheCorrectBaseUri(fullUri, serviceBaseUri)); } // COMPAT 29: Slash in key lookup breaks URI parser // TODO: The code below has a bug that / in the named values will be considered a segment separator // so for example /Customers('abc/pqr') is treated as two segments, which is wrong. try { Uri uri = fullUri; int numberOfSegmentsToSkip = 0; // Skip over the base URI segments #if !ORCAS // need to calculate the number of segments to skip in the full // uri (so that we can skip over http://blah.com/basePath for example, // get only the odata specific parts of the path). // // because of differences in system.uri between portable lib and // the desktop library, we need to handle this differently. // in this case we get the number of segments to skip as simply // then number of tokens in the serviceBaseUri split on slash, with // length - 1 since its a zero based array. numberOfSegmentsToSkip = serviceBaseUri.AbsolutePath.Split('/').Length - 1; string[] uriSegments = uri.AbsolutePath.Split('/'); #else numberOfSegmentsToSkip = serviceBaseUri.Segments.Length; string[] uriSegments = uri.Segments; #endif int escapedStart = -1; List <string> segments = new List <string>(); for (int i = numberOfSegmentsToSkip; i < uriSegments.Length; i++) { string segment = uriSegments[i]; // Skip the empty segment or the "/" segment if (segment.Length == 0 || segment == "/") { continue; } // When we use "uri.Segments" to get the segments, // The segment element includes the "/", we should remove that. if (segment[segment.Length - 1] == '/') { segment = segment.Substring(0, segment.Length - 1); } if (segments.Count == this.maxSegments) { throw new ODataException(Strings.UriQueryPathParser_TooManySegments); } // Handle the "root...::/{xyz}" if (segment.Length >= 2 && segment.EndsWith("::", StringComparison.Ordinal)) { // It should be the terminal of the provious escape segment and the start of next escape semgent. // Otherwise, it's an invalid Uri. if (escapedStart == -1) { throw new ODataException(Strings.UriQueryPathParser_InvalidEscapeUri(segment)); } else { string value = String.Join("/", uriSegments, escapedStart, i - escapedStart + 1); segments.Add(":" + value.Substring(0, value.Length - 1));// because the last one has "::", remove one. escapedStart = i + 1; } } else if (segment.Length >= 1 && segment[segment.Length - 1] == ':') { // root:/{abc}.... if (escapedStart == -1) { if (segment != ":") { segments.Add(segment.Substring(0, segment.Length - 1));// remove the last ':' } escapedStart = i + 1; } else { // root:/{abc}:.... string escapedSegment = ":" + String.Join("/", uriSegments, escapedStart, i - escapedStart + 1); // the last has one ":"; segments.Add(escapedSegment); escapedStart = -1; } } else { // if we didn't find a starting escape, the current segment is normal segment, accept it. // otherwise, it's part of the escape, skip it and process it when we find the ending delimiter. if (escapedStart == -1) { segments.Add(Uri.UnescapeDataString(segment)); } } } if (escapedStart != -1 && escapedStart < uriSegments.Length) { string escapedSegment = ":" + String.Join("/", uriSegments, escapedStart, uriSegments.Length - escapedStart); segments.Add(escapedSegment); // We should not use "segments.Add(Uri.UnescapeDataString(escapedSegment));" to keep the orignal string. } return(segments.ToArray()); } #if !ORCAS catch (FormatException uriFormatException) #else catch (UriFormatException uriFormatException) #endif { throw new ODataException(Strings.UriQueryPathParser_SyntaxError, uriFormatException); } }
public void UriInvariantInsensitiveIsBaseOf_DifferentBaseShouldReturnFalse() { UriUtils.UriInvariantInsensitiveIsBaseOf(new Uri("http://www.example.com/OData.svc/"), new Uri("http://www.example.com/One/Two")).Should().BeFalse(); }
/// <summary> /// Validates that a string is either a valid absolute URI, or (if it begins with '#') it is a valid URI fragment. /// </summary> /// <param name="metadataDocumentUri">The metadata document uri.</param> /// <param name="propertyName">The property name to validate.</param> internal static void ValidateMetadataReferencePropertyName(Uri metadataDocumentUri, string propertyName) { Debug.Assert(metadataDocumentUri != null, "metadataDocumentUri != null"); Debug.Assert(metadataDocumentUri.IsAbsoluteUri, "metadataDocumentUri.IsAbsoluteUri"); Debug.Assert(!String.IsNullOrEmpty(propertyName), "!string.IsNullOrEmpty(propertyName)"); string uriStringToValidate = propertyName; // If it starts with a '#', validate that the rest of the string is a valid Uri fragment. if (propertyName[0] == ODataConstants.ContextUriFragmentIndicator) { // In order to use System.Uri to validate a fragement, we first prepend the metadataDocumentUri // so that it becomes an absolute URI which we can validate with Uri.IsWellFormedUriString. uriStringToValidate = UriUtils.UriToString(metadataDocumentUri) + UriUtils.EnsureEscapedFragment(propertyName); } if (!Uri.IsWellFormedUriString(uriStringToValidate, UriKind.Absolute) || !ODataJsonLightUtils.IsMetadataReferenceProperty(propertyName) || propertyName[propertyName.Length - 1] == ODataConstants.ContextUriFragmentIndicator) { throw new ODataException(Strings.ValidationUtils_InvalidMetadataReferenceProperty(propertyName)); } if (IsOpenMetadataReferencePropertyName(metadataDocumentUri, propertyName)) { throw new ODataException(Strings.ODataJsonLightValidationUtils_OpenMetadataReferencePropertyNotSupported(propertyName, UriUtils.UriToString(metadataDocumentUri))); } }
private ODataPayloadKind ParseContextUriFragment(string fragment, Func <IEdmType, string, IEdmType> clientCustomTypeResolver, bool throwIfMetadataConflict, out bool isUndeclared) { bool hasItemSelector = false; ODataDeltaKind kind = ODataDeltaKind.None; isUndeclared = false; // Deal with /$entity if (fragment.EndsWith(ODataConstants.ContextUriFragmentItemSelector, StringComparison.Ordinal)) { hasItemSelector = true; fragment = fragment.Substring(0, fragment.Length - ODataConstants.ContextUriFragmentItemSelector.Length); } else if (fragment.EndsWith(ODataConstants.ContextUriDeltaResourceSet, StringComparison.Ordinal)) { kind = ODataDeltaKind.ResourceSet; fragment = fragment.Substring(0, fragment.Length - ODataConstants.ContextUriDeltaResourceSet.Length); } else if (fragment.EndsWith(ODataConstants.ContextUriDeletedEntry, StringComparison.Ordinal)) { kind = ODataDeltaKind.DeletedEntry; fragment = fragment.Substring(0, fragment.Length - ODataConstants.ContextUriDeletedEntry.Length); } else if (fragment.EndsWith(ODataConstants.ContextUriDeltaLink, StringComparison.Ordinal)) { kind = ODataDeltaKind.Link; fragment = fragment.Substring(0, fragment.Length - ODataConstants.ContextUriDeltaLink.Length); } else if (fragment.EndsWith(ODataConstants.ContextUriDeletedLink, StringComparison.Ordinal)) { kind = ODataDeltaKind.DeletedLink; fragment = fragment.Substring(0, fragment.Length - ODataConstants.ContextUriDeletedLink.Length); } this.parseResult.DeltaKind = kind; // Deal with query option if (fragment.EndsWith(")", StringComparison.Ordinal)) { int index = fragment.Length - 2; for (int rcount = 1; rcount > 0 && index > 0; --index) { switch (fragment[index]) { case '(': rcount--; break; case ')': rcount++; break; } } if (index == 0) { throw new ODataException(ODataErrorStrings.ODataJsonLightContextUriParser_InvalidContextUrl(UriUtils.UriToString(this.parseResult.ContextUri))); } string previous = fragment.Substring(0, index + 1); // Don't treat Collection(Edm.Type) as SelectExpand segment if (!previous.Equals("Collection")) { string selectExpandStr = fragment.Substring(index + 2); selectExpandStr = selectExpandStr.Substring(0, selectExpandStr.Length - 1); // Do not treat Key as SelectExpand segment if (KeyPattern.IsMatch(selectExpandStr)) { throw new ODataException(ODataErrorStrings.ODataJsonLightContextUriParser_LastSegmentIsKeySegment(UriUtils.UriToString(this.parseResult.ContextUri))); } this.parseResult.SelectQueryOption = ExtractSelectQueryOption(selectExpandStr); fragment = previous; } } ODataPayloadKind detectedPayloadKind = ODataPayloadKind.Unsupported; EdmTypeResolver edmTypeResolver = new EdmTypeReaderResolver(this.model, clientCustomTypeResolver); if (!fragment.Contains(ODataConstants.UriSegmentSeparator) && !hasItemSelector && kind == ODataDeltaKind.None) { // Service document: no fragment if (fragment.Length == 0) { detectedPayloadKind = ODataPayloadKind.ServiceDocument; } else if (fragment.Equals(ODataConstants.CollectionPrefix + "(" + ODataConstants.EntityReferenceSegmentName + ")")) { detectedPayloadKind = ODataPayloadKind.EntityReferenceLinks; } else if (fragment.Equals(ODataConstants.EntityReferenceSegmentName)) { detectedPayloadKind = ODataPayloadKind.EntityReferenceLink; } else { var foundNavigationSource = this.model.FindDeclaredNavigationSource(fragment); if (foundNavigationSource != null) { // Resource Set: {schema.entity-container.entity-set} or Singleton: {schema.entity-container.singleton} this.parseResult.NavigationSource = foundNavigationSource; this.parseResult.EdmType = edmTypeResolver.GetElementType(foundNavigationSource); detectedPayloadKind = foundNavigationSource is IEdmSingleton ? ODataPayloadKind.Resource : ODataPayloadKind.ResourceSet; } else { // Property: {schema.type} or Collection({schema.type}) where schema.type is primitive or complex. detectedPayloadKind = this.ResolveType(fragment, clientCustomTypeResolver, throwIfMetadataConflict); Debug.Assert( this.parseResult.EdmType.TypeKind == EdmTypeKind.Primitive || this.parseResult.EdmType.TypeKind == EdmTypeKind.Enum || this.parseResult.EdmType.TypeKind == EdmTypeKind.TypeDefinition || this.parseResult.EdmType.TypeKind == EdmTypeKind.Complex || this.parseResult.EdmType.TypeKind == EdmTypeKind.Collection || this.parseResult.EdmType.TypeKind == EdmTypeKind.Entity || this.parseResult.EdmType.TypeKind == EdmTypeKind.Untyped, "The first context URI segment must be a set or a non-entity type."); } } } else { Debug.Assert(this.parseResult.MetadataDocumentUri.IsAbsoluteUri, "this.parseResult.MetadataDocumentUri.IsAbsoluteUri"); string metadataDocumentStr = UriUtils.UriToString(this.parseResult.MetadataDocumentUri); if (!metadataDocumentStr.EndsWith(ODataConstants.UriMetadataSegment, StringComparison.Ordinal)) { throw new ODataException(ODataErrorStrings.ODataJsonLightContextUriParser_InvalidContextUrl(UriUtils.UriToString(this.parseResult.ContextUri))); } Uri serviceRoot = new Uri(metadataDocumentStr.Substring(0, metadataDocumentStr.Length - ODataConstants.UriMetadataSegment.Length)); ODataUriParser odataUriParser = new ODataUriParser(this.model, serviceRoot, new Uri(serviceRoot, fragment)); ODataPath path; try { path = odataUriParser.ParsePath(); } catch (ODataException) { throw new ODataException(ODataErrorStrings.ODataJsonLightContextUriParser_InvalidContextUrl(UriUtils.UriToString(this.parseResult.ContextUri))); } if (path.Count == 0) { throw new ODataException(ODataErrorStrings.ODataJsonLightContextUriParser_InvalidContextUrl(UriUtils.UriToString(this.parseResult.ContextUri))); } this.parseResult.Path = path; parseResult.NavigationSource = path.NavigationSource(); parseResult.EdmType = path.LastSegment.EdmType; ODataPathSegment lastSegment = path.TrimEndingTypeSegment().LastSegment; if (lastSegment is EntitySetSegment || lastSegment is NavigationPropertySegment) { if (kind != ODataDeltaKind.None) { detectedPayloadKind = ODataPayloadKind.Delta; } else { detectedPayloadKind = hasItemSelector ? ODataPayloadKind.Resource : ODataPayloadKind.ResourceSet; } if (this.parseResult.EdmType is IEdmCollectionType) { var collectionTypeReference = this.parseResult.EdmType.ToTypeReference().AsCollection(); if (collectionTypeReference != null) { this.parseResult.EdmType = collectionTypeReference.ElementType().Definition; } } } else if (lastSegment is SingletonSegment) { detectedPayloadKind = ODataPayloadKind.Resource; } else if (path.IsIndividualProperty()) { isUndeclared = path.IsUndeclared(); detectedPayloadKind = ODataPayloadKind.Property; IEdmComplexType complexType = parseResult.EdmType as IEdmComplexType; if (complexType != null) { detectedPayloadKind = ODataPayloadKind.Resource; } else { IEdmCollectionType collectionType = parseResult.EdmType as IEdmCollectionType; if (collectionType != null) { if (collectionType.ElementType.IsComplex()) { this.parseResult.EdmType = collectionType.ElementType.Definition; detectedPayloadKind = ODataPayloadKind.ResourceSet; } else { detectedPayloadKind = ODataPayloadKind.Collection; } } } } else { throw new ODataException(ODataErrorStrings.ODataJsonLightContextUriParser_InvalidContextUrl(UriUtils.UriToString(this.parseResult.ContextUri))); } } return(detectedPayloadKind); }
/// <summary> /// Returns the string representation of the URI /// </summary> /// <param name="uri">The uri to process.</param> /// <returns>Returns the string representation of the URI.</returns> internal string UriToString(Uri uri) { Debug.Assert(uri != null, "uri != null"); // Get the metadataDocumentUri directly from MessageWriterSettings and not using ContextUriBuilder because in the case of getting the service document with nometadata // ContextUriBuilder returns null, but the metadataDocumentUri is needed to calculate Absolute Uris in the service document. In any other case jsonLightOutputContext.CreateContextUriBuilder() should be used. Uri metadataDocumentUri = this.jsonLightOutputContext.MessageWriterSettings.MetadataDocumentUri; Uri resultUri; if (this.jsonLightOutputContext.UrlResolver != null) { // The resolver returns 'null' if no custom resolution is desired. resultUri = this.jsonLightOutputContext.UrlResolver.ResolveUrl(metadataDocumentUri, uri); if (resultUri != null) { return(UriUtils.UriToString(resultUri)); } } resultUri = uri; if (!resultUri.IsAbsoluteUri) { if (!this.allowRelativeUri) { // TODO: Check if it is dead code to be removed. if (metadataDocumentUri == null) { throw new ODataException(Strings.ODataJsonLightSerializer_RelativeUriUsedWithoutMetadataDocumentUriOrMetadata(UriUtils.UriToString(resultUri))); } resultUri = UriUtils.UriToAbsoluteUri(metadataDocumentUri, uri); } else { resultUri = UriUtils.EnsureEscapedRelativeUri(resultUri); } } return(UriUtils.UriToString(resultUri)); }
/// <summary> /// Converts the specified URI into an absolute URI. /// </summary> /// <param name="uri">The uri to process.</param> /// <param name="baseUri">The base Uri to use.</param> /// <returns>An absolute URI which is either the specified <paramref name="uri"/> if it was absolute, /// or it's a combination of the <paramref name="baseUri"/> and the relative <paramref name="uri"/>. /// The return value is the string representation of the URI.</returns> /// <remarks>This method will fail if the specified <paramref name="uri"/> is relative and there's no base URI available.</remarks> internal static string UriToAbsoluteUriString(Uri uri, Uri baseUri) { DebugUtils.CheckNoExternalCallers(); Debug.Assert(uri != null, "uri != null"); Uri resultUri; if (uri.IsAbsoluteUri) { resultUri = uri; } else { if (baseUri == null) { throw new ODataException(Strings.ODataWriter_RelativeUriUsedWithoutBaseUriSpecified(UriUtils.UriToString(uri))); } resultUri = UriUtils.UriToAbsoluteUri(baseUri, uri); } return(UriUtils.UriToString(resultUri)); }
private void ItemWatcher_ValueLoaded(object sender, EventArgs e) { this.@event = this.Value; this.labelUriString.Content = String.Format(CultureInfo.CurrentUICulture, "{0} ({1})", UriUtils.GetDisplayName([email protected]), [email protected]); this.labelPackage.Content = String.Format(CultureInfo.CurrentUICulture, "Package ({0})", [email protected]); this.labelStatus.Content = String.Format(CultureInfo.CurrentUICulture, "{0} ({1})", ItemWatcher.GetAsString([email protected]), ItemWatcher.GetAsString([email protected])); switch ([email protected]) { case watcherStatus.active: this.imageStatus.Source = MyImageConverter.FromBitmap(Properties.Resources.bullet_ball_glass_green_16); this.ctxMenu_Allow.IsEnabled = false; break; case watcherStatus.pending: this.imageStatus.Source = MyImageConverter.FromBitmap(Properties.Resources.bullet_ball_glass_yellow_16); break; case watcherStatus.waiting: this.imageStatus.Source = MyImageConverter.FromBitmap(Properties.Resources.bullet_ball_glass_grey_16); break; case watcherStatus.terminated: this.imageStatus.Source = MyImageConverter.FromBitmap(Properties.Resources.bullet_ball_glass_red_16); this.ctxMenu_Allow.IsEnabled = false; this.ctxMenu_Block.IsEnabled = false; this.ctxMenu_Revoke.IsEnabled = false; break; } }