/// <summary>
        /// Gets the encrypted key value.
        /// </summary>
        /// <param name="certToEncryptTo">The cert to use.</param>
        /// <returns>A function delegate that returns the future result to be available through the Task&lt;byte[]&gt;.</returns>
        public Task <byte[]> GetEncryptedKeyValueAsync(X509Certificate2 certToEncryptTo)
        {
            if (certToEncryptTo == null)
            {
                throw new ArgumentNullException("certToEncryptTo");
            }

            // Start a new task here because the ExecutAsync on the DataContext returns a Task<string>
            return(System.Threading.Tasks.Task.Factory.StartNew <byte[]>(() =>
            {
                byte[] returnValue = null;

                if (this._cloudMediaContext != null)
                {
                    string certToSend = Convert.ToBase64String(certToEncryptTo.Export(X509ContentType.Cert));
                    certToSend = HttpUtility.UrlEncode(certToSend);

                    Uri uriRebindContentKey = new Uri(string.Format(CultureInfo.InvariantCulture, "/RebindContentKey?id='{0}'&x509Certificate='{1}'", this.Id, certToSend), UriKind.Relative);
                    DataServiceContext dataContext = this._cloudMediaContext.DataContextFactory.CreateDataServiceContext();

                    IEnumerable <string> results = dataContext.Execute <string>(uriRebindContentKey);
                    string reboundContentKey = results.Single();

                    returnValue = Convert.FromBase64String(reboundContentKey);
                }

                return returnValue;
            }));
        }
Example #2
0
        //
        // 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());
        }
        public void TestSpecialCharactersInPrimaryKey()
        {
            DataServiceContext ctx = new DataServiceContext(new Uri(this.BaseAddress));
            var  todoes            = ctx.CreateQuery <SpecialCharactersLinkGenerationTestsModel>("SpecialCharactersLinkGenerationWebTests").ToList();
            bool success           = true;

            foreach (var todo in todoes)
            {
                try
                {
                    Uri selfLink;
                    Assert.True(ctx.TryGetUri(todo, out selfLink));
                    Console.WriteLine(selfLink);

                    //ctx.UpdateObject(todo);

                    //var response = ctx.SaveChanges().Single();

                    //Assert.Equal(204, response.StatusCode);

                    ctx.Execute <SpecialCharactersLinkGenerationTestsModel>(selfLink, "GET", true);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                    success = false;
                }
            }

            Assert.True(success);
        }
Example #4
0
        public void DeleteItem()
        {
            DataServiceContext ctx = new DataServiceContext(new Uri("http://localhost/Chapter9/MovieService.svc"));

            MovieService.Film FilmToDelete =
                ctx.Execute <MovieService.Film>(new Uri("Films(1)", UriKind.Relative)).First();
            ctx.DeleteObject(FilmToDelete);
            ctx.SaveChanges();
        }
        /// <summary>
        /// Gets the protection key id for content key.
        /// </summary>
        /// <param name="dataContext">The data context.</param>
        /// <param name="contentKeyType">Type of the content key.</param>
        /// <returns>The content key.</returns>
        internal static string GetProtectionKeyIdForContentKey(DataServiceContext dataContext, ContentKeyType contentKeyType)
        {
            // First query Nimbus to find out what certificate to encrypt the content key with.
            string uriString             = string.Format(CultureInfo.InvariantCulture, "/GetProtectionKeyId?contentKeyType={0}", Convert.ToInt32(contentKeyType, CultureInfo.InvariantCulture));
            Uri    uriGetProtectionKeyId = new Uri(uriString, UriKind.Relative);
            IEnumerable <string> results = dataContext.Execute <string>(uriGetProtectionKeyId);

            return(results.Single());
        }
Example #6
0
        public virtual void InvokeActionWithOverloads(string actionUrl)
        {
            DataServiceContext ctx = new DataServiceContext(new Uri(this.BaseAddress), DataServiceProtocolVersion.V3);
            var result             = ctx.Execute(
                new Uri(this.BaseAddress + actionUrl),
                "POST");

            Assert.Equal(204, result.StatusCode);
        }
Example #7
0
        static void Main(string[] args)
        {
            DataServiceContext ctx = new DataServiceContext(new Uri("http://localhost/Chapter9/MovieService.svc"));
            var Orders             =
                ctx.Execute <MovieService.Order>(new Uri("Orders", UriKind.Relative));

            foreach (MovieService.Order Order in Orders)
            {
                Console.WriteLine(Order.Firstname);
            }
            Console.ReadKey();
        }
