Giter Site home page Giter Site logo

commercetools / commercetools-dotnet-sdk Goto Github PK

View Code? Open in Web Editor NEW
8.0 82.0 14.0 13.72 MB

The e-commerce SDK from commercetools running on the .NET platform

Home Page: https://docs.commercetools.com/sdk/dotnet-sdk#net-sdk

License: MIT License

C# 99.87% PowerShell 0.13%
commercetools dotnet commercetools-sdk commercetools-dotnet-sdk dotnet-sdk sdk audit-sdk

commercetools-dotnet-sdk's Introduction

commercetools-dotnet-sdk

⚠️ **This Composable Commerce .NET SDK is deprecated effective 1st September 2021., We recommend to use our .NET Core SDK V2.

Travis Build Status AppVeyor Build Status NuGet Version and Downloads count

The Composable Commerce SDK allows developers to work effectively by providing typesafe access to commercetools Composable Commerce in their .NET applications.

For more documentation please see the wiki

Supported Platforms

  • .NET Standard 2.0

Using the SDK

You will need a Composable Commerce Project to use the SDK. If you don't already have one, you can create a free trial project on Composable Commerce and configure the API credentials.

The namespaces in the SDK mirror the sections of the commercetools HTTP API. Access to these namespaces is provided by a fluent interface on the Client class.

Responses from the client are wrapped in a Response object so you can determine if the request was successful and view the error(s) returned from the API if it was not.

using System;
using System.Threading.Tasks;

using commercetools.Common;
using commercetools.Products;

class Program
{
    static void Main(string[] args)
    {
        new Program().Run().Wait();

        Console.WriteLine("Press any key to exit.");
        Console.ReadKey();
    }

    private async Task Run()
    {
        Configuration config = new Configuration(
            "https://auth.europe-west1.gcp.commercetools.com/oauth/token",
            "https://api.europe-west1.gcp.commercetools.com",
            "[your project key]",
            "[your client ID]",
            "[your client secret]",
            ProjectScope.ManageProject);

        Client client = new Client(config);

        Response<ProductQueryResult> response = await client.Products().QueryProductsAsync();

        if (response.Success)
        {
            ProductQueryResult productQueryResult = response.Result;

            foreach (Product product in productQueryResult.Results)
            {
                Console.WriteLine(product.Id);
            }
        }
        else
        {
            Console.WriteLine("{0}: {1}", response.StatusCode, response.ReasonPhrase);

            foreach (ErrorMessage errorMessage in response.Errors)
            {
                Console.WriteLine("{0}: {1}", errorMessage.Code, errorMessage.Message);
            }
        }
    }
}

Not all API sections and representations have been implemented in the SDK. If you need to work with areas of the API that have not yet been covered, you can use the Client to make JSON requests directly. Ask the client for a JObject and you will get the entire JSON response that is returned from the API.

This code snippet will have the same output as the code snippet above:

Response<JObject> response = await client.GetAsync<JObject>("/products");

if (response.Success)
{
    dynamic responseObj = response.Result;

    foreach (dynamic product in responseObj.results)
    {
        Console.WriteLine(product.id);
    }
}
else
{
    Console.WriteLine("{0}: {1}", response.StatusCode, response.ReasonPhrase);

    foreach (ErrorMessage errorMessage in response.Errors)
    {
        Console.WriteLine("{0}: {1}", errorMessage.Code, errorMessage.Message);
    }
}

License, Contributing

This software is licenses under the MIT License, which allows commercial use and modification as well as open source collaboration.

We are warmly welcoming contributors and are happy to help out. To contribute changes or improvements, please fork the repository into your account on GitHub and create a pull request.

