本文整理汇总了C#中DataServiceContext.AddObject方法的典型用法代码示例。如果您正苦于以下问题:C# DataServiceContext.AddObject方法的具体用法?C# DataServiceContext.AddObject怎么用?C# DataServiceContext.AddObject使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类DataServiceContext
的用法示例。
在下文中一共展示了DataServiceContext.AddObject方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: InnerSubmit
private void InnerSubmit(DataServiceContext dataContext)
{
if (!string.IsNullOrWhiteSpace(this.TemplateId))
{
dataContext.AddObject(JobBaseCollection.JobSet, this);
foreach (IAsset asset in this.InputMediaAssets)
{
AssetData target = asset as AssetData;
if (target == null)
{
throw new ArgumentException(StringTable.ErrorInputTypeNotSupported);
}
dataContext.AttachTo(AssetCollection.AssetSet, asset);
dataContext.AddLink(this, InputMediaAssetsPropertyName, target);
}
}
else
{
X509Certificate2 certToUse = null;
Verify(this);
dataContext.AddObject(JobBaseCollection.JobSet, this);
List<AssetData> inputAssets = new List<AssetData>();
AssetNamingSchemeResolver<AssetData, OutputAsset> assetNamingSchemeResolver = new AssetNamingSchemeResolver<AssetData, OutputAsset>(inputAssets);
foreach (ITask task in ((IJob)this).Tasks)
{
Verify(task);
TaskData taskData = (TaskData)task;
if (task.Options.HasFlag(TaskOptions.ProtectedConfiguration))
{
ProtectTaskConfiguration(taskData, ref certToUse, dataContext);
}
taskData.TaskBody = CreateTaskBody(assetNamingSchemeResolver, task.InputAssets.ToArray(), task.OutputAssets.ToArray());
taskData.InputMediaAssets.AddRange(task.InputAssets.OfType<AssetData>().ToArray());
taskData.OutputMediaAssets.AddRange(
task.OutputAssets
.OfType<OutputAsset>()
.Select(
c =>
{
AssetData assetData = new AssetData { Name = c.Name, Options = (int)c.Options, AlternateId = c.AlternateId };
assetData.InitCloudMediaContext(this._cloudMediaContext);
return assetData;
})
.ToArray());
dataContext.AddRelatedObject(this, TasksPropertyName, taskData);
}
foreach (IAsset asset in inputAssets)
{
dataContext.AttachTo(AssetCollection.AssetSet, asset);
dataContext.AddLink(this, InputMediaAssetsPropertyName, asset);
}
}
}
示例2: EdmValidNamesNotAllowedInUri
public void EdmValidNamesNotAllowedInUri()
{
DSPMetadata metadata = new DSPMetadata("Test", "TestNS");
var entityType = metadata.AddEntityType("MyType", null, null, false);
metadata.AddKeyProperty(entityType, "ID", typeof(int));
metadata.AddPrimitiveProperty(entityType, "Pròjè_x00A2_tÎð瑞갂థ్క_x0020_Iiلإَّ", typeof(string));
var resourceSet = metadata.AddResourceSet("EntitySet", entityType);
metadata.SetReadOnly();
DSPServiceDefinition service = new DSPServiceDefinition()
{
Metadata = metadata,
Writable = true
};
DSPContext data = new DSPContext();
service.CreateDataSource = (m) => { return data; };
using (TestWebRequest request = service.CreateForInProcessWcf())
{
request.StartService();
DataServiceContext context = new DataServiceContext(request.ServiceRoot);
context.EnableAtom = true;
context.Format.UseAtom();
string value = "value of Pròjè_x00A2_tÎð瑞갂థ్క_x0020_Iiلإَّ";
context.AddObject("EntitySet", new MyType() {
ID = 1,
Pròjè_x00A2_tÎð瑞갂థ్క_x0020_Iiلإَّ = value,
});
context.SaveChanges();
var result = context.Execute<MyType>(new Uri("EntitySet?$orderby=Pròjè_x00A2_tÎð瑞갂థ్క_x0020_Iiلإَّ", UriKind.Relative)).First();
Assert.AreEqual(value, result.Pròjè_x00A2_tÎð瑞갂థ్క_x0020_Iiلإَّ, "The roundtrip value not as expected");
}
}
示例3: ProtectTaskConfiguration
private static void ProtectTaskConfiguration(TaskTemplateData taskTemplate, ref X509Certificate2 certToUse, DataServiceContext dataContext)
{
using (ConfigurationEncryption configEncryption = new ConfigurationEncryption())
{
// Update the task template with the required data.
taskTemplate.Configuration = configEncryption.Encrypt(taskTemplate.Configuration);
taskTemplate.EncryptionKeyId = configEncryption.GetKeyIdentifierAsString();
taskTemplate.EncryptionScheme = ConfigurationEncryption.SchemeName;
taskTemplate.EncryptionVersion = ConfigurationEncryption.SchemeVersion;
taskTemplate.InitializationVector = configEncryption.GetInitializationVectorAsString();
if (certToUse == null)
{
// Get the certificate to use to encrypt the configuration encryption key.
certToUse = ContentKeyBaseCollection.GetCertificateToEncryptContentKey(dataContext, ContentKeyType.ConfigurationEncryption);
}
// Create a content key object to hold the encryption key.
ContentKeyData contentKeyData = ContentKeyBaseCollection.CreateConfigurationContentKey(configEncryption, certToUse);
dataContext.AddObject(ContentKeyCollection.ContentKeySet, contentKeyData);
}
}
示例4: EFFK_1To1_BasicInsertAndBind_Batch_ChangedUriCompositionRulesOnServer
public void EFFK_1To1_BasicInsertAndBind_Batch_ChangedUriCompositionRulesOnServer()
{
// Fix URI composition in Astoria for V3 payloads
ctx = new DataServiceContext(web.ServiceRoot, Microsoft.OData.Client.ODataProtocolVersion.V4);
ctx.EnableAtom = true;
ctx.Format.UseAtom();
// Create new office type
EFFKClient.Office o = new EFFKClient.Office() { ID = 1, BuildingName = "Building 35", FloorNumber = 2, OfficeNumber = 2173 };
ctx.AddObject("CustomObjectContext.Offices", o);
// create new employee type
EFFKClient.Worker e = new EFFKClient.Worker() { ID = 1, FirstName = "Pratik", LastName = "Patel" };
ctx.AddObject("CustomObjectContext.Workers", e);
// Establish relationship between employee and office
ctx.SetLink(o, "Worker", e);
ctx.SetLink(e, "Office", o);
ctx.SaveChanges(SaveChangesOptions.BatchWithSingleChangeset);
// clean the context
ctx.DeleteObject(e);
ctx.DeleteObject(o);
ctx.SaveChanges(SaveChangesOptions.BatchWithSingleChangeset);
}
示例5: ClientSerializeGeographyTest_AddDataPresentAndNamespaceNotDuplicated
public void ClientSerializeGeographyTest_AddDataPresentAndNamespaceNotDuplicated()
{
DataServiceContext ctx = new DataServiceContext(new Uri("http://localhost"));
ctx.AddObject("Entities", testEntity);
ClientSerializeGeographyTest_Validate(ctx);
}
示例6: EnsureInsert
public static void EnsureInsert(DataServiceContext context, object entity, string entitySetName, Workspace workspace, string skipEntitySet)
{
#if !ClientSKUFramework
IEdmEntityType entityType = null;
if (DataServiceMetadata.ServiceMetadata == null)
{
DataServiceMetadata.LoadServiceMetadata(workspace.ServiceUri);
}
if (DataServiceMetadata.EntityTypes.Any(eType => eType.Name == entitySetName))
{
entityType = DataServiceMetadata.EntityTypes.First(eType => eType.Name == entitySetName);
}
if (entityType == null && DataServiceMetadata.EntityTypes.Any(eType => eType.Name == entity.GetType().Name))
{
entityType = DataServiceMetadata.EntityTypes.First(eType => eType.Name == entity.GetType().Name);
entitySetName = entity.GetType().Name;
}
if (entityType == null) return;
foreach (IEdmNavigationProperty navProperty in entityType.NavigationProperties())
{
if (context.Links.All(ld => (ld.SourceProperty != navProperty.Name)))
{
if (navProperty.TargetMultiplicity() == EdmMultiplicity.One && navProperty.Name != skipEntitySet)
{
IEdmEntityType navProperyEntityType = DataServiceMetadata.GetEntityType(navProperty);
ResourceType resourceType = workspace.ServiceContainer.ResourceTypes.First(rt => rt.Name == navProperyEntityType.Name);
object instance = resourceType.CreateInstance(false);
context.AddObject(navProperyEntityType.Name == "College" ? "Colleges" : navProperyEntityType.Name, instance);
context.SetLink(entity, navProperty.Name, instance);
}
}
}
#endif
}
示例7: RequestHeadersAndStreamTest
public void RequestHeadersAndStreamTest()
{
// SaveChanges with multiple changes, using a variety of configurations (including sync, async, batch) and verify the request headers and payloads
using (PlaybackService.InspectRequestPayload.Restore())
using (PlaybackService.OverridingPlayback.Restore())
using (TestWebRequest request = TestWebRequest.CreateForInProcessWcf())
{
request.ServiceType = typeof(PlaybackService);
request.StartService();
Customer newCustomer1 = new Customer();
newCustomer1.Address = new Address();
newCustomer1.Address.City = "CustCity1";
newCustomer1.GuidValue = new Guid();
newCustomer1.Name = "CustName1";
Customer newCustomer2 = new Customer();
newCustomer2.ID = 2;
newCustomer2.Address = new Address();
newCustomer2.Address.City = "CustCity2";
newCustomer2.GuidValue = new Guid();
newCustomer2.Name = "CustName2";
Dictionary<string, string> responseHeaders1 = new Dictionary<string, string>();
responseHeaders1.Add("Content-ID", newCustomer1.ID.ToString());
responseHeaders1.Add("Location", String.Format("{0}/Customers({1})", request.BaseUri, newCustomer1.ID));
Dictionary<string, string> responseHeaders2 = new Dictionary<string, string>();
responseHeaders2.Add("Content-ID", newCustomer2.ID.ToString());
responseHeaders2.Add("Location", String.Format("{0}/Customers({1})", request.BaseUri, newCustomer2.ID));
string[] nonBatchHttpResponses = new string[]
{
PlaybackService.ConvertToPlaybackServicePayload(responseHeaders1, null, HttpStatusCode.Created),
PlaybackService.ConvertToPlaybackServicePayload(responseHeaders2, null, HttpStatusCode.Created)
};
string batchPayload;
string batchHttpResponse = PlaybackService.ConvertToBatchResponsePayload(nonBatchHttpResponses, false, out batchPayload);
var saveChangesModes = (IEnumerable<SaveChangesMode>)Enum.GetValues(typeof(SaveChangesMode));
var saveChangesOptions = new SaveChangesOptions[] { SaveChangesOptions.None, SaveChangesOptions.BatchWithSingleChangeset };
Dictionary<string, string> expectedRequestHeadersBatch = new Dictionary<string, string>();
expectedRequestHeadersBatch.Add("Content-Type", "multipart/mixed; boundary=batch_");
expectedRequestHeadersBatch.Add("Accept", "multipart/mixed");
AddCommonRequestHeaders(expectedRequestHeadersBatch);
expectedRequestHeadersBatch.Add("__Uri", String.Format("{0}/$batch", request.BaseUri));
Dictionary<string, string> expectedRequestHeadersNonBatch = new Dictionary<string, string>();
expectedRequestHeadersNonBatch.Add("Content-Type", "application/atom+xml");
expectedRequestHeadersNonBatch.Add("Accept", "application/atom+xml,application/xml");
AddCommonRequestHeaders(expectedRequestHeadersNonBatch);
expectedRequestHeadersNonBatch.Add("__Uri", String.Format("{0}/Customers", request.BaseUri));
TestUtil.RunCombinations(saveChangesModes, saveChangesOptions, (saveChangesMode, saveChangesOption) =>
{
DataServiceContext context = new DataServiceContext(new Uri(request.BaseUri));
context.EnableAtom = true;
context.Format.UseAtom();
HttpTestHookConsumer testHookConsumer = new HttpTestHookConsumer(context, false);
bool isBatch = saveChangesOption == SaveChangesOptions.BatchWithSingleChangeset;
int actualRequestCount = 0;
PlaybackService.InspectRequestPayload.Value = (requestStream) =>
{
// Verify request headers
Assert.AreEqual(1, testHookConsumer.RequestHeaders.Count, "Wrong number of request headers tracked by the test hook");
Dictionary<string, string> actualRequestHeaders = testHookConsumer.RequestHeaders[0];
Dictionary<string, string> expectedRequestHeaders = isBatch ? expectedRequestHeadersBatch : expectedRequestHeadersNonBatch;
VerifyHeaders(expectedRequestHeaders, actualRequestHeaders);
testHookConsumer.RequestHeaders.Clear();
// Verify request stream
Assert.AreEqual(1, testHookConsumer.RequestWrappingStreams.Count, "Wrong number of request streams tracked by the test hook");
string actualString = testHookConsumer.RequestWrappingStreams[0].GetLoggingStreamAsString();
StreamReader reader = new StreamReader(requestStream);
string expectedString = reader.ReadToEnd();
Assert.AreEqual(expectedString, actualString, "Request stream does not contain the expected value in the test hook.");
testHookConsumer.RequestWrappingStreams.Clear();
// Set the response payload here because a single SaveChanges call can produce multiple requests that
// require different responses, when not using batching.
string httpResponse = isBatch ? batchHttpResponse : nonBatchHttpResponses[actualRequestCount];
PlaybackService.OverridingPlayback.Value = httpResponse;
actualRequestCount++;
};
// Add multiple objects to ensure that multiple streams in a single API call will still get passed to the test hook
context.AddObject("Customers", newCustomer1);
context.AddObject("Customers", newCustomer2);
// Verify no requests have been made yet
Assert.AreEqual(0, actualRequestCount, "No HTTP requests should have been made yet.");
DataServiceContextTestUtil.SaveChanges(context, saveChangesOption, saveChangesMode);
// Verify that the expected number of requests were made during SaveChanges
int expectedRequestCount = isBatch ? 1 : 2;
Assert.AreEqual(expectedRequestCount, actualRequestCount, "Wrong number of HTTP requests made during SaveChanges.");
//.........这里部分代码省略.........
示例8: FailureOnInsertEntity
public void FailureOnInsertEntity()
{
// Make sure if the POST fails, then also named stream request also fails, since we don't have the edit link for the named stream
TestUtil.RunCombinations(
(IEnumerable<SaveChangesMode>)Enum.GetValues(typeof(SaveChangesMode)), UnitTestsUtil.BooleanValues,
(mode, continueOnError) =>
{
using (PlaybackService.OverridingPlayback.Restore())
using (PlaybackService.InspectRequestPayload.Restore())
{
DataServiceContext context = new DataServiceContext(request.ServiceRoot, ODataProtocolVersion.V4);
PlaybackService.OverridingPlayback.Value = null;
Customer c = new Customer() { ID = 1, Name = "Foo" };
context.AddObject("Customers", c);
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();
int i = 0;
PlaybackService.InspectRequestPayload.Value = (message) =>
{
if (i == 1)
{
// Verify the first request was a POST request
Assert.IsTrue(PlaybackService.LastPlayback.Contains(String.Format("POST {0}/Customers", request.ServiceRoot)), "the first request must be a POST request");
}
i++;
};
try
{
DataServiceContextTestUtil.SaveChanges(context, continueOnError ? SaveChangesOptions.ContinueOnError : SaveChangesOptions.None, mode);
Assert.Fail("SaveChanges should always fail");
}
catch (DataServiceRequestException ex)
{
// here the server throws instream error (bad xml), so we'll always continue on error, even if it's not set..
Assert.AreEqual(2, ((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");
Assert.AreEqual(entityDescriptor.State, EntityStates.Added, "entityDescriptor is in the added state");
}
Assert.AreEqual(i, 1, "the number of requests sent to the server will only be 1, since the named stream request fails on the client side");
// Retrying again will always fail, since we have closed the stream.
}
});
}
示例9: ApplyToObject
/// <summary>
/// Applies this state to the specfied <paramref name="target"/> such that after invocation,
/// the target in the given <paramref name="context"/> is in this state.
/// </summary>
/// <param name="context">Context to apply changes to.</param>
/// <param name="target">Target to change state on.</param>
/// <param name="entitySetName">Name of entity set (necessary for certain transitions).</param>
public void ApplyToObject(DataServiceContext context, object target, string entitySetName)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
if (target == null)
{
throw new ArgumentNullException("target");
}
EntityStates current = GetStateForEntity(context, target);
if (current == this.state)
{
return;
}
switch (this.state)
{
case EntityStates.Added:
if (current != EntityStates.Detached)
{
context.Detach(target);
}
context.AddObject(entitySetName, target);
break;
case EntityStates.Detached:
context.Detach(target);
break;
case EntityStates.Deleted:
if (current == EntityStates.Detached)
{
context.AttachTo(entitySetName, target);
}
context.DeleteObject(target);
break;
case EntityStates.Modified:
if (current == EntityStates.Detached)
{
context.AttachTo(entitySetName, target);
}
context.UpdateObject(target);
break;
case EntityStates.Unchanged:
if (current != EntityStates.Detached)
{
context.Detach(target);
}
context.AttachTo(entitySetName, target);
break;
}
}
示例10: CreateStorageContentKey
private static ContentKeyData CreateStorageContentKey(AssetData tempAsset, NullableFileEncryption fileEncryption, DataServiceContext dataContext)
{
// Create the content key.
fileEncryption.Init();
// Encrypt it for delivery to Nimbus.
X509Certificate2 certToUse = ContentKeyCollection.GetCertificateToEncryptContentKey(dataContext, ContentKeyType.StorageEncryption);
ContentKeyData contentKeyData = ContentKeyBaseCollection.CreateStorageContentKey(fileEncryption.FileEncryption, certToUse);
dataContext.AddObject(ContentKeyCollection.ContentKeySet, contentKeyData);
dataContext.SaveChanges();
// Associate it with the asset.
((IAsset) tempAsset).ContentKeys.Add(contentKeyData);
return contentKeyData;
}
示例11: InsertMLEAndSetSaveStream
public void InsertMLEAndSetSaveStream()
{
// Making sure that inserting an MLE/MR followed by SetSaveStream works well
TestUtil.RunCombinations(
(IEnumerable<SaveChangesMode>)Enum.GetValues(typeof(SaveChangesMode)),
UnitTestsUtil.BooleanValues,
(mode, closeStream) =>
{
using (PlaybackService.OverridingPlayback.Restore())
using (PlaybackService.InspectRequestPayload.Restore())
{
DataServiceContext context = new DataServiceContext(request.ServiceRoot, ODataProtocolVersion.V4);
context.EnableAtom = true;
context.Format.UseAtom();
ClientCSharpRegressionTests.CustomerWithStream c = new ClientCSharpRegressionTests.CustomerWithStream() { ID = 1, Name = "Foo" };
context.AddObject("Customers", c);
MemoryStream defaultStream = new MemoryStream(new byte[] { 0, 1, 2, 3 });
MemoryStream thumbnailStream = new MemoryStream(new byte[] { 0, 1, 2, 3, 4 });
context.SetSaveStream(c, defaultStream, closeStream, new DataServiceRequestArgs() { ContentType = "image/bmp" });
context.SetSaveStream(c, "Thumbnail", thumbnailStream, closeStream, new DataServiceRequestArgs() { ContentType = "image/bmp" });
// verify the entity descriptor state
EntityDescriptor entityDescriptor = context.Entities.Single();
StreamDescriptor streamInfo = entityDescriptor.StreamDescriptors.Single();
Assert.IsTrue(entityDescriptor.State == EntityStates.Added, "entity must be in added state");
Assert.AreEqual(streamInfo.StreamLink.Name, "Thumbnail");
Assert.IsTrue(streamInfo.State == EntityStates.Modified, "named stream must be in modified state");
string editLink = request.ServiceRoot.AbsoluteUri + "/editLink/Customers(1)";
int i = 0;
PlaybackService.InspectRequestPayload.Value = (message) =>
{
if (i == 2)
{
// Verify that the second request was a PUT request
Assert.IsTrue(PlaybackService.LastPlayback.Contains(String.Format("PATCH {0}", editLink)), "the second request must be a PATCH request with the edit link");
Assert.AreEqual(!defaultStream.CanWrite, closeStream, "The default stream must have been in the desired state");
}
else if (i == 1)
{
// Verify the first request was a POST request
Assert.IsTrue(PlaybackService.LastPlayback.Contains(String.Format("POST {0}/Customers", request.ServiceRoot)), "the first request must be a POST request");
PlaybackService.OverridingPlayback.Value = PlaybackService.ConvertToPlaybackServicePayload(null, null);
XDocument document = XDocument.Load(message);
Assert.IsTrue(document.Element(AstoriaUnitTests.Tests.UnitTestsUtil.AtomNamespace + "entry") != null, "must contain an entry element");
Assert.AreEqual(!defaultStream.CanWrite, closeStream, "The default stream must have been in the desired state immd after the request");
}
else if (i == 0)
{
// Populate the context with a single customer instance
string payload = AtomParserTests.MediaEntry(
id: Id,
editLink: editLink,
properties: Properties,
readStreamUrl: request.ServiceRoot + "/Customers(1)/readStreamUrl/$value",
links: GetNamedStreamSelfLink(request.ServiceRoot + "/Customers(1)/SelfLink/Thumbnail", contentType: MediaContentType) +
GetNamedStreamEditLink(request.ServiceRoot.AbsoluteUri + "/Customers(1)/EditLink/Thumbnail", contentType: MediaContentType, etag: MediaETag));
var headers = new List<KeyValuePair<string, string>>() {
new KeyValuePair<string, string>("Location", "http://locationservice/locationheader") };
PlaybackService.OverridingPlayback.Value = PlaybackService.ConvertToPlaybackServicePayload(headers, payload);
// entity state should not be modified until all the responses have been changed
Assert.IsTrue(entityDescriptor.State == EntityStates.Modified, "entity must be in added state");
Assert.IsTrue(defaultStream.CanWrite, "The default stream hasn't been closed yet");
}
Assert.AreEqual(streamInfo.StreamLink.Name, "Thumbnail");
Assert.IsTrue(streamInfo.State == EntityStates.Modified, "named stream must be in modified state");
// Also the stream info links should not be modified
Assert.IsTrue(streamInfo.StreamLink.SelfLink == null, "descriptor should not have been modified yet - self link must be null");
Assert.IsTrue(streamInfo.StreamLink.EditLink == null, "descriptor should not have been modified yet - edit link must be null");
Assert.IsTrue(String.IsNullOrEmpty(streamInfo.StreamLink.ContentType), "descriptor should not have been modified yet - content type must be null");
Assert.IsTrue(String.IsNullOrEmpty(streamInfo.StreamLink.ETag), "descriptor should not have been modified yet - etag must be null");
Assert.IsTrue(thumbnailStream.CanWrite, "The thumbnail stream hasn't been closed yet");
i++;
};
DataServiceContextTestUtil.SaveChanges(context, SaveChangesOptions.None, mode);
Assert.AreEqual(i, 3, "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}", streamInfo.StreamLink.EditLink)), "the second request must be a PUT request with the edit link");
Assert.AreEqual(streamInfo.StreamLink.SelfLink.AbsoluteUri, request.ServiceRoot + "/Customers(1)/SelfLink/Thumbnail", "self link must be null, since the payload did not have self link");
Assert.AreEqual(streamInfo.StreamLink.EditLink.AbsoluteUri, request.ServiceRoot + "/Customers(1)/EditLink/Thumbnail", "edit link should have been populated");
Assert.AreEqual(!thumbnailStream.CanWrite, closeStream, "The stream must be in the desired state");
}
});
}
示例12: Collection_Blobs
public void Collection_Blobs()
{
DSPMetadata metadata = CreateMetadataForXFeatureEntity(true);
DSPServiceDefinition service = new DSPServiceDefinition() {
Metadata = metadata,
Writable = true,
SupportMediaResource = true,
MediaResourceStorage = new DSPMediaResourceStorage()
};
byte[] clientBlob = new byte[] { 0xcc, 0x10, 0x00, 0xff };
DSPContext data = new DSPContext();
service.CreateDataSource = (m) => { return data; };
using (TestWebRequest request = service.CreateForInProcessWcf())
using (DSPResourceWithCollectionProperty.CollectionPropertiesResettable.Restore())
{
DSPResourceWithCollectionProperty.CollectionPropertiesResettable.Value = true;
request.StartService();
XFeatureTestsMLE clientMle = new XFeatureTestsMLE() {
ID = 1,
Description = "Entity 1",
Strings = new List<string>(new string[] { "string 1", "string 2", string.Empty }),
Structs = new List<XFeatureTestsComplexType>(new XFeatureTestsComplexType[] {
new XFeatureTestsComplexType() { Text = "text 1" },
new XFeatureTestsComplexType() { Text = "text 2" }}) };
DataServiceContext ctx = new DataServiceContext(new Uri(request.BaseUri), ODataProtocolVersion.V4);
ctx.EnableAtom = true;
ctx.Format.UseAtom();
ctx.AddObject("Entities", clientMle);
ctx.SetSaveStream(clientMle, new MemoryStream(clientBlob), true, "application/octet-stream", clientMle.ID.ToString());
ctx.SaveChanges();
VerifyMLEs(service, clientMle, clientBlob);
// Read stream and verify stream contents
using (Stream serverStream = ctx.GetReadStream(clientMle).Stream)
{
VerifyStream(clientBlob, serverStream);
}
// modify MLE and the corresponding stream
clientMle.Structs.Add(new XFeatureTestsComplexType() { Text = "text 3" });
clientMle.Strings.RemoveAt(0);
clientBlob[0] ^= 0xff;
ctx.UpdateObject(clientMle);
ctx.SetSaveStream(clientMle, new MemoryStream(clientBlob), true, "application/octet-stream", clientMle.ID.ToString());
ctx.SaveChanges();
VerifyMLEs(service, clientMle, clientBlob);
// delete MLE
ctx.DeleteObject(clientMle);
ctx.SaveChanges();
Assert.IsNull((DSPResource)service.CurrentDataSource.GetResourceSetEntities("Entities").
FirstOrDefault(e => (int)(((DSPResource)e).GetValue("ID")) == (int)clientMle.GetType().GetProperty("ID").GetValue(clientMle, null)),
"MLE has not been deleted.");
Assert.AreEqual(0, service.MediaResourceStorage.Content.Count(), "The stream on the server has not been deleted.");
};
}
示例13: Collection_ChangeInterceptors
public void Collection_ChangeInterceptors()
{
var metadata = CreateMetadataForXFeatureEntity();
InterceptorServiceDefinition service = new InterceptorServiceDefinition()
{
Metadata = metadata,
CreateDataSource = (m) => new DSPContext(),
Writable = true,
EnableChangeInterceptors = true
};
// client cases
TestUtil.RunCombinations(new string[] { "POST", "PUT", "PATCH", "DELETE" }, new bool[] { false, true }, (httpMethod, batch) =>
{
using (DSPResourceWithCollectionProperty.CollectionPropertiesResettable.Restore())
using (TestWebRequest request = service.CreateForInProcessWcf())
{
DSPResourceWithCollectionProperty.CollectionPropertiesResettable.Value = true;
request.Accept = "application/atom+xml,application/xml";
request.StartService();
DataServiceContext ctx = new DataServiceContext(request.ServiceRoot, ODataProtocolVersion.V4);
ctx.EnableAtom = true;
ctx.Format.UseAtom();
if (httpMethod != "POST")
{
service.EnableChangeInterceptors = false;
PopulateClientContextWithTestEntities(ctx);
service.EnableChangeInterceptors = true;
}
ctx.IgnoreResourceNotFoundException = true;
var resource = ctx.CreateQuery<XFeatureTestsEntity>("Entities").FirstOrDefault();
SaveChangesOptions saveOptions = batch ? SaveChangesOptions.BatchWithSingleChangeset : SaveChangesOptions.None;
switch (httpMethod)
{
case "POST":
resource = new XFeatureTestsEntity() { ID = 42, Strings = new List<string>(), Structs = new List<XFeatureTestsComplexType>() };
ctx.AddObject("Entities", resource);
break;
case "PUT":
saveOptions |= SaveChangesOptions.ReplaceOnUpdate;
ctx.UpdateObject(resource);
break;
case "PATCH":
ctx.UpdateObject(resource);
break;
case "DELETE":
ctx.DeleteObject(resource);
break;
}
ctx.SaveChanges(saveOptions);
Assert.AreEqual((int?)resource.ID, service.ChangeInterceptorCalledOnEntityId, "The change interceptor was not called or it was called with a wrong entity");
service.ChangeInterceptorCalledOnEntityId = null;
}
});
service.EnableChangeInterceptors = true;
service.ChangeInterceptorCalledOnEntityId = null;
// server cases (these operations can't be done using client API)
TestUtil.RunCombinations(
new string[] { "Strings", "Structs" },
new string[] { UnitTestsUtil.MimeApplicationXml},
(collectionPropertyName, format) =>
{
using (DSPResourceWithCollectionProperty.CollectionPropertiesResettable.Restore())
using (TestWebRequest request = service.CreateForInProcessWcf())
{
DSPResourceWithCollectionProperty.CollectionPropertiesResettable.Value = true;
request.StartService();
DataServiceContext ctx = new DataServiceContext(request.ServiceRoot, ODataProtocolVersion.V4);
ctx.EnableAtom = true;
ctx.Format.UseAtom();
service.EnableChangeInterceptors = false;
PopulateClientContextWithTestEntities(ctx);
service.EnableChangeInterceptors = true;
// Get the collection property payload
var payload = UnitTestsUtil.GetResponseAsAtomXLinq(request, "/Entities(1)/" + collectionPropertyName, format);
// And send a PUT with that payload back
request.HttpMethod = "PUT";
request.Accept = format;
request.RequestContentType = format;
request.RequestUriString = "/Entities(1)/" + collectionPropertyName;
request.SetRequestStreamAsText(payload.ToString());
request.SendRequest();
Assert.AreEqual((int?)1, service.ChangeInterceptorCalledOnEntityId, "The change interceptor was not called or it was called with a wrong entity");
service.ChangeInterceptorCalledOnEntityId = null;
}
});
}
示例14: Collection_BatchIDataServiceHostAndChangeTracking
public void Collection_BatchIDataServiceHostAndChangeTracking()
{
DSPMetadata metadata = CreateMetadataForXFeatureEntity();
TestUtil.RunCombinations(
new bool[] { false, true },
new bool[] { false, true },
new Type[] { typeof(IDataServiceHost), typeof(IDataServiceHost2) },
(sendAsBatch, replaceOnUpdate, hostInterfaceType) => {
DSPServiceDefinition service = new DSPServiceDefinition() { Metadata = metadata, Writable = true, HostInterfaceType = hostInterfaceType };
DSPContext data = new DSPContext();
service.CreateDataSource = (m) => { return data; };
// This test operates just on 2 entities - so let's take just first two from the set
List<object> testEntities = CreateClientTestEntities().Take(2).ToList<object>();
SaveChangesOptions saveOptions =
(sendAsBatch ? SaveChangesOptions.BatchWithSingleChangeset : SaveChangesOptions.None) |
(replaceOnUpdate ? SaveChangesOptions.ReplaceOnUpdate : SaveChangesOptions.None);
using (TestWebRequest request = service.CreateForInProcessWcf())
using (DSPResourceWithCollectionProperty.CollectionPropertiesResettable.Restore())
{
DSPResourceWithCollectionProperty.CollectionPropertiesResettable.Value = true;
request.StartService();
// Add entities
DataServiceContext ctx = new DataServiceContext(new Uri(request.BaseUri), ODataProtocolVersion.V4);
ctx.EnableAtom = true;
ctx.Format.UseAtom();
foreach (XFeatureTestsEntity entity in testEntities)
{
ctx.AddObject("Entities", entity);
}
VerifyStateOfEntities(ctx, testEntities, EntityStates.Added);
ctx.SaveChanges(saveOptions);
VerifyStateOfEntities(ctx, testEntities, EntityStates.Unchanged);
VerifyEntitySetsMatch(testEntities, data.GetResourceSetEntities("Entities"));
// Change one of the entities
((XFeatureTestsEntity)testEntities[0]).Structs.RemoveAt(0);
ctx.UpdateObject(testEntities[0]);
VerifyStateOfEntities(ctx, new[] { testEntities[0] }, EntityStates.Modified);
VerifyStateOfEntities(ctx, new[] { testEntities[1] }, EntityStates.Unchanged);
ctx.SaveChanges(saveOptions);
VerifyStateOfEntities(ctx, testEntities, EntityStates.Unchanged);
VerifyEntitySetsMatch(testEntities, data.GetResourceSetEntities("Entities"));
// Change collection in both entities
List<string> tempCollection = ((XFeatureTestsEntity)testEntities[0]).Strings;
((XFeatureTestsEntity)testEntities[0]).Strings = ((XFeatureTestsEntity)testEntities[1]).Strings;
((XFeatureTestsEntity)testEntities[1]).Strings = tempCollection;
ctx.UpdateObject(testEntities[0]);
ctx.UpdateObject(testEntities[1]);
VerifyStateOfEntities(ctx, testEntities, EntityStates.Modified);
ctx.SaveChanges(saveOptions);
VerifyStateOfEntities(ctx, testEntities, EntityStates.Unchanged);
VerifyEntitySetsMatch(testEntities, data.GetResourceSetEntities("Entities"));
// Delete entities
ctx.DeleteObject(testEntities[0]);
ctx.DeleteObject(testEntities[1]);
VerifyStateOfEntities(ctx, testEntities, EntityStates.Deleted);
ctx.SaveChanges(saveOptions);
testEntities.RemoveAt(0);
testEntities.RemoveAt(0);
VerifyEntitySetsMatch(testEntities, data.GetResourceSetEntities("Entities"));
}
});
}
示例15: PopulateClientContextWithTestEntities
private static void PopulateClientContextWithTestEntities(DataServiceContext context)
{
foreach (var entity in CreateClientTestEntities())
{
context.AddObject("Entities", entity);
}
context.SaveChanges(SaveChangesOptions.BatchWithSingleChangeset);
}