Example #8
0
        public void DocketCodes(string partialDocketCode)
        {
            Uri uri = new Uri(_dataServiceUrlBase + "/DocketCodeService.svc/");
            DataServiceContext context = new DataServiceContext(uri);

            StringBuilder cmdBuilder = new StringBuilder();

            cmdBuilder.AppendFormat("DocketCodes?$filter=substringof('{0}',DocketDescription)", partialDocketCode);

            IEnumerable <DocketCode> dcQuery =
                context.Execute <ClientDataModel.DocketCodeModel.DocketCode>(new Uri(strCmd, UriKind.Relative));
            List <ClientDataModel.DocketCodeModel.DocketCode> dcs = dcQuery.ToList <ClientDataModel.DocketCodeModel.DocketCode>();
        }
 private void VerifyErrorString(DataServiceContext context, string errorUrl, string errorString, params object[] arguments)
 {
     try
     {
         context.Execute <Computer>(new Uri(this.ServiceUri.OriginalString + errorUrl));
         Assert.True(false, "Expected Exception not thrown for " + errorUrl);
     }
     catch (DataServiceQueryException ex)
     {
         Assert.NotNull(ex.InnerException);
         Assert.IsType <DataServiceClientException>(ex.InnerException);
         StringResourceUtil.VerifyDataServicesString(ClientExceptionUtil.ExtractServerErrorMessage(ex), errorString, arguments);
     }
 }
Example #10
0
 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);
     }
 }
Example #11
0
        public void ExecuteUriAndCompare <TResult>(IAsyncContinuation continuation, bool isAsync, IQueryable <TResult> query, string uriString, QueryValue expectedValue, DataServiceContext dataContext, ExpectedClientErrorBaseline clientExpectedError)
        {
            this.isAsynchronous = isAsync;
            this.ExecuteQueryAction(
                continuation,
                expectedValue,
                dataContext,
                clientExpectedError,
                delegate(List <object> entityPayloads, IAsyncContinuation continuation2)
            {
                AsyncHelpers.CatchErrors(
                    continuation2,
                    () =>
                {
                    this.Logger.WriteLine(LogLevel.Verbose, "Executing query, async:{0}, Uri:{1}:", isAsync, dataContext.BaseUri + "/" + uriString);

                    Uri builtUri = new Uri(dataContext.BaseUri + "/" + uriString);
#if !SILVERLIGHT
                    EventHandler <SendingRequest2EventArgs> sendingRequest = delegate(object sender, SendingRequest2EventArgs args)
                    {
                        HttpWebRequest request = ((HttpWebRequestMessage)args.RequestMessage).HttpWebRequest;
                        this.VerifyCommonExecuteHeaders(request.Headers);
                    };

                    dataContext.SendingRequest2 += sendingRequest;
#endif
                    dataContext.Execute(
                        continuation2,
                        isAsync,
                        builtUri,
                        delegate(IEnumerable <TResult> results)
                    {
                        this.Compare(expectedValue, () => results, dataContext);

                        if (entityPayloads.Count > 0)
                        {
                            this.VerifyDescriptorAfterExecute(continuation2, dataContext, entityPayloads, expectedValue);
                        }
                        else
                        {
#if !SILVERLIGHT
                            dataContext.SendingRequest2 -= sendingRequest;
#endif
                            continuation2.Continue();
                        }
                    });
                });
            });
        }
Example #12
0
        public static void ExecuteUri(this DataServiceContext context, IAsyncContinuation continuation, bool async, Uri requestUri, HttpVerb verb, OperationParameter[] inputParameters, Action <OperationResponse> onCompletion)
        {
            ExceptionUtilities.CheckArgumentNotNull(context, "context");
            ExceptionUtilities.CheckArgumentNotNull(continuation, "continuation");
            ExceptionUtilities.CheckArgumentNotNull(onCompletion, "onCompletion");

            string method = Enum.GetName(typeof(HttpVerb), verb).ToUpperInvariant();

            AsyncHelpers.InvokeSyncOrAsyncMethodCall <OperationResponse>(
                continuation,
                async,
                () => context.Execute(requestUri, method, inputParameters),
                c => context.BeginExecute(requestUri, c, null, method, inputParameters),
                r => context.EndExecute(r),
                onCompletion);
        }