Contribution Guidelines

  • The namespaces and directory names in the SDK should match up exactly with the project name in the documentation. For your contributions.

    For Example: The namespace should be commercetools.CartDiscounts (plural) should be used rather than commercetools.CartDiscount (singular).

  • Only the required properties for an API entity should be used as constructor parameters in the corresponding SDK class. Parameters marked as optional in the documentation should not be required for creating a new instance of the class.

    For Example: In the commercetools.CartDiscounts.CartDiscountDraft class, description, target, isActive, validFrom and validUntil should not be used as constructor parameters as they are not required.

  • Wherever applicable, try to treat objects as groups of entities and use a factory to create these groups of entities when response is being parsed.

    For Example: The CartDiscountValue entities (AbsoluteCartDiscountValue/RelativeCartDiscountValue/GiftLineItemCartDiscountValue) are treated as a group of entities that share a common type property, Type (Relative/Absolute/GiftLineItem). These entities are created by a CartDiscountValueFactory when we parse the response from the Composable Commerce API.

Mac Users

The Visual Studio IDE is available for Mac OS (preview version as of 2016)

A more lightweight Coding Environment that also manages the .NET setup automatically for you is Microsoft Visual Studio Code (free).

commercetools-dotnet-sdk's People

Contributors

andersekdahl avatar ashishhk avatar bolingar avatar btastic avatar daschy avatar daviddevries avatar hajoeichler avatar jenschude avatar jherey avatar jhumber avatar marvin-brouwer avatar michelerezk avatar purquhart avatar sarvasana avatar sshibani avatar sucrose0413 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 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  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

commercetools-dotnet-sdk's Issues

Setting a localized string is not possible in SetAttributeAction

Since the Value of SetAttributeAction requires a FieldType, we seem to not be able to set the LocalizedString array to it.

Maybe we are doing something wrong but setting the type for value to dynamic can fix it. It is not a good solution since providing dynamic properties to top level API's can easily lead to mistakes that developers will make.

I am working with a local master branch right now, and will keep that until fixed or you provide a working alternative.

Thank you

Add Images to Products is not working

ProductDraft newDraft = new ProductDraft(productName, resourceIdentifier, productSlug);.
                JObject itemFieldValue = new JObject
                            {
                                { "url", "http://someurl.jpg"},
                                {"dimensions", new JObject{{"w", 1500},{"h", 1500} } },
                                {"label", "some label"}
                            };
               Image image = new Image(itemFieldValue);
                List<Image> images = new List<Image>() { image };
                newDraft.MasterVariant.Images = images;.
                                  Response<Product> productResponse = await client.Products().CreateProductAsync(productDraft);

The reason for this can be identified as the properties for the image are deserialized in a flat manner. But there is no special handler for serializing the Image back to the expected JSON structure of the API. So it's not possible to create products with images as well to set them using the update actions.

Introduce gitflow branching mechanism

  • Create a feature/2.0 branch from the master
  • Delete all files from feature/2 branch
  • create feature branches from feature2.0

During the development of v2.0 all feature branches need to be merged into feature/2 by PR

Remove legacy hostnames

Description

To improve the developer experience and easen our support and training burden all existing references to *.sphere.io and .commercetools.co host names should be removed in favor of not defaulting to a specific region (a common complaint of US and AWS customers is that EU is defaulted everywhere) or, if needed for backwards compatibility, be replaced with the new *.europe-west1.gcp.commercetools.com notation.

Expected Behavior

full text search over the repository for ".sphere.io" and ".commercetools.co" should yield zero results

Context

https://docs.commercetools.com/release-notes#releases-2020-02-03-aws-and-new-hostnames

Error while creating a cart with CustomLineItems

While I try to create a cart with the following JSON

{
   "currency":"EUR",
   "taxMode":"Disabled",
   "customLineItems":[
      {
         "name":{
            "en":"Test"
         },
         "quantity":40,
         "money":{
            "currencyCode":"EUR",
            "centAmount":30
         },
         "slug":"test",
         "custom":{
            "type":{
               "key":"custom-line-item-custom-fields"
            },
            "fields":{
               "ProductId":"123",
               "PapId":"456"
            }
         }
      }
   ]
}

The cart gets created as this is a valid JSON. The response returned by the commercetools is

