Quantcast
Channel: WCF Data Services forum
Viewing all 877 articles
Browse latest View live

What is wrong with this url?


Bug: WCF DS Client fails to update OperationDescriptors (Actions) even in MergeOption.OverwriteChanges mode.

$
0
0

Hi,

Actions can be state dependent.

When doing updates (or caling Actions - that by definition has side effects) WCF DS Client correctly updates the properties on the client entity with the server values when using MergeOption.OverwriteChanges. However it fails to do so for the OperationDescriptors (the Actions) in the EntityDescriptor for the entity.

This must be a bug.

Actually it should ALWAYS overwrite the OperationDescriptors regardless of the MergeOption as the availability of an Action is always decided by the server.

An example scenario is as follows...

1. Say i have a Movie type with two state dependent Actions, CheckOut and CheckIn.

2. If the Movie is in a checked in state the CheckOut action is advertized but not the CheckIn action and vice versa.

3. Now query for some Movie in the checked in state and look at the available Actions on the movie by calling context.GetEntityDescriptor(movie).OperationDescriptors. Notice that the CheckOut Action is in the collection and the CheckIn action is not. This is as expected.

4. Now call the CheckOut action like this context.Execute(context.GetEntityDescriptor(movie).OperationDescriptors.Where(a => a.Title = "CheckOut").Single().Target, "POST").

5. The Movie is now in the checked out state on the server.

6. Refetch it on the client and inspect the result return from the server (using Fiddler) and verify that the CheckOut action is no longer advertized, but the CheckIn action is.

7. Now look at the context.GetEntityDescriptor(movie).OperationDescriptors for the movie. It still shows the CheckOut action as being present and not the CheckIn action. This is not as expected.

8. This wrong behaviour is independent of the MergeOption setting on the context.

Btw I am running on WCF DS 5.4.0.0

Kind regards

Uffe


Cannot add WCF Data Service Client reference

$
0
0
Using NuGet, I have just installed the latest WCF Data Service Server and Clients version 5.4.0.0.  I have cleaned and rebuilt my solution which includes a WCF Data Service named RapDataService.  When I try to add a Data Service Reference to RapDataService in my UI project, I get the error "Could not load file or assembly 'Microsoft.Data.Edm, Version=5.3.0.0", however both the Data Service project and the UI project are referencing version 5.4.0.0 which was installed using NuGet.  I have checked the properties of the references in both projects and they are indeed referencing 5.4.0.0.  I am at a loss as to why the service reference is trying to load version 5.3.0.0.

Al G.

How does asynchronous call get handled by service with multiple callers?

$
0
0

If I have a client app that is currently making a (synchronous) call to a wcf service method, and I change it to call it asynchronous, how will other requests get handled by the service?  I dont want the service to handle multiple requests at the same time...errr I guess I just answered my own question.  The requests will probably stack up in the request queue in IIS (wcf service hosted in IIS).

I suppose my question is - will making asynchronous calls to a wcf service, affect the way it handles calls from multiple client apps?

What does this error mean?

$
0
0

One of our customers is getting this error when using our system, which calls via the .NET OData layer, into their OData provider (which they created):