Example #13
0
        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);
            }
        }
        public void SetDollarFormatInBuildingRequest()
        {
            using (TestWebRequest web = TestWebRequest.CreateForInProcessWcf())
            {
                web.DataServiceType = typeof(DollarFormatTestService);
                web.StartService();

                DataServiceContext ctx     = new DataServiceContext(web.ServiceRoot, ODataProtocolVersion.V4);
                List <string>      options = new List <string>()
                {
                    // "atom",  It will be enabled by finishing
                    // "json",  enable the json case by involving proper EDM model in DataServiceContext.
                    "xml",
                };
                string option = string.Empty;
                ctx.BuildingRequest += (sender, arg) => arg.RequestUri = new Uri(arg.RequestUri.AbsoluteUri + "?$format=" + option);

                foreach (string s in options)
                {
                    try
                    {
                        option = s;
                        ctx.Execute <Customer>(new Uri(web.ServiceRoot + "/Customers"));
                        ctx.CreateQuery <Customer>("Customers");
                        //  Assert.IsTrue(option == "json");
                    }
                    catch (DataServiceQueryException e)
                    {
                        if (option == "xml")
                        {
                            TestUtil.AssertContains(e.InnerException.Message, "A supported MIME type could not be found that matches the acceptable MIME types for the request.");
                            Assert.AreEqual(415, e.Response.StatusCode);
                        }
                        else
                        {
                            // Assert.AreEqual("atom", option);
                            // Assert.AreEqual(DataServicesClientResourceUtil.GetString("DataServiceClientFormat_ValidServiceModelRequiredForAtom"), e.InnerException.Message);
                        }
                    }
                }
            }
        }
        /// <summary>
        /// Gets the clear key value.
        /// </summary>
        /// <returns>A function delegate that returns the future result to be available through the Task&lt;byte[]&gt;.</returns>
        public Task <byte[]> GetClearKeyValueAsync()
        {
            // Start a new task here because the ExecutAsync on the DataContext returns a Task<string>
            return(System.Threading.Tasks.Task.Factory.StartNew <byte[]>(() =>
            {
                byte[] returnValue = null;
                if (this._cloudMediaContext != null)
                {
                    Uri uriRebindContentKey = new Uri(string.Format(CultureInfo.InvariantCulture, "/RebindContentKey?id='{0}'&x509Certificate=''", this.Id), UriKind.Relative);
                    DataServiceContext dataContext = this._cloudMediaContext.DataContextFactory.CreateDataServiceContext();

                    IEnumerable <string> results = dataContext.Execute <string>(uriRebindContentKey);
                    string reboundContentKey = results.Single();

                    returnValue = Convert.FromBase64String(reboundContentKey);
                }

                return returnValue;
            }));
        }
Example #16
0
        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();
        }
Example #17
0
        /// <summary>
        /// InvokeDataServiceQuery
        /// </summary>
        /// <param name="queryString">OData QueryString</param>
        /// <param name="type">RequestType : Atom, Json</param>
        /// <returns>dynamic</returns>
        public dynamic InvokeDataServiceQuery(String queryString, RequestType type)
        {
            try
            {
                if (type == RequestType.JSON && queryString.Contains("json"))
                {
                    throw new DataServiceClientException("Wrong Query!! could not use both '$format=json' and 'RequestType.JSON'");
                }

                //if (queryString.IndexOf('?') < 0)
                //{
                //	queryString = queryString.Insert(0, "?");
                //}

                var result = context.Execute <dynamic>(new Uri(queryString, UriKind.Relative));

                if (type == RequestType.JSON)
                {
                    ///JSon SerializeObject String타입으로 변경
                    String jsonResult = JsonConvert.SerializeObject(result);
                    return(jsonResult);
                }
                else
                {
                    return(result);
                }
            }
            catch (System.Data.Services.Client.DataServiceQueryException ex)
            {
                QueryOperationResponse response = ex.Response;

                string message    = response.Error.Message;
                int    statusCode = response.StatusCode;

                throw;
            }
            catch (Exception)
            {
                throw;
            }
        }
        /// <summary>
        /// Gets the certificate for protection key id.
        /// </summary>
        /// <param name="dataContext">The data context.</param>
        /// <param name="protectionKeyId">The protection key id.</param>
        /// <returns>The content key.</returns>
        internal static X509Certificate2 GetCertificateForProtectionKeyId(DataServiceContext dataContext, string protectionKeyId)
        {
            // First check to see if we have the cert in our store already.
            X509Certificate2 certToUse = EncryptionUtils.GetCertificateFromStore(protectionKeyId);

            if ((certToUse == null) && (dataContext != null))
            {
                // If not, download it from Nimbus to use.
                Uri uriGetProtectionKey       = new Uri(string.Format(CultureInfo.InvariantCulture, "/GetProtectionKey?protectionKeyId='{0}'", protectionKeyId), UriKind.Relative);
                IEnumerable <string> results2 = dataContext.Execute <string>(uriGetProtectionKey);
                string certString             = results2.Single();

                byte[] certBytes = Convert.FromBase64String(certString);
                certToUse = new X509Certificate2(certBytes);

                // Finally save it for next time.
                EncryptionUtils.SaveCertificateToStore(certToUse);
            }

            return(certToUse);
        }
Example #19
0
        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");
            }
        }
Example #20
0
        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);
                });
            }
        }
        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);
        }
Example #22
0
        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));
        }
