Giter Site home page Giter Site logo

unchase / unchase.odata.connectedservice Goto Github PK

View Code? Open in Web Editor NEW
43.0 4.0 12.0 8.03 MB

:scroll: A Visual Studio extension for connecting to OData services with generating client-side C# proxy-classes

License: Apache License 2.0

C# 96.77% PowerShell 3.23%
odata-service visual-studio proxy odata-client odata-codegen visual-studio-extension vsix vsix-extensions scaffolding

unchase.odata.connectedservice's Introduction

Unchase OData (Swagger) Connected Service Logo

Unchase OData Connected Service is a Visual Studio extension to generate C# or VB client code for OData web service.

Starting from Visual Studio Community 2019 v16.1.3 extensions based on Microsoft Connected Services now work fine.

Getting Started

Install from Tools -> Extensions and Updates menu inside Visual Studio (including 2019) or download as VSIX package from VSGallery or download as VSIX package from Visual Studio Marketplace:

Adding Unchase OData Connected Service in Visual Studio

The project is developed and maintained by Nikolay Chebotov (Unchase).

Builds status

Status Value
Build Build status
Buid History Build history
GitHub Release GitHub release
GitHub Release Date GitHub Release Date
GitHub Release Downloads Github Releases
VS Marketplace VS Marketplace
VS Marketplace Downloads VS Marketplace Downloads
VS Marketplace Installs VS Marketplace Installs

Features

  • Generate C# and VB clients/proxies (client code) from OData specifications for OData protocol versions 1.0-4.0
  • Support for emitting dynamic properties on open types for OData protocol version 4.0
  • Support selection OperationImports (Actions and FunctionImports) that will be generated for OData protocol versions 1.0-4.0
  • Support loading client code generation parameters from json files (including Connected Service .json from OData Connected Service by Microsoft)
  • Generate C# proxy-class extension methods for OData protocol versions 1.0-3.0
  • Generate functions to call service methods from OData protocol versions 1.0-3.0 FunctionImports or from OData protocol version 4.0 OperationImports
    • You can select the necessary methods that will be added after generation for OData protocol versions 1.0-4.0
  • Add required dependencies for the C# client (before generating):
    • Libraries for OData v3 Client:
      1. Microsoft.Data.Services.Client (NuGet)
      2. Microsoft.Data.OData (NuGet)
      3. Microsoft.Data.Edm (NuGet)
      4. System.Spatial (NuGet)
      5. In additional: System.ValueTuple (NuGet)
    • Libraries for OData v4 Client:
      1. Microsoft.OData.Client (NuGet)
      2. Microsoft.OData.Core (NuGet)
      3. Microsoft.OData.Edm (NuGet)
      4. Microsoft.Spatial (NuGet)
  • Storage of the last 10 endpoints (json-specification path)

Features are supported since v1.0.0

Generation VB client code for OData protocol versions 1.0-4.0

Unchase OData Connected Service VisualBasic

Features are supported since v1.2.0

Selection FunctionImports that will be generated for OData protocol versions 1.0-4.0

Unchase OData Connected Service FunctionImports

Features are supported since v1.3.0

Loading client code generation parameters from json files (including Connected Service .json from OData Connected Service by Microsoft)

Unchase OData Connected Service Load Parameters

HowTos

Troubleshooting

Installation completes but I can't see the Service in the list of connected services (Visual Studio 2019)

Roadmap

See the changelog for the further development plans and version history.

Feedback

Please feel free to add your review, request a feature, ask a question or report a bug including in connected service:

Unchase OData Connected Service Report a Bug

Thank you in advance!

Thank me!

If you like what I am doing and you would like to thank me, please consider:

Buy me a coffe!

Thank you for your support!


Copyright © 2019 Nikolay Chebotov (Unchase) - Provided under the Apache License 2.0.

unchase.odata.connectedservice's People

Contributors

chrisschaller avatar unchase avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

unchase.odata.connectedservice's Issues

C# OData MS Business Central - Add child record belonging to a parent

I'm trying to add a Business Central [Sales Line] child record to a [Sales Header] parent invoice record in a C# OData program using an Unchase Connected Service. I know the header record exists because the program has just created it & I can see it in BC, but when I try to add the child record using the binding tablerelation Document No: 102206 I get an error (see below) that indicates it can't see the header record. I've tried synchronous and asynchronous methods; same failure. In both tables the tablerelation field is Code[20]. Same data type.

Error: The field Document No. of table Sales Line contains a value (102206) that cannot be found in the related table (Sales Header).

This doesn't make any sense. Any thoughts?

Sample code:-

ReferenceBC.NAV.APISalesLine lobjUSL = ReferenceBC.NAV.APISalesLine.CreateAPISalesLine("Invoice", "102206", 10000);

// lobjPSL is a Sales Invoice Line object (Posted)
// lobjUSL is a Sales Invoice Line object (Unposted)
// gobjDSC is the DataServiceContext object in the Unchase connected service

