private static void VerifyLinksPayload(Workspace w, CommonPayload payload, LinqQueryBuilder linqBuilder) { ArrayList expectedEntities = CommonPayload.CreateList(linqBuilder.QueryResult); if (payload == null) { AstoriaTestLog.AreEqual(expectedEntities.Count, 0, "Unexpected null $ref payload"); } else { KeyExpressions expectedKeys = new KeyExpressions(); foreach (object o in expectedEntities) { KeyExpression keyExp = w.CreateKeyExpressionFromProviderObject(o); expectedKeys.Add(keyExp); } List <string> linksFound = new List <string>(); if (payload.Resources == null) { linksFound.Add(payload.Value); } else { foreach (PayloadObject o in (payload.Resources as List <PayloadObject>)) { if (o.PayloadProperties.Any(p => p.Name == "uri")) { linksFound.Add((o["uri"] as PayloadSimpleProperty).Value); } } } AstoriaTestLog.AreEqual(expectedKeys.Count, linksFound.Count, "Number of expected entities does not match number of links found"); foreach (string link in linksFound) { KeyExpression match = null; foreach (KeyExpression expectedKey in expectedKeys) { if (compareKeyURI(link, expectedKey)) { match = expectedKey; break; } } if (match != null) { expectedKeys.Remove(match); } else { AstoriaTestLog.WriteLineIgnore("Unexpected URI: '" + link + "'"); AstoriaTestLog.FailAndThrow("Unexpected URI found in $ref payload"); } } } }
//--------------------------------------------------------------------- // Replaces existing method code with that from embedded resources. //--------------------------------------------------------------------- protected string ReplaceCode(string existingCode, string methodRegex, string resourceName) { // Find embedded resource. foreach (string fullName in GetType().Assembly.GetManifestResourceNames()) { if (fullName.Contains(resourceName)) { // Replace type resolver. using (StreamReader reader = new StreamReader(GetType().Assembly.GetManifestResourceStream(fullName), true)) { // Read new code from resources. string newCode = reader.ReadToEnd(); // Find method signature in existing code and replace Regex method = new Regex(methodRegex, RegexOptions.Singleline); if (method.Match(existingCode).Success) { return(method.Replace(existingCode, newCode)); } AstoriaTestLog.FailAndThrow("Test error: unable to match " + methodRegex + " in embedded code: " + existingCode); return(null); } } } AstoriaTestLog.FailAndThrow("Test error: unable to find embedded resource: " + existingCode); return(null); }
public AstoriaServiceHost(Workspace workspace, string webDataServicePrefixName, string machineName, AstoriaDatabase database) : base(workspace, webDataServicePrefixName, machineName, database) { if (AstoriaTestProperties.Host == Host.IDSH || AstoriaTestProperties.Host == Host.IDSH2) { if (AstoriaTestProperties.HostAuthenicationMethod != "None") { AstoriaTestLog.FailAndThrow("Test implementations of IDSH do not support authentication"); } } waitHandleName = waitHandlePrefix + identifier; serviceInstanceName = this.WebDataServicePrefixName + "_" + identifier; exeName = serviceName + this.WebDataServicePrefixName; if (ProcessHelper.IsLocalMachine(this.MachineName)) { DestinationFolder = Path.Combine(serviceHostFolder, serviceInstanceName); DestinationFolder_Local = DestinationFolder; ExecutablePath = Path.Combine(DestinationFolder, exeName + ".exe"); localExecutablePath = ExecutablePath; } else { string remoteMachineLocalPath = IISHelper.GetLocalMachineWWWRootSharePath(this.MachineName); DestinationFolder_Local = Path.Combine(IISHelper.GetLocalMachineWWWRootSharePath(this.MachineName), serviceInstanceName); DestinationFolder = Path.Combine(IISHelper.GetWWWRootSharePath(this.MachineName), serviceInstanceName); ExecutablePath = Path.Combine(DestinationFolder, exeName + ".exe"); localExecutablePath = Path.Combine(DestinationFolder_Local, exeName + ".exe"); } rootUri = Uri.UriSchemeHttp + "://" + this.MachineName + ":7777"; }
public virtual void CompareSingleValue(object expected, bool stripQuotes, bool valueUri) { if (this.Resources == null && expected == null) { return; } PayloadSimpleProperty simpleProperty = this.Resources as PayloadSimpleProperty; if (simpleProperty == null) { AstoriaTestLog.FailAndThrow("Payload did not represent a single value"); } if (expected == null) { if (!simpleProperty.IsNull) { AstoriaTestLog.FailAndContinue(new TestFailedException("Compare failed - Expected: null, got: " + simpleProperty.Value)); } } else { ComparePrimitiveValuesObjectAndString(expected, expected.GetType(), simpleProperty.Value, valueUri, this.Format, false); } }
public static void VerifyConcurrency(AstoriaResponse response) { if (response.Request.ETagHeaderExpected) { if (!response.ETagHeaderFound && !RequestUtil.ExpectEmptyHeaders(response)) { AstoriaTestLog.FailAndThrow("Missing ETag header in response"); } } else if (response.ETagHeaderFound) { if (string.IsNullOrEmpty(response.ETagHeader)) { if (Versioning.Server.BugFixed_NullETagWhenTypeHasNoConcurrency) { AstoriaTestLog.FailAndThrow("Unexpected null ETag header in response"); } else { AstoriaTestLog.WriteLine("Ignoring unexpected null ETag header in response due to known bug"); } } else { AstoriaTestLog.FailAndThrow("Unexpected ETag header in response: '" + response.ETagHeader + "'"); } } }
//--------------------------------------------------------------------- // Adds code from embedded resources to data service source file. //--------------------------------------------------------------------- protected void InjectCode(Workspace w, params string[] resourceNames) { foreach (string resourceName in resourceNames) { // Find embedded resource. bool found = false; foreach (string fullName in GetType().Assembly.GetManifestResourceNames()) { if (fullName.Contains(resourceName)) { // Append contents to service code. using (StreamReader reader = new StreamReader(GetType().Assembly.GetManifestResourceStream(fullName), true)) { w.GlobalAdditionalCode += reader.ReadToEnd(); found = true; break; } } } if (!found) { AstoriaTestLog.FailAndThrow("Test error: embedded resource not found!"); } } }
/// <summary> /// Constructs a new CodeGeneratingDataInserter for the given workspace /// </summary> /// <param name="w">the worspace to add data to</param> public CodeGeneratingDataInserter(Workspace w) { if (w.DataLayerProviderKind != DataLayerProviderKind.InMemoryLinq && w.DataLayerProviderKind != DataLayerProviderKind.NonClr) { AstoriaTestLog.FailAndThrow("CodeGeneratingDataInserter only supported for InMemory and NonClr workspaces"); } workspace = w; }
//--------------------------------------------------------------------- // Sends and verifies request for all possible access rights. //--------------------------------------------------------------------- public void TestAccess(string container) { // Save current state. HttpStatusCode normalStatusCode = ExpectedStatusCode; #if !ClientSKUFramework for (uint i = 0; i <= (uint)Microsoft.OData.Service.EntitySetRights.All; i++) { // Set entity set access right. Workspace.DataService.ConfigSettings.SetEntitySetAccessRule(container, (Microsoft.OData.Service.EntitySetRights)i); // Calculate minimum access needed for request to succeed. Microsoft.OData.Service.EntitySetRights minAccess = Microsoft.OData.Service.EntitySetRights.All; switch (Verb) { case RequestVerb.Post: minAccess = Microsoft.OData.Service.EntitySetRights.WriteAppend; break; case RequestVerb.Get: minAccess = Microsoft.OData.Service.EntitySetRights.ReadSingle; break; case RequestVerb.Put: minAccess = Microsoft.OData.Service.EntitySetRights.WriteReplace | Microsoft.OData.Service.EntitySetRights.ReadSingle; break; case RequestVerb.Patch: minAccess = Microsoft.OData.Service.EntitySetRights.WriteMerge | Microsoft.OData.Service.EntitySetRights.ReadSingle; break; case RequestVerb.Delete: minAccess = Microsoft.OData.Service.EntitySetRights.WriteDelete | Microsoft.OData.Service.EntitySetRights.ReadSingle; break; default: AstoriaTestLog.FailAndThrow("Test issue - unknown request verb (2)"); break; } // Calculate expected status code. ExpectedStatusCode = i == 0 ? HttpStatusCode.NotFound : (i & (uint)minAccess) == (uint)minAccess ? normalStatusCode : HttpStatusCode.Forbidden; // Send and verify request. AstoriaResponse response = SendAndVerify(null); // Delete the entity if it was created to avoid "key already exists" collisions. if (response.Headers.ContainsKey("Location")) { string newEntity = response.Headers["Location"]; Workspace.DataService.ConfigSettings.SetEntitySetAccessRule(container, Microsoft.OData.Service.EntitySetRights.WriteDelete | Microsoft.OData.Service.EntitySetRights.ReadSingle); BlobsRequest.MLE(Workspace, Format, RequestVerb.Delete, null, HttpStatusCode.NoContent, newEntity).SendAndVerify(null); } } #endif // Restore previous state. ExpectedStatusCode = normalStatusCode; #if !ClientSKUFramework Workspace.DataService.ConfigSettings.SetEntitySetAccessRule(container, Microsoft.OData.Service.EntitySetRights.All); #endif }
public static T Execute <T>(Func <T> f, bool inWebRequest, out System.Net.WebException exc) { exc = null; for (int i = 0; i < SocketExceptionRetries; i++) { try { exc = null; return(TrustedMethods.ReturnFuncResult <T>(f)); } catch (WebException ex) { exc = ex; if (ex.InnerException is SocketException) { HandleSocketException(inWebRequest, (SocketException)exc.InnerException); } else { if (inWebRequest) { return(default(T)); // it will handle this } if (ex.Status == WebExceptionStatus.Timeout && CatchTimeouts) { HandleWebRequestTimeout(inWebRequest, ex); } else { throw ex; } } } catch (Exception ex) { if (ex.InnerException == null || !(ex.InnerException is System.Net.WebException)) { throw ex; } exc = (WebException)ex.InnerException; if (exc.InnerException != null && (exc.InnerException is SocketException)) { HandleSocketException(inWebRequest, (SocketException)exc.InnerException); } else if (exc.Status == WebExceptionStatus.Timeout && CatchTimeouts) { HandleWebRequestTimeout(inWebRequest, exc); } else { throw ex; } } } AstoriaTestLog.FailAndThrow("Repeated socket exceptions encountered, consequences unpredictable."); return(default(T)); }
public static void Verify(APICallLogBuilder callLogBuilder, AstoriaResponse response, params ComplexType[] types) { if (!response.Request.LogAPICalls) { AstoriaTestLog.FailAndThrow("Cannot verify call order when the request did not log the calls"); } Verify(callLogBuilder, response, Equal, types); }
public static BatchResponse ParseBatchResponse(BatchRequest batchRequest, StringReader reader, string boundary) { // even if content-id is specified, we may not get it back in error cases. This doesn't feel entirely correct, it seems like there should // always be a 1-1 mapping that explicitly honors content-id's // TODO: responses / requests without content IDs should be matched up in order within changeset only // changesets should have the right number of responses too BatchResponse response = null;// new BatchResponse(batchRequest); List <ResponseFragment> unmatchedFragments = new List <ResponseFragment>(); List <AstoriaRequest> unmatchedRequests = batchRequest.Requests .Union(batchRequest.Changesets.SelectMany(changeset => changeset.AsEnumerable())) .ToList(); foreach (ResponseFragment fragment in ParseBatchResponse(reader, boundary)) { AstoriaRequest request = null; if (fragment.ContentID != null) { request = unmatchedRequests .FirstOrDefault(r => r.Headers.ContainsKey("Content-ID") && r.Headers["Content-ID"].Equals(fragment.ContentID)); } if (request == null) { unmatchedFragments.Add(fragment); } else { unmatchedRequests.Remove(request); response.Responses.Add(FragmentToResponse(request, fragment)); } } if (unmatchedFragments.Any()) { if (unmatchedFragments.Count < unmatchedRequests.Count) { AstoriaTestLog.WriteLine("Warning: recieved fewer batch response fragments than expected"); } else if (unmatchedFragments.Count > unmatchedRequests.Count) { AstoriaTestLog.FailAndThrow("Recieved more batch fragments than expected"); } for (int i = 0; i < unmatchedFragments.Count; i++) { response.Responses.Add(FragmentToResponse(unmatchedRequests[i], unmatchedFragments[i])); } } return(response); }
public static void VerifySpecificResponseVersion(AstoriaResponse response, int major, int minor) { if (response.DataServiceVersion == null) { AstoriaTestLog.FailAndThrow("Data service version should always be specified in response"); } AstoriaTestLog.IsTrue(response.DataServiceVersion.StartsWith(major + "." + minor), String.Format("Unexpected value in response's DataServiceVersion header: {0}, expected: {1}.{2}", response.DataServiceVersion, major, minor)); }
private static IEnumerable <ResponseFragment> ParseBatchResponse(StringReader reader, string boundary) { //--batchresponse_aa2a62c3-d5f4-447e-9302-d31f062b02f7 //Content-Type: multipart/mixed; boundary=changesetresponse_1837899f-f0ce-447e-a980-d2596a561051 string boundaryLine = reader.ReadLine(); if (!boundaryLine.Contains(boundary)) { AstoriaTestLog.FailAndThrow(String.Format("Unexpected line in batch response: '{0}', expected boundary '{1}'", boundaryLine, boundary)); } string headerLine; while (null != (headerLine = reader.ReadLine())) { Match match = Regex.Match(headerLine, @"Content-Type: multipart/mixed; boundary=(\S+)"); if (match.Success) { // eat the extra newline reader.ReadLine(); foreach (ResponseFragment fragment in ParseChangeSet(reader, match.Groups[1].Value, boundary)) { yield return(fragment); } } else { // this might be a batch get instead //--batch(36522ad7-fc75-4b56-8c71-56071383e77b) //Content-Type: application/http //Content-Transfer-Encoding:binary if (!Regex.IsMatch(headerLine, @"Content-Type:\s+application/http")) { AstoriaTestLog.FailAndThrow(String.Format("Could not parse batch content type or boundary, line was '{0}'", headerLine)); } headerLine = reader.ReadLine(); if (!Regex.IsMatch(headerLine, @"Content-Transfer-Encoding:\s+binary")) { AstoriaTestLog.FailAndThrow(String.Format("Missing content-transfer-encoding, line was '{0}'", headerLine)); } // eat the extra newline reader.ReadLine(); yield return(ParseBatchFragment(reader, boundary)); } } }
//--------------------------------------------------------------------- public static BlobsPayload Parse(SerializationFormatKind format, AstoriaResponse response) { switch (format) { case SerializationFormatKind.Atom: return(new BlobsPayload.Atom(response.Payload)); case SerializationFormatKind.JSON: return(new BlobsPayload.JSON(response.Payload)); default: AstoriaTestLog.FailAndThrow("Unknown serialization format kind: " + format.ToString()); return(null); } }
public static KeyExpression ConstructKey(ResourceContainer container, PayloadObject entity) { Dictionary <string, object> properties = new Dictionary <string, object>(); ResourceType type = container.BaseType; if (entity.Type != type.Namespace + "." + type.Name) { type = container.ResourceTypes.SingleOrDefault(rt => rt.Namespace + "." + rt.Name == entity.Type); if (type == null) { AstoriaTestLog.FailAndThrow("Could not find resource type for payload type value: " + entity.Type); } } foreach (ResourceProperty property in type.Properties.OfType <ResourceProperty>()) { if (property.IsNavigation || property.IsComplexType) { continue; } string propertyName = property.Name; string valueString; if (entity.PayloadProperties.Any(p => p.Name == propertyName)) { PayloadSimpleProperty simpleProperty = entity[propertyName] as PayloadSimpleProperty; if (simpleProperty == null) { continue; } valueString = simpleProperty.Value; } else { continue; } object value = CommonPayload.DeserializeStringToObject(valueString, property.Type.ClrType, false, entity.Format); if (value is DateTime && entity.Format == SerializationFormatKind.JSON) { // TODO: this is because the server will make any JSON datetime into UTC, and currently we always send 'unspecified' values value = new DateTime(((DateTime)value).Ticks, DateTimeKind.Unspecified); } properties[propertyName] = value; } return(new KeyExpression(container, type, properties)); }
private static ResponseFragment ParseBatchFragment(StringReader reader, string boundary) { //HTTP/1.1 200 Ok //Content-Type: application/atom+xml;type=entry //Content-Length: ### string line = reader.ReadLine(); Match match = Regex.Match(line, @"HTTP/1.1 ([0-9]{3}).*"); if (!match.Success) { AstoriaTestLog.FailAndThrow(String.Format("Expected HTTP protocol and status code, got '{0}'", line)); } HttpStatusCode statusCode = (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), match.Groups[1].Value); Dictionary <string, string> headers = new Dictionary <string, string>(); while (null != (line = reader.ReadLine()) && !line.Contains(boundary) && (match = Regex.Match(line, @"([A-Za-z-]+):\s*(.+)")).Success) { string headerString = match.Groups[1].Value;//.Replace("-", String.Empty).ToLowerInvariant(); string value = match.Groups[2].Value; headers.Add(headerString, value); } // the rest is payload StringBuilder payload = new StringBuilder(); while (null != (line = reader.ReadLine()) && !line.Contains(boundary)) { payload.AppendLine(line); } ResponseFragment fragment = new ResponseFragment() { ContentID = null, ContentType = "application/xml", // will be overwritten if present Payload = payload.ToString().Trim(), StatusCode = statusCode, Headers = headers }; headers.TryGetValue("Content-Type", out fragment.ContentType); headers.TryGetValue("Content-ID", out fragment.ContentID); return(fragment); }
public static XmlNode FindFirstChild(string payload) { XmlDocument xmlDocument = new XmlDocument(); try { xmlDocument.LoadXml(payload); } catch { AstoriaTestLog.FailAndThrow("payload was not valid xml."); } return(xmlDocument.FirstChild.NextSibling); }
public static void RegisterTypesForUnDeclaredProperties(Workspace w) { if (w.DataService == null || w.DataService.ConfigSettings == null) { AstoriaTestLog.FailAndThrow("Cannot register complex types as service is not set up yet"); } IEnumerable <Type> toAdd = w.ServiceContainer.ResourceTypes .SelectMany(rt => rt.Properties.OfType <ResourceProperty>()) .Where(rp => !rp.Facets.IsDeclaredProperty) .Select(rp => rp.Type.ClrType) .Distinct(); //foreach (Type type in toAdd) // w.DataService.ConfigSettings.AddRegisterKnownType(type.FullName); }
private static bool MethodAllowed(ContainmentQuery query, ContainmentQuerySuffix suffix, RequestVerb verb) { if (query.SetExpected) { if (suffix != ContainmentQuerySuffix.None) { AstoriaTestLog.FailAndThrow("Only the NONE suffix can be used when a set is expected"); } return(verb == RequestVerb.Get || verb == RequestVerb.Post); } else { return(VerbMap.Valid(suffix, verb)); } }
private static T ConvertToEnum <T>(string value, T defaultValue) { if (string.IsNullOrEmpty(value)) { return(defaultValue); } T converted = Enum.GetValues(typeof(T)).Cast <T>().SingleOrDefault(e => e.ToString().Equals(value, StringComparison.InvariantCultureIgnoreCase)); if (converted == null) { AstoriaTestLog.FailAndThrow(String.Format("Could not convert value '{0}' into enum type '{1}'", value, typeof(T))); } return(converted); }
public ResourceInstanceProperty this[string name] { get { return(this.FirstOrDefault(p => p.Name == name)); } set { if (value.Name != name) { AstoriaTestLog.FailAndThrow("Cannot add property with wrong name"); } this.Add(value); } }
public static void Verify(List <APICallLogEntry> expectedCalls, List <APICallLogEntry> observedCalls, Func <APICallLogEntry, APICallLogEntry, bool> compare) { observedCalls = observedCalls.Where(e => !ClassesToIgnore.Any(c => e.MethodName.StartsWith(c + "."))).ToList(); List <int> mismatchedLines = new List <int>(); AstoriaTestLog.WriteLineIgnore("Observed call order: "); for (int i = 0; i < observedCalls.Count; i++) { if (i >= expectedCalls.Count || !compare(expectedCalls[i], observedCalls[i])) { AstoriaTestLog.WriteLine("(Observed) " + i + " - " + observedCalls[i].ToString()); mismatchedLines.Add(i); } else if (!AstoriaTestProperties.IsLabRun) { AstoriaTestLog.WriteLineIgnore("(Observed) " + i + " - " + observedCalls[i].ToString()); } } if (observedCalls.Count < expectedCalls.Count) { for (int i = observedCalls.Count; i < expectedCalls.Count; i++) { mismatchedLines.Add(i); } } if (mismatchedLines.Any()) { AstoriaTestLog.WriteLineIgnore("Expected call order: "); for (int i = 0; i < expectedCalls.Count; i++) { if (mismatchedLines.Contains(i)) { AstoriaTestLog.WriteLine("(Expected) " + i + " - " + expectedCalls[i].ToString()); } else { AstoriaTestLog.WriteLineIgnore("(Expected) " + i + " - " + expectedCalls[i].ToString()); } } AstoriaTestLog.FailAndThrow("Observed call log did not match baseline"); } }
private T LoadProperty <T>(object entity, string propertyName) { if (entity == null) { throw new ArgumentNullException("entity"); } if (propertyName == null) { throw new ArgumentNullException("propertyName"); } object value; if (TryLoadProperty_EF(entity, propertyName, out value)) { return((T)value); } // L2S types have the DataServiceKey attribute, need to try them first if (TryLoadProperty_L2S(entity, propertyName, out value)) { return((T)value); } if (TryLoadProperty_Client(entity, propertyName, out value)) { return((T)value); } #if !ClientSKUFramework if (TryLoadProperty_RowEntityType(entity, propertyName, out value)) { return((T)value); } #endif if (TryLoadProperty_Reflection(entity, propertyName, out value)) { return((T)value); } AstoriaTestLog.FailAndThrow("Could not load property '" + propertyName + "' on entity of type '" + entity.GetType() + "'"); return(default(T)); }
private static string ParseResponseErrorJSON(AstoriaResponse response, bool inStream) { // error should be something like //{ // "error": { // "code": "", "message": "Error message" // } //} ServiceError serviceError = new ServiceError(); string payloadString = response.Payload; CommonPayload payload; if (inStream) { Match match = JsonInStreamErrorRegex.Match(payloadString); if (!match.Success) { AstoriaTestLog.TraceLine(payloadString); AstoriaTestLog.FailAndThrow("Payload did not contain expected in-stream error"); } response.Payload = match.Groups[1].Value; } payload = response.CommonPayload; PayloadProperty prop; PayloadComplexProperty complex = payload.Resources as PayloadComplexProperty; if (complex != null) { if (complex.PayloadProperties.TryGetValue("message", out prop)) { if (prop is PayloadComplexProperty) { if ((prop as PayloadComplexProperty).PayloadProperties.TryGetValue("value", out prop)) { serviceError.message = (prop as PayloadSimpleProperty).Value; } } } } return(serviceError.message); }
protected void CompareDynamicPropertyValues(PayloadProperty inserted, PayloadProperty returned) { if (inserted.IsNull || returned.IsNull) { if (!inserted.IsNull) { AstoriaTestLog.FailAndThrow("Null inserted value was non-null in return payload"); } if (!returned.IsNull) { AstoriaTestLog.FailAndThrow("Non-null inserted value was null in return payload"); } } else { NodeType insertType = GetDynamicPropertyType(inserted); NodeType returnType = GetDynamicPropertyType(returned); if (inserted.MappedOutOfContent == returned.MappedOutOfContent) { bool equivalentTypes = false; if (EquivalentValues(insertType, inserted, returnType, returned)) { equivalentTypes = true; } if (EquivalentValues(returnType, returned, insertType, inserted)) { equivalentTypes = true; } if (!equivalentTypes) { AstoriaTestLog.AreEqual(insertType, returnType, "Type of inserted/updated dynamic property value does not match returned type for property", false); } } else if (inserted.MappedOutOfContent) { insertType = returnType; } ComparePropertyValues(insertType, inserted, returned, true); } }
public static KeyExpression GetContainingKey(this ContainmentAttribute att, KeyExpression childKey, ResourceType parentType, bool abbreviate) { AstoriaTestLog.Compare(childKey.ResourceContainer == att.ChildContainer, String.Format("ChildKey does not belong to expected set (Expected '{0}', got '{1}'", att.ChildContainer.Name, childKey.ResourceContainer.Name)); List <PropertyExpression> parentProperties = new List <PropertyExpression>(); List <ConstantExpression> parentValues = new List <ConstantExpression>(); foreach (NodeProperty p_prop in att.ParentContainer.BaseType.Key.Properties) { string c_name; if (!att.KeyMapping.TryGetValue(p_prop.Name, out c_name)) { AstoriaTestLog.FailAndThrow(String.Format("Parent key property {0} does not appear in derived key mapping", p_prop.Name)); } // need to get the offset now int c_offset = 0; for (; c_offset < childKey.Properties.Length; c_offset++) { if (childKey.Properties[c_offset].Name == c_name) { break; } } if (c_offset >= childKey.Properties.Length) { AstoriaTestLog.FailAndThrow(String.Format("Could not find property '{0}' in child key", c_name)); } NodeProperty c_prop = childKey.Properties[c_offset]; parentProperties.Add(p_prop.Property()); parentValues.Add(new ConstantExpression(childKey.Values[c_offset])); if (abbreviate) { childKey.IncludeInUri[c_offset] = false; } } return(new KeyExpression(att.ParentContainer, parentType, parentProperties.ToArray(), parentValues.ToArray())); }
public static Dictionary <string, string> ParseETag(ResourceType type, string ETag) { string[] values = SplitETag(ETag); List <string> etagProperties = type.Properties.Where(p => p.Facets.ConcurrencyModeFixed).Select(p => p.Name).ToList(); if (values.Length != etagProperties.Count) { AstoriaTestLog.FailAndThrow("Could not parse etag"); return(null); } else { Dictionary <string, string> etagMap = new Dictionary <string, string>(); for (int i = 0; i < values.Length; i++) { etagMap[etagProperties[i]] = values[i]; } return(etagMap); } }
private static IEnumerable <ResponseFragment> ParseChangeSet(StringReader reader, string changeSetBoundary, string batchBoundary) { // first line should be the boundary // second line should be content type // third line should be content-transfer-encoding //--changesetresponse_1837899f-f0ce-447e-a980-d2596a561051 //Content-Type: application/http //Content-Transfer-Encoding: binary string boundaryLine = reader.ReadLine(); if (!boundaryLine.Contains(changeSetBoundary)) { AstoriaTestLog.FailAndThrow(String.Format("Unexpected line in batch response: '{0}', expected boundary '{1}'", boundaryLine, changeSetBoundary)); } string line; while (null != (line = reader.ReadLine()) && !line.Contains(batchBoundary)) { if (!Regex.IsMatch(line, @"Content-Type:\s*application/http")) { AstoriaTestLog.FailAndThrow(String.Format("Could not parse change set content type, line was '{0}'", line)); } line = reader.ReadLine(); if (!Regex.IsMatch(line, @"Content-Transfer-Encoding:\s*binary")) { AstoriaTestLog.FailAndThrow(String.Format("Missing change set content-transfer-encoding, line was '{0}'", line)); } // eat the newline reader.ReadLine(); yield return(ParseBatchFragment(reader, changeSetBoundary)); } }
public static string GetLocalizedResourceString(Workspace w, ResourceIdentifier identifier, bool isLocal, object[] args) { try { if (isLocal) { return(ResourceUtil.GetLocalizedResourceString(identifier, args)); } else { return(w.GetLocalizedResourceString(identifier.Id, args)); } } catch (ArgumentException e) { if (e.Message == ResourceUtil.MissingLocalizeResourceString) { AstoriaTestLog.FailAndThrow(String.Format("Resource identifier '{0}' could not be found {1}", identifier.Id, (isLocal ? "locally" : "remotely"))); } throw; } }
public static void SetupDefaultOpenTypeAttributes(Workspace w) { if (w.DataLayerProviderKind != DataLayerProviderKind.NonClr) { AstoriaTestLog.FailAndThrow("Open types not supported for data-layers other than NonCLR"); } #if !ClientSKUFramework // let the open types tests do their own thing if (w is OpenTypesWorkspace) { return; } #endif if (w.Name.Equals("Northwind", StringComparison.InvariantCultureIgnoreCase)) { foreach (ResourceType type in w.ServiceContainer.ResourceTypes.Distinct().Where(t => !t.Facets.IsOpenType)) { type.Facets.Add(NodeFacet.Attribute(new OpenTypeResourceAttribute(type, (rp => rp.IsNavigation || rp.PrimaryKey != null || rp.Facets.ConcurrencyModeFixed)))); } } else if (w.Name.Equals("Aruba", StringComparison.InvariantCultureIgnoreCase)) { foreach (ResourceType type in w.ServiceContainer.ResourceTypes.Distinct().Where(t => !t.Facets.IsOpenType)) { type.Facets.Add(NodeFacet.Attribute(new OpenTypeResourceAttribute(type, (rp => rp.IsNavigation || rp.PrimaryKey != null || rp.Facets.ConcurrencyModeFixed)))); } } #if !ClientSKUFramework w.AfterServiceCreation.Add(() => (w as NonClrWorkspace).OpenTypeMethodsImplementation = System.Data.Test.Astoria.LateBound.OpenTypeMethodsImplementations.Realistic); #endif // immediately after creating the service, register the undeclared properties' types w.AfterServiceCreation.Insert(0, () => RegisterTypesForUnDeclaredProperties(w)); }