Example #23
0
            public void SDPC_QORFullLoad()
            {
                using (Utils.ConfigurationCacheCleaner())
                using (Utils.RestoreStaticValueOnDispose(typeof(SimpleDataServiceHelper), "PageSizeCustomizer"))
                {
                    SimpleDataServiceHelper.PageSizeCustomizer = PageSizeCustomizerFast;
                    SimpleWorkspace workspace = this.NorthwindWorkspacePaged;
                    Uri baseUri = new Uri(workspace.ServiceEndPoint + workspace.ServiceContainer.Name + ".svc", UriKind.Absolute);

                    DataServiceContext ctx = new DataServiceContext(baseUri);
                    ctx.EnableAtom = true;
                    ctx.Format.UseAtom();
                    var q = ctx.CreateQuery<northwindBinding.Customers>("Customers").Expand("Orders");

                    int totalCustomerCount = q.Count();
                    int totalOrdersCount = ctx.CreateQuery<northwindBinding.Orders>("Orders").Count();

                    var qor = q.Execute() as QueryOperationResponse<northwindBinding.Customers>;

                    DataServiceQueryContinuation<northwindBinding.Customers> nextCustLink = null;
                    int custCount = 0;
                    int orderCount = 0;
                    do
                    {
                        ICollection previousOrderCollection = null;

                        foreach (var c in qor)
                        {
                            try
                            {
                                if (previousOrderCollection != null)
                                {
                                    qor.GetContinuation(previousOrderCollection);
                                    Assert.Fail("Out of scope collection did not throw");
                                }
                            }
                            catch (ArgumentException)
                            {
                            }

                            var nextOrderLink = qor.GetContinuation(c.Orders);
                            while (nextOrderLink != null)
                            {
                                if (custCount % 2 == 0)
                                {
                                    var innerQOR = ctx.Execute<northwindBinding.Orders>(nextOrderLink) as QueryOperationResponse<northwindBinding.Orders>;
                                    foreach (var innerOrder in innerQOR)
                                    {
                                        ctx.AttachLink(c, "Orders", innerOrder);
                                        c.Orders.Add(innerOrder);
                                    }
                                    nextOrderLink = innerQOR.GetContinuation();
                                }
                                else
                                {
                                    nextOrderLink = ctx.LoadProperty(c, "Orders", nextOrderLink).GetContinuation();
                                }
                            }

                            previousOrderCollection = c.Orders;

                            orderCount += c.Orders.Count;
                            custCount++;
                        }

                        nextCustLink = qor.GetContinuation();
                        if (nextCustLink != null)
                        {
                            qor = ctx.Execute<northwindBinding.Customers>(nextCustLink) as QueryOperationResponse<northwindBinding.Customers>;
                        }

                    } while (nextCustLink != null);

                    Assert.AreEqual(totalCustomerCount, custCount);
                    Assert.AreEqual(totalOrdersCount, orderCount);
                    Assert.AreEqual(totalOrdersCount, ctx.Links.Count);
                    Assert.AreEqual(totalCustomerCount + totalOrdersCount, ctx.Entities.Count);
                }
            }
Example #24
0
        public void SetSaveStreamNotAllowedInBatch()
        {
            // Saving named stream is not supported in batch
            DataServiceContext context = new DataServiceContext(request.ServiceRoot, ODataProtocolVersion.V4);
            context.EnableAtom = true;
            Customer c;
            using (PlaybackService.OverridingPlayback.Restore())
            {
                // Populate the context with a single customer instance
                string payload = AtomParserTests.AnyEntry(
                    id: Id,
                    properties: Properties,
                    links: GetNamedStreamEditLink(MediaEditLink, contentType: MediaContentType, etag: MediaETag) + GetNamedStreamSelfLink(MediaQueryLink, MediaContentType));

                PlaybackService.OverridingPlayback.Value = PlaybackService.ConvertToPlaybackServicePayload(null, payload);
                c = context.Execute<Customer>(new Uri("/Customers(1)", UriKind.Relative)).Single();
            }

            context.SetSaveStream(c, "Thumbnail", new MemoryStream(), true, "image/jpeg");

            TestUtil.RunCombinations((IEnumerable<SaveChangesMode>)Enum.GetValues(typeof(SaveChangesMode)), (mode) =>
            {
                try
                {
                    DataServiceContextTestUtil.SaveChanges(context, SaveChangesOptions.BatchWithSingleChangeset, mode);
                    Assert.Fail("Named streams requests are not support in batch mode");
                }
                catch (NotSupportedException e)
                {
                    Assert.AreEqual(e.Message, AstoriaUnitTests.DataServicesClientResourceUtil.GetString("Context_BatchNotSupportedForNamedStreams"), "Expecting the correct error message");
                }
            });
        }