Message: A value without a type name was found and no expected type is available. When the model is specified, each value in the payload must have a type which can be either specified in the payload, explicitly by the caller or implicitly inferred from the parent value.

    Stack:               at Microsoft.Data.OData.ReaderValidationUtils.ResolveAndValidateTargetTypeWithNoExpectedType(EdmTypeKind expectedTypeKind, IEdmType payloadType, String payloadTypeName, SerializationTypeNameAnnotation& serializationTypeNameAnnotation)

                                               at Microsoft.Data.OData.ReaderValidationUtils.ResolveAndValidateNonPrimitiveTargetType(EdmTypeKind expectedTypeKind, IEdmTypeReference expectedTypeReference, EdmTypeKind payloadTypeKind, IEdmType payloadType, String payloadTypeName, IEdmModel model, ODataMessageReaderSettings messageReaderSettings, ODataVersion version, SerializationTypeNameAnnotation& serializationTypeNameAnnotation)

                                               at Microsoft.Data.OData.ReaderValidationUtils.ResolvePayloadTypeNameAndComputeTargetType(EdmTypeKind expectedTypeKind, IEdmType defaultPrimitivePayloadType, IEdmTypeReference expectedTypeReference, String payloadTypeName, IEdmModel model, ODataMessageReaderSettings messageReaderSettings, ODataVersion version, Func`1 typeKindFromPayloadFunc, EdmTypeKind& targetTypeKind, SerializationTypeNameAnnotation& serializationTypeNameAnnotation)

                                               at Microsoft.Data.OData.Atom.ODataAtomPropertyAndValueDeserializer.ReadNonEntityValueImplementation(IEdmTypeReference expectedTypeReference, DuplicatePropertyNamesChecker duplicatePropertyNamesChecker, CollectionWithoutExpectedTypeValidator collectionValidator, Boolean validateNullValue, Boolean epmPresent)

                                               at Microsoft.Data.OData.Atom.ODataAtomPropertyAndValueDeserializer.ReadProperty(IEdmTypeReference expectedPropertyTypeReference, ODataNullValueBehaviorKind nullValueReadBehaviorKind, Boolean epmPresent)

                                               at Microsoft.Data.OData.Atom.ODataAtomPropertyAndValueDeserializer.ReadTopLevelProperty(IEdmTypeReference expectedPropertyTypeReference)

                                               at Microsoft.Data.OData.Atom.ODataAtomInputContext.ReadProperty(IEdmTypeReference expectedPropertyTypeReference)

                                               at Microsoft.Data.OData.ODataMessageReader.<>c__DisplayClass18.<ReadProperty>b__17(ODataInputContext context)

                                               at Microsoft.Data.OData.ODataMessageReader.ReadFromInput[T](Func`2 readFunc, ODataPayloadKind[] payloadKinds)

                                               at Microsoft.Data.OData.ODataMessageReader.ReadProperty(IEdmTypeReference expectedPropertyTypeReference)

                                               at Microsoft.Data.OData.ODataMessageReader.ReadProperty()

Any ideas?

thanks - dave


Who will win The Windward International Collegiate Programming Championships?

Problem - ASP.NET MVC Ignores Metadata in WCF Data Service Reference

$
0
0

I'm using the database first approach with Entity Framework.

My ASP.NET MVC client ignores the metadata included in the service reference to a WCF Data Service. 

I can use partial classes and metadata tags to add metadata. I'd rather get ASP.NET MVC to honor the metadata that the service reference creates, i.e. the metadata in service.edmx file the service reference includes.

Does anyone know how to get ASP.NET MVC to honor the service reference metadata?

How do I configure IIS 7.5 to handle body from Apache with WCF REST service

$
0
0

I have a REST service in IIS 7.5 that is working properly with my calls, but when Apache sends a request, the body is discarded and the length is set to 0.

Web config:

  <system.web>    <compilation debug="true" targetFramework="4.0" />  </system.web>  <system.webServer>    <modules runAllManagedModulesForAllRequests="true">      <add name="UrlRoutingModule" type="System.Web.Routing.UrlRoutingModule, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />    </modules>  </system.webServer>  <system.serviceModel>    <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>    <standardEndpoints>      <webHttpEndpoint>        <!--             Configure the WCF REST service base address via the global.asax.cs file and the default endpoint             via the attributes on the <standardEndpoint> element below        -->        <standardEndpoint name="" helpEnabled="true" automaticFormatSelectionEnabled="true"/>      </webHttpEndpoint>    </standardEndpoints>  </system.serviceModel>