// populate properties
lobjUSL.Property1 = lobjPSL.Property1;
lobjUSL.Property2 = lobjPSL.Property2;
// etc...

gobjDSC.AddToAPISalesLine(lobjUSL);
gobjDSC.SaveChanges(SaveChangesOptions.None); // Error shown above

FEATURE: HMAC

Is there a possibility to use HMAC with this plugin?

Getting IDIctionary to Dictionary error when upgraded to 1.4.1.0

Error listed below from the generated proxy after the upgrade

Error CS1503 Argument 2: cannot convert from 'System.Collections.Generic.IDictionary<string, object>' to 'System.Collections.Generic.Dictionary<string, object>' C:...\Connected Services\TestService\Reference.cs

Sample code that is no longer working...
public static global::Test.Service.Models.TestObjectSingle ByKey(this global::Microsoft.OData.Client.DataServiceQuery<global::Test.Service.Models.TestObject> _source, global::System.Collections.Generic.IDictionary<string, object> keys) { return new global::Test.Service.Models.TestObjectSingle(_source.Context, _source.GetKeyPath(global::Microsoft.OData.Client.Serializer.GetKeyString(_source.Context, keys))); }

Where "keys" is causing the error.

BUG: Request.Method and Request.HttpWebRequest.Method are different

When deleting a Entity and then calling SaveChanges i noticed that the server returned an error. While investigating with wireshark i discovered that the HTTP method was set to POST instead of delete. I debugged the values in the event SendingRequest2.

The screenshot below demonstrates the bug where ActualMehtod is POST and the method is DELETE (which is the right one):
Annotation 2020-01-08 155514

There is a simple fix bij adding this line to the SendingRequest2 Event:

Private Sub WebCon_SendingRequest2(sender As Object, e As SendingRequest2EventArgs)
        Dim request As HttpWebRequestMessage = CType(e.RequestMessage, HttpWebRequestMessage)
        request.HttpWebRequest.Method = request.Method ' This fixes the bug
End Sub

DTD Prohibited When Creating (or Updating) a Service

Describe the bug

Have a WCF Entity Framework OData service which was successfully connected to by the client using the wizard. The initial service was implemented with no security which is being re-programmed to support basic security using message interception. In client, when attempting to initially update the connection encountered "DTD is prohibited in the XML Document." Subsequently attempting to create a new connect to encounter the same error.

Assemblies affected

Unknown

Steps to reproduce

  1. Complete required fields and options
  2. Select Finish

Expected result

Update of model

Actual result

Error message encountered

Screenshots

2019-09-29 212110

Additional detail

Assuming from error message that the XMLReader in the wizard needs to have an option enabled for DTD processing to read the response from the service.

Create entities as separate classes for reverse scaffolding

Hello,

I am a test automation analyst trying to build a framework for the Australian Department of Human Services to test OData which is exposing SAP entities and resources. I found this very useful to auto generate classes from metadata. As I am only testing this not consuming in the traditional sense I need to simulate the user input through simulation and I am having to maintain the database tables for the entities to store the input data. I have seen example where a class in the visual studio C# can be scaffold to create a table in the connected SQL server. Is this possible at all.

Problem with navigation property in complex type

I'm trying to consume an OData service and the code generation worked just fine.
However, when I execute a query I get the following error:
The property 'X' is of entity type and it cannot be a property of the type 'Y', which is not of entity type. Only entity types can contain navigation properties.

I checked the definition and there is a complex type, which has a navigation property to an entity type. As the message states this is not supported.

However, according to the following link, it should be supported in OData Core Lib V7: https://docs.microsoft.com/en-us/odata/odatalib/navigation-under-complex
I'm not sure though, if that version maps to the dlls used by the generated connected service:
Microsoft.OData.Client 7.6.3
Microsoft.OData.Core 7.6.3
Microsoft.OData.Edm 7.6.3
etc.

I don't control the service I'm consuming, so I can't change that.
Does anyone know if it's possible to get this to work?

Question: DataServiceQuery vs DataServiceCollection

Quick question: I use the autogenerate Client code for VB.net i noticed that in v4 i have difficulties updating a object. i get the exception No routing convention was found to select an action for the OData path with template '~/entityset/key'. I back traced this due to the fact that on SaveChanges the method PUT is passed while the backend expects PATCH instead. In OData v3 you had this option SaveChangesOptions.PatchOnUpdate but that's gone in v4. So i dived in deeper and noticed then when i change it to DataServiceCollection instead of DataServiceQuery the PUT/PATCH method seems to be correct.

So i was wondering why it is a DataServiceQuery instead of DataServiceCollection generated?

My knowledge about OData isn't expert so hopefully you could explain it in simple words :-)

In the meantime i'm using this dirty workarround to get it working:
If request.Method = Method.PUT.ToString Then request.Method = Method.PATCH.ToString

QUESTION: How to use $Expand on POST reqeusts

So OData is still new to me and i figure out by calling $Expand on a GET request i can retrieve objects and collections. However i then whant to change/update them and POST it back but it seems that when calling .SaveChanges it isn't serialized?