Example #25
0
 /// <summary>
 /// Extension method to perform sync/async version of DataServiceContext.Execute dynamically
 /// </summary>
 /// <typeparam name="TElement">The element type of the expression results</typeparam>
 /// <param name="context">The context to call execute on</param>
 /// <param name="continuation">The asynchronous continuation</param>
 /// <param name="async">A value indicating whether or not to use async API</param>
 /// <param name="requestUri">The uri to make a request to</param>
 /// <param name="onCompletion">A callback for when the call completes</param>
 public static void Execute <TElement>(this DataServiceContext context, IAsyncContinuation continuation, bool async, Uri requestUri, Action <IEnumerable <TElement> > onCompletion)
 {
     ExceptionUtilities.CheckArgumentNotNull(context, "context");
     AsyncHelpers.InvokeSyncOrAsyncMethodCall <IEnumerable <TElement> >(continuation, async, () => context.Execute <TElement>(requestUri), c => context.BeginExecute <TElement>(requestUri, c, null), r => context.EndExecute <TElement>(r), onCompletion);
 }
 /// <summary>
 /// Executes the action and returns the operation response.
 /// </summary>
 /// <returns>Operation result.</returns>
 /// <exception cref="InvalidOperationException">Problem materializing result of query into object.</exception>
 public OperationResponse Execute()
 {
     return(Context.Execute(this.RequestUri, XmlConstants.HttpMethodPost, Parameters));
 }
        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++]);
                }
            }
        }
Example #28
0
            public void QueryFailureUsingExecute()
            {
                Uri baseUri = ctx.BaseUri;

                Uri requestUri = new Uri(baseUri.OriginalString + "/Customers('VAR1')");

                try
                {
                    ctx.Execute <northwindClient.Customers>(requestUri);
                }
                catch (DataServiceQueryException ex)
                {
                    QueryOperationResponse response = ex.Response;
                    Utils.IsErrorResponse(response, HttpStatusCode.NotFound, false);
                    Assert.IsTrue(response.Query.RequestUri.Equals(requestUri), "expecting the same request uri");
                }
            }
        public void AdvertiseLargeNumberOfActionsTests()
        {
            // Test advertising large number of actions.
            var testCases = new[]
            {   
                new 
                {
                    RequestUri = "/Customers(1)",
                },
            };

            using (TestWebRequest request = service.CreateForInProcessWcf())
            {
                request.StartService();
                t.TestUtil.RunCombinations(testCases, (testCase) =>
                {
                    DataServiceContext ctx = new DataServiceContext(request.ServiceRoot, ODataProtocolVersion.V4);
                    ctx.EnableAtom = true;
                    ctx.Format.UseAtom();
                    ctx.ResolveType = name => typeof(Customer);
                    Uri uri = new Uri(request.ServiceRoot + testCase.RequestUri);
                    QueryOperationResponse<object> qor = (QueryOperationResponse<object>)ctx.Execute<object>(uri);
                    Assert.IsNotNull(qor);
                    IEnumerator<object> entities = qor.GetEnumerator();
                    entities.MoveNext();
                    Assert.IsNotNull(entities.Current);
                    EntityDescriptor ed = ctx.GetEntityDescriptor(entities.Current);
                    Assert.IsNotNull(ed);
                    Assert.IsNotNull(ed.OperationDescriptors);
                    Assert.AreEqual(ed.OperationDescriptors.Count(), TotalNumberOfActions, "Invalid count of total number of advertised actions.");
                });
            }
        }
            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);
                }
            }
        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++]);
                }
            }
        }
        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);
                    });
            }
        }
        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++]);
                }
            }
        }