Service Description:

   

    [ServiceContract]    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]    [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]    publicclassMedherentRESTservice    {        #region Register User        [Description("Returns ACK msg using requested database: Staging, Demo or Production")]        [WebInvoke(UriTemplate = "RegisterUser", Method = "POST")]        publicstring RegisterUser(string hl7StringIn)

I am expecting the REST body to come in in the hl7StringIn variable and it does when I use the following call:

             
using (HttpClient proxy = newHttpClient("http://wwwstaging.carasolva.com/MedherentWCFRest/"))
            proxy.DefaultHeaders.Add("login_id""t");            proxy.DefaultHeaders.Add("passcode""p");            proxy.DefaultHeaders.Add("hl7TransactionHeader"Constants.MhRegisterUserRequestHeader);               var uri = "RegisterUser";            var c = Constants.MhRegisterUserRequestBody;            var content = HttpContentExtensions.CreateDataContract(c);            try            {                using (HttpResponseMessage response = proxy.Post(uri, content))                {                    response.EnsureStatusIsSuccessful();                    var responseText = response.Content.ReadAsString();                    Console.WriteLine(responseText);                }

WireShark shows me that a POST is made that includes only the header, with a continuation flag set. IIS sends the ACK and the continuation is sent (also as a POST), merged with the headers and passed into my service.

Here is the code on the Apache side:

HttpClient httpclient =  newDefaultHttpClient();     
ResponseHandler<String> responseHandler = newBasicResponseHandler();
String response = "";
HttpPost httppost = newHttpPost(request.getHost());                        
for(@SuppressWarnings("rawtypes") Header header : request.getHeaders()){
    httppost.setHeader(header.getKey(), header.getValue());
}
if(requestBody.length()>0){
      // append the body data to the post
      StringBuilder sb = newStringBuilder();
      sb.append(requestBody);
      StringEntity stringentity = newStringEntity(sb.toString(), HTTP.UTF_8);
      httppost.setEntity(stringentity);                             
}
// hit the server
response = httpclient.execute(httppost, responseHandler);
// clean up 
httppost = null;
return response;    

For completeness, the block:

if(requestBody.length()>0){
      // append the body data to the post
      StringBuilder sb = newStringBuilder();
      sb.append(requestBody);
      StringEntity stringentity = newStringEntity(sb.toString(), HTTP.UTF_8);
      httppost.setEntity(stringentity);                             
}

is getting executed.

The code is using the Apache HTTP stack:

import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;

import org.apache.http.protocol.HTTP;

Wireshark is showing only one POST with a body length = 0;

I hope this is enough information for someone to help.

According to the developer using Apache, he can send his request to IIS 6 and the body is there.


Scott Simpson





WCF Data Services and EF5 auto-compiled query support with parameterized query

$
0
0

Hi,

EF5 introduced auto-compiled query, this feature dramatically improve performance of Entity Framework.

When we use WCF Data Service over an EF5 context, we automatically benefit from this feature. However it is possible to improve the way WCF Data Service build it expression tree to better use the auto-compiled query feature.

Imagine we have the following query :

http://localhost/WebApplication6/DataService.svc/Products(1)

WCF Data Service will translate it to the following expression tree :

.Call System.Linq.Queryable.Where(
    .Constant<System.Linq.EnumerableQuery`1[WebApplication6.Product]>(WebApplication6.Product[]),
    '(.Lambda #Lambda1<System.Func`2[WebApplication6.Product,System.Boolean]>))

.Lambda #Lambda1<System.Func`2[WebApplication6.Product,System.Boolean]>(WebApplication6.Product $element) {
    $element.ProductId == 1
}

This expression tree will be compiled by EF5 (great!).
However, if we query for another productId, WCF Data Service will generate a new expression tree (the only difference will be the constant value). When EF5 will verify if it has already compiled this expression tree, it won't find it and think that this expression is a new one, so it will compiled this new expression tree.

  => Each time we query for a new ProductId, EF5 will compiled a new expression tree (and cache it) :(

EF5 can compiled these expression trees once if they used a ParameterExpressioninstead of ConstantExpression.

Does the WCF Data Services team has planned to used ParameterExpression instead ofConstantExpression ? If no, pleased could you planned it ?I think it will boost a lot of WCF Data Services Scenario :-)

By the way, I think it should be possible to use an ExpressionVisitor to rewrite the query and use parameterExpression instead of ConstantExpression. I didn't try it yet.

Thanks,

Cyril DURAND 




How to implement EF Code First and WCFDataService

$
0
0

A bit of history first.  I created a EF Code First Library that contains POCO Objects as my Models, a generic DataProvider that inherits from DbContext, generic Repostory that implements the generic DataProvider, and a generic Service that implements the repository.  I have used this library successfully in WPF (MVVM), ASP.Net, Window Forms, and ASP MVC applications.

For this discussion I will reference the Company Model

From the top down, I create a Service class called CompanyService that inherits from a base Service Class.  The CompanyService class contains all of the business logic for the Company Model.  This class uses the Repository class to perform the CRUD operations.  The Repository then encapsulates all the DataProvider class operations.

