Coder Social home page Coder Social logo

bukimedia / prestasharp Goto Github PK

View Code? Open in Web Editor NEW
154.0 43.0 152.0 647 KB

CSharp .Net client library for the PrestaShop API via web service

License: GNU General Public License v3.0

C# 99.62% Shell 0.38%
prestashop prestashop-webservice prestashop-api c-sharp csharp dotnet dot-net

prestasharp's Introduction

PrestaSharp

Build Status Total alerts Language grade: C#

CSharp .Net client library for the PrestaShop API via web service

Introduction

A simple .Net REST client written in C# for the Prestashop API. PrestaSharp uses the RestSharp library to consume the Prestashop services.

Installation

NuGet

PrestaSharp is available on NuGet. Use the package manager console to install it:

Install-Package PrestaSharp

Basic usage

  1. Initiate a client instance:
string baseUrl = "http://www.myweb.com/api";
string account = "ASDLKJOIQWEPROQWUPRPOQPPRQOW";
string password = "";

ManufacturerFactory manufacturerFactory = new ManufacturerFactory(baseUrl, account, password);
  1. Perform CRUD actions through the client:
Bukimedia.PrestaSharp.Entities.manufacturer manufacturer = manufacturerFactory.Get(6);
manufacturer.name = "Iron Maiden";
manufacturer.active = 1;
manufacturerFactory.Add(manufacturer);
manufacturerFactory.Update(manufacturer);
manufacturerFactory.Delete(manufacturer);
  1. Add an image:
Bukimedia.PrestaSharp.Entities.product myProduct = new Bukimedia.PrestaSharp.Entities.product();
ProductFactory productFactory = new ProductFactory(baseUrl, account, password);
myProduct = productFactory.Add(myProduct);
ImageFactory imageFactory = new ImageFactory(baseUrl, account, password);
imageFactory.AddProductImage((long)myProduct.id, "C:\\MyImage.jpg");
  1. Set quantity of products: The quantity of a product may not be updated directly in the 'product' entity. You need to update 'stock_available' entity.
StockAvailableFactory stockAvailableFactory = new StockAvailableFactory(baseUrl, account, password);
long stockAvailableId = myProduct.associations.stock_availables[0].id;
Bukimedia.PrestaSharp.Entities.stock_available myStockAvailable = stockAvailableFactory.Get(stockAvailableId);
myStockAvailable.quantity = 99; // Number of available products
myStockAvailable.out_of_stock = 1; // Must enable orders
stockAvailableFactory.Update(myStockAvailable);

Advanced usage

  1. Get all. This sample retrieves the list of manufacturers:
List<manufacturer> manufacturers = ManufacturerFactory.GetAll();
  1. Get ids. This sample retrieves the list of the manufacturer ids:
List<long> ids = ManufacturerFactory.GetIds();
  1. Get by filter. This sample retrieves the list of manufacturers which name is "Metallica":
Dictionary<string, string> dtn = new Dictionary<string, string>();
dtn.Add("name", "Metallica");
List<manufacturer> manufacturers = ManufacturerFactory.GetByFilter(dtn, null, null);
  1. Get by filter with wildcards. This sample retrieves the manufacturers which name starts with "Metall":
Dictionary<string, string> dtn = new Dictionary<string, string>();
dtn.Add("name", "[Metall]%");
List<manufacturer> manufacturers = ManufacturerFactory.GetByFilter(dtn, null, null);
  1. Get ids by filter. This sample retrieves the list of the manufacturers ids which name is "Metallica":
Dictionary<string, string> dtn = new Dictionary<string, string>();
dtn.Add("name", "Metallica");
List<long> ids = ManufacturerFactory.GetIdsByFilter(dtn, null, null);
  1. Get ids by filter with wildcards. This sample retrieves the list of the manufacturers ids which name starts with "Metall":
Dictionary<string, string> dtn = new Dictionary<string, string>();
dtn.Add("name", "[Metall]%");
List<long> ids = ManufacturerFactory.GetIdsByFilter(dtn, null, null);
  1. Get by complex filter. This sample retrieves the top five manufacturers in ascendent sorting which name starts with "Metall":
Dictionary<string, string> dtn = new Dictionary<string, string>();
dtn.Add("name", "[Metall]%");
List<manufacturer> manufacturers = ManufacturerFactory.GetByFilter(dtn, "name_ASC", "5");
  1. Get by filter for pagination. This sample retrieves the top five manufacturers from tenth position in ascendent sorting which name starts with "Metall":
Dictionary<string, string> dtn = new Dictionary<string, string>();
dtn.Add("name", "[Metall]%");
List<manufacturer> manufacturers = ManufacturerFactory.GetByFilter(dtn, "name_ASC", "9,5");
  1. Get ids by filter. This sample retrieves the list of the manufacturers ids which name is "Metallica", "Nirvana" or "Pantera":
Dictionary<string, string> dtn = new Dictionary<string, string>();
dtn.Add("name", "[Metallica|Nirvana|Pantera]");
List<long> ids = ManufacturerFactory.GetIdsByFilter(dtn, null, null);
  1. Get by filter by range date. This sample retrieves the orders in a date range:
DateTime startDate = new DateTime (2016, 1, 1);
DateTime endDate = new DateTime (2016, 1, 31);
Dictionary<string, string> filter = new Dictionary<string, string>();
string dFrom = string.Format("{0:yyyy-MM-dd HH:mm:ss}", startDate);
string dTo = string.Format("{0:yyyy-MM-dd HH:mm:ss}", endDate);
filter.Add("date_add", "[" + dFrom + "," + dTo + "]");
List<long> prestaSharpOrderIds = this.OrderFactory.GetIdsByFilter(filter, "id_DESC", null);