Example #34
0
        public void VerifyMissingLinkQueryScenario()
        {
            // Make sure the query scenarios fail, when self/edit links for named stream is missing
            TestUtil.RunCombinations(
                UnitTestsUtil.BooleanValues,
                UnitTestsUtil.BooleanValues,
                UnitTestsUtil.BooleanValues,
                (syncRead, hasSelfLink, hasEditLink) =>
                {
                    using (PlaybackService.OverridingPlayback.Restore())
                    {
                        DataServiceContext context = new DataServiceContext(request.ServiceRoot, ODataProtocolVersion.V4);
                        context.EnableAtom = true;

                        string links = null;
                        string contentType = null;
                        string selfLink = null;
                        string editLink = null;

                        if (hasSelfLink)
                        {
                            selfLink = request.ServiceRoot + "/Customers(1)/SelfLink/Thumbnail";
                            links += GetNamedStreamSelfLink(selfLink);
                        }

                        if (hasEditLink)
                        {
                            editLink = request.ServiceRoot + "/Customers(1)/EditLink/Thumbnail";
                            contentType = MediaContentType;
                            links += GetNamedStreamEditLink(editLink, contentType);
                        }

                        string payload = AtomParserTests.AnyEntry(
                                     id: Id,
                                     selfLink: request.ServiceRoot.AbsoluteUri + "/selfLink/Customers(1)",
                                     editLink: request.ServiceRoot.AbsoluteUri + "/editLink/Customers(1)",
                                     properties: Properties,
                                     links: links);

                        PlaybackService.OverridingPlayback.Value = PlaybackService.ConvertToPlaybackServicePayload(null, payload);
                        Customer c = context.Execute<Customer>(new Uri("/Customers(1)", UriKind.Relative)).Single();
                        PlaybackService.OverridingPlayback.Value = null;

                        EntityDescriptor ed = context.Entities.Single();
                        StreamDescriptor ns = null;
                        bool expectException = false;

                        if (!hasEditLink && !hasSelfLink)
                        {
                            expectException = true;
                            Assert.AreEqual(0, ed.StreamDescriptors.Count, "No named streams should be present");
                        }
                        else
                        {
                            ns = ed.StreamDescriptors.Single();
                            Assert.AreEqual(ns.StreamLink.SelfLink, selfLink, "self link must match");
                            Assert.AreEqual(ns.StreamLink.EditLink, editLink, "edit link must match");
                            Assert.AreEqual(ns.StreamLink.ContentType, contentType, "content type must match");
                            Assert.AreEqual(context.GetReadStreamUri(c, ns.StreamLink.Name).AbsoluteUri, ns.StreamLink.SelfLink != null ? ns.StreamLink.SelfLink.AbsoluteUri : ns.StreamLink.EditLink.AbsoluteUri,
                                "Make sure that context.GetReadStreamUri returns the self link if present, otherwise returns edit link");
                        }

                        try
                        {
                            if (syncRead)
                            {
                                context.GetReadStream(c, "Thumbnail", new DataServiceRequestArgs() { ContentType = "image/jpeg" });
                            }
                            else
                            {
                                IAsyncResult result = context.BeginGetReadStream(c, "Thumbnail", new DataServiceRequestArgs() { ContentType = "image/jpeg" }, (r) =>
                                    {
                                        context.EndGetReadStream(r);
                                    },
                                    null);

                                if (!result.CompletedSynchronously)
                                {
                                    Assert.IsTrue(result.AsyncWaitHandle.WaitOne(new TimeSpan(0, 0, AstoriaUnitTests.TestConstants.MaxTestTimeout), false), "BeginExecute timeout");
                                }
                            }

                            Assert.IsTrue(!expectException, "should reach here when no exception is expected");
                            Assert.IsTrue(PlaybackService.LastPlayback.Contains("GET " + selfLink ?? editLink), "should use self link if present, otherwise editlink");
                        }
                        catch (ArgumentException ex)
                        {
                            Assert.IsTrue(expectException, "should get exception when expected");
                            ArgumentException expectedException = new ArgumentException(DataServicesClientResourceUtil.GetString("Context_EntityDoesNotContainNamedStream", "Thumbnail"), "name");
                            Assert.AreEqual(expectedException.Message, ex.Message, "Error message did not match");
                            Assert.AreEqual(0, ed.StreamDescriptors.Count, "No named streams should be present");
                        }
                    }
                });
        }
        private void savePhotoDetails_Click(object sender, RoutedEventArgs e)
        {
            EntityDescriptor entity = null;

            try
            {
                if (photoEntity.FileName == string.Empty ||
                    photoEntity.FileName == null)
                {
                    MessageBox.Show("You must first select an image file to upload.");
                    return;
                }

                // Send the update (POST or MERGE) request to the data service and
                // capture the added or updated entity in the response.
                ChangeOperationResponse response =
                    context.SaveChanges().FirstOrDefault() as ChangeOperationResponse;

                // When we issue a POST request, the photo ID and edit-media link are not updated
                // on the client (a bug), so we need to get the server values.
                if (photoEntity.PhotoId == 0)
                {
                    if (response != null)
                    {
                        entity = response.Descriptor as EntityDescriptor;
                    }

                    // Verify that the entity was created correctly.
                    if (entity != null && entity.EditLink != null)
                    {
                        // Cache the current merge option (we reset to the cached
                        // value in the finally block).
                        cachedMergeOption = context.MergeOption;

                        // Set the merge option so that server changes win.
                        context.MergeOption = MergeOption.OverwriteChanges;

                        // Get the updated entity from the service.
                        // Note: we need Count() just to execute the query.
                        context.Execute <PhotoInfo>(entity.EditLink).Count();
                    }
                }

                this.DialogResult = true;
                this.Close();
            }
            catch (DataServiceRequestException ex)
            {
                // Get the change operation result.
                ChangeOperationResponse response =
                    ex.Response.FirstOrDefault() as ChangeOperationResponse;

                string errorMessage = string.Empty;

                // Check for a resource not found error.
                if (response != null && response.StatusCode == 404)
                {
                    // Tell the user to refresh the photos from the data service.
                    errorMessage = "The selected image may have been removed from the data service.\n"
                                   + "Click the Refresh Photos button to refresh photos from the service.";
                }
                else
                {
                    // Just provide the general error message.
                    errorMessage = string.Format("The photo data could not be updated or saved. {0}",
                                                 ex.Message);
                }

                // Show the messsage box.
                MessageBox.Show(errorMessage, "Operation Failed");

                // Return false since we could not add or update the photo.
                this.DialogResult = false;
                return;
            }
            finally
            {
                // Reset to the cached merge option.
                context.MergeOption = cachedMergeOption;
            }
        }