Is it possible to generate the template and add it to the project?

Describe the bug

A clear and concise description of what the bug is.
Hi Nickolay,

Have an issue with generating template. Using VS 2019 Community Version 16.1.1

Trying to replicate:
https://docs.microsoft.com/en-us/aspnet/web-api/overview/odata-support-in-aspnet-web-api/odata-v4/create-an-odata-v4-client-app
Using your .gif file as a sample
Everything works when i don't add the code template.

But getting errors when try to check "Add code templates...:
In your image after you check it you choose from the drop down ...
But when i check it (place the check mark) i don't see any drop downs to appear...
As the result I'm getting an error and nothing is generated.

Is it possible to generate the template and add it to the project?

Please suggest

Thank you, Elena

Assemblies affected

Which assemblies and versions are known to be affected?

Steps to reproduce

The simplest set of steps to reproduce the issue. If possible, reference a commit that demonstrates the issue:

  1. Go to '...'
  2. Click on '....'
  3. Scroll down to '....'
  4. See error
    ...

Expected result

A clear and concise description of what you expected to happen.
What would happen if there wasn't a bug.

Actual result

What is actually happening.

Screenshots

If applicable, add screenshots to help explain your problem.

Additional detail

Add any other context about the problem here.
Optional, details of the root cause if known.

FEATURE: Bearer Token

I see the ability to add network credentials but would be great if there was an option to add header for bearer token, or let me know if it is capable and I just missed it.

The value can't be evaluated into type Time.

So, I have a datetime column called [Starting Time] in an SQL Server Dynamics NAV (On-Prem) database. It appears to have a default value of '1753-01-01 00:00:00.000'. If a time is assigned to the field in Business Central the date part in the database advances one year (e.g.) '1754-01-01 15:07:27.007'

I've created an AL Extension in VS Code containing an API Page in which one of the fields defined is the aforementioned [Starting Time] (see below):
field(StartingTime; "Starting Time") { }
When I hover the mouse cursor over this field in VS Code it reports: '(field) "Starting Time": Time'

I've then downloaded the XML metadata from Dynamics NAV (see section below). Notice, it has defined the field as "Edm.String" ?

<Property Name=""StartingTime"" Type=""Edm.String"">
<Annotation Term=""NAV.LabelId"" String=""StartingTime"" />
<Annotation Term=""NAV.NavType"">
NAV.NavType/String

I've then create an Unchase OData connected service in a C# .NET Core 2.2 Web App in Visual Studio 2019.
See auto-generated code below:-

///


/// There are no comments for Property StartingTime in the schema.
///

[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "2.6.0")]
public string StartingTime
{
get
{
return this._StartingTime;
}
set
{
this.OnStartingTimeChanging(value);
this._StartingTime = value;
this.OnStartingTimeChanged();
}
}
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "2.6.0")]
private string _StartingTime;
partial void OnStartingTimeChanging(string value);
partial void OnStartingTimeChanged();

I have a Razor View as below, which displays a nice TimePicker control:-
@Html.EditorFor(model => Model.ServiceHeader.StartingTime, new { htmlAttributes = new { @Class = "form-control", @type = "time" } })

The value chosen is returned to the Controller (e.g.) "01:00".

I populate the relevant object's properties and call the functions below to update the database via the OData interface:-

_context.AttachTo("API_Service_Header", lobjSH, "*");
_context.UpdateObject(lobjSH);
await _context.SaveChangesAsync(SaveChangesOptions.None);

... And I get the following error:-
{"error":{"code":"Application_EvaluateException","message":"The value "1754-01-01 01:00:00" can't be evaluated into type Time."}}

By the way I've tried formatting the value as just a time (e.g.) "01:00" and I've tried formatting it as full datetime (e.g.) "1754-01-01 01:00:00" - Same error.

Any help would be greatly appreciated?

Update of Services causes problem when having more than one Endpoint

If you have a Project with more than one ConnectedService it seems not to be possible to update the proxies after Generation so that the Right endpoint is taken for update. The wizard Always only suggests the last created Service. Also custom namespaces seem to be set to Default after reopening the visualstudio.
With this fixed your addin would be extremely useful because it supports entering of user credentials which the Microsoft one does not.

CS8103 Combined length of user strings used by the program exceeds allowed limit because of embedded Edmx

Edmx included in Reference.cs could be very big, which generates the following error while compiing

Severity Code Description Project File Line Suppression State
Error CS8103 Combined length of user strings used by the program exceeds allowed limit. Try to decrease use of string literals. PROJECTXXXX PATHYYYY 1 Active

        private abstract class GeneratedEdmModel {
          private const string Edmx = @"....";
  }

An option is to include the metadata file in the project as content

How to invoke methods that use Contained entities?

Describe the bug

The generated client worked perfectly, except for one use case we have in our project. Please, take a look to the PricesController.

There is the root entity Price and the child entity PriceValue. PriceValue is set as [Contained] inside Price and we have the following methods. GetValores and PostToValores that deal with PriceValue.

image