Supported resources

  • Address
  • Carriers
  • Carts
  • Categories
  • Combinations
  • Currencies
  • Customers
  • Customer Messages
  • Customer Threads
  • Guests
  • Groups
  • Images
  • Languages
  • Manufacturers
  • Messages
  • Orders
  • Order Carriers
  • Order Cart Rules
  • Order Histories
  • Order Invoices
  • Order States
  • Products
  • Product Features
  • Product Feature Values
  • Product Options
  • Product Option Values
  • Product Suppliers
  • Shops
  • Specific Prices
  • Specific Price Rules
  • States
  • Stock Availables
  • Tags
  • Tax
  • Tax Rule
  • Tax Rule Groups
  • Warehouse
  • Zones

Supported actions

  • Create
  • Read
  • Update
  • Delete

Roadmap

  • Add other resources

Debugging

Enabling debugging in PrestaShop would make PrestaSharp exceptions more verbose, to enable that, edit /config/defines.inc.php file in your PrestaShop website and edit this code block:

define('_PS_MODE_DEV_', false);

to:

define('_PS_MODE_DEV_', true);

More information in the development section of PrestaShop's documentation.

License

PrestaSharp is GNU General Public License (GPL)

This program is distributed in the hope that it will be useful, but without any warranty; without even the implied warranty of merchantabilty or fitness for a particular purpose. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/.

Bukimedia reserves the right to mention of companies or individuals who use this software.

Copyright (C) 2019 Bukimedia

prestasharp's People

Contributors

adastier avatar asscasc avatar bryant1410 avatar dakmorsd avatar dependabot[bot] avatar eduleonpavon avatar francmunoz avatar gryzzli avatar jakobt avatar kookaburracoder avatar krpec avatar lameulefr avatar ldellacherie avatar luisalb avatar markbeazley avatar mowcixo avatar newturko avatar nturini-cascinanet avatar ologesa avatar oromand avatar oscarlate avatar pumamood avatar pylenius avatar robinbittner avatar sanctusmob avatar scherer-michael avatar shemes avatar snelgrafics avatar toldotechnik avatar xavehoo 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  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

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

prestasharp's Issues

product image factory missing image id parameter

Hello Eduardo,

I notice that the image factory for product, does not consider the image id parameter when delete or update product image. According to the PrestaShop web service, the url to delete or update the image for produtcs is:
http://prestashopsite/api/images/products/1/2

As you can see the url has two parameters at the end, the first one is the product id (that you already handled in the factory) and the last one is the image id (that actually is missing for the delete and update methods).

So, the image factory have to consider the image id also.

Best regards

Problem with product_option

Hello Eduardo

I was trying to insert new product option with prestasharp library with that values:

Dim Item As New PrestaSharp.Entities.product_option()
Item.id = 0
Item.group_type = "select"
Item.is_color_group = 0
Item.position = 0
Item.name.Add(New Entities.AuxEntities.language("1", "Talla"))
Item.public_name.Add(New Entities.AuxEntities.language("1", "Talla"))
Item = factoria.Add(Item)

And always recieve the same exception error but the record is inserted.
Could you help me with this problem.
I was using 1.5.6.1 Prestasharp versión

setWsProductOptionValues() Query was : DELETE FROM `ps_attribute` WHERE `id_attribute_group` = 7 AND `id_attribute` NOT IN ()]]>

Thanks
Sergio

int instead of long (factories)

the factories all provide a .get(int id) function, but the entities all have an id of type long (and the associated AuxEntities are of type int)

(nice job btw, exactly what i needed :D)

Problema actualizando producto

Hola,
Estoy intentando actualizar un producto que tiene accesorios
ArticuloPs.associations.accessories.Clear() ' tiene accesorios pero los borro para cambiarlos por otros
ArticuloPs.associations.accessories.Add(New AuxEntities.Product() With {.id = 125})
ArticulosFactory.Update(ArticuloPs)

setWsAccessories() Query was : INSERT INTO `ps_accessory` (`id_product_1`, `id_product_2`) VALUES (143, 0)]]>

Add accessoires to AssociationsPrtoduct

Hi, i'v added accories to the product assosications by adding the following:

// optionalproduct instead of product because parsing in prestasharp replaces <product> with <prestashop><product> ......
public List<AuxEntities.optionalproduct> accessories { get; set; }

only the follow in the restsharpfactory gives some problems, so i made optionalproduct instead of AuxEntities.product. But this is a nasty solution to the problem. Could you make a permant fix in prestasharp ? Also my solution doesn't solve the problem for getting data from prestashop only for storing into prestashop.

 protected RestRequest RequestForUpdate(string Resource, long? Id, Entities.PrestashopEntity PrestashopEntity)
        {
            if (Id == null)
            {
                throw new ApplicationException("Id is required to update something.");
            }
            var request = new RestRequest();
            request.RootElement = "prestashop";
            request.Resource = Resource;
            request.AddParameter("id", Id, ParameterType.UrlSegment);
            request.Method = Method.PUT;
            request.RequestFormat = DataFormat.Xml;
            request.XmlSerializer = new RestSharp.Serializers.DotNetXmlSerializer();
            request.AddBody(PrestashopEntity);

// bit strange original code ??
            request.Parameters[1].Value = request.Parameters[1].Value.ToString().Replace("<" + PrestashopEntity.GetType().Name+">", "<prestashop>\n<" + PrestashopEntity.GetType().Name + ">");
            request.Parameters[1].Value = request.Parameters[1].Value.ToString().Replace("</" + PrestashopEntity.GetType().Name + ">", "</" + PrestashopEntity.GetType().Name + "></prestashop>");

// dirty fix to get auxentity.product in request 
            request.Parameters[1].Value = request.Parameters[1].Value.ToString().Replace("<optionalproduct>", "<product>");
            request.Parameters[1].Value = request.Parameters[1].Value.ToString().Replace("</optionalproduct>", "</product>");

            return request;
        }