Example #36
0
        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");
                     }
                 });
        }
Example #37
0
        public void VerifyMissingLinkSaveChangesScenario()
        {
            // Make sure update scenarios fail, whenever edit link is missing
            TestUtil.RunCombinations(
                (IEnumerable<SaveChangesMode>)Enum.GetValues(typeof(SaveChangesMode)),
                UnitTestsUtil.BooleanValues,
                (mode, hasSelfLink) =>
                {
                    using (PlaybackService.OverridingPlayback.Restore())
                    {
                        DataServiceContext context = new DataServiceContext(request.ServiceRoot, ODataProtocolVersion.V4);
                        context.EnableAtom = true;

                        string links = null;
                        string selfLink = null;
                        string contentType = null;
                        if (hasSelfLink)
                        {
                            selfLink = request.ServiceRoot + "/Customers(1)/SelfLink/Thumbnail";
                            contentType = MediaContentType;
                            links = GetNamedStreamSelfLink(selfLink, contentType);
                        }

                        string payload = AtomParserTests.AnyEntry(
                                    id: Id,
                                    selfLink: request.ServiceRoot.AbsoluteUri + "/selfLink/Customers(1)",
                                    editLink: request.ServiceRoot.AbsoluteUri + "/editLink/Customers(1)",
                                    properties: Properties,
                                    links: links);

                        PlaybackService.OverridingPlayback.Value = PlaybackService.ConvertToPlaybackServicePayload(null, payload);
                        Customer c = context.Execute<Customer>(new Uri("/Customers(1)", UriKind.Relative)).Single();
                        PlaybackService.OverridingPlayback.Value = null;

                        EntityDescriptor ed = context.Entities.Single();
                        if (hasSelfLink)
                        {
                            StreamDescriptor streamInfo = ed.StreamDescriptors.Single();
                            Assert.AreEqual(streamInfo.StreamLink.SelfLink.AbsoluteUri, selfLink, "self links must match");
                            Assert.AreEqual(streamInfo.StreamLink.EditLink, null, "edit link must be null");
                            Assert.AreEqual(streamInfo.StreamLink.ContentType, contentType, "content type must match");
                            Assert.AreEqual(streamInfo.StreamLink.ETag, null, "no etag");
                        }
                        else
                        {
                            Assert.AreEqual(0, ed.StreamDescriptors.Count, "No named streams should be present");
                        }

                        context.SetSaveStream(c, "Thumbnail", new MemoryStream(new byte[] { 0, 1, 2, 3, 4 }), true, new DataServiceRequestArgs() { ContentType = "image/jpeg" });

                        StreamDescriptor ns = ed.StreamDescriptors.Single();
                        Assert.AreEqual(ns.StreamLink.SelfLink, selfLink, "self links must match");
                        Assert.AreEqual(ns.StreamLink.EditLink, null, "edit link must be null");
                        Assert.AreEqual(ns.StreamLink.ContentType, contentType, "content type must match");
                        Assert.AreEqual(ns.StreamLink.ETag, null, "no etag");
                        Assert.AreEqual(EntityStates.Modified, ns.State, "named stream must be in modified state");

                        try
                        {
                            DataServiceContextTestUtil.SaveChanges(context, SaveChangesOptions.None, mode);
                        }
                        catch (DataServiceRequestException ex)
                        {
                            Assert.AreEqual(typeof(DataServiceClientException), ex.InnerException.GetType());
                            Assert.AreEqual(DataServicesClientResourceUtil.GetString("Context_SetSaveStreamWithoutNamedStreamEditLink", "Thumbnail"), ex.InnerException.Message);
                        }

                        Assert.AreEqual(EntityStates.Modified, ns.State, "Since save changes failed, the stream should still be in modified state");
                    }
                });
        }
        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");
                    Assert.AreEqual(o.Collection.First().Stream1Url.EditLink, request.ServiceRoot.AbsoluteUri + "/MySet3('ABCDE')/ColStream", "the stream url of the collection stream must be populated correctly - index 0");
                    Assert.AreEqual(o.Collection.First().Collection1.Single().Stream1Url.EditLink, request.ServiceRoot.AbsoluteUri + "/MySet2(3)/RefStream1", "the stream url of the collection stream must be populated correctly - index 0 - index 0");
                }

                Assert.AreEqual(context.Entities.Count, 0, "there should be no entities tracked by the context");
            }
        }