I have done some research on using EF with WCFDataService, but I can't get my head around how to implement my library with it, particulary when it comes to overriding the CreateDataSource() Method. 

It may be that I should just use a WCF Service instead, maybe I'm not understanding the purpose of the WCFDataService.

I have listed partial code for the classes involved:

	public class CompanyService : ServiceBase<Company> ,ICompanyService
    {
        public Company GetCompanyByFolderId(string eFolderId)
        {
            return (Company)GetModelByFolderId(eFolderId);
        }
	}
    public abstract class ServiceBase<TModel> : IService<TModel> where TModel : class, IModel
    {
        private IDataProvider _dataProvider;
        public IDataProvider DataProvider
        {
            get
            {
                if (_dataProvider == null)
                {
                    string connectionStringName = Properties.Settings.Default.DataProvider;
                    bool enableLazyLoading = true;
                    _dataProvider = new DataProvider(connectionStringName, enableLazyLoading);
                }
                return _dataProvider;
            }
            set
            {
                _dataProvider = value;
            }
        }
        private IRepository<TModel> _repository;
        public IRepository<TModel> Repository
        {
            get
            {
                if (_repository == null)
                {
                    _repository = new Repository<TModel>(DataProvider);
                }
                return _repository;
            }
            set
            {
                _repository = value;
            }
        }
        public TModel GetModelByFolderId(String folderId)
        {
            return GetTable().FirstOrDefault(o => o.EFolderid == folderId);
        }
        public virtual IQueryable<TModel> GetTable()
        {
            return Repository.GetTable();
        }
	}
    public class Repository<TModel> : IRepository<TModel> where TModel : class, IModel
    {
        private IDataProvider _dataProvider;
        public Repository(IDataProvider dataProvider)
        {
            _dataProvider = dataProvider;
        }
        private IDbSet<TModel> DbSet
        {
            get
            {
                return _dataProvider.Set<TModel>();
            }
        }
		public IQueryable<TModel> GetTable()
        {
            return _dataProvider.GetTable<TModel>();
        }
	}
	public class DataProvider : DbContext, IDataProvider 
    {
        public DataProvider()
        {
        }
        public DataProvider(string connectionStringName, bool enableLazyLoading = true)
            : base(connectionStringName)
        {
            Configuration.LazyLoadingEnabled = enableLazyLoading;
            //Configuration.ProxyCreationEnabled = false;
        }
        public new IDbSet<TModel> Set<TModel>() where TModel : class
        {
            return base.Set<TModel>();
        }
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Configurations.Add(new CompanyMapping());
            base.OnModelCreating(modelBuilder);
        }
        public IQueryable<TModel> GetTable<TModel>() where TModel : class
        {
            return Set<TModel>().AsQueryable();
        }
	}

Then my Test looks something like this:

[TestClass()]
    public class CompanyServiceTest
    {
        [TestMethod()]
        public void GetCompanies()
        {
            CompanyService target = new CompanyService();
            IQueryable<Company> companies = target.GetTable();
            Assert.IsNotNull(companies);
        }
        [TestMethod()]
        public void GetCompanyByFolderId()
        {
            CompanyService target = new CompanyService();
            Company company = target.GetCompanyByFolderId("0000000000000000000000000172403");
            Assert.IsNotNull(company);
        }
	}


Bill Behning

WCF Self-Hosted Data Services with CORS and Basic Auth support

$
0
0

I'm building a WCF Self-Hosted Data Service (OData, by the way) and I'm using Basic Authentication to authenticate users. It wasn't very hard, I just needed some configuration steps, build a UserNamePasswordValidator and a IAuthorizationPolicy - DONE.

Now I need to support CORS (Cross-Origin Resource Sharing). I've tried many implementations, some documented (for instance, this), other made by myself.

The problem is, if I let Basic Auth enabled, because the CORS preflight request (OPTIONS) doesn't have the 'Authorization' header, and I can't manipulate the request (of course, or that would defeat the purpose for the browser to do it), I'm unable to intercept/respond the request on the server. I can't even check how far does it go! I've tried to implement many Behaviours, Bindings, Managers, etc., but I can't catch that request, not even on "DataService<>.OnStartProcessingRequest()".