Problem updating a product

Hello!
I can add product with PrestaSharp, eg:
PrestaSharp.Entities.product towar = new PrestaSharp.Entities.product();
ProductFactory fabrykaProduktu = new ProductFactory(BaseUrl, Account, Password);
towar.active = 1;
..
..
..

When, I will get product from ProductFactory (wg. id =22) I have always: Null Exception.

I can add new product, I can't update (get) product with PrestaSharp.
Any idea?

Sorry, My Bad English.

Detailed error when adding

Hi!

I'd like to get the actual error being returned by the PS API when adding or updating an entity.

Right now it just returns (in RestSharpFactory) response.Data with a single message "check innter details" or something like that, accompanied by a response.StatusCode = "badrequest", but It would be very useful to get the message actually outputted by the API, such as "parameter X is mandatory".

Any help?

Thanks in advance!

Method GetByFilter() doesn't support field list

Hi, I'm back...
really this is not a bug but a limit, but with huge catalogs can be a problem (mine is 40k+ products).

Methods GetByFilter(...), I'm especially interested in ProductFactory, use 'full' as value for the 'display' parameter (see and follow: Factories\ProductFactory.cs, line 60): this forces to download full infos... May be usefull the opportunity to select fields in query.

Another way can be to overload GetIds() passing filters to this method too.

This way is possible to download only records of interest.

bye,
marco

Error update product

Sub Main()
Dim BaseUrl As String = "http://www.xxxx.com/api"
Dim Account As String = "xxxxx"
Dim Password As String = ""

    Dim ProductFactory As New ProductFactory(BaseUrl, Account, Password)

    Dim Articoli = ProductFactory.Get(1)

    Articoli.active = 0

    ProductFactory.Update(Articoli)

End Sub

If the active fault display works otherwise gives me a generic internal server error.

Problema con category

Hola Eduardo, darte las gracias por la iniciativa del proyecto Prestasharp.
Tengo un problema y no se cómo solucionarlo.
Al intentar realizar un update de la tabla categorias recibo el siguiente error:

Error al reflejar el tipo PrestaSharp.Entities.category.
El motivo parece porque tanto la clase
PrestaSharp.Entities.category como PrestaSharp.Entities.AuxEntities.category tienen el mismo nombre.

Utilizo visual studio 2010 y .net 4.
Como podría solucionarlo.
Muchas gracias de antemano

Bug in ImageFactor.DeleteCategoryImage

The method content should be this:
this.DeleteImage("categories", CategoryID, null);
instead of this:
this.DeleteImage("categories", null, CategoryID);
Otherwise the delete process will fail with an exception

Create Order Factory

Hi,

I want to pull orders by a date range and a number range. How do I create an orders class? I can't pull the orders rows:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;

namespace PrestaSharp.Entities
{
[XmlType(Namespace = "PrestaSharp/Entities")]
public class order : PrestashopEntity
{

    private string idField;

    private string id_address_deliveryField;

    private string id_address_invoiceField;

    private string id_cartField;

    private string id_currencyField;

    private string id_langField;

    private string id_customerField;

    private string id_carrierField;

    private string current_stateField;

    private string moduleField;

    private string invoice_numberField;

    private string invoice_dateField;

    private string delivery_numberField;

    private string delivery_dateField;

    private string validField;

    private string date_addField;

    private string date_updField;

    private string id_shop_groupField;

    private string id_shopField;

    private string secure_keyField;

    private string paymentField;

    private string recyclableField;

    private string giftField;

    private string gift_messageField;

    private string mobile_themeField;

    private string total_discountsField;

    private string total_discounts_tax_inclField;

    private string total_discounts_tax_exclField;

    private string total_paidField;

    private string total_paid_tax_inclField;

    private string total_paid_tax_exclField;

    private string total_paid_realField;

    private string total_productsField;

    private string total_products_wtField;

    private string total_shippingField;

    private string total_shipping_tax_inclField;

    private string total_shipping_tax_exclField;

    private string carrier_tax_rateField;

    private string total_wrappingField;

    private string total_wrapping_tax_inclField;

    private string total_wrapping_tax_exclField;

    private string shipping_numberField;

    private string conversion_rateField;

    private string referenceField;

    private Order_rows[] associationsField;



    public string id
    {
        get
        {
            return this.idField;
        }
        set
        {
            this.idField = value;
        }
    }



    public string id_address_delivery
    {
        get
        {
            return this.id_address_deliveryField;
        }
        set
        {
            this.id_address_deliveryField = value;
        }
    }



    public string id_address_invoice
    {
        get
        {
            return this.id_address_invoiceField;
        }
        set
        {
            this.id_address_invoiceField = value;
        }
    }



    public string id_cart
    {
        get
        {
            return this.id_cartField;
        }
        set
        {
            this.id_cartField = value;
        }
    }



    public string id_currency
    {
        get
        {
            return this.id_currencyField;
        }
        set
        {
            this.id_currencyField = value;
        }
    }



    public string id_lang
    {
        get
        {
            return this.id_langField;
        }
        set
        {
            this.id_langField = value;
        }
    }



    public string id_customer
    {
        get
        {
            return this.id_customerField;
        }
        set
        {
            this.id_customerField = value;
        }
    }



