本文整理汇总了C#中DataServiceContext.Execute方法的典型用法代码示例。如果您正苦于以下问题:C# DataServiceContext.Execute方法的具体用法?C# DataServiceContext.Execute怎么用?C# DataServiceContext.Execute使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类DataServiceContext
的用法示例。
在下文中一共展示了DataServiceContext.Execute方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: WebGrid
//
// GET: /OData/
public ActionResult WebGrid(int page = 1, int rowsPerPage = 10, string sort = "ProductID", string sortDir = "ASC")
{
DataServiceContext nwd = new DataServiceContext(new Uri("http://services.odata.org/Northwind/Northwind.svc/"));
var Products2 =
(QueryOperationResponse<Product>)nwd.Execute<Product>(
new Uri("http://services.odata.org/Northwind/Northwind.svc/Products()?$expand=Category,Supplier&$select=ProductID,ProductName,Category/CategoryName,Supplier/CompanyName,Supplier/Country"));
var t = from p in Products2
select new JointProductModel
{
ProductID = p.ProductID,
ProductName = p.ProductName,
CategoryName = p.Category.CategoryName,
CompanyName = p.Supplier.CompanyName,
Country = p.Supplier.Country
};
// ViewBag.count = t.Count();
ViewBag.page = page;
ViewBag.rowsPerPage = rowsPerPage;
ViewBag.sort = sort;
ViewBag.sortDir = sortDir;
var r2 = t.AsQueryable().OrderBy(sort + " " + sortDir).Skip((page - 1) * rowsPerPage).Take(rowsPerPage);
return View(r2.ToList());
}
示例2: WebGrid
public ActionResult WebGrid(int page = 1, int rowsPerPage = 10, string sort = "ProductId", string sortDir = "ASC")
{
string sortTable = "";
var nwd = new DataServiceContext(new Uri("http://services.odata.org/Northwind/Northwind.svc/"));
switch (sort)
{
case "CategoryName": sortTable = "Category/CategoryName"; break;
case "CompanyName": sortTable = "Supplier/CompanyName"; break;
case "Country": sortTable = "Supplier/Country"; break;
case "ProductID": sortTable = "ProductID"; break;
case "ProductName": sortTable = "ProductName"; break;
}
var Products2 =
(QueryOperationResponse<Product>)nwd.Execute<Product>(
new Uri("http://services.odata.org/Northwind/Northwind.svc/Products()?$inlinecount=allpages&$orderby=" + sortTable + " " + sortDir.ToLower() + ",ProductID&$skip=" + (page - 1) * rowsPerPage + "&$top=" + rowsPerPage + "&$expand=Category,Supplier&$select=ProductID,ProductName,Category/CategoryName,Supplier/CompanyName,Supplier/Country")); //Products2.Dump("Products2");
var products2List = Products2.ToList();
var m = Products2.TotalCount;
//m.Dump("m");
ViewBag.rows = (int)(Products2.TotalCount);
var t = from p in products2List
select new JointProductModel
{
ProductID = p.ProductID,
ProductName = p.ProductName,
CategoryName = p.Category.CategoryName,
CompanyName = p.Supplier.CompanyName,
Country = p.Supplier.Country
};
return View(t);
}
示例3: RunPositiveFunctionTest
private void RunPositiveFunctionTest(ODataFormat format, TestCase testCase)
{
// All of the functions tests use the PlaybackService since the WCF Data Services server doesn't support functions
// The PlaybackService itself will not automatically turn Metadata into an absolute URI, so set that to false on all tests.
// The tests also use absolute URIs for Target, so suppress that as well.
testCase.AddBaseUriToMetadata = false;
testCase.AddBaseUriToTarget = false;
using (TestWebRequest request = TestWebRequest.CreateForInProcessWcf())
using (PlaybackService.ProcessRequestOverride.Restore())
{
request.ServiceType = typeof(AstoriaUnitTests.Stubs.PlaybackService);
request.StartService();
var payloadBuilder = testCase.ResponsePayloadBuilder;
PlaybackService.ProcessRequestOverride.Value = (req) =>
{
string contentType;
if (format == ODataFormat.Json)
{
contentType = UnitTestsUtil.JsonLightMimeType;
payloadBuilder.Metadata = request.BaseUri + "/$metadata#TestService.CustomerEntities/$entity";
}
else
{
contentType = UnitTestsUtil.AtomFormat;
}
req.SetResponseStreamAsText(PayloadGenerator.Generate(payloadBuilder, format));
req.ResponseHeaders.Add("Content-Type", contentType);
req.SetResponseStatusCode(200);
return req;
};
testCase.AddBaseUriStringToExpectedDescriptors(request.ServiceRoot.OriginalString, format);
Uri uri = new Uri(request.ServiceRoot + "/" + testCase.RequestUriString);
DataServiceContext ctx = new DataServiceContext(request.ServiceRoot, ODataProtocolVersion.V4);
ctx.EnableAtom = true;
if (format == ODataFormat.Json)
{
string serviceEdmx = GetServiceEdmxWithOperations(payloadBuilder);
JsonLightTestUtil.ConfigureContextForJsonLight(ctx, serviceEdmx);
}
QueryOperationResponse<CustomerEntity> qor = (QueryOperationResponse<CustomerEntity>)ctx.Execute<CustomerEntity>(uri);
Assert.IsNotNull(qor);
Assert.IsNull(qor.Error);
IEnumerator<CustomerEntity> entities = qor.GetEnumerator();
int expectedDescriptorsPerEntity = 0;
while (entities.MoveNext())
{
CustomerEntity c = entities.Current;
EntityDescriptor ed = ctx.GetEntityDescriptor(c);
IEnumerable<OperationDescriptor> actualDescriptors = ed.OperationDescriptors;
TestEquality(actualDescriptors, testCase.GetExpectedDescriptors(format)[expectedDescriptorsPerEntity++]);
}
}
}
示例4: RunPositiveTest
private static void RunPositiveTest(ODataFormat format, TestCase testCase)
{
MyDSPActionProvider actionProvider = new MyDSPActionProvider();
DSPServiceDefinition service = new DSPServiceDefinition() {Metadata = Metadata, CreateDataSource = CreateDataSource, ActionProvider = actionProvider};
service.DataServiceBehavior.MaxProtocolVersion = ODataProtocolVersion.V4;
using (TestWebRequest request = service.CreateForInProcessWcf())
{
request.StartService();
DataServiceContext ctx = new DataServiceContext(request.ServiceRoot, ODataProtocolVersion.V4);
ctx.EnableAtom = true;
Uri uri = new Uri(request.ServiceRoot + "/" + testCase.RequestUriString);
MakeFinalChangesToTestCase(testCase, format, actionProvider, request);
if (format == ODataFormat.Json)
{
JsonLightTestUtil.ConfigureContextForJsonLight(ctx, null);
}
else
{
ctx.Format.UseAtom();
}
QueryOperationResponse<CustomerEntity> qor = (QueryOperationResponse<CustomerEntity>)ctx.Execute<CustomerEntity>(uri);
Assert.IsNotNull(qor);
Assert.IsNull(qor.Error);
IEnumerator<CustomerEntity> entities = qor.GetEnumerator();
int expectedDescriptorsPerEntity = 0;
while (entities.MoveNext())
{
CustomerEntity c = entities.Current;
EntityDescriptor ed = ctx.GetEntityDescriptor(c);
IEnumerable<OperationDescriptor> actualDescriptors = ed.OperationDescriptors;
TestEquality(actualDescriptors, testCase.GetExpectedDescriptors(format)[expectedDescriptorsPerEntity++]);
}
}
}
示例5: RunNegativeActionTestWithAtom
private static void RunNegativeActionTestWithAtom(TestCase testCase)
{
// These tests are specific to Atom and don't apply to JSON Light.
// Any JSON Light negative cases are covered by ODL reader tests. See ODL tests OperationReaderJsonLightTests and ODataJsonLightDeserializerTests.
using (TestWebRequest request = TestWebRequest.CreateForInProcessWcf())
using (PlaybackService.ProcessRequestOverride.Restore())
{
request.ServiceType = typeof(AstoriaUnitTests.Stubs.PlaybackService);
request.StartService();
PlaybackService.ProcessRequestOverride.Value = (req) =>
{
// These tests intentionally don't set the base URI of the context, so we need to also remove the xml:base attribute that is automatically
// generated by the PayloadGenerator. Otherwise another parsing error will occur before we hit the actual errors we are trying to validate.
string payload = PayloadGenerator.Generate(testCase.ResponsePayloadBuilder, ODataFormat.Atom);
string xmlBaseAttribute = @"xml:base=""/""";
payload = payload.Remove(payload.IndexOf(xmlBaseAttribute), xmlBaseAttribute.Length);
req.SetResponseStreamAsText(payload);
req.ResponseHeaders.Add("Content-Type", "application/atom+xml");
req.SetResponseStatusCode(200);
return req;
};
Uri uri = new Uri(request.ServiceRoot + "/" + testCase.RequestUriString);
DataServiceContext ctx = new DataServiceContext(null, ODataProtocolVersion.V4);
ctx.EnableAtom = true;
QueryOperationResponse<CustomerEntity> qor = (QueryOperationResponse<CustomerEntity>)ctx.Execute<CustomerEntity>(uri);
Assert.IsNotNull(qor);
Assert.IsNull(qor.Error);
IEnumerator<CustomerEntity> entities = qor.GetEnumerator();
Exception exception = AstoriaTest.TestUtil.RunCatching(delegate()
{
while (entities.MoveNext())
{
CustomerEntity c = entities.Current;
EntityDescriptor ed = ctx.GetEntityDescriptor(c);
IEnumerable<OperationDescriptor> actualDescriptors = ed.OperationDescriptors;
}
});
Assert.IsNotNull(exception);
Assert.AreEqual(testCase.ExpectedErrorMessage, exception.Message);
}
}
示例6: VerifyErrorString
private void VerifyErrorString(DataServiceContext context, string errorUrl, string errorString, params object[] arguments)
{
try
{
context.Execute<Computer>(new Uri(this.ServiceUri.OriginalString + errorUrl));
Assert.Fail("Expected Exception not thrown for " + errorUrl);
}
catch (DataServiceQueryException ex)
{
Assert.IsNotNull(ex.InnerException, "No inner exception found");
Assert.IsInstanceOfType(ex.InnerException, typeof(DataServiceClientException), "Unexpected inner exception type");
StringResourceUtil.VerifyDataServicesString(ClientExceptionUtil.ExtractServerErrorMessage(ex), errorString, arguments);
}
}
示例7: GetScore
public double GetScore(string url, string email, string apiKey, string textToAnalyze)
{
using (var wb = new WebClient())
{
var acitionUri = new Uri(url);
DataServiceContext ctx = new DataServiceContext(acitionUri);
var cred = new NetworkCredential(email, apiKey);
var cache = new CredentialCache();
cache.Add(acitionUri, "Basic", cred);
ctx.Credentials = cache;
var query = ctx.Execute<ScoreResult>(acitionUri, "POST", true, new BodyOperationParameter("Text", textToAnalyze));
ScoreResult scoreResult = query.ElementAt(0);
double result = scoreResult.result;
return result;
}
}
示例8: DisposeShouldBeCalledOnResponseMessageForExecuteWithNoContent
public void DisposeShouldBeCalledOnResponseMessageForExecuteWithNoContent()
{
DataServiceContext context = new DataServiceContext();
bool responseMessageDisposed = false;
context.Configurations.RequestPipeline.OnMessageCreating = args =>
{
var requestMessage = new InMemoryMessage { Url = args.RequestUri, Method = args.Method, Stream = new MemoryStream() };
var responseMessage = new InMemoryMessage { StatusCode = 204, Stream = new MemoryStream() };
responseMessage.DisposeAction = () => responseMessageDisposed = true;
return new TestDataServiceClientRequestMessage(requestMessage, () => responseMessage);
};
context.Execute(new Uri("http://host/voidAction", UriKind.Absolute), "POST").StatusCode.Should().Be(204);
responseMessageDisposed.Should().BeTrue();
}
示例9: GetAlertsFromAnomalyDetectionAPI
public AnomalyRecord[] GetAlertsFromAnomalyDetectionAPI(string timeSeriesData)
{
var acitionUri = new Uri(_detectorUrl);
var cred = new NetworkCredential(_liveId, _detectorAuthKey); // your Microsoft live Id here
var cache = new CredentialCache();
cache.Add(acitionUri, "Basic", cred);
DataServiceContext ctx = new DataServiceContext(acitionUri);
ctx.Credentials = cache;
var query = ctx.Execute<ADResult>(acitionUri, "POST", true,
new BodyOperationParameter("data", timeSeriesData),
new BodyOperationParameter("params", _spikeDetectorParams));
var resultTable = query.FirstOrDefault();
var results = resultTable.GetADResults();
var presults = results;
return filterAnomaly(presults);
}
示例10: FailureOnModifyEntity
public void FailureOnModifyEntity()
{
// Make sure that if the update fails, the state of the stream still remains modified and then next savechanges succeeds
TestUtil.RunCombinations(
(IEnumerable<SaveChangesMode>)Enum.GetValues(typeof(SaveChangesMode)),
(mode) =>
{
using (PlaybackService.OverridingPlayback.Restore())
using (PlaybackService.InspectRequestPayload.Restore())
{
DataServiceContext context = new DataServiceContext(request.ServiceRoot, ODataProtocolVersion.V4);
context.EnableAtom = true;
// Populate the context with an entity
string payload = AtomParserTests.AnyEntry(
id: Id,
editLink: request.ServiceRoot.AbsoluteUri + "/editLink/Customers(1)",
properties: Properties,
links: GetNamedStreamSelfLink(request.ServiceRoot + "/Customers(1)/SelfLink/Thumbnail", contentType: MediaContentType) +
GetNamedStreamEditLink(request.ServiceRoot.AbsoluteUri + "/Customers(1)/EditLink/Thumbnail", contentType: MediaContentType, etag: MediaETag));
PlaybackService.OverridingPlayback.Value = PlaybackService.ConvertToPlaybackServicePayload(null, payload);
Customer c = context.Execute<Customer>(new Uri("/Customers(1)", UriKind.Relative)).Single();
PlaybackService.OverridingPlayback.Value = PlaybackService.ConvertToPlaybackServicePayload(null, null, statusCode: System.Net.HttpStatusCode.BadRequest);
context.SetSaveStream(c, "Thumbnail", new MemoryStream(new byte[] { 0, 1, 2, 3 }), true, new DataServiceRequestArgs() { ContentType = "image/bmp" });
EntityDescriptor entityDescriptor = context.Entities.Single();
StreamDescriptor streamInfo = entityDescriptor.StreamDescriptors.Single();
try
{
DataServiceContextTestUtil.SaveChanges(context, SaveChangesOptions.None, mode);
Assert.Fail("SaveChanges should always fail");
}
catch (DataServiceRequestException ex)
{
Assert.AreEqual(1, ((IEnumerable<OperationResponse>)ex.Response).Count(), "we are expected 2 response for this SaveChanges operation");
Assert.IsTrue(ex.Response.Where<OperationResponse>(or => or.Error == null).SingleOrDefault() == null, "all responses should have errors");
Assert.AreEqual(streamInfo.State, EntityStates.Modified, "streamdescriptor should still be in modified state, so that next save changes can try this");
}
// Retrying will always fail, since the client closes the underlying stream.
}
});
}
示例11: SetSaveStreamAndUpdateEntity
public void SetSaveStreamAndUpdateEntity()
{
// Making sure that setting the save stream followed by updating an entity works well
TestUtil.RunCombinations((IEnumerable<SaveChangesMode>)Enum.GetValues(typeof(SaveChangesMode)), (mode) =>
{
using (PlaybackService.OverridingPlayback.Restore())
using (PlaybackService.InspectRequestPayload.Restore())
{
DataServiceContext context = new DataServiceContext(request.ServiceRoot, ODataProtocolVersion.V4);
context.EnableAtom = true;
context.Format.UseAtom();
string payload = AtomParserTests.AnyEntry(
id: Id,
editLink: request.ServiceRoot.AbsoluteUri + "/editLink/Customers(1)",
properties: Properties,
links: GetNamedStreamSelfLink(request.ServiceRoot + "/Customers(1)/SelfLink/Thumbnail", contentType: MediaContentType) +
GetNamedStreamEditLink(request.ServiceRoot.AbsoluteUri + "/Customers(1)/EditLink/Thumbnail", MediaContentType));
PlaybackService.OverridingPlayback.Value = PlaybackService.ConvertToPlaybackServicePayload(null, payload);
Customer c = context.Execute<Customer>(new Uri("/Customers(1)", UriKind.Relative)).Single();
PlaybackService.OverridingPlayback.Value = PlaybackService.ConvertToPlaybackServicePayload(null, null);
context.SetSaveStream(c, "Thumbnail", new MemoryStream(), true, new DataServiceRequestArgs() { ContentType = "image/bmp" });
context.UpdateObject(c);
int i = 0;
PlaybackService.InspectRequestPayload.Value = (message) =>
{
if (i == 1)
{
// Verify that the second request was a PUT request
Assert.IsTrue(PlaybackService.LastPlayback.Contains(String.Format("PUT {0}/Customers(1)/EditLink/Thumbnail", request.ServiceRoot)), "the second request must be a PUT request to named stream");
Assert.IsTrue(!PlaybackService.LastPlayback.Contains(String.Format("If-Match", "no if-match header must be sent if the named stream does not have etag")));
// Verify the payload of the first request - it must have an entry element.
XDocument document = XDocument.Load(message);
Assert.IsTrue(document.Element(AstoriaUnitTests.Tests.UnitTestsUtil.AtomNamespace + "entry") != null, "must contain an entry element");
}
i++;
};
DataServiceContextTestUtil.SaveChanges(context, SaveChangesOptions.ContinueOnError, mode);
Assert.AreEqual(i, 2, "Only 2 request should have been made");
// Verify the first request was a PUT request to the entity
Assert.IsTrue(PlaybackService.LastPlayback.Contains(String.Format("PATCH {0}/editLink/Customers(1)", request.ServiceRoot)), "the first request must be a PUT request to the entity");
}
});
}
示例12: UpdateEntityAndSetSaveStream
public void UpdateEntityAndSetSaveStream()
{
// Making sure that updating an entity followed by SetSaveStream works well
TestUtil.RunCombinations(
UnitTestsUtil.BooleanValues,
(IEnumerable<SaveChangesMode>)Enum.GetValues(typeof(SaveChangesMode)),
UnitTestsUtil.BooleanValues,
(sendResponse, mode, closeStream) =>
{
using (PlaybackService.OverridingPlayback.Restore())
using (PlaybackService.InspectRequestPayload.Restore())
{
DataServiceContext context = new DataServiceContext(request.ServiceRoot, ODataProtocolVersion.V4);
context.EnableAtom = true;
context.Format.UseAtom();
string payload = AtomParserTests.AnyEntry(
id: Id,
editLink: request.ServiceRoot.AbsoluteUri + "/editLink/Customers(1)",
serverTypeName: typeof(Customer).FullName,
properties: Properties,
links: GetNamedStreamSelfLink(request.ServiceRoot + "/Customers(1)/SelfLink/Thumbnail", contentType: MediaContentType) +
GetNamedStreamEditLink(request.ServiceRoot.AbsoluteUri + "/Customers(1)/EditLink/Thumbnail", contentType: MediaContentType, etag: MediaETag));
PlaybackService.OverridingPlayback.Value = PlaybackService.ConvertToPlaybackServicePayload(null, payload);
context.ResolveType = name => typeof(Customer);
Customer c = (Customer)context.Execute<object>(new Uri("/Customers(1)", UriKind.Relative)).Single();
context.UpdateObject(c);
MemoryStream thumbnailStream = new MemoryStream();
context.SetSaveStream(c, "Thumbnail", thumbnailStream, closeStream, new DataServiceRequestArgs() { ContentType = "image/bmp" });
string namedStreamETagInEntityResponse = null;
string namedStreamETagInResponseHeader = "ETagInResponseHeader";
int i = 0;
PlaybackService.InspectRequestPayload.Value = (message) =>
{
if (i == 1)
{
// Verify the first request was a PUT request to the entity
Assert.IsTrue(PlaybackService.LastPlayback.Contains(String.Format("PATCH {0}/editLink/Customers(1)", request.ServiceRoot)), "the first request must be a PUT request to the entity");
var headers = new KeyValuePair<string, string>[] { new KeyValuePair<string, string>("ETag", namedStreamETagInResponseHeader) };
PlaybackService.OverridingPlayback.Value = PlaybackService.ConvertToPlaybackServicePayload(headers, null);
}
else if (i == 0)
{
string updatePayload = null;
if (sendResponse)
{
namedStreamETagInEntityResponse = "ETagInResponsePayload";
updatePayload = AtomParserTests.AnyEntry(
id: Id,
editLink: request.ServiceRoot.AbsoluteUri + "/editLink/Customers(1)",
properties: Properties,
links: GetNamedStreamSelfLink(request.ServiceRoot + "/Customers(1)/SelfLink/Thumbnail", contentType: MediaContentType) +
GetNamedStreamEditLink(request.ServiceRoot.AbsoluteUri + "/Customers(1)/EditLink/Thumbnail", contentType: MediaContentType, etag: namedStreamETagInEntityResponse));
}
PlaybackService.OverridingPlayback.Value = PlaybackService.ConvertToPlaybackServicePayload(null, updatePayload);
// Verify the payload of the first request - it must have an entry element.
XDocument document = XDocument.Load(message);
Assert.IsTrue(document.Element(AstoriaUnitTests.Tests.UnitTestsUtil.AtomNamespace + "entry") != null, "must contain an entry element");
}
i++;
Assert.IsTrue(thumbnailStream.CanWrite, "The thumbnail stream hasn't been closed yet");
};
DataServiceContextTestUtil.SaveChanges(context, SaveChangesOptions.None, mode);
Assert.AreEqual(i, 2, "Only 2 request should have been made");
// Verify that the second request was a PUT request
Assert.IsTrue(PlaybackService.LastPlayback.Contains(String.Format("PUT {0}/Customers(1)/EditLink/Thumbnail", request.ServiceRoot)), "the second request must be a PUT request to named stream");
// If the first update sent a response, then the new etag must be used
Assert.IsTrue(PlaybackService.LastPlayback.Contains(String.Format("If-Match: {0}", namedStreamETagInEntityResponse ?? MediaETag)), "etag must be sent in the PUT request to the named stream");
Assert.AreEqual(!thumbnailStream.CanWrite, closeStream, "The thumbnail stream must be desired state after SaveChanges returns");
StreamDescriptor sd = context.Entities[0].StreamDescriptors[0];
// Verify that the etag from the response overrides the etag from the header when the response is present
Assert.AreEqual(sd.StreamLink.ETag, namedStreamETagInResponseHeader, "make sure the etag was updated to the latest etag");
}
});
}
示例13: NamedStreams_NestedQuery_2
public void NamedStreams_NestedQuery_2()
{
// projecting out collection of collection properties - both narrow type and anonymous type
{
// Querying url of the nested type - doing this makes the entity non-tracking, but populated the link property
DataServiceContext context = new DataServiceContext(request.ServiceRoot, ODataProtocolVersion.V4);
context.EnableAtom = true;
context.Format.UseAtom();
DataServiceQuery<EntityWithNamedStreams1> q = (DataServiceQuery<EntityWithNamedStreams1>)from s in context.CreateQuery<EntityWithNamedStreams1>("MySet1")
select new EntityWithNamedStreams1
{
ID = s.ID,
Stream1 = s.Stream1,
Collection = (from c in s.Collection
select new EntityWithNamedStreams2()
{
ID = c.ID,
ColStream = c.ColStream,
Collection1 = (from c1 in c.Collection1
select new EntityWithNamedStreams1()
{
ID = c1.ID,
RefStream1 = c1.RefStream1
}).ToList()
}).ToList()
};
Assert.AreEqual(request.ServiceRoot.AbsoluteUri + "/MySet1?$expand=Collection($select=ID),Collection($select=ColStream),Collection($expand=Collection1($select=ID)),Collection($expand=Collection1($select=RefStream1))&$select=ID,Stream1", q.ToString(), "make sure the right uri is produced by the linq translator");
var response = (QueryOperationResponse<EntityWithNamedStreams1>)q.Execute();
DataServiceQueryContinuation<EntityWithNamedStreams2> continuation = null;
foreach (var o in response)
{
Assert.IsNotNull(o.Stream1.EditLink, "Stream1 should not be null");
Assert.AreEqual(o.Stream1.EditLink, context.GetReadStreamUri(o, "Stream1"), "the stream url for Stream1 must be populated correctly");
foreach (var c in o.Collection)
{
Assert.IsNotNull(c.ColStream.EditLink, "ColStream should not be null");
Assert.AreEqual(c.ColStream.EditLink, context.GetReadStreamUri(c, "ColStream"), "the url for the nested collection entity should match - Level 0");
foreach (var c1 in c.Collection1)
{
Assert.IsNotNull(c1.RefStream1.EditLink, "RefStream1 should not be null");
Assert.AreEqual(c1.RefStream1.EditLink, context.GetReadStreamUri(c1, "RefStream1"), "the url for the nested collection entity should match - Level 1");
}
}
// Make sure you get the continuation token for the collection and try and get the next page
continuation = response.GetContinuation(o.Collection);
}
Assert.AreEqual(context.Entities.Count, 3, "there should be 3 entities tracked by the context");
Assert.AreEqual(context.Entities[0].EditLink.AbsoluteUri, request.ServiceRoot.AbsoluteUri + "/MySet1(1)", "top level entity must be tracked");
Assert.AreEqual(context.Entities[1].EditLink.AbsoluteUri, request.ServiceRoot.AbsoluteUri + "/MySet3('ABCDE')", "top level entity must be tracked");
Assert.AreEqual(context.Entities[2].EditLink.AbsoluteUri, request.ServiceRoot.AbsoluteUri + "/MySet2(3)", "the nested entity must be tracked");
Assert.IsNotNull(continuation, "since SDP is turned on, we should get the continuation token");
// Get the next page and make sure we get the right entity and the link is populated.
foreach (var entity in context.Execute(continuation))
{
Assert.IsNotNull(entity.ColStream.EditLink, "ColStream should not be null");
Assert.AreEqual(entity.ColStream.EditLink, context.GetReadStreamUri(entity, "ColStream"), "the url for the nested collection entity should match - Level 1");
foreach (var c1 in entity.Collection1)
{
Assert.IsNotNull(c1.RefStream1.EditLink, "RefStream1 should not be null");
Assert.AreEqual(c1.RefStream1.EditLink, context.GetReadStreamUri(c1, "RefStream1"), "the url for the nested collection entity should match - Level 1");
}
}
Assert.AreEqual(context.Entities.Count, 4, "there should be 4 entities tracked by the context");
}
{
// Querying url of the nested type - doing this makes the entity non-tracking, but populated the link property
DataServiceContext context = new DataServiceContext(request.ServiceRoot, ODataProtocolVersion.V4);
context.EnableAtom = true;
context.Format.UseAtom();
var q = from s in context.CreateQuery<EntityWithNamedStreams1>("MySet1")
select new
{
ID = s.ID,
Stream1Url = s.Stream1,
Collection = (from c in s.Collection
select new
{
Name = c.Name,
Stream1Url = c.ColStream,
Collection1 = (from c1 in c.Collection1
select new
{
ID = c1.ID,
Stream1Url = c1.RefStream1
})
})
};
Assert.AreEqual(request.ServiceRoot.AbsoluteUri + "/MySet1?$expand=Collection($select=Name),Collection($select=ColStream),Collection($expand=Collection1($select=ID)),Collection($expand=Collection1($select=RefStream1))&$select=ID,Stream1", q.ToString(), "make sure the right uri is produced by the linq translator");
foreach (var o in q)
{
Assert.AreEqual(o.Stream1Url.EditLink, request.ServiceRoot.AbsoluteUri + "/MySet1(1)/Stream1", "the stream url for Stream1 must be populated correctly");
//.........这里部分代码省略.........
示例14: Collection_QueryInterceptors
public void Collection_QueryInterceptors()
{
var metadata = CreateMetadataForXFeatureEntity();
InterceptorServiceDefinition service = new InterceptorServiceDefinition()
{
Metadata = metadata,
CreateDataSource = (m) => new DSPContext(),
Writable = true
};
using (TestWebRequest request = service.CreateForInProcessWcf())
{
request.StartService();
DataServiceContext ctx = new DataServiceContext(request.ServiceRoot, ODataProtocolVersion.V4);
ctx.EnableAtom = true;
ctx.Format.UseAtom();
PopulateClientContextWithTestEntities(ctx);
ctx.IgnoreResourceNotFoundException = true;
// Client test cases
QueryInterceptors_VerifyClientEntity(1, ctx.Execute<XFeatureTestsEntity>(new Uri("/Entities", UriKind.Relative)).AsEnumerable().First(), service);
QueryInterceptors_VerifyClientEntity(1, ctx.CreateQuery<XFeatureTestsEntity>("Entities").AsEnumerable().First(), service);
QueryInterceptors_VerifyClientEntity(1, ctx.CreateQuery<XFeatureTestsEntity>("Entities").OrderBy(e => e.ID).AsEnumerable().First(), service);
QueryInterceptors_VerifyClientEntity(1, ctx.CreateQuery<XFeatureTestsEntity>("Entities").Where(e => e.ID == 1).First(), service);
QueryInterceptors_VerifyClientEntity(null, ctx.CreateQuery<XFeatureTestsEntity>("Entities").Where(e => e.ID == 2).FirstOrDefault(), service);
// .Where(e => e.ID < 3) means "consider just first two entities". In this case we skip the first entity and the second is not there so null is expected
QueryInterceptors_VerifyClientEntity(null, ctx.CreateQuery<XFeatureTestsEntity>("Entities").Where(e => e.ID < 3).Skip(1).FirstOrDefault(), service);
QueryInterceptors_VerifyClientEntity(1, ctx.CreateQuery<XFeatureTestsEntity>("Entities").Select(e =>
new XFeatureTestsEntity { Strings = e.Strings }).AsEnumerable().First(), service);
QueryInterceptors_VerifyClientEntity(1, ctx.CreateQuery<XFeatureTestsEntity>("Entities").Select(e =>
new XFeatureTestsEntity { Structs = e.Structs }).AsEnumerable().First(), service);
QueryInterceptors_VerifyClientEntity(1, ctx.CreateQuery<XFeatureTestsEntity>("Entities").Select(e =>
new XFeatureTestsEntity { ID = e.ID }).AsEnumerable().First(), service);
// Server test cases (queries like this can't be executed through client API)
QueryInterceptors_VerifyServerRequest(200, "/Entities(1)/Strings", request, service);
QueryInterceptors_VerifyServerRequest(404, "/Entities(2)/Strings", request, service);
QueryInterceptors_VerifyServerRequest(200, "/Entities(1)/Structs", request, service);
QueryInterceptors_VerifyServerRequest(404, "/Entities(2)/Structs", request, service);
}
}
示例15: ActionWithLargeParameterPayloadTests
public void ActionWithLargeParameterPayloadTests()
{
// Test action with large number of parameters.
var testCases = new []
{
new
{
RequestUri = "/Customers(1)/AstoriaUnitTests.ActionTestsWithLargePayload.ActionWithLargeParameterPayload",
ExpectedResults = new object[] { },
StatusCode = 204,
ExpectedReturnType = typeof(void),
OperationParameters = this.GetParametersWithLargePayload(),
},
new
{
RequestUri = "/Customers(1)/AstoriaUnitTests.ActionTestsWithLargePayload.ActionWithLargeCollectionParameterPayload",
ExpectedResults = new object[] { },
StatusCode = 204,
ExpectedReturnType = typeof(void),
OperationParameters = this.GetCollectionParameterWithLargePayload(),
},
};
using (TestWebRequest request = service.CreateForInProcessWcf())
{
request.StartService();
t.TestUtil.RunCombinations(testCases, (testCase) =>
{
DataServiceContext ctx = new DataServiceContext(request.ServiceRoot, ODataProtocolVersion.V4);
Uri uri = new Uri(request.ServiceRoot + testCase.RequestUri);
OperationResponse operationResponse = ctx.Execute(uri, "POST", testCase.OperationParameters);
Assert.IsNotNull(operationResponse);
Assert.AreEqual(testCase.StatusCode, operationResponse.StatusCode);
Assert.IsNull(operationResponse.Error);
});
}
}