{
  "type": "Cart",
  "id": "2f002000-261e-41ac-afc3-2a0a9ab5e4d9",
  "version": 1,
  "createdAt": "2017-06-07T09:41:16.912Z",
  "lastModifiedAt": "2017-06-07T09:41:16.912Z",
  "lineItems": [],
  "cartState": "Active",
  "totalPrice": {
    "currencyCode": "EUR",
    "centAmount": 1200
  },
  "customLineItems": [
    {
      "totalPrice": {
        "currencyCode": "EUR",
        "centAmount": 1200
      },
      "id": "94cd3448-7db5-4127-b680-8c590c1f5a87",
      "name": {
        "en": "Test"
      },
      "money": {
        "currencyCode": "EUR",
        "centAmount": 30
      },
      "slug": "test",
      "quantity": 40,
      "discountedPricePerQuantity": [],
      "state": [
        {
          "quantity": 40,
          "state": {
            "typeId": "state",
            "id": "936c92bd-790f-4de5-9b4a-747401275f32"
          }
        }
      ],
      "custom": {
        "type": {
          "typeId": "type",
          "id": "26233599-7464-4962-8f76-019deea0508c"
        },
        "fields": {
          "ProductId": "123",
          "PapId": "456"
        }
      }
    }
  ],
  "discountCodes": [],
  "inventoryMode": "None",
  "taxMode": "Disabled",
  "taxRoundingMode": "HalfEven",
  "refusedGifts": []
}

While the cart gets created , the sdk throws an exception while trying to parse the JSON returned by the commercetools platform. The exception returned is

Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: 'Cannot convert null to 'int' because it is a non-nullable value type'

This exception is caused by the dynamic assignment of null to the the property 'Version' of the class State

Also note that in the response JSON above, CommerceTools platform does not return a version for the 'state' property of the 'customLineItem'. Only the 'typeId' and the 'id' is returned.

clarify profile / standard / version / PCL compatibility

For an external, the dotnet world of compatibility is hard to understand. E.g. https://docs.microsoft.com/en-us/dotnet/articles/standard/library is precise and they try hard, but it's still not an easy answer to "will this work on device / OS xyz?" questions and getting into the details of https://blogs.msdn.microsoft.com/dotnet/2016/09/26/introducing-net-standard/ is not exactly motivating, too (but they end with "will get much easier" :-) )

To me as a pretty software-knowledgeable but not very dotnet experienced guy it would be super helpful to explicitly state the effective compatibility in a form like this (imaginary "whishful thinking" entries!!! )

The dotnet SKD is compatible with dotnet version / profile / etc. foobar e.g. Profile111 .NET Portable Subset (.NET Framework 4.5, Windows 8, Windows Phone 8.1), practically meaning it runs on:

  • Windows servers 2012+ with dotnet 4.foobar
  • not on dotnet core 1.x (but maybe, or never?)
  • Linux servers with mono 4.foobar
  • Windows desktop computers from version 8.x? upwards (without additional dotnet installation)
  • (Not) on windows phone 99.88
  • (Not) on Windows mobile abcde.

ProductVariantAvailability properties are always NULL

It looks like the ProductVariantAvailability object on a ProductVariant does not get initialized properly.

In the raw JSON data the availability data is an array of availability for each channel.

However the ProductVariantAvailability class is only a single object that is passed that a array in the constructor.

Which then fails to populate the 3 availability properties because the dynamic data object passed to it is an array.

Add License File

As agreed contractually. Just call it "LICENSE" in the root directory -> like in the other SDKs.

Decide on Git Branching and Release Model

Concerning branching two options:

  • Gitflow (like PHP SDK): "develop" is the trunk-like branch where feature branches are merged into. "master" represents the last stable release. versions are tags on the master branch.
  • Plain Git: (like JVM SDK) "master" ist the trunk-like branch