    public string id_carrier
    {
        get
        {
            return this.id_carrierField;
        }
        set
        {
            this.id_carrierField = value;
        }
    }



    public string current_state
    {
        get
        {
            return this.current_stateField;
        }
        set
        {
            this.current_stateField = value;
        }
    }



    public string module
    {
        get
        {
            return this.moduleField;
        }
        set
        {
            this.moduleField = value;
        }
    }



    public string invoice_number
    {
        get
        {
            return this.invoice_numberField;
        }
        set
        {
            this.invoice_numberField = value;
        }
    }



    public string invoice_date
    {
        get
        {
            return this.invoice_dateField;
        }
        set
        {
            this.invoice_dateField = value;
        }
    }



    public string delivery_number
    {
        get
        {
            return this.delivery_numberField;
        }
        set
        {
            this.delivery_numberField = value;
        }
    }



    public string delivery_date
    {
        get
        {
            return this.delivery_dateField;
        }
        set
        {
            this.delivery_dateField = value;
        }
    }



    public string valid
    {
        get
        {
            return this.validField;
        }
        set
        {
            this.validField = value;
        }
    }



    public string date_add
    {
        get
        {
            return this.date_addField;
        }
        set
        {
            this.date_addField = value;
        }
    }



    public string date_upd
    {
        get
        {
            return this.date_updField;
        }
        set
        {
            this.date_updField = value;
        }
    }



    public string id_shop_group
    {
        get
        {
            return this.id_shop_groupField;
        }
        set
        {
            this.id_shop_groupField = value;
        }
    }



    public string id_shop
    {
        get
        {
            return this.id_shopField;
        }
        set
        {
            this.id_shopField = value;
        }
    }



    public string secure_key
    {
        get
        {
            return this.secure_keyField;
        }
        set
        {
            this.secure_keyField = value;
        }
    }



    public string payment
    {
        get
        {
            return this.paymentField;
        }
        set
        {
            this.paymentField = value;
        }
    }



    public string recyclable
    {
        get
        {
            return this.recyclableField;
        }
        set
        {
            this.recyclableField = value;
        }
    }



    public string gift
    {
        get
        {
            return this.giftField;
        }
        set
        {
            this.giftField = value;
        }
    }



    public string gift_message
    {
        get
        {
            return this.gift_messageField;
        }
        set
        {
            this.gift_messageField = value;
        }
    }



    public string mobile_theme
    {
        get
        {
            return this.mobile_themeField;
        }
        set
        {
            this.mobile_themeField = value;
        }
    }



    public string total_discounts
    {
        get
        {
            return this.total_discountsField;
        }
        set
        {
            this.total_discountsField = value;
        }
    }



    public string total_discounts_tax_incl
    {
        get
        {
            return this.total_discounts_tax_inclField;
        }
        set
        {
            this.total_discounts_tax_inclField = value;
        }
    }



    public string total_discounts_tax_excl
    {
        get
        {
            return this.total_discounts_tax_exclField;
        }
        set
        {
            this.total_discounts_tax_exclField = value;
        }
    }



    public string total_paid
    {
        get
        {
            return this.total_paidField;
        }
        set
        {
            this.total_paidField = value;
        }
    }



    public string total_paid_tax_incl
    {
        get
        {
            return this.total_paid_tax_inclField;
        }
        set
        {
            this.total_paid_tax_inclField = value;
        }
    }



    public string total_paid_tax_excl
    {
        get
        {
            return this.total_paid_tax_exclField;
        }
        set
        {
            this.total_paid_tax_exclField = value;
        }
    }



    public string total_paid_real
    {
        get
        {
            return this.total_paid_realField;
        }
        set
        {
            this.total_paid_realField = value;
        }
    }



    public string total_products
    {
        get
        {
            return this.total_productsField;
        }
        set
        {
            this.total_productsField = value;
        }
    }



    public string total_products_wt
    {
        get
        {
            return this.total_products_wtField;
        }
        set
        {
            this.total_products_wtField = value;
        }
    }



    public string total_shipping
    {
        get
        {
            return this.total_shippingField;
        }
        set
        {
            this.total_shippingField = value;
        }
    }



    public string total_shipping_tax_incl
    {
        get
        {
            return this.total_shipping_tax_inclField;
        }
        set
        {
            this.total_shipping_tax_inclField = value;
        }
    }



    public string total_shipping_tax_excl
    {
        get
        {
            return this.total_shipping_tax_exclField;
        }
        set
        {
            this.total_shipping_tax_exclField = value;
        }
    }



    public string carrier_tax_rate
    {
        get
        {
            return this.carrier_tax_rateField;
        }
        set
        {
            this.carrier_tax_rateField = value;
        }
    }



    public string total_wrapping
    {
        get
        {
            return this.total_wrappingField;
        }
        set
        {
            this.total_wrappingField = value;
        }
    }



    public string total_wrapping_tax_incl
    {
        get
        {
            return this.total_wrapping_tax_inclField;
        }
        set
        {
            this.total_wrapping_tax_inclField = value;
        }
    }



    public string total_wrapping_tax_excl
    {
        get
        {
            return this.total_wrapping_tax_exclField;
        }
        set
        {
            this.total_wrapping_tax_exclField = value;
        }
    }



    public string shipping_number
    {
        get
        {
            return this.shipping_numberField;
        }
        set
        {
            this.shipping_numberField = value;
        }
    }



    public string conversion_rate
    {
        get
        {
            return this.conversion_rateField;
        }
        set
        {
            this.conversion_rateField = value;
        }
    }