If I disable Basic Auth on the server side, I'm able to catch the CORS preflight request and eventually respond to it (using a IDispatchMessageInspector and a BehaviorExtensionElement), but that way I have to implement Basic Auth on my own... damn.

Please help me. How do I support both? How can I intercept the CORS preflight request before Basic Auth simply respond 401 Unauthorized?

JSON.NET convert object but not data.

$
0
0

I have a WCF/REST service returning JSON and I am using JSON.NET to deserialize back to the native object. It does that just fine but the data that is return from the REST call is wiped out after deserialization. Here is the code:

WebClient webClient = new WebClient();
String utf8 = DownloadString(webClient, url, Encoding.UTF8);
var list = JsonConvert.DeserializeObject<MyClass>(utf8);

I don't get what is happening.

Implementing WCF Data Service without Entity Framework

$
0
0

Hi,

  I would like to know if there is a way to implement WCF Data Services exposing data from SQL Server without using Entity Framework. I did some search on the internet and most samples seem to suggest that we have load the entire data in memory. 

Thanks

 

 

Data service caching issue

$
0
0
Hi

In my VS solution,  I have two projects, one is a Silverlight5 app and the other is a WCF Services app. My Silverlight5 app is hosted on a page in the WCF Services app. In the service app, I added a ADO.NET Entity Data Model, and a WCF data service that maps to this data model. I reference the data service in my Silverlight5 app. This works and I can also query and update my database from the Silverlight5 app using the data service.

The problem that I have is in the Silverlight5 app. For example I have a UserControl called Customers which allows users to add/edit/delete customer records and another called OrdersReports which allows users to select a Customer record from a drop down and then list the orders for that particular customer in a DataGrid below. If the count of orders is zero, it displays "No order to display". In the background of the two user controls, I instantiate a variable _dataService which creates an instance of the data service reference allowing me to communicate with the data service. The user clicks the option to edit customers and loads the Customers UserControl. Data service is instantiated and the user can add, edit and delete records as intended. For example, if the user adds or edits a customer record at that point, everything is saved in the database perfectly. When the user clicks the option for the OrdersReport UserControl, this loads and the data service client is intantiated. The code loads a Customer data service collection with all customer data (to display in drop down) and expands on the Orders node to also bring in the list of orders per customer (to display in data grid). In this case, customers without orders are also retrieved and their Orders property is a empty collection. My problem is that if the user had just added or edited a customer record in the Customers UserControl and even saved these changes, when the OrdersReport UserControl loads, the new or edited customer record is not listed. If I close the app and reopen, then the new and changes are listed.

I would like to find out what is causing this and what is the best method to solve it. Someone has recommended that I instantiate my data service client at the application level and then use it for data service operations everywhere in my app. For sure that works, but this is not efficient because I do not need data service operations everywhere in my app and to leave that object there instantiated when I do not need it is against every rule of good and efficient programming. I think that I am dealing with a cache issue here because the Customers do get saved to the database, but data service calls in OrdersReport seem to be retrieving its data from a cache somewhere. How do I get it to read from the database all the time?

Regards

Terence

UseJson and IgnoreMissingProperties

$
0
0

I am using the new WCF DataServices 5.1 and trying to convert my client app from Atom to JsonLight but I am having some problems with the datacontext setting IgnoreMissingProperties. This is quite important because I want to avoid a substantional rewrite of my code.

I have one of many generated client entity object which has a custom property marked with a special attribute. This property is not defined in the EDM. Previously I intercepted the serialization of the entity using the datacontext WritingEntity callback and filtered out the custom property to avoid getting errors when writing data.

When I try to set the context.Format.UseJson() then I can read data from the server without problems but when posting changes to the server for the client entity object I get the exception below. The strange thing is as far as I can see in the code for ReadUndeclaredProperty it is only supposed to throw an exception if the flag IgnoreUndeclaredValueProperty is not set.

From ODataJsonLightEntryAndFeedDeserializer

if (!base.MessageReaderSettings.UndeclaredPropertyBehaviorKinds.HasFlag(ODataUndeclaredPropertyBehaviorKinds.IgnoreUndeclaredValueProperty))
            {
                throw new ODataException(Microsoft.Data.OData.Strings.ValidationUtils_PropertyDoesNotExistOnType(propertyName, entryState.EntityType.ODataFullName()));
            }