Concerning release Model:

  • I suggest semantic versioning like we do with PHP and JVM SDKs (http://semver.org/ ). If ok, please document in the README
  • concerning pre-1.0 release naming : probably depends on the package manager's assumptions. Please propose something. In PHP and JVM we did "1.0.0-M1" counting milestone releases. But something was not good about it, but I don't know what any more.

@jayS-de @schleichardt @lauraluiz @jhumber Please decide somehow. It just needs to be defined.

Discount Information is lost when we parse the response from the CommerceTools Platform

When a cart discount is applied on a cart, the response does not contain correct information about the discounts applied. This is due to incorrect parsing of data. The code with the issue is highlighted below.

Wrong Code

        public DiscountedLineItemPriceForQuantity(dynamic data)
        {
            if (data == null)
            {
                return;
            }
            this.Value = new Money(data.value);
            this.IncludedDiscounts = Helper.GetListFromJsonArray<DiscountedLineItemPortion>(data.includedDiscounts);
        }

Correct Code

        public DiscountedLineItemPriceForQuantity(dynamic data)
        {
            if (data == null)
            {
                return;
            }
            this.Value = new Money(data.discountedPrice.value);
            this.IncludedDiscounts = Helper.GetListFromJsonArray<DiscountedLineItemPortion>(data.discountedPrice.includedDiscounts);
        }

Multiple Scopes in Client Configuration

Hi

I'm not sure if I'm missing something but it looks like its only possible to specify a single scope in the Configuration object. I have a requirement to get products and manage orders in the same project and would prefer to not have to make multiple clients.

Is there something I'm missing?

Thanks,
Henry

Try and document best way to run and try this on a Mac

Goal is not ideal full developer support (for that it's clear that some VM with real Visual Studio is best).

Goal: Enable a broader set of people to usefully try the SDK, write some example user side code, do code review etc.

Options I stumbled upon:

Since MS is strategically investing into cross-platform

My VS Code 2-minutes try was relatively positive - it's seamless with Git, preconfigures the "Original" .NET core Mac runtime (no mono required) etc., but I did not go into serious work.

How to write tests for customers with IClient

Hello,

another thing I found was that there is no way to create a Customer by myself. I'd have to fill the constructor with a fake dynamic object since all the properties are locked via private set.

While I see that the Customer is usually never created via code side, rather created via CustomerDraft and a quick CreateCustomerAsync which takes the CustomerDraft, I can not use it in my tests.

This is the code I want to test without using a real CT Client:

Response<Customer> customer = 
    await _client.Customers().GetCustomerByIdAsync(userId);

Thanks in advance

SDK to support NET Core

Currently I see that the the sdk supports .NET 4.5 and 4.6. At Albelli we try hosting most of our APIs on AWS Lambda. Would it be possible to release a version of the SDK that supports

  • .NET Core 1.0.1

Support high precision prices

Support reference number
https://jira.commercetools.com/browse/SUPPORT-4239

Is your feature request related to a problem? Please describe.
In the "Price" class CommerceTools SDK has a property named "value". This property is of "Money" type. In the Money class, "fractionDigits" property is missing.
When I am using Impex, I am getting the mentioned missing property but in SDK it is missing.
As the "Money" class has "centAmount" instead of actual amount, we need this property in the class.

User story
As a User I want to have full support for high precision prices so that i can set product prices to a higher precision than cent amount

Thanks.

Logging

Add logging middleware for the HttpClient

Optional parameters in UpdateActions

The RemoveLineItemAction has an optional parameter quantity. The implementation uses a default value of 0. But this value should not be transported on the API when not set else the line item will not be removed.

I didn't checked for other update actions and optional parameters but most likely this can happen also at other update action models

CustomerGroup support

Hi,

We are trying to get a customer group by key but we do not find the proper method to do that. Is this included in the SDK?

Thanks!

Do a one-time feature completeness check on Carts and Discount features

A relevant customer project is starting on this SDK that will use the Discount and Cart related APIs heavily.

To not bring extra risk into their project timeline we would like to do a one-time feature coverage check on the data fields, update actions and API calls. -> i.e. check the "breadth" of the coverage.

Reference is the API documentation:

https://dev.commercetools.com/http-api-projects-carts.html
https://dev.commercetools.com/http-api-projects-cartDiscounts.html
https://dev.commercetools.com/http-api-projects-discountCodes.html

TODO: product discounts, too?

The "depth" of coverage will remain as-is since it's currently not planned to e.g. add fully typed query buildersn or similar features to the .NET SDK.

DiscountCodeState enum incomplete

This is the current state of the DiscountCodeState enum (decompiled source):

namespace commercetools.Carts
{
    public enum DiscountCodeState
    {
        NotActive = 0,
        DoesNotMatchCart = 1,
        MatchesCart = 2,
        MaxApplicationReached = 3
    }
}

There are four options:

  • NotActive
  • DoesNotMatchCart
  • MatchesCart
  • MaxApplicationReached

However if I read the documentation I see 6:

  • NotActive
  • NotValid
  • DoesNotMatchCart
  • MatchesCart
  • MaxApplicationReached
  • ApplicationStoppedByPreviousDiscount

The missing two should be added to prevent unexpected results when using the SDK

SetAttributeAction does not default to staged

In SetAttributeAction.cs the line 43 (master branch) states that the property defaults to true.

However, when not setting this value, it will default to false due to serialization and the fact that the default value of a bool is false.

[JsonProperty(PropertyName = "staged")]
public bool Staged { get; set; } = true;

This would fix it. I might do a PR later.

MessageQueryResult includes empty Results

The response to QueryMessagesAsync seems to include the count of the messages but not the messages themselves.

Although response.Result.Count is 20 (as the screenshot shows), Results is empty in the same response.

screen shot 2017-05-23 at 10 13 19 am

Support ProductDeleted Messages

A product is created and then deleted.

When using the QueryMessagesAsync() function i get the ProductCreated Message in the Results. The following Message is a null reference, which should be the ProductDeleted Message. ProductDeleted Messages are missing in the .NET SDK.

configure for and publish on nuGet

The SDKs have all been published as usable artifacts way before the final release to push adoption and feedback.

nuGet seems to be the de facto standard package repository and is even natively integrated into Visuals Studio.

Instructions here https://docs.nuget.org/ndocs/quickstart/create-and-publish-a-package

In addition to the .nuspec file we'll need a nuGet account ( https://www.nuget.org/users/account/LogOn )

@stmeissner @hajoeichler who's usually holding and managing such accounts? e.g. like mavencentral, PHP packagist etc. ?

Remaining domain classes

Add the remaining domain classes.
This might include the addition of new commands that are needed for the remaining domain classes.

HttpClient is created and disposed on every request

Creating and disposing HttpClient on every request is not recomended. See:
Improper Instantiation antipattern
You're Using HttpClient Wrong and it is Destabilizing Your Software

I suggest that Client instead take a HttpClient constructor argument and use that instance. Lifetime of the HttpClient is managed by the consuming application and thus also making it possible to orchestrate HttpClients with whichever delegate handlers needed. The logging delegate handler currently enforced could be removed (also dropping log4net dependency). Perhaps put that handler in the examples project for reference.

Implement scalable foundation

Design a scalable foundation layer

  • Wrap HTTPClient
  • Factory classes for different endpoint to create a HTTPRequestMethod

Custom Field in the CustomLineItemDraft should not be List<CustomFieldsDraft>

Hi,

Currently the "Custom" Property in the file CustomLineItemDraft should not be a list. Instead it should just be a POCO of type "CustomFieldsDraft"

This is based on the documentation as specified in

Due to this issue I am not able to add a cart with custom fields

Request JSON generated by library

{
   "currency":"EUR",
   "taxMode":"Disabled",
   "customLineItems":[
      {
         "name":{
            "en":"Test"
         },
         "quantity":40,
         "money":{
            "currencyCode":"EUR",
            "centAmount":30
         },
         "slug":"test",
         "custom":[
            {
               "type":{
                  "key":"custom-line-item-custom-fields"
               },
               "fields":{
                  "ProductId":"123",
                  "PapId":"456"
               }
            }
         ]
      }
   ]
}

Response (via Impex)

{
  "statusCode": 400,
  "message": "Request body does not contain valid JSON.",
  "errors": [
    {
      "code": "InvalidJsonInput",
      "message": "Request body does not contain valid JSON.",
      "detailedErrorMessage": "customLineItems -> custom: JSON object expected."
    }
  ]
}

Decide where to do general documentation, tutorials etc.

Since @jhumber and his Falcon colleagues don't get access to editing our https://dev.commercetools.com site where the tutorials and general pages on the JVM SDK live we could consider writing the HOWTOs and other version-agnostic content somewhere else.

Options:

@jhumber @stmeissner please vote or propose something.

I prefer the github wiki as it's most approachable. known downside: embedding images is a bit of a hassle.

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.