    public string reference
    {
        get
        {
            return this.referenceField;
        }
        set
        {
            this.referenceField = value;
        }
    }


    //[System.Xml.Serialization.XmlArrayAttribute(Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
    //[System.Xml.Serialization.XmlArrayItemAttribute("order_rows", typeof(Order_rows), Form = System.Xml.Schema.XmlSchemaForm.Unqualified, IsNullable = false)]
    public Order_rows[] associations
    {
        get
        {
            return this.associationsField;
        }
        set
        {
            this.associationsField = value;
        }
    }
}

/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class Order_rows
{

    private Order_row[] order_rowField;

    private string virtual_entityField;

    private string node_typeField;


    [System.Xml.Serialization.XmlElementAttribute("order_row", Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
    public Order_row[] order_row
    {
        get
        {
            return this.order_rowField;
        }
        set
        {
            this.order_rowField = value;
        }
    }


    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string virtual_entity
    {
        get
        {
            return this.virtual_entityField;
        }
        set
        {
            this.virtual_entityField = value;
        }
    }


    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string node_type
    {
        get
        {
            return this.node_typeField;
        }
        set
        {
            this.node_typeField = value;
        }
    }
}

/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class Order_row
{

    private string idField;

    private string product_idField;

    private string product_attribute_idField;

    private string product_quantityField;

    private string product_nameField;

    private string product_priceField;

    private string unit_price_tax_inclField;

    private string unit_price_tax_exclField;



    public string id
    {
        get
        {
            return this.idField;
        }
        set
        {
            this.idField = value;
        }
    }



    public string product_id
    {
        get
        {
            return this.product_idField;
        }
        set
        {
            this.product_idField = value;
        }
    }



    public string product_attribute_id
    {
        get
        {
            return this.product_attribute_idField;
        }
        set
        {
            this.product_attribute_idField = value;
        }
    }



    public string product_quantity
    {
        get
        {
            return this.product_quantityField;
        }
        set
        {
            this.product_quantityField = value;
        }
    }



    public string product_name
    {
        get
        {
            return this.product_nameField;
        }
        set
        {
            this.product_nameField = value;
        }
    }



    public string product_price
    {
        get
        {
            return this.product_priceField;
        }
        set
        {
            this.product_priceField = value;
        }
    }



    public string unit_price_tax_incl
    {
        get
        {
            return this.unit_price_tax_inclField;
        }
        set
        {
            this.unit_price_tax_inclField = value;
        }
    }



    public string unit_price_tax_excl
    {
        get
        {
            return this.unit_price_tax_exclField;
        }
        set
        {
            this.unit_price_tax_exclField = value;
        }
    }
}

}

Here is my XML:

I am unfamiliar with your syntax.

Problems with combinations properties (weight, price,...) because of Decimal type

Hi Eduardo,
First of all, congratulation for your project, it is really well done !

I encountered a little problem in adding a price, a wholesale_price or a weight in a combination object due to their decimal type.
When I set one of those properties (I tried different way of setting those), I get one of the following errors ;

  1. "Input entry value is not correctly formatted."
  2. "[combination->wholepricde is not valid]!"

The first one seems to be a CultureInfo problem, I can solve it with a Decimal.Parse(stringVariable, CultureInfo.InvariantCulture) or by setting it an integer value like "1" or "69", but the second is absolutely depressing. It seems that my prestashop Web Service don't like the decimal values I send to him.
text visualizer_2014-05-14_21-23-24

My question is : If it works for you, can you tell me wich format is expected by the prestashop web service ? Is it "1.20" or "1,20" or something else ?
base prestasharp entities prestashopentity prestasharp entities combination_2014-05-14_21-28-28

Do I need a specific treatment's step before sending the combination object through the CombinationFactory ?

If needed, here is my developpment environment :
Visual Studio Ultimate 2012
.Net Framework 4.5
Prestashop version 1.5.4.1

Thanks in advance, if you can help me with this issue !
One more time, congratulation for your great job !
I hope you will continue to develop this project !
Cordialy,
Psyko

product_feature / product_feature_value

i am currently trying to add features to a product (cause it is crucial for the program i am currently writing). While analyzing the code I noticed that the product_feature's AuxEntity is already implemented, but it is missing the "custom" field:

return of a product with a feature:

<product_features node_type="product_feature"><product_feature xlink:href="http://localhost/prestashop/api/product_features/5"><id>5</id><custom>0</custom><id_feature_value xlink:href="http://localhost/prestashop/api/product_feature_values/1">1</id_feature_value></product_feature></product_features>

current prestasharp.entities.auxentities.product_feature:

    public class product_feature:PrestashopEntity
    {
        public long id { get; set; }
        public long id_feature_value { get; set; }
    }

First question: is this a bug or intended?

Second question: When implementing product_feature/product_feature_value do i need to add/modify any other files than creating entities for product_feature/product_feature_value, the aux and filter-entities and the 2 factories?

Duda con articulos

Buenas noches Eduardo.
Estoy haciendo pruebas de la libreria prestasharp sobre la versión 1.4.11 de prestashop y al hacer el update de artículos siempre recibo una excepción. Adapté la entidad de artículos a la definición de la versión, pero nada.
El problema es que no se la forma de obtener información de la excepción. He activado lo que comentas en el fichero de texto.
Me podrías indicar por favor la forma en la que comprobáis los errores desde visual studio.
Muchas gracias de antemano.

Where associate carrier with product ?

Hi, where define a shipping (Carrier) associated with a product with prestasharp / web services ?

In Prestahop: Product -> Shipping -> Selected Carrier (Producto -> Transporte -> Transportistas Selecionados)

Regards

Missing property in product entity

Hello EduLeonPavon,

I notice that in the product entity the property id_default_image is missing:
public long? id_default_image { get; set; }

Could you add it?

Thanks

Prices are getting higher with each product update

I was testing the following code:
[code]
public void Test()
{
const long shoplang = 7;

        string productid = "accord10";
        long featureid = 7;
        string featurevalue = "TestColor2";
        ProductFactory prodfact = new ProductFactory(uri, user, password);
        ProductFeatureFactory prodfeatfact = new ProductFeatureFactory(uri, user, password);
        ProductFeatureValueFactory prodfeatvalfact = new ProductFeatureValueFactory(uri, user, password);
        Dictionary<string, string> dtn = new Dictionary<string, string>();

        dtn.Clear();
        dtn.Add("reference", productid);
        List<product> products = prodfact.GetByFilter(dtn, null, null);
        product_feature_value storedval = null;
        if ((products != null) && (products.Count == 1))
        {
            product prod = products[0];
            prodfact.Update(prod);

            //storedval = FeatureValue(prodfeatvalfact, featureid, featurevalue);
            //if (storedval ==null)
            //{
            //    product_feature_value val = new product_feature_value();                
            //    val.id_feature = featureid;  // color feauture
            //    val.value.Add(new PrestaSharp.Entities.AuxEntities.language(shoplang, featurevalue));
            //    storedval = prodfeatvalfact.Add(val);
            //}

            //PrestaSharp.Entities.AuxEntities.product_feature ft = ProductFeature(prod, 7);
            //if (ft == null)
            //{
            //    ft = new PrestaSharp.Entities.AuxEntities.product_feature();
            //    ft.id = featureid;
            //    ft.id_feature_value = (long)storedval.id;
            //    prod.associations.product_features.Add(ft);
            //    prodfact.Update(prod);
            //}
            //else
            //{
            //   if (ft.id_feature_value != storedval.id)
            //    {
            //        ft.id_feature_value = (long)storedval.id;
            //        string hash = ProductMD5(prod);
            //        // color2 = "8990007"
            //        // color2 = "63249743"
            //        prodfact.Update(prod);
            //    }
            //}
        }
    }

[/code]

(i commented the irrelevant code for this problem).

As you can see i only fetch a product and update it immediately.
Before this the product has the following pricing informtion in the backend:
netto: 1597.01
bruto: 1932.38
taxrate: 21%

after the update it became:
netto: 1952.77
bruto: 2362.85
taxrate: 21%

Adding several entities at once?

Hi!

I have to add several entities in batch, so right now I end up with a for loop enclosing an EntityFactory.Add(myentity) statement, resulting in multiple calls to the PS API.

Is there any possibility of having a method for adding a collection (or list) of entities at once?

Many thanks in advance!

wildcards in filters

I'm your nightmare ;)
according to http://doc.prestashop.com/display/PS14/Chapter+8+-+Advanced+Use#Chapter8-AdvancedUse-RenderingFilters
the wildcards in filters should be put after square brackets (ie: URL: (Store URL)/api/manufacturers/?display=[name]&filter[name]=[appl]%), so I can't write:

Dictionary<string, string> filters = new Dictionary<string, string>();
filters.Add("reference", "ferr%");

to get a family of products: it doesn't work :(
really... I didn't peek into restsharp, any suggestion?

thank you,
marco

xmnls attributes added when updating

Hi there!

I'm getting an "namespace warning : xmlns: URI PrestaSharp/Entities is not absolute" when updating a category with 18 associations.

When I check the xml being sent, it is "decorated" with lots of xmnls attributes that don't get added when "adding" an entity nor "updating" any other prestasharp entity!.

This is the xml returned by the RestRequest request = this.RequestForUpdate("categories", Category.id, Category); method:

EDIT. Image attached
untitled-1

Error when update products

I'm doing some tests to implement prestasharp in my application to update products.

Prestashop version 1.5.6.1 with demo database

When I try to update a product I get more lines with this error message:

[omissis...]

An object reference not set to an instance of an object.


If enabled in the configuration error messages, the error message does not appear and the update is successful

CODE:

        string BaseUrl = this.url;
        string Account = this.key;
        string Password = "";
        ProductFactory ProductFactory = new ProductFactory(BaseUrl, Account, Password);

        List<PrestaSharp.Entities.product> Articoli = ProductFactory.GetAll();
        PrestaSharp.Entities.product articolo = new PrestaSharp.Entities.product();

        foreach (PrestaSharp.Entities.product tmp in Articoli)
        {
            if (tmp.id == 10) {
                articolo = tmp;
                break;
            }
        }
        articolo.name[0].Value += "Prova\n";
        ProductFactory.Update(articolo);

Thanks

Help please

Hello Eduardo

I try to use prestasharp to update a Prestashop in a web server.

I can't add any entities using the prestasharp library.

For example in categoryfactory when use add function I debug the function the response.statuscode return ok but response.data is null. I trace the response object and see ErrorException and ErrorMessage object has '=' es un token inesperado. Se esperaba ';'.....

1

The same process in a local server work succesfully
Please can you help me I don't know what's happen.

Some operations

Hello to all.
Should I get a list of all orders with a certain status.
Scroll through the list of all the products inside and filter only those without code ean valued.
as the last thing to group them by name or product code.
you can do it ?

Thank you.

No permission - namespace null

Hi there :)

First off, +1 for the lib !

I'm running into a problem where I do have API access, but didn't have API access for the stock_available Entity. There are no errors when I tried to connect (since I do have a valid API key), but the response is null in PrestaSharp and the lib throws a nullpointer Exception.

See file
PrestashopDeserializer.cs