Example #39
0
        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);
        }
        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");
                    Assert.AreEqual(o.Collection.First().Stream1Url.EditLink, request.ServiceRoot.AbsoluteUri + "/MySet3('ABCDE')/ColStream", "the stream url of the collection stream must be populated correctly - index 0");
                    Assert.AreEqual(o.Collection.First().Collection1.Single().Stream1Url.EditLink, request.ServiceRoot.AbsoluteUri + "/MySet2(3)/RefStream1", "the stream url of the collection stream must be populated correctly - index 0 - index 0");
                }

                Assert.AreEqual(context.Entities.Count, 0, "there should be no entities tracked by the context");
            }
        }
Example #41
0
 /// <summary>
 /// Executes the action and returns the result.
 /// </summary>
 /// <returns>Action result.</returns>
 /// <exception cref="InvalidOperationException">Problem materializing result of query into object.</exception>
 public T GetValue()
 {
     return(context.Execute <T>(this.RequestUri, XmlConstants.HttpMethodPost, true, parameters).Single());
 }
        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++]);
                    }
                }
        }
Example #43
0
        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.
                    }
                });
        }
Example #44
0
            public void SDPC_QORFullLoad()
            {
                using (Utils.ConfigurationCacheCleaner())
                    using (Utils.RestoreStaticValueOnDispose(typeof(SimpleDataServiceHelper), "PageSizeCustomizer"))
                    {
                        SimpleDataServiceHelper.PageSizeCustomizer = PageSizeCustomizerFast;
                        SimpleWorkspace workspace = this.NorthwindWorkspacePaged;
                        Uri             baseUri   = new Uri(workspace.ServiceEndPoint + workspace.ServiceContainer.Name + ".svc", UriKind.Absolute);

                        DataServiceContext ctx = new DataServiceContext(baseUri);
                        ctx.EnableAtom = true;
                        ctx.Format.UseAtom();
                        var q = ctx.CreateQuery <northwindBinding.Customers>("Customers").Expand("Orders");

                        int totalCustomerCount = q.Count();
                        int totalOrdersCount   = ctx.CreateQuery <northwindBinding.Orders>("Orders").Count();

                        var qor = q.Execute() as QueryOperationResponse <northwindBinding.Customers>;

                        DataServiceQueryContinuation <northwindBinding.Customers> nextCustLink = null;
                        int custCount  = 0;
                        int orderCount = 0;
                        do
                        {
                            ICollection previousOrderCollection = null;

                            foreach (var c in qor)
                            {
                                try
                                {
                                    if (previousOrderCollection != null)
                                    {
                                        qor.GetContinuation(previousOrderCollection);
                                        Assert.Fail("Out of scope collection did not throw");
                                    }
                                }
                                catch (ArgumentException)
                                {
                                }

                                var nextOrderLink = qor.GetContinuation(c.Orders);
                                while (nextOrderLink != null)
                                {
                                    if (custCount % 2 == 0)
                                    {
                                        var innerQOR = ctx.Execute <northwindBinding.Orders>(nextOrderLink) as QueryOperationResponse <northwindBinding.Orders>;
                                        foreach (var innerOrder in innerQOR)
                                        {
                                            ctx.AttachLink(c, "Orders", innerOrder);
                                            c.Orders.Add(innerOrder);
                                        }
                                        nextOrderLink = innerQOR.GetContinuation();
                                    }
                                    else
                                    {
                                        nextOrderLink = ctx.LoadProperty(c, "Orders", nextOrderLink).GetContinuation();
                                    }
                                }

                                previousOrderCollection = c.Orders;

                                orderCount += c.Orders.Count;
                                custCount++;
                            }

                            nextCustLink = qor.GetContinuation();
                            if (nextCustLink != null)
                            {
                                qor = ctx.Execute <northwindBinding.Customers>(nextCustLink) as QueryOperationResponse <northwindBinding.Customers>;
                            }
                        } while (nextCustLink != null);

                        Assert.AreEqual(totalCustomerCount, custCount);
                        Assert.AreEqual(totalOrdersCount, orderCount);
                        Assert.AreEqual(totalOrdersCount, ctx.Links.Count);
                        Assert.AreEqual(totalCustomerCount + totalOrdersCount, ctx.Entities.Count);
                    }
            }
Example #45
0
        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");
                    }
                });
        }
        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;
            }
        }
        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");
            }
        }
Example #48
0
 /// <summary>
 /// Executes the action and returns the results as a collection.
 /// </summary>
 /// <returns>Action results.</returns>
 /// <exception cref="InvalidOperationException">Problem materializing result of query into object.</exception>
 public IEnumerable <T> Execute()
 {
     return(Context.Execute <T>(this.RequestUri, XmlConstants.HttpMethodPost, false, Parameters));
 }
        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();
        }
        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);
            }    
        }
Example #51
0
 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);
     }
 }