The problem is that I don't know how to invoke this method using the client.

For example, using Postman, I can invoke the GetValores method by requesting HTTP GET: https://localhost:44326/odata/Prices(2)/Values

Assemblies affected

Latest available version

More info

I've attached the metadata of my service inside a .zip file
$metadata.zip

Use from VS Code

Once configured in Visual Studio 2019 , connected to Microsoft Dynamics 365 CRM Odata metadata endpoint.
I need to be able to call your .exe from command prompt and use Visual Studio Code for further development. Please explain in docs how this can be achieved.

Blazor support

is this going to support async issues with new stack such as Blazor, etc.?

More details can be found here

Creating Unchase OData V1-V4 Connected Service (Unauthorized)

somewhere between
[11.04.2019 17:43:49.073] Generating Client Proxy extensions class for OData V3...
[11.04.2019 17:43:50.147] Error: Remote host ...... : (401) Unauthorized..
[11.04.2019 17:43:51.786] Client Proxy extensions class for OData V3 was generated.

This happens only with checked
Generate OData methods from FunctionImports.

Adding Unchase OData Connected Service to the project failed

i got this error when i was tried to connect CRM Dynamics 365 Metadata link:

Failed to access the metadata document. The OData service requires authentication for accessing it. Please download the metadata, store it into a local file, and set the value of “MetadataDocumentUri” in the .odata.config file to the file path. After that, run custom tool again to generate the OData Client code

Member names cannot be the same as their enclosing type.

Describe the bug

Thanks for this awesome connected service. and i use this connected service in vs2017 to generate the service proxy files for sap success factor's odata api. but i met the issues below:

Error:Adding Unchase OData Connected Service to the project failed: Schema specified is not valid. Errors:
(0,0) : error 0042: Name cust_SalaryTemplate cannot be used in type SFOData.cust_SalaryTemplate. Member names cannot be the same as their enclosing type.
(0,0) : error 0042: Name cust_Dependents cannot be used in type SFOData.cust_Dependents. Member names cannot be the same as their enclosing type.
(0,0) : error 0042: Name cust_PaySlip cannot be used in type SFOData.cust_PaySlip. Member names cannot be the same as their enclosing type.
(0,0) : error 0042: Name cust_TrainingTotal cannot be used in type SFOData.cust_TrainingTotal. Member names cannot be the same as their enclosing type.
(0,0) : error 0042: Name cust_ContractSalary cannot be used in type SFOData.cust_ContractSalary. Member names cannot be the same as their enclosing type.

Assemblies affected

Which assemblies and versions are known to be affected?
vs2017.

Steps to reproduce

as normal steps.

Expected result

A clear and concise description of what you expected to happen.
What would happen if there wasn't a bug.

Actual result

What is actually happening.

Screenshots

If applicable, add screenshots to help explain your problem.

Additional detail

Add any other context about the problem here.
Optional, details of the root cause if known.

OData-Functions are generated wrong for VB.NET (ODataT4CodeGenerator)

OData-Functions are wrong generated for VB.NET. You need to remove the slash before function name.