 private object HandleListDerivative(object x, XElement root, string propName, Type type)
        {
            (.......)
# Below throws a nullpointer because "root" is null :)
            var elements = root.Elements(t.Name.AsNamespaced(Namespace)); 
            (.......)
        }

doesn't compile under vs2012 express for web

Hi,
it doesn't compile under vs2012 express for web (update 3).
I got:

Error 1
Error 175: The specified store provider cannot be found in the configuration, or is not valid. C:\Users\marco\Documents\Visual Studio 2012\Projects\PrestaSharp-master\Models\Prestashop.edmx
line: 7
column: 7
project: PrestaSharp
<<<

line 7 (starts at col 7):
< Schema Namespace="Modelos.Prestashop.Store" Alias="Self" Provider="MySql.Data.MySqlClient" ProviderManifestToken="5.5" xmlns:store="http://schemas.microsoft.com/ado/2007/12/edm/EntityStoreSchemaGenerator" xmlns="http://schemas.microsoft.com/ado/2009/11/edm/ssdl" >

Note:
.required packages are installed and referenced, mysql too
.in database explorer I can't connect mysql db (I think: not supported by express)

I have vs2010 premium and I don't want to buy a new version, any idea?

thanks,
marco

Specific product prices

so nice work, ty
but its possible to access specific product prices?
is it require some news entites?

Error adding images to categories

Hi, I've tried this code to add an image of a category:

    ImageFactory oImageFactory = new ImageFactory(tbUrlBase.Text, tbUser.Text, tbPassword.Text);

    oImageFactory.AddCategoryImage((long)6, @"D:\Temp\Category.jpg");
    //oImageFactory.AddCategoryImage((long)6, File.ReadAllBytes(@"D:\Temp\Category.jpg"));

And the following error occurs

<?xml version="1.0" encoding="UTF-8"?>
<prestashop xmlns:xlink="http://www.w3.org/1999/xlink">
<errors>
<error>
<code><![CDATA[76]]></code>
<message><![CDATA[Image upload error : formato de imagen no reconocida; use los formatos: gif, .jpg, .png]]></message>
</error>
</errors>
</prestashop>
HttpStatusCode: BadRequest

The error occurs in prestashop 1.6.0.6 and 1.5.6.1 with 2 sintaxis:

    public void AddCategoryImage(long? CategoryId, string CategoryImagePath)
    {
        this.AddImage("categories", CategoryId, CategoryImagePath);
    }

    public void AddCategoryImage(long? CategoryId, byte[] CategoryImage)
    {
        this.AddImage("categories", CategoryId, CategoryImage);
    }

Thank you.

Problem with product_option_value

Hello Eduardo

I was trying to insert new product option value with prestasharp library with that values:

Dim item As New Entities.product_option_value
item.id = 0
item.name = addLanguajes("1", "XL")
item.id_attribute_group = 1
item.position = 0
item.color = ""
item = factoria.Add(item)

The response.StatusCode on Execute method in RestSharpFactory has "created" value but response.Data is null. Execute functión return response.Data and then in then Add method in ProductOptionValueFactory in this line:
"return this.Get((long)aux.id); " throws an exception because aux has null value.

The record in the MySQL database is inserted.
This exception only occurs when is the first value in the product options. If the product option has one o more values then the Add method works fine and response.Data has a correct value.

I was using 1.5.6.1 Prestasharp versión and MySQL version server is 5.6.11

Thanks a lot
Sergio

Error when update product - meta_description

I have a problem:
I have a code like this:

        List<product> ProductsT = ProductFactory.GetByFilter(new Dictionary<string, string> {
            { "name", "[tv]%" },
        }, null, null);

        foreach (var product in ProductsT)
        {
            product.active = 0;
            ProductFactory.Update(product);
        }

and when I ran the program its fail in:RestsharpFactory\RequestForUpdate in line:
request.AddBody(PrestashopEntity);

and in InnerDescription I Found that is a problem with:
'PrestaSharp.Entities.AuxEntities.language
with property: meta_description

my data in product for meta_description is:
id = 6
Value = ""

Can You help me? or give me any advice?

Method Get return nothing for all entities

Hello

I've tried this code for retrieving a manufacturer by ID, but it always returns null no matter what entity I try:

Dim mManufacturerFactory As New PrestaSharp.Factories.ManufacturerFactory(oConfiguracion.URLServicio, oConfiguracion.IDToken, "")
Dim mManufacturer As PrestaSharp.Entities.manufacturer
mManufacturer = mManufacturerFactory.Get(4)

Having a look inside the method Get of the Factory, I've seen that the request is sent, but in this method response.data is null.

protected T Execute(RestRequest Request) where T : new()
{
var client = new RestClient();
client.BaseUrl = this.BaseUrl;
client.Authenticator = new HttpBasicAuthenticator(this.Account, this.Password);
Request.AddParameter("Account", this.Account, ParameterType.UrlSegment); // used on every request
var response = client.Execute(Request);
if (response.StatusCode == HttpStatusCode.InternalServerError
|| response.StatusCode == HttpStatusCode.BadRequest
|| response.StatusCode == HttpStatusCode.MethodNotAllowed
|| response.StatusCode == 0)
{
var Exception = new ApplicationException(response.Content + " " + response.ErrorMessage, response.ErrorException);
throw Exception;
}
return response.Data;
}

Here you have a screen capture of the response's inspection. There is an error, but I can figure out what the problem is. Here is the translation: data at the root level is invalid line 1 position 1.

I've traced the traffic with Fiddler and the response message apparently doesn't have any mistake.

captura

Thank you
Blas

Problem with get method in ProductFactory

Hello Eduardo

I was using get method from ProductFactory to get and product item.

Dim i As PrestaSharp.Entities.product = f.Get(9)

Sometimes I don't know the cause the function return null value when the product id exist in database.

I used the getall() method to see all record and throw an exception in the ID 9, price property.
I put in navigator the url http://localhost/prestashop156/api/products/9 to see the xml and the price property has empty value.

The product has a correct price in the database.

The exception happens because the Map method from PrestasharDeserializer try to parse a Decimal value with empty value.

value = Decimal.Parse(value.ToString(), Culture);
prop.SetValue(x, value, null);

This is a bug or I'm doing something wrong???

Info

use. 4.5 net vb.net language, I can use this library ?

It works with version 1.5.6 ?

Issue related to RestSharp

If I try to execute the following code:
{
string BaseUrl = "http://prestahospsite//api";
string Account = "webservicekey";
string Password = "";
CategoryFactory factory = new CategoryFactory(BaseUrl, Account, Password);
List<PrestaSharp.Entities.category> item = factory.GetAll();
}
against a default PrestaShop installation, I get more categories than I should get (because in the answer there are some xelement nested with the same name "category").

The issue is related to the XmlDeserializer method HandleListDerivative and I tryed to change the following code:
var elements = root.Descendants(t.Name.AsNamespaced(Namespace));
with this:
var elements = root.Elements(t.Name.AsNamespaced(Namespace));
and now it works like a charm.
To be honest, I don't now if it is correct or not and this is why I posted this argument here instead to open an issue on RestSharp.

JSON serialization error on manufacturer entity

If I try to serialize a manufacturer obeject I get an error on the method Equals of the manufacturer class.
In order to solve the error I changed the code in this way:

    public override bool Equals(object obj)
    {
        //return this.name == ((manufacturer)obj).name;
        manufacturer other = obj as manufacturer;
        return other != null && name == other.name;
    }

and now it works.
In order to reproduce the error you can do this, using the assemby Newtonsoft.Json.dll:

        CategoryFactory factory = new CategoryFactory(BaseUrl, Account, Password);

        List<PrestaSharp.Entities.category> item = factory.GetAll();
        var manufacturers = factory.GetByFilter(null, null, "0,30");

        var response = JsonConvert.SerializeObject(manufacturers);

ContentType null value

Hello Eduardo.

I'm trying to upload a image product. I use AddProductImage method from the ImageFactory Class. In execution I see that the ContentType Image File has null value and throw BadRequest in Response.StatusCode. If I write some value manually in ContentType like "image/jpg" the webservice upload the image but Response.StatusCode return Unauthorized.

Could you help me with any idea?

I'm using prestashop 1.4.11
Best regards

More entities support

Hello,
I would like to ask you if you will support more prestashop entities (like "orders", "carts" , etc.) in near future?

Thanks

k__BackingField appended on properties included in class with Serializable attribute

I am writing an asp net webapi application (use ApiController). If a method return an object that include a class with Serializable attribute, I see each property with k__BackingField as prefix for instance:
[
{
"id": 1,
"id_parent": 0,
"id_shop_default": 1,
"nleft": 0,
"nright": 0,
"active": 1,
"date_add": "2013-10-18 23:27:57",
"date_upd": "2013-10-18 23:27:57",
"position": 1,
"is_root_category": 0,
"name": [
{
"k__BackingField": 1,
"k__BackingField": "Root"
}
],
"link_rewrite": [
{
"k__BackingField": 1,
"k__BackingField": "root"
}
],
"description": [
{
"k__BackingField": 1,
"k__BackingField": ""
}
],
"meta_title": [
{
"k__BackingField": 1,
"k__BackingField": ""
}
],
"meta_description": [
{
"k__BackingField": 1,
"k__BackingField": ""
}
],
"meta_keywords": [
{
"k__BackingField": 1,
"k__BackingField": ""
}
],
"associations": {
"categories": [
{
"id": 2
}
],
"products": []
}
}]

In order to solve this matter, I changed Serializable with DataContract, for instance:
//[Serializable]
[DataContract]
public class language: PrestashopEntity
{
public language()
{
}

    public language(long id, string Value)
    {
        this.id = id;
        this.Value = Value;
    }


    //[XmlAttribute]
    [DataMember]
    public long id { get; set; }

    // Value is reserved word from RestSharp for loading the CDATA content from the XML file.
    //[XmlTextAttribute]
    [DataMember]
    public string Value { get; set; }

}

and now the result is correct:
[
{
"id": 1,
"id_parent": 0,
"id_shop_default": 1,
"nleft": 0,
"nright": 0,
"active": 1,
"date_add": "2013-10-18 23:27:57",
"date_upd": "2013-10-18 23:27:57",
"position": 1,
"is_root_category": 0,
"name": [
{
"id": 1,
"Value": "Root"
}
],
"link_rewrite": [
{
"id": 1,
"Value": "root"
}
],
"description": [
{
"id": 1,
"Value": ""
}
],
"meta_title": [
{
"id": 1,
"Value": ""
}
],
"meta_description": [
{
"id": 1,
"Value": ""
}
],
"meta_keywords": [
{
"id": 1,
"Value": ""
}
],
"associations": {
"categories": [
{
"id": 2
}
],
"products": []
}
}]

Authentication Mode

Hi,

some hosting solutions not permits authentication with account.
In this case authentication must be with querystring and parameter "ws_key=webservicekey"

in this case it would be useful to choose authentication mode with account or querystring.

Regards
Max

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.