Here is the exception

System.Data.Services.Client.DataServiceRequestException: An error occurred while processing this request.
---> System.Data.Services.Client.DataServiceClientException: {"odata.error":{"code":"","message":{"lang":"nb-NO","value":"An error occurred while processing this request."},
"innererror":{"message":"The property 'Name' does not exist on type 'Baze.DataEngine.DataModel.BazeInputAdapter'.
Make sure to only use property names that are defined by the type.","type":"Microsoft.Data.OData.ODataException","stacktrace":"   
at Microsoft.Data.OData.JsonLight.ODataJsonLightEntryAndFeedDeserializer.ReadUndeclaredProperty(IODataJsonLightReaderEntryState entryState, String propertyName, Boolean propertyWithValue)\r\n   
at Microsoft.Data.OData.JsonLight.ODataJsonLightEntryAndFeedDeserializer.ReadEntryPropertyWithValue(IODataJsonLightReaderEntryState entryState, String propertyName)\r\n   
at Microsoft.Data.OData.JsonLight.ODataJsonLightEntryAndFeedDeserializer.ReadEntryContent(IODataJsonLightReaderEntryState entryState)\r\n   
at Microsoft.Data.OData.JsonLight.ODataJsonLightReader.ReadAtEntryStartImplementationSynchronously()\r\n   
at Microsoft.Data.OData.JsonLight.ODataJsonLightReader.ReadAtEntryStartImplementation()\r\n   
at Microsoft.Data.OData.ODataReaderCore.ReadImplementation()\r\n   
at Microsoft.Data.OData.ODataReaderCore.ReadSynchronously()\r\n   
at Microsoft.Data.OData.ODataReaderCore.InterceptException[T](Func`1 action)\r\n   
at Microsoft.Data.OData.ODataReaderCore.Read()\r\n   
at System.Data.Services.Serializers.EntityDeserializer.ReadEntry(ODataReader odataReader, SegmentInfo topLevelSegmentInfo)\r\n   
at System.Data.Services.Serializers.EntityDeserializer.Read(SegmentInfo segmentInfo)\r\n   
at System.Data.Services.Serializers.ODataMessageReaderDeserializer.Deserialize(SegmentInfo segmentInfo)"}}}
   --- End of inner exception stack trace ---
   at System.Data.Services.Client.SaveResult.HandleResponse()
   at System.Data.Services.Client.BaseSaveResult.EndRequest()
   at System.Data.Services.Client.DataServiceContext.SaveChanges(SaveChangesOptions options)
   at System.Data.Services.Client.DataServiceContext.SaveChanges()
   at Baze.DataEngine.Manager.AdapterForms.ManageNodeForm.btnOK_Click(Object sender, EventArgs e) in C:\Baze.DataEngine\Branches\DataEngine_3.0\Services\DataEngine\Source\Management\Imatis.DataEngine.Manager\AdapterForms\ManageNodeForm.cs:line 79

EF5 service with context derived from DbContext

$
0
0

Okay,  so I'm using entity framework 5.0 and a WCF data service.  I am a little confused because some people are saying that Entity Framework with WCF data services will work out of the box even for database updates and not just reads, I read elsewhere that WCF database services with regular ADO .NET does not do data base update operations out of the box but for Entity Framework they do, but from my understanding of a blog by Rowan Miller about Entity Framework and WCF data services, you need to tweak some things to get it to work if your context derives from DbContext, which mine does.  When I try to do this:

public ObjectContext UnderlyingContext

{ get { return this.ObjectContext; } }

there is no "ObjectContext" in this for my context that derives from DbContext.

Well, I admit I don't have a thorough understanding of what is going on here, that's why I'm asking. Rowen Miller's post is also for CTP4 and I'm using 5.0.

I just want to be able to use my EF 5.0 WCF data servce (custom class deriving from DataService) and be able to do database updates, but I'm unable to get updates to work, only reads.  And my update and savechanges syntax is 100% correct, so I'm thinking that that means that I will have to do some kind of tweak like Miller, except for EF 5.0.

Now I admit possibly the fact that my updates aren't working doesn't have anything to do with the idea that EF and WCF can't do updates out of the box, but that's just a coincidence that mine's not working but I will still have to do a tweak, or maybe I just have a bug or both.

If anyone could help, that would be great.  I will mark any answer as answer.


Change tracking issues with WCF Data Services

$
0
0

So I'll admit I'm not in love with the design of this, but I've inherited a problem. I have a wpf application that uses wcf data services as a portion of it's service tier. For a reason unknown to me, they decided to not allow the context to manage change tracking and they do it themselves. So needless to say, everytime they want to update an entity, they do something like this:

Context.AttachTo(entitySetName, entity);

Context.UpdateObject(entity);

Context.SaveChanges();

It's all base classed out very nicely and is loosely coupled, the problem is, it doesn't always work. For instance, if I have say a bank entity, and I change it's phone number and click save this works once beautifully. The changes are pushed to the db and everything is happy. But, if I change that phone number again and click save, it errors out on the attachTo method with a good old:

"The context is already tracking a different entity with the same resource Uri"

Every call to save the entity after the first error gives me this message. This made sense, I just assumed that the entity was there, it was very unhappy about me trying to feed that entity to it again, and I should prevent that. So, with a little research I found this method:

var descriptor = Context.GetEntityDescriptor(entity);
 

Which should give me a bit of information about the state of that entity for the given context. Yet, for both call 1 (which works) and call 2 (which fails with the tracking error), that method returns null. Which according to the documentation means it's not in the context. So I'm at a spot where the context won't let me attach the entity because it believes it has it, yet if I ask it if it's there it tells me no.

Any suggestions would be greatly appreciated!

Thanks everyone,

Ryan

WCF Data Services 5 Authentication with datajs

$
0
0

I have an WCF Data Service in .NET and I am consuming this service with datajs in Phonegap. I am trying to implement authentication as decribed here:http://goo.gl/0xQvC, and sending credentials with OData.read method (datajs), but when I read credentials with HttpContext.Current.Request.Headers["Authorization"], I found they are empty. What I am doing wrong?

Service Code:

[ServiceBehavior( IncludeExceptionDetailInFaults = true )]
    public class TeyunaDataService : DataService< Meteora.TeyunaServices.Models.TeyunaContext >
    {
        public static void InitializeService(DataServiceConfiguration config)
        {
            config.SetEntitySetAccessRule("Clientes", EntitySetRights.AllRead );
            config.SetEntitySetAccessRule("Transacciones", EntitySetRights.All);

            config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2;
            config.UseVerboseErrors = true;
        }

        public TeyunaDataService()
        {
            this.ProcessingPipeline.ProcessingRequest += new EventHandler<DataServiceProcessingPipelineEventArgs>(OnRequest);
        }

        void OnRequest(object sender, DataServiceProcessingPipelineEventArgs e)
        {
            var auth = HttpContext.Current.Request.Headers["Authorization"]; //This is empty
        }
    }
}

Javascript Client code:

OData.read({ requestUri: url, user: "pruebausr", password: "passprb" },    
    function (data, request) {
        // ... code to procesing data (It works fine)

    },  function(err) {
            $.mobile.hidePageLoadingMsg();
            alert("Error al obtener clientes. " + err.message);
    }
);

Service web.config here: https://gist.github.com/3746043

I am using IIS Express.


El servidor remoto devolvió una respuesta inesperada: (413) Request Entity Too Large.

$
0
0
Buenas noches me encuentro con el siguiente error al tratar de guardar o modificar (El servidor remoto devolvió una respuesta inesperada: (413) Request Entity Too Large) soy nuevo en esto y le agradecería a quien pudiera ayudarme.

Stone test qa.social.msdn.microsoft.com

How do I tell my service (all calls REST/JSON) to handle OPTIONS requests?

$
0
0

Hi;

I have written a WCF service to return JSON on REST requests. Works great with a browser hitting it. But when my JavaScript hits it, the first request is an OPTIONS request for the url with "Access-Control-Request-Method: GET".

What do I need to do so the service will respond appropriately when asked if a GET can be requested on a url?

thanks - dave


Who will win The Windward International Collegiate Programming Championships?

Viewing all 877 articles
Browse latest View live