You need to change those lines (Remove / ) and then it will works right. (C#-Code is generated fine)

Line 6874 in ODataT4CodeGenerator.cs

this.Write(")\r\n            Return Me.CreateFunctionQuery(Of ");
this.Write(this.ToStringHelper.ToStringWithCulture(returnTypeName));
this.Write(")(\"\", \"");

Line 6935 in ODataT4CodeGenerator.cs

this.Write("Me.CreateFunctionQuerySingle(");
this.Write(this.ToStringHelper.ToStringWithCulture("Of " + returnTypeName));
this.Write(")(\"\", \"");

Resource not found for the segment

I've create an API Page called APISP3 in a VSCode AL Extension. The SourceTable is "Sales Price". I've deployed to Business Central and I've added a web service for the aforementioned API Page. I've downloaded the metadata. Now I'm trying to perform CRUD operations in a C# program via an Unchase OData Connected service. I'm reading records OK. I can add a new record OK, but when I try to perform an update I'm getting: "Resource not found for the segment 'APISP3'" when I call context.SaveChanges. The relevant part of my code is below. Any help would be greatly appreciated.
decimal newValue = 65;
Gulf.NAV.APISP3 gobjRecToUpdate = null;
var qryAllSPs = from lobjSP in objContext.APISP3 select lobjSP;
DataServiceCollection<Gulf.NAV.APISP3> colAllSPs = new DataServiceCollection<Gulf.NAV.APISP3>(qryAllSPs, TrackingMode.None);
foreach (Gulf.NAV.APISP3 item in colAllSPs)
{
gobjRecToUpdate = item;
break;
}
gobjRecToUpdate.UnitPrice = newValue;
foreach (var entry in objContext.EntityTracker.Entities)
{
objContext.Detach(entry.Entity);
}
objContext.AttachTo("APISP3", gobjRecToUpdate, "*");
objContext.UpdateObject(gobjRecToUpdate);
objContext.SaveChanges(SaveChangesOptions.None); // <--- Resource not found for the segment 'APISP3'

How to fix wrong naming?

I got a property with a name starting with underscore, i ahve to remove it from the metafile before Unchase will accept the metafile, is it possible to get it to accept the name with starting underscore?
<Property Name="_x003C_Document_Exchange_Status_x003E_" Type="Edm.Boolean"/>

Having trouble using Connected Service in .Net Standard

After running through the wizard in a brand new .NET standard project there are 2 errors:
(both the same thin really)

  • Loading the include file 'Reference1.ttinclude' returned a null or empty string. The transformation will not be run.
  • Failed to resolve include text for file:C:\Users\chris\source\repos\standard1\standard1\Connected Services\SkyMove\Reference1.ttinclude standard1

When I look in the file system, the Reference1.ttinclude file is there but the Reference1.cs has the "ErrorGeneratingOutput" content.

If I then try to execute the Reference1.tt file manually the following errors are now observed:

  • Compiling transformation: Method must have a return type … (line: \Reference1.tt 7464)
  • Compiling transformation: Invalid token 'this' in class, struct, or interface member declaration standard1 C:\Users\chris\source\repos\standard1\standard1\Connected Services\SkyMove\Reference1.tt 7464

Microsoft Visual Studio Professional 2019
Version 16.4.3

BUG: Collections can become empty when updating the same collection.

When i try to update a large class with several collections (large) in it than it can occur when calling .execute that not all collections are updated. If i check in whireshark i can see that the data is there.

For example i call: GET /odata/v1/Customers()?$top=99999&$expand=Orders,BillingAddress,BillingAddress/Country,ShippingAddress,CustomerRoles,Addresses

Wireshark:
image

DataServiceQuery:
image

If i test it in a loop like:

        For i As Integer = 0 To 9

            dsqCustomers = CType(WebCon.Customers.Expand("Orders").Expand("BillingAddress").Expand("BillingAddress/Country").Expand("ShippingAddress").Expand("CustomerRoles").Expand("Addresses").Take(MaxTop), DataServiceQuery(Of Customer))
            dsqCustomers.Execute()

            For Each item As Customer In dsqCustomers

                If item.Addresses.Count = 0 Then
                    Debug.Print($"{i} = {item.Company} = No addresses")
                End If
            Next
        Next

Then i cannot reproduce it. It seems to occur "random". I know this isn't much and will try to get more debug information, but maybe in te meantime you got an idea what is going wrong?

QUESTION: Is the generated client proxy code compatible with net core 3.1?

Hi,

We recently moved to net core 3.1 which meant that we had to switch to vs 2019 in order to have some kind of OData client proxy generation cababilities and tried out Unchase. Code generation works fine but when running our existing code it fails and it complains:

...
return _context.Order
.Expand(x => x.Order_Line)
.Where(a => a.Submit_Date >= fromQueryDate.Value)
.Where(a => a.Submit_Date.Value <= toQueryDate.Value)
.OrderByDescending(x => x.Submit_Date.Value).Skip(page.PageNumber * page.PageSize).Take(page.PageSize).ToList();

  One or more errors occurred. (This target framework does not enable you to directly enumerate over a data service query. This is because enumeration automatically sends a synchronous request to the data service. Because this framework only supports asynchronous operations, you must instead call the BeginExecute and EndExecute methods to obtain a query result that supports enumeration.)

System.AggregateException: One or more errors occurred. (This target framework does not enable you to directly enumerate over a data service query. This is because enumeration automatically sends a synchronous request to the data service. Because this framework only supports asynchronous operations, you must instead call the BeginExecute and EndExecute methods to obtain a query result that supports enumeration.)
---> System.NotSupportedException: This target framework does not enable you to directly enumerate over a data service query. This is because enumeration automatically sends a synchronous request to the data service. Because this framework only supports asynchronous operations, you must instead call the BeginExecute and EndExecute methods to obtain a query result that supports enumeration.

Changing the code a litte bit to:
var query = _context.Order
.Expand(x => x.Order_Line)
.Where(a => a.Submit_Date >= fromQueryDate.Value)
.Where(a => a.Submit_Date.Value <= toQueryDate.Value)
.OrderByDescending(x => x.Submit_Date.Value).Skip(page.PageNumber * page.PageSize).Take(page.PageSize);

        var result = await query.ToAsync();
        
        return result.ToList();

where the ToAsync method is:

public static class QueryExtensions
{
public async static Task<IEnumerable> ToAsync(this IQueryable query)
{
if (query is System.Data.Services.Client.DataServiceQuery dataServiceQuery)
{
var factory = new TaskFactory<IEnumerable>();
var result = await factory.FromAsync(
dataServiceQuery.BeginExecute(null, null),
a => dataServiceQuery.EndExecute(a));

            return result;
        }

        return query;
    }
}

causes a new error:
One or more errors occurred. (An error occurred while processing this request.)
System.AggregateException: One or more errors occurred. (An error occurred while processing this request.)
---> System.Data.Services.Client.DataServiceQueryException: An error occurred while processing this request.
---> System.Data.Services.Client.DataServiceClientException: NotFound
at System.Data.Services.Client.BaseAsyncResult.EndExecute[T](Object source, String method, IAsyncResult asyncResult)
at System.Data.Services.Client.QueryResult.EndExecuteQuery[TElement](Object source, String method, IAsyncResult asyncResult)
--- End of inner exception stack trace ---
at System.Data.Services.Client.QueryResult.EndExecuteQuery[TElement](Object source, String method, IAsyncResult asyncResult)
at System.Data.Services.Client.DataServiceRequest.EndExecute[TElement](Object source, DataServiceContext context, String method, IAsyncResult asyncResult)
at System.Data.Services.Client.DataServiceQuery`1.EndExecute(IAsyncResult asyncResult)

Which deep down seems to be caused by an underlying 404 (although the query seems correct when I copy it and run it in a browser).

So question is: Is there something wrong in my code or some kind of incompatibility issue?

BUG install fail

I downloaded the vsix clicked to install it and got this error message:
vsixinstallfail

Question: AutoUpdate Collection

When a Entity is created/updated on the server the server than returns the entity in the repsone body. Is there a way/boolean that takes this data and automatically update the collection? For example when creating a Entity the ID is empty because this is generated on the server. If we POST a new Entity to the server the server will return the newly created Entity WITH the ID value.

Question

When i have a object that contains a collection than the collection is serialized as [].

For example:

Public WebCon As New Container(New Uri(serverBaseUrl))
Private dsqProductAttributes As DataServiceQuery(Of ProductAttribute) = CType(WebCon.ProductAttributes.Take(120), DataServiceQuery(Of ProductAttribute))

Dim x As New ProductAttribute With {.Name = "API_Test_" & Now.ToString}
x.ProductAttributeOptionsSets.Add(New ProductAttributeOptionsSet With {.Name = "Default"})
WebCon.AddToProductAttributes(x343)
WebCon.SaveChanges()

Then when i captured the POST command with wireshark only the Name is serialized but the ProductAttributeOptionsSets is missing. Also the other way arround when i GET ProductAttributes then the ProductAttributeOptionsSets is []

I tested with other collection and all result in the same. It seems that is an object containt a collection this isn't parsed/requested?

Cannot convert from 'System.Xml.XmlReader' to System.Collections.Generic.IEnumerable<System.Xml.XmlReader>'

Describe the bug

When generating model classes, I get two errors in my LoadModelFromString method in the Reference.cs class:

	private static global::Microsoft.OData.Edm.IEdmModel LoadModelFromString()
	{
		global::System.Xml.XmlReader reader = CreateXmlReader(Edmx);
		try
		{
			global::System.Collections.Generic.IEnumerable<global::Microsoft.OData.Edm.Validation.EdmError> errors;
			global::Microsoft.OData.Edm.IEdmModel edmModel;
			
			if (!global::Microsoft.OData.Edm.Csdl.CsdlReader.TryParse(reader, false, out edmModel, out errors))
			{
				global::System.Text.StringBuilder errorMessages = new global::System.Text.StringBuilder();
				foreach (var error in errors)
				{
					errorMessages.Append(error.ErrorMessage);
					errorMessages.Append("; ");
				}
				throw new global::System.InvalidOperationException(errorMessages.ToString());
			}

			return edmModel;
		}
		finally
		{
			((global::System.IDisposable)(reader)).Dispose();
		}
	}

Argument 1: Cannot convert from 'System.Xml.XmlReader' to System.Collections.Generic.IEnumerable<System.Xml.XmlReader>'

Argument 2: cannot convert from 'bool' to 'Microsoft.OData.Edm.IEdmModel'

I need to manually fix the code after each time the Reference class is generated via the Unchase OData Connected Service.

Assemblies affected

Unchase OData Connected Service v1.4.1
Microsoft Visual Studio Professional 2017 15.9.28307.1093

Steps to reproduce

  1. Take my ConnectedService.json file here
  2. Generate Reference class using my metadata file
  3. The error will be present in the LoadModelFromString method of the Reference.cs class

SetSaveStream - Document Attachment

I'm trying to add a Document Attachment record via an Unchase Connected Service to a Microsoft Dynamics NAV database in C# (Visual Studio 2019).
I downloaded the XML metadata from a Dynamics NAV URL. In Visual Studio, I perform an Add / Update Unchase Connected Service and pointed it at the metadata file.
This process auto-generates a Reference.cs code-file. I then call the appropriate objects / properties / methods (see code below):-

private NAV.NAV gobjDSC; // DataServiceContext

const int SHTABLEID = 5900;
string lstrFileName = @"C:\Test\Test Attachment 3.pdf";
System.IO.FileInfo lfi = new System.IO.FileInfo(lstrFileName);
NAV.API_Document_Attachment lobjDA = NAV.API_Document_Attachment.CreateAPI_Document_Attachment(SHTABLEID, "SO000006", "Order", 0, 1);
lobjDA.AttachedDate = DateTime.Now;
lobjDA.FileName = lfi.Name;
lobjDA.FileExtension = lfi.Extension.Replace(".", string.Empty);
lobjDA.FileType = "2";
FileStream lobjFS = new FileStream(lstrFileName, FileMode.Open);
var ms = new MemoryStream();
lobjFS.CopyTo(ms);
System.Guid lobjGuid = System.Guid.NewGuid();
lobjDA.DocumentReferenceID = NAV.Media.CreateMedia(lobjGuid);
gobjDSC.AddToAPI_Document_Attachment(lobjDA);

gobjDSC.SetSaveStream(lobjDA.DocumentReferenceID.Content, ms, true, new DataServiceRequestArgs { ContentType = "application/pdf" }); // ERROR

gobjDSC.SaveChanges();

The SetSaveStream line of code above produces the error: 'Value cannot be null. Parameter name: entity' Sure enough the Content property is null.
As the Content property is of type: DataServiceStreamLink and there doesn't appear to be a way of instantiating it in the conventional way
(e.g.) lobjDA.DocumentReferenceID.Content = new DataServiceStreamLink();
error CS1729: 'DataServiceStreamLink' does not contain a constructor that takes 0 arguments
… I'm stuck in a stalemate. It was my understanding that SetSaveStream would assign a value to: lobjDA.DocumentReferenceID.Content but it is objecting to it being null? (Chicken and Egg)
Any thoughts? Thanks in advance for any support given.

C4C OData invalid Namespace attribute

Hi,

I want to extract data from C4C via OData. I enter the metadata url, but the connected service cannot be added. It says "The 'Namespace' attribute is invalid".
image

Screenshot of metadata XML:
image

Thank you for your help.

Getting System.IndexOutOfRangeException when processing results of a batch request

Describe the bug

When submitting a batch request (specifically a batch of PATCH requests), the request succeeds, but the client throws a System.IndexOutOfRangeException. Repros > 90% of the time for our code. I noticed the issue went away when I moved back to Microsoft.OData.ConnectedService.

Assemblies affected

Generated OData v4 Client
Using Microsoft.OData.Client 7.6.4

Steps to reproduce

  1. Have an OData API available - I'm currently using Microsoft.AspNet.OData 7.4.0
  2. Generate OData client using Unchase (I'm using Microsoft.OData.Client 7.6.4)
  3. Create a DataServiceCollection for one of the entities (i.e. var collection = new DataServiceCollection<EntityType>(context);)
  4. Load several entities to the DataServiceCollection (i.e. using collection.Load(entity)) and modify them (I am modifying existing entities and adding new entities in my code)
  5. Call context.SaveChanges(SaveChangesOptions.BatchWithSingleChangeset)

Expected result

Batch API call succeeds and client handles response correctly.

Actual result

Batch API call succeeds (confirmed in fiddlers), but client fails on handling the response with the following exception:

Microsoft.OData.Client.DataServiceRequestException: An error occurred while processing this request. ---> System.IndexOutOfRangeException: Index was outside the bounds of the array.
at System.Array.Clear(Array array, Int32 index, Int32 length)
at System.Collections.Generic.HashSet`1.Clear()
at Microsoft.OData.Client.BaseSaveResult.HandleResponsePut(Descriptor descriptor, HeaderCollection responseHeaders)
at Microsoft.OData.Client.BaseSaveResult.HandleOperationResponse(Descriptor descriptor, HeaderCollection contentHeaders)
at Microsoft.OData.Client.BatchSaveResult.d__26.MoveNext()
--- End of inner exception stack trace ---
at Microsoft.OData.Client.BatchSaveResult.HandleBatchResponseInternal(ODataBatchReader batchReader)
at Microsoft.OData.Client.BatchSaveResult.HandleBatchResponse()
at Microsoft.OData.Client.BatchSaveResult.HandleResponse()
at Microsoft.OData.Client.BaseSaveResult.EndRequest()
at Microsoft.OData.Client.DataServiceContext.SaveChanges(SaveChangesOptions options)
at CALLING_CODE

Additional detail

This only fails if I generate the client with the Unchase client. When I go back to using Microsoft.OData.ConnectedService (0.9.0) it starts succeeding again.

Why create URI class ?

I have try to migrate my App that use OData v4 Client Code Generator to Unchase.
My problem is that Unchase generate

namespace System
{
///


/// There are no comments for Uri in the schema.
///

public partial class Uri
..........

and

namespace System.Net.Mime
{
///


/// There are no comments for ContentType in the schema.
///

public partial class ContentType
{

my app to connect odata service use :
_containerPrimario = new Default.Container (new Uri(_serviceUri, UriKind.RelativeOrAbsolute));

but uri is generated from unchase and not work.

how can i exclude the uri from generation?

Updating to OData 4.0 breaks UI in WPF?

The OData backend has updated from OData v3 to v4. This is a backend managed by a thrid part. Now i updated the Unchase.OData.ConnectedService from v1.4.1.0 to v1.4.2.0. Then i rebooted the computer, opend the solution again and then Clicked on Update Unchase ODate Connected Service... The update all goes when and update the exists OData v3 class to v4. This goes well but when i build the solution then i get thons off errors indicating the reference to my WPF ui object can't be found anymore. Saying "SomeComponent" is not a member of "MySolution.System"

What am i overlooking here?

This is the configuration:

{ "ProviderId": "Unchase.OData.ConnectedService", "Version": "1.4.2.0", "GettingStartedDocument": { "Uri": "http://odata.github.io/odata.net/" }, "ExtendedData": { "EnableNamingAlias": false, "IgnoreUnexpectedElementsAndAttributes": false, "GenerateDynamicPropertiesCollection": true, "DynamicPropertiesCollectionName": "DynamicProperties", "IncludeT4File": false, "MakeTypesInternal": false, "OperationImportsGenerator": 0, "IncludeExtensionsT4File": false, "GenerateOperationImports": false, "ServiceName": "OData_MyClass_v4", "AcceptAllUntrustedCertificates": false, "Endpoint": "https://domain.com/odata/v1/$metadata", "EdmxVersion": { "Major": 4, "Minor": 0, "Build": 0, "Revision": 0, "MajorRevision": 0, "MinorRevision": 0 }, "GeneratedFileNamePrefix": "MyClass_v4", "UseNameSpacePrefix": false, "NamespacePrefix": null, "UseDataServiceCollection": false, "UseAsyncDataServiceCollection": false, "OpenGeneratedFilesOnComplete": false, "LanguageOption": 1, "FunctionImports": null, "OperationImports": null, "ExcludedOperationImportsNames": "", "UseNetworkCredentials": false, "NetworkCredentialsUserName": null, "NetworkCredentialsPassword": null, "NetworkCredentialsDomain": null, "WebProxyUri": null, "UseWebProxy": false, "UseWebProxyCredentials": false, "WebProxyNetworkCredentialsUserName": null, "WebProxyNetworkCredentialsPassword": null, "WebProxyNetworkCredentialsDomain": null } }

In the meantime i created a new solution, added the Connected Service and exactly the same problem. The newly created solution was based on WPF, VB.NET running on .NET 4.7.2. It seems it created a namespace conflict is guess

Generate Odata V3 Connected Service

Describe the bug

Although the metadata states "m:MaxDataServiceVersion="3.0"", a dynamic v4 reference.cs is generated.

Assemblies affected

OData References

Steps to reproduce

  1. Select a v3 OData Service
  2. Finish Generation

Expected result

A detailed v3 Reference.cs file (Example 1)

Actual result

A dynamic v4 Reference.cs file (Example 2)

Screenshots

NA

Additional detail

Example1.txt

Example2.txt

NA

Operation is not supported on this platform.

When trying to use ODada Connected Service with Client Side Blazor all initial processes for client generation seems smooth. However the proxy generated works only with the server side blazor.
With Client Side Blazor it gives an error
System.PlatformNotSupportedException: Operation is not supported on this platform.
Any idean on how sort this out.

Remember setting "Add extensions code template for OData proxy-class" on update connected service

Describe the bug

When adding a new Connected Service for OData, then it is possible to set different parameters in the Wizard UI.
One important setting for us is to be able to un-check the "Add extensions code template for OData proxy-class" as we create our own code for that.

When updating the existing Connected Service, then it seems that the advanced setting "Add extensions code template for OData proxy-class" is not remembered and since the advanced settings are collapsed, it is easy for a developer to miss that and accidently generate the ReferenceExtensions.cs file.

Expected result

Excepted that all settings initially set, are be remembered when updating the connected services and just clicking "Finish".

Actual result

The setting "Add extensions code template for OData proxy-class" seems to be forgotten and this results in an unwanted ReferenceExtensions.cs file being generated.

Cannot find OrgConext

Hello,

I have migrated my projet from .NET Framework to .NET Core, WCF is not fully supported by .NET Core. that's why I orientated to Unchase.Odata.Connectedservice but when i generate oData, i don't find OrgContext in Reference.cs

Appreciate any assistance or suggestions. Thank you

Cannot connect to ODATA v4 from MS Business Central

I am unable to add the Reference for ODATA service published from MS Business Central.

Following is the message after pressing finish.

Adding service instance...
Adding Nuget Packages for OData V4...
Nuget Package "Microsoft.OData.Client" for OData V4 already installed.
Nuget Package "Microsoft.OData.Core" for OData V4 already installed.
Nuget Package "Microsoft.OData.Edm" for OData V4 already installed.
Nuget Package "Microsoft.Spatial" for OData V4 already installed.
Nuget Packages for OData V4 were installed.
Generating Client Proxy for OData V4...
Error:Adding Unchase OData Connected Service to the project failed: Failed to access the metadata document. The OData service requires authentication for accessing it. Please download the metadata, store it into a local file, and set the value of “MetadataDocumentUri” in the .odata.config file to the file path. After that, run custom tool again to generate the OData Client code.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.