#StackBounty: #java #api #networking #socket #web-services Java Messenger data transmission

Bounty: 50

This is a very simple concern, could somebody take a look at a few lines of my code? I’m writing a simple Java multi-user messenger, it is structured in a desktop client with a Swing GUI, a java server based on plain sockets and a service library holding general utilities… At the moment I transmit messages through a ObjectOutputStream/ObjectInputStream with a custom Packet class…

package org.x1c1b.carrierpigeon.service.packet;

import java.io.Serializable;
import java.util.Objects;

public class Packet implements Serializable
{
    protected String source;
    protected String destination;

    protected int type;
    protected String payload;

    public Packet(String source, String destination, PacketType type, String payload)
    {
        this.source = source;
        this.destination = destination;

        this.type = type.getIdentifier();
        this.payload = payload;
    }

    public Packet(Packet packet)
    {
        this.source = packet.source;
        this.destination = packet.destination;

        this.type = packet.type;
        this.payload = packet.payload;
    }

    protected Packet(PacketBuilder builer)
    {
        this.source = builer.source;
        this.destination = builer.destination;

        this.type = builer.type;
        this.payload = builer.payload;
    }

    public String getSource()
    {
        return this.source;
    }

    public String getDestination()
    {
        return this.destination;
    }

    public PacketType getType()
    {
        return PacketType.getByIdentifier(this.type);
    }

    public String getPayload()
    {
        return this.payload;
    }

    @Override public boolean equals(Object object)
    {
        if(this == object)
        {
            return true;
        }

        if(object == null || getClass() != object.getClass())
        {
            return false;
        }

        Packet packet = (Packet) object;

        return type == packet.type && Objects.equals(source, packet.source) && Objects
                .equals(destination, packet.destination) && Objects.equals(payload, packet.payload);
    }

    @Override public int hashCode()
    {
        return Objects.hash(this.source, this.destination, this.type, this.payload);
    }
}

This is the Packet class used to transmit the message, for identifying the message purpose I uses a Enum defining different PacketType‘s…

package org.x1c1b.carrierpigeon.service.packet;

import java.util.NoSuchElementException;

public enum PacketType
{
    HANDSHAKE_REQUEST(1),
    HANDSHAKE_REPLY(2),
    HANDSHAKE_ERROR(3),
    AUTHENTICATION_REQUEST(4),
    AUTHENTICATION_REPLY(5),
    AUTHENTICATION_ERROR(6),
    CONNECTIVITY_ESTABLISHED(7),
    CONNECTIVITY_HALTED(8),
    CONNECTIVITY_STATUS(9),
    CONNECTIVITY_SETUP(10),
    CONNECTIVITY_ERROR(11),
    DATA_TRANSFER(12),
    DATA_TRANSFER_ERROR(13);

    private int identifier;

    private PacketType(int identifier)
    {
        this.identifier = identifier;
    }

    public int getIdentifier()
    {
        return this.identifier;
    }

    public static PacketType getByIdentifier(int identifier)
    {
        for(PacketType type : PacketType.values())
        {
            if(type.identifier == identifier)
            {
                return type;
            }
        }

        throw new NoSuchElementException("Identifier: " + identifier);
    }
}

Maybe for taking a look at the whole project:

I’m not that much expired in network development with java, so are there any improvements by transmission of messages? Is it common practice to use ObjectStream‘s with a custom “Protocol”/Packet to transmit data or should I use already existing protocols like HTTP instead? I tried to hold it simple without REST or huge webservers…

I will be glad about any improvements or tips for the data transmission…

EDIT

I also anticipate to write a basic API with the Remote Procedure Call pattern, here a basic example to illustrate what I mean:

public interface MessengerServiceAPI
{
    public abstract boolean login(String name);
}

Here the server-side implementation of the service API:

public class MessengerService implements MessengerServiceAPI
{
    @Override public boolean login(String name)
    {
        // Some login logic and database interaction on server-side
    }
}

Now I superior to call this server-side method with RPC through a ObjectStream:

// Method used on client-side to call remote method of service API

public Object call(String name, Object [] params) throws Exception
{
    try(Socket socket = new Socket(this.address, this.port);
            ObjectOutputStream sout = new ObjectOutputStream(socket.getOutputStream());
            ObjectInputStream sin = new ObjectInputStream(socket.getInputStream()))
    {
        sout.writeObject(name);
        sout.writeObject(params);
        sout.flush();

        Object object = sin.readObject();

        if(object instanceof Exception)
        {
            throw (Exception) object;
        }

        return object;
    }
}

// The server-side handler to handle API requests, which execute the requested action on server-side and return the return value of it

@Override public void handle(Socket socket)
{
    try (ObjectInputStream sin = new ObjectInputStream(socket.getInputStream());
                ObjectOutputStream sout = new ObjectOutputStream(socket.getOutputStream()))
    {
        Object object;
        String name = (String) sin.readObject();
        Object [] params = (Object[]) sin.readObject();

        try
        {
            Class <?> [] paramTypes = null;

            if(null != params)
            {
                types = new Class[params.length];

                for(int index = 0; index < params.length; ++index)
                {
                    paramTypes[index] = params[index].getClass();
                }
            }

            Method method = this.service.getClass().getMethod(name, paramTypes);
            object = method.invoke(this.service, params);
        }
        catch(InvocationTargetException exc)
        {
            object = exc.getTargetException();
        }
        catch(Exception exc)
        {
            object = exc;
        }

        sout.writeObject(object);
        sout.flush();
    }
    catch(Exception exc)
    {
        exc.printStackTrace();
    }
}

This is one possible implementation of such a service handling, but is it recommended to write such a basic API and service? Or is it recommended to send a string or packet instead with a identifier and the server executes the action by parsing this identifier?

Sorry because it is also in big parts software design not just code review but I’m waiting for somebody who takes a look on my code to give tips or improvements…


Get this bounty!!!

#StackBounty: #c# #web-services #wcf Simple Wcf WebService frontend

Bounty: 50

This is a WCF Web Service for customers to send us the definition and update of their items.
Items are : Foo, Foobar. The service expose the “Push” method for those items.
For this review an Mcve has been created with Bogus class foobar. Still The mcve was create simply by renaming class and cutting fluff.
Both orginal file and renamed one had been “tested”, No unit test yet just functional testing.

The aim of this question is to validate the code and the canevas/architechtur.

├DataExchanger
  └Db
    ├DLO.cs
    ├ModelDB.cs
    └Repository.cs
  └Service
    └DataContract
      ├Foo.cs
      ├Bar.cs
      └Foo.cs
    └ServiceContract
      ├IFrontPortal.cs
      └FrontPortalDataExchange.cs
└Utils.cs

DLO.cs:

The class definition for Ef code first. Table have been prefixed to orginise them by name.

[Table("DE_Foos")]
public class Foo {
    [Key]
    public int Id { get; set; }
    [MaxLength(20)]
    public string ExternalId { get; set; }
    public Bar PersonalBar { get; set; }
    public RowInformationDlo RowInformation { get; set; }
}
[Table("DE_Bars")]
public class Bar {
    [Key]
    public int Id { get; set; }
    [MaxLength(20)]
    public string ExternalId { get; set; }
}

[Table("DE_FooBars")]
public class FooBar {
    [Key]
    public int Id { get; set; }
    [MaxLength(20)]
    public string ExternalId { get; set; }
    public List<Foo> Foos { get; set; }
    public List<Bar> Bars { get; set; }
    public RowInformationDlo RowInformation { get; set; }
}

[Table("DE_RowInformation")]
public class RowInformationDlo {
    [Key]
    public int Id { get; set; }
    public DateTime Created { get; set; } = DateTime.Now;
    public string Source { get; set; }
    public DateTime? Updated { get; set; }
    public string UpdateBy { get; set; }
    [MaxLength(50)]
    public string IdentificationKeyFrom { get; set; }
    [MaxLength(50)]
    public string IdentificationKeyContract { get; set; }
    public bool Validate { get; set; } = false;
    public bool Cancel { get; set; } = false;
}

[Table("DE_Log")]
public class LogDlo
{
    [Key]
    public int Id { get; set; }
    public DateTime Date { get; set; } = DateTime.Now;
    [MaxLength(200)]
    public string Logger { get; set; }
    [MaxLength(200)]
    public string From { get; set; }
    public string Message { get; set; }
    public string Dump { get; set; }
    public string Exception { get; set; }
    public RowInformationDlo RowInformation { get; set; } = new RowInformationDlo();
}

ModelDB.cs:

A simple creation of Ef code first table. DropCreateDatabaseIfModelChanges is a dev setting to avoid having migration, proper model changes handeling will be add when

public class DEModelDBcontext : DbContext
{
    public DEModelDBcontext() : base("DEModelDB")
    {
        Database.SetInitializer<DEModelDBcontext>(
              new DropCreateDatabaseIfModelChanges<DEModelDBcontext>()
          );
        public DbSet<Foo> Foos { get; set; }
        public DbSet<Bar> Bars { get; set; }
        public DbSet<FooBar> FooBars { get; set; }
        public DbSet<RowInformationDlo> RowInformationDlos { get; set; }
    }

Repository.cs:

The repository is here mainly for the factorisation of the creation of an Item.

public interface IRepository<T>
{
    void Insert(T entity);
    void Delete(T entity);
    void Update(T entity);
    bool Save();
    IQueryable<T> SearchFor(Expression<Func<T, bool>> predicate);
    IQueryable<T> GetAll();

    [System.Obsolete("Do not load sub entities")]
    T GetById(int id);
}

public class Repository<T> : IRepository<T> where T : class
{

    private DbContext dataContext;
    private DbSet<T> DbSet;

    public Repository(DbContext dataContext)
    {
        DbSet = dataContext.Set<T>();
    }

    public Repository()
    {
        dataContext = new DEModelDBcontext();
        DbSet = dataContext.Set<T>();
    }

    #region

    public void Insert(T entity)
    {
        DbSet.Add(entity);
    }
    public void Delete(T entity)
    {
        DbSet.Remove(entity);
    }
    public void Update(T obj)
    {
        dataContext.Entry(obj).State = EntityState.Modified;
    }
    public bool Save()
    {
        bool result = false;
        try
        {
            result = dataContext.SaveChanges() > 0;
        }
        catch
        {
            // Want to cancel erronous entity and try again ?
        }

        return result;
    }
    public IQueryable<T> SearchFor(Expression<Func<T, bool>> predicate)
    {
        return DbSet.Where(predicate);
    }
    public IQueryable<T> GetAll()
    {
        return DbSet.Select(x => x);
    }
    public T GetById(int id)
    {
        return DbSet.Find(id);
    }
    #endregion
}

IFrontPortal.cs: Service definition

[ServiceContract]
public interface IDataExchanger
{
    [OperationContract]
    bool SetFoo(Foo newFoo);

    [OperationContract]
    bool SetFooBar(FooBar newFooBar);
}

FrontPortalDataExchange.cs: Service implementation

Here the Method Notify as been cut off and can be part of an other question are they are related to the backoffice webservice.

public class DataExchanger : IDataExchanger
{
    private void Notify(int id, string newEntity)
    {} // Notify new entity to the back office Web Service.
    private void Notify(int[] ids, string newEntity)
    {}

    public bool SetFoo(Foo newFoo)
    {
        bool flag = false;
        FooDlo dbFoo;
        try
        {
            dbFoo = newFoo.ToDLO();
            var repo = new Repository<FooDlo>();
            repo.Insert(dbFoo);
            flag = repo.Save();
            Notify(dbFoo.Id, "SetFoo");
        }
        catch (Exception e)
        {
            var errorRepo = new Repository<LogDlo>();
            var temp = new LogDlo
            {
                Exception = "InvalidDataException",
                Message = $"Error with FooDlo, Message=#{e.Message}#",
                Dump = newFoo.ToXML(),
                From = "DataExchanger > SetFoo(Foo newFoo)"
            };
            errorRepo.Insert(temp);
            errorRepo.Save();

            Notify(temp.Id, "Error_SetFoo");
        }
        return flag;
    }

    public bool SetFooBar(FooBar newFooBar)
    {
        bool flag = false;
        FooBarDlo dbFooBar;
        try
        {
            dbFooBar = newFooBar.ToDLO();
            var repo = new Repository<FooBarDlo>();
            repo.Insert(dbFooBar);
            flag = repo.Save();
            Notify(dbFooBar.Id, "SetFoo");
        }
        catch (Exception e)
        {
            var errorRepo = new Repository<LogDlo>();
            var temp = new LogDlo
            {
                Exception = "InvalidDataException",
                Message = $"Error with FooBarDlo, Message=#{e.Message}#",
                Dump = newFooBar.ToXML(),
                From = "DataExchanger > SetFooBar(FooBar newFooBar)"
            };
            errorRepo.Insert(temp);
            errorRepo.Save();

            Notify(temp.Id, "Error_SetFooBar");
        }
        return flag;
    }
}

DataContract

Each class implement a ToDLO returning their Dabatase Equivalent.
This methode use a validate that is use to enforce the contract limitation (size for exemple).
If the web service consumer use an old definition or edited it so his client can send us null on required field. this will throw errors.

[DataContract]
public class FooBar
{
    [DataMember(IsRequired = true)]
    public RequestHeader Header;

    [DataMember(IsRequired = true)]
    [StringLength(20)]
    public string ExternalId;
    [DataMember] public List<Foo> Foos;

    [DataMember] public List<Bar> Bars;

    internal FooBarDlo ToDLO()
    {
        var result = new FooBarDlo()
        {
            ExternalId = this.ExternalId
        };
        result.RowInformation = new RowInformationDlo
        {
            Source = "FrontItemExchanger"
        };
        if (this.Header != null)
        {
            result.RowInformation.IdentificationKeyContract = Header.IdentificationKeyContract;
            result.RowInformation.IdentificationKeyFrom = Header.IdentificationKeyFrom;
        }
        if (this.Foos != null && this.Foos.Any())
        {
            result.Foos = new List<FooDlo>();
            foreach (var a in this.Foos)
            {
                if (a != null)
                {
                    result.Foos.Add(a.ToDLO());
                }
            }
        }
        if (this.Bars != null && this.Bars.Any())
        {
            result.Bars = new List<BarDlo>();
            foreach (var a in this.Bars)
            {
                if (a != null)
                {
                    result.Bars.Add(a.ToDLO());
                }
            }
        }

        result.Validate();
        return result;
    }
}

[DataContract]
public class Bar
{
    [DataMember(IsRequired = true)]
    [StringLength(20)]
    public string ExternalId;
    internal BarDlo ToDLO()
    {
        var result = new BarDlo()
        {
            ExternalId = this.ExternalId
        };
        result.Validate();
        return result;
    }
}

[DataContract]
public class Foo
{
    [DataMember(IsRequired = true)]
    public RequestHeader Header;

    [DataMember(IsRequired = true)]
    [StringLength(20)]
    public string ExternalId;


    internal FooDlo ToDLO()
    {
        var result = new FooDlo()
        {
            ExternalId = this.ExternalId
        };

        result.RowInformation = new RowInformationDlo
        {
            Source = "FrontItemExchanger"
        };
        if (this.Header != null)
        {
            result.RowInformation.IdentificationKeyContract = Header.IdentificationKeyContract;
            result.RowInformation.IdentificationKeyFrom = Header.IdentificationKeyFrom;
        }

        result.RowInformation.Validate();
        result.Validate();
        return result;
    }
}

Utils.cs, brunch of extention method or usefull function.

public static class XmlExtension
{
    public static string ToXML<T>(this T value)
    {
        if (value == null) { return string.Empty; }

        var xmlSerializer = new XmlSerializer(typeof(T));

        using (var stringWriter = new StringWriter())
        {
            using (var xmlWriter = XmlWriter.Create(stringWriter, new XmlWriterSettings { Indent = true }))
            {
                xmlSerializer.Serialize(xmlWriter, value);
                return stringWriter.ToString();
            }
        }
    }

    public static string ToJson<T>(this T value)
    {
        if (value == null) { return string.Empty; }

        var ser = new DataContractJsonSerializer(typeof(T));
        var output = string.Empty;
        using (var ms = new MemoryStream())
        {
            ser.WriteObject(ms, value);
            output = Encoding.UTF8.GetString(ms.ToArray());
        }

        return output;
    }

    public static ICollection<ValidationResult<T>> Validate<T>(this T o, bool throwError = true)
    {
        var results = new List<ValidationResult<T>>();
        var vc = new ValidationContext(o, null, null);

        try
        {
            var problems = new List<ValidationResult>();
            var valid = Validator.TryValidateObject(o, vc, problems, true);

            if (!valid)
            {
                results.AddRange(problems.Select(p => new ValidationResult<T> { FailedItem = o, Message = p.ErrorMessage }));
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }

        if (results.Any() && throwError)
        {
            string err = string.Join(Environment.NewLine, results.Select((x, i) => $" #{i + 1} -{x.Message}"));
            throw new InvalidDataException(err);
        }
        return results;
    }
}

public class ValidationResult<T>
{
    public T FailedItem { get; set; }
    public string Message { get; set; }
}


Get this bounty!!!

#StackBounty: #javascript #performance #node.js #interview-questions #web-services Find currency exchange rates

Bounty: 50

Description:

Design a service to fetch exchange rate from a remote resource and
then calculate the exchange rate for each currency pair.

The remote resource contains the exchange rates of each currency in
Euro.

This is an interview assignment and I came up with an easy solution.

index.js

'use strict';

const joi = require('joi');

const api = require('./api');
const Exchange = require('./exchange');
const xmlParser = require('./parse-xml');

const schema = joi
  .object({
    source: joi.string().required().min(3).max(3).example('EUR'),
    target: joi.string().required().min(3).max(3).example('GBP')
  })
  .unknown()
  .required();

const defaults = {
  timeout: 1000 // 1 sec
};

const exchange = async (pair, options = {}) => {
  options = Object.assign({}, defaults, options);
  const {source, target} = joi.attempt(pair, schema);

  const {requestApi = api, parser = xmlParser} = options;

  const exchange = new Exchange(requestApi, parser, options);
  const rate = await exchange.convert({source, target});
  return {source, target, rate};
};

module.exports = exchange;

exchange.js

'use strict';

const URL = 'https://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml';

class Exchange {
  constructor(api, parser, options = {}) {
    this.api = api;
    this.options = options;
    this.parser = parser;
  }

  async convert({source, target}) {
    if (!this.xml) {
      await this.fetch();
      this.euroToAll = this.parser(this.xml);
    }
    const euroToSource = this.euroToAll[source];
    const euroToTarget = this.euroToAll[target];
    return exchange(euroToSource, euroToTarget);
  }

  async fetch() {
    const response = await this.api.fetch(URL, this.options);
    this.xml = response.body || '';
  }
}

function exchange(from, to) {
  return round(parseFloat(to) / parseFloat(from));
}

function round(result, digits = 4) {
  return Math.round(result * (10 ** digits)) / (10 ** digits);
}

module.exports = Exchange;

parse-xml.js

'use strict';

const xmldoc = require('xmldoc');
const debug = require('debug')('exchange-rate:parse');

const currencies = require('./currencies');

const parse = xml => {
  const doc = new xmldoc.XmlDocument(xml);
  const cube = doc.childNamed('Cube').childNamed('Cube');

  const rates = currencies.reduce(
    (accumulator, currency) => {
      const exchange = cube.childWithAttribute('currency', currency);
      if (exchange) {
        const {rate} = exchange.attr;
        accumulator[currency] = rate;
      } else {
        debug(`Node not found for currency: ${currency}`);
      }
      return accumulator;
    },
    {}
  );
  // Add EUR rate to make it consistent
  rates.EUR = '1.0';
  return rates;
};

module.exports = parse;

api.js

'use strict';

const got = require('got');

module.exports = {
  async fetch(url, options = {}) {
    return got(url, options);
  }
};

Questions:

  1. What if in future we need to add different providers with different representation? How can I make it more flexible and keep the core logic decoupled?
  2. I am also curious to know if the design of the api from the client perspective is good or it can be improved.
  3. In NodeJs we can define dependency via require but I found it difficult to mock them for testing so, I have tried at couple of places to pass dependencies via arguments, is this fine?


Get this bounty!!!

#StackBounty: #file-management #web-services #archiving #multi-user #duplicate-files File download URLs sharing webapp that checks for …

Bounty: 50

I’m looking for a web-based system that supports the following workflow:

  1. User enters a URL of a file and some metadata
  2. The software downloads the file (via http, ftp, torrent?) and calculates one or more hashes (MD5, SHA, etc.)
  3. If it’s a duplicate, the software adds the URL to the file’s list of mirrors

It needs user management and maybe moderation like a wiki or web forum.

I thought of using a wiki but I think it would be too cumbersome. Maybe a document management system?

Musicbrainz is similar to what I am looking for, but for files and URLs.


Get this bounty!!!

#StackBounty: #file-management #web-services #archiving #multi-user #duplicate-files URL-based file catalog?

Bounty: 50

I’m looking for a web-based system that supports the following workflow:

  1. User enters a URL of a file and some metadata
  2. The software downloads the file (via http, ftp, torrent?) and calculates one or more hashes (MD5, SHA, etc.)
  3. If it’s a duplicate, the software adds the URL to the file’s list of mirrors

It needs user management and maybe moderation like a wiki or web forum.

I thought of using a wiki but I think it would be too cumbersome. Maybe a document management system?


Get this bounty!!!

#StackBounty: #php #web-services #wcf #soap PHP SOAP Clients http headers Error

Bounty: 50

I need to consume a web service https://www.example.com/example.svc?wsdl in PHP. For this purpose, I am using PHP SOAP client. The code snippet like below:

$client = new SoapClient("https://www.example.com/example.svc?wsdl",
    array('soap_version' => SOAP_1_2,
        'location'=>'https://www.example.com/example.svc',
        'login'=> '#####',
        'password'=> '#######',
        'exceptions'=>true,
        'trace'=>1,
        'cache_wsdl'=>WSDL_CACHE_NONE,
        'encoding'=>'UTF-8',
        'connection_timeout' => 500,
        'keep_alive' =>false));

$client->__call('getProductList',array());

However, when I run this its through following error:

Warning: SoapClient::__doRequest(): SSL: The operation completed successfully. in E:locationtest1.php on line 37

Fatal error: Uncaught SoapFault exception: [HTTP] Error Fetching http headers in E:locationtest1:37 Stack trace: #0 [internal function]: SoapClient->__doRequest('<?xml version="...', 'https://travius...', 'Travius/ITraviu...', 2, 0) #1 E:locationtest1(37): SoapClient->__call('getProductList', Array) #2 {main} thrown in E:locationtest1.php on line 37

I am struggling several days to solve the error but can’t figure out. I tried the different solution in stack overflow like 'keep_alive' =>false, connection_timeout but nothing works.

I also try with php nusoap library. its request and response are like following:

Error

HTTP Error: Unsupported HTTP response status 400 Bad Request (soapclient->response has contents of the response)

Request

POST /#####.svc?wsdl HTTP/1.0
Host: #####.#####.eu
User-Agent: NuSOAP/0.9.5 (1.123)
Content-Type: application/soap+xml;charset=UTF-8; charset=UTF-8
SOAPAction: ""
Authorization: Basic RGVtb2FwaTpEdXE1dmRWdA==
Content-Length: 529

<?xml version="1.0" encoding="UTF-8"?><SOAP-ENV:Envelope SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" xmlns:SOAP-ENV="http://www.w3.org/2003/05/soap-envelope" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"><SOAP-ENV:Body><GetProduct><parameters><intProductID xsi:type="xsd:int">1266</intProductID><lang xsi:type="xsd:string">CN</lang></parameters></GetProduct></SOAP-ENV:Body></SOAP-ENV:Envelope>

Response

HTTP/1.1 400 Bad Request
Server: Microsoft-IIS/7.5
X-Powered-By: ASP.NET
Date: Mon, 02 Oct 2017 16:03:04 GMT
Content-Length: 0

Any help highly appreciated. Thanks in advance.


Get this bounty!!!

#StackBounty: #orders #ce-1.9.1.0 #sales #web-services #integration Sending order XML to web service

Bounty: 50

I have a requirement to create a scheduled task that will send orders (since the last time the task ran) to an external web service. The data needs to be sent in cXML format and one xml per order. It needs to be the cXML formatted data rather than actual file.

I’m looking for some advice really on how best to accomplish this. I have created a base module with a cronjob that will run every 5 minutes.

I have a Model/Export.php as follows that is pretty basic at the moment to just get orders with specific statuses;

class OrderSync_Model_Export
{

    public function ExportSales()
    {
        //A collection of orders
        $order = Mage::getModel('sales/order')->getCollection();
        $order->addAttributeToFilter('status', array('in' => array('pending','complete')));
        $orders = $order->getItems();
    }
}

I obviously then need to get the specific data from each order but the part i’m not sure is how to get/send each individual order as cXML ( http://cxml.org/) to the web service. I assume I would probably need to cURL this to the web service but it’s the part about sending each individual order when the cronjob runs that i’m not so sure of and wondered if someone might be able to help?

Also, the web service returns a response for each order cXML that it receives like so and I’d like to be able to update an order attribute with the status detail (code and text) if anyone has any pointers for this too?

The example response is as follows;

<?xml version="1.0" encoding="utf-16"?>
<cXML payloadID="int.coupahost.com" xml:lang="en" timestamp="2017-04-06T11:43:25.2681984+01:00">
  <Response>
    <Status code="500" text="Price does not match current pricelist- 653244    Possibly out of date Pricelist, Please contact supplier for updated pricelist " />
  </Response>
</cXML>


Get this bounty!!!

#StackBounty: #orders #sales-order #sales #web-services #integration Sending order XML to web service

Bounty: 50

I have a requirement to create a scheduled task that will send orders (since the last time the task ran) to an external web service. The data needs to be sent in cXML format and one xml per order. It needs to be the cXML formatted data rather than actual file.

I’m looking for some advice really on how best to accomplish this. I have created a base module with a cronjob that will run every 5 minutes.

I have a Model/Export.php as follows that is pretty basic at the moment to just get orders with specific statuses;

class OrderSync_Model_Export
{

    public function ExportSales()
    {
        //A collection of orders
        $order = Mage::getModel('sales/order')->getCollection();
        $order->addAttributeToFilter('status', array('in' => array('pending','complete')));
        $orders = $order->getItems();
    }
}

I obviously then need to get the specific data from each order but the part i’m not sure is how to get/send each individual order as cXML ( http://cxml.org/) to the web service. I assume I would probably need to cURL this to the web service but it’s the part about sending each individual order when the cronjob runs that i’m not so sure of and wondered if someone might be able to help?

Also, the web service returns a response for each order cXML that it receives like so and I’d like to be able to update an order attribute with the status detail (code and text) if anyone has any pointers for this too?

The example response is as follows;

<?xml version="1.0" encoding="utf-16"?>
<cXML payloadID="int.coupahost.com" xml:lang="en" timestamp="2017-04-06T11:43:25.2681984+01:00">
  <Response>
    <Status code="500" text="Price does not match current pricelist- 653244    Possibly out of date Pricelist, Please contact supplier for updated pricelist " />
  </Response>
</cXML>


Get this bounty!!!

#StackBounty: #c# #asp.net #.net #web-services #asp.net-core .NET Core 2.0 & old WebService error

Bounty: 50

I’ve been trying to rewrite an older web application in the latest version of .NET Core. The project started out in .NET Core 1.1 but we quickly realized we’d have to move to .NET 2.0 (currently in preview 2) so that we could get access to DataSets/DataTables since our middleware service uses them and we’re not looking to upgrade them as of right now.

From what I’m seeing everything is correct and connecting to the service works as expected when using the “HelloWorldAsync” test. The problem comes when we use our execute method that contains a DataSet as one of the parameters. I’ve literally boiled down the issue to that (the DataSet Paramenter) specific parameter.

Helper Method

    public async static Task<DataSet> CheckTIN(int TIN) {
        ParameterArrayBuilder pab = new ParameterArrayBuilder();
        pab.Add("@TIN", SqlDbType.Int, TIN);

        DataSet ds = await GetData("usp_CheckTIN", pab);
        if (ds == null) {
            ds.Tables.Add();
        }
        return ds;
    }

    public async static Task<string> HellowWorldAsync() {
        BusLogic40.FactorySoapClient factory = new BusLogic40.FactorySoapClient(BusLogic40.FactorySoapClient.EndpointConfiguration.FactorySoap, "http://localhost/BusLogic40/Request.asmx");
        var result = await factory.HelloWorldAsync();

        return result;
    }

    private async static Task<DataSet> GetData(string procedure, ParameterArrayBuilder pab) {
        string ProviderName = "";
        string Service = "";
        string AuthKey = "";
        string CmdName = procedure;

        BusLogic40.FactorySoapClient factory = new BusLogic40.FactorySoapClient(BusLogic40.FactorySoapClient.EndpointConfiguration.FactorySoap, "http://localhost/BusLogic40/Request.asmx");

        var theDataSet = await factory.ExecuteAsync(ProviderName, Service, AuthKey, CmdName, pab.AsDataSet());

        if (theDataSet.Tables.Count > 0) {
            return theDataSet;
        } else {
            return null;
        }
    }

Results

Application version: 1.0.0.0
AspNetCoreEnvironment: Development
Client IP address: ::1
DeveloperMode: true
Event time: 7/5/2017 4:50:58 PM
Exception type: System.ServiceModel.FaultException
handledAt: Platform
Message: System.Web.Services.Protocols.SoapException: Server was unable to read request. ---> System.InvalidOperationException: There is an error in XML document (1, 1269). ---> System.ArgumentException: Column requires a valid DataType.
   at System.Data.DataColumn.set_DataType(Type value)
   at System.Data.XSDSchema.SetProperties(Object instance, XmlAttribute[] attrs)
   at System.Data.XSDSchema.HandleElementColumn(XmlSchemaElement elem, DataTable table, Boolean isBase)
   at System.Data.XSDSchema.HandleParticle(XmlSchemaParticle pt, DataTable table, ArrayList tableChildren, Boolean isBase)
   at System.Data.XSDSchema.HandleComplexType(XmlSchemaComplexType ct, DataTable table, ArrayList tableChildren, Boolean isNillable)
   at System.Data.XSDSchema.InstantiateTable(XmlSchemaElement node, XmlSchemaComplexType typeNode, Boolean isRef)
   at System.Data.XSDSchema.HandleTable(XmlSchemaElement node)
   at System.Data.XSDSchema.HandleDataSet(XmlSchemaElement node, Boolean isNewDataSet)
   at System.Data.XSDSchema.LoadSchema(XmlSchemaSet schemaSet, DataSet ds)
   at System.Data.DataSet.ReadXml(XmlReader reader, XmlReadMode mode, Boolean denyResolving)
   at System.Data.DataSet.System.Xml.Serialization.IXmlSerializable.ReadXml(XmlReader reader)
   at System.Xml.Serialization.XmlSerializationReader.ReadSerializable(IXmlSerializable serializable, Boolean wrappedAny)
   at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReader1.Read3_Execute()
   at Microsoft.Xml.Serialization.GeneratedAssembly.ArrayOfObjectSerializer4.Deserialize(XmlSerializationReader reader)
   at System.Xml.Serialization.XmlSerializer.Deserialize(XmlReader xmlReader, String encodingStyle, XmlDeserializationEvents events)
   --- End of inner exception stack trace ---
   at System.Xml.Serialization.XmlSerializer.Deserialize(XmlReader xmlReader, String encodingStyle, XmlDeserializationEvents events)
   at System.Web.Services.Protocols.SoapServerProtocol.ReadParameters()
   --- End of inner exception stack trace ---
   at System.Web.Services.Protocols.SoapServerProtocol.ReadParameters()
   at System.Web.Services.Protocols.WebServiceHandler.CoreProcessRequest()
Node name:
Operation ID: 0HL63ONV9T29O
Operation name: GET Home/Index
Problem ID: System.ServiceModel.FaultException at Infx.FIDM.WebUI.SecureWebUI.Helpers.Utilities.GetData
Role instance:
SDK version: aspnet5c:2.0.0

Stack Trace
System.ServiceModel.FaultException: System.Web.Services.Protocols.SoapException: Server was unable to read request. ---> System.InvalidOperationException: There is an error in XML document (1, 1269). ---> System.ArgumentException: Column requires a valid DataType.
   at System.Data.DataColumn.set_DataType(Type value)
   at System.Data.XSDSchema.SetProperties(Object instance, XmlAttribute[] attrs)
   at System.Data.XSDSchema.HandleElementColumn(XmlSchemaElement elem, DataTable table, Boolean isBase)
   at System.Data.XSDSchema.HandleParticle(XmlSchemaParticle pt, DataTable table, ArrayList tableChildren, Boolean isBase)
   at System.Data.XSDSchema.HandleComplexType(XmlSchemaComplexType ct, DataTable table, ArrayList tableChildren, Boolean isNillable)
   at System.Data.XSDSchema.InstantiateTable(XmlSchemaElement node, XmlSchemaComplexType typeNode, Boolean isRef)
   at System.Data.XSDSchema.HandleTable(XmlSchemaElement node)
   at System.Data.XSDSchema.HandleDataSet(XmlSchemaElement node, Boolean isNewDataSet)
   at System.Data.XSDSchema.LoadSchema(XmlSchemaSet schemaSet, DataSet ds)
   at System.Data.DataSet.ReadXml(XmlReader reader, XmlReadMode mode, Boolean denyResolving)
   at System.Data.DataSet.System.Xml.Serialization.IXmlSerializable.ReadXml(XmlReader reader)
   at System.Xml.Serialization.XmlSerializationReader.ReadSerializable(IXmlSerializable serializable, Boolean wrappedAny)
   at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReader1.Read3_Execute()
   at Microsoft.Xml.Serialization.GeneratedAssembly.ArrayOfObjectSerializer4.Deserialize(XmlSerializationReader reader)
   at System.Xml.Serialization.XmlSerializer.Deserialize(XmlReader xmlReader, String encodingStyle, XmlDeserializationEvents events)
   --- End of inner exception stack trace ---
   at System.Xml.Serialization.XmlSerializer.Deserialize(XmlReader xmlReader, String encodingStyle, XmlDeserializationEvents events)
   at System.Web.Services.Protocols.SoapServerProtocol.ReadParameters()
   --- End of inner exception stack trace ---
   at System.Web.Services.Protocols.SoapServerProtocol.ReadParameters()
   at System.Web.Services.Protocols.WebServiceHandler.CoreProcessRequest()
    at  System.ServiceModel.Channels.ServiceChannel.HandleReply(ProxyOperationRuntime operation, ProxyRpc& rpc)
    at  System.ServiceModel.Channels.ServiceChannel.EndCall(String action, Object[] outs, IAsyncResult result)
    at  System.ServiceModel.Channels.ServiceChannelProxy.TaskCreator.<>c__DisplayClass1_0.<CreateGenericTask>b__0(IAsyncResult asyncResult)
    at  End of stack trace from previous location where exception was thrown ---
    at  System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
    at  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
    at  System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
    at  Infx.FIDM.WebUI.SecureWebUI.Helpers.Utilities.<GetData>d__2.MoveNext() in C:ProjectsFIDMWebInfx.FIDM.WebUI.SecureWebUIHelpersUtilities.cs:line 32
    at  End of stack trace from previous location where exception was thrown ---
    at  System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
    at  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
    at  System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
    at  Infx.FIDM.WebUI.SecureWebUI.Helpers.Utilities.<CheckTIN>d__0.MoveNext() in C:ProjectsFIDMWebInfx.FIDM.WebUI.SecureWebUIHelpersUtilities.cs:line 11
    at  End of stack trace from previous location where exception was thrown ---
    at  System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
    at  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
    at  System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
    at  Infx.FIDM.WebUI.SecureWebUI.Controllers.HomeController.<Index>d__0.MoveNext() in C:ProjectsFIDMWebInfx.FIDM.WebUI.SecureWebUIControllersHomeController.cs:line 8
    at  End of stack trace from previous location where exception was thrown ---
    at  System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
    at  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
    at  Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.<InvokeActionMethodAsync>d__27.MoveNext()
    at  End of stack trace from previous location where exception was thrown ---
    at  System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
    at  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
    at  Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.<InvokeNextActionFilterAsync>d__25.MoveNext()
    at  End of stack trace from previous location where exception was thrown ---
    at  System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
    at  Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Rethrow(ActionExecutedContext context)
    at  Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
    at  Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.<InvokeNextResourceFilter>d__22.MoveNext()
    at  End of stack trace from previous location where exception was thrown ---
    at  System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
    at  Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Rethrow(ResourceExecutedContext context)
    at  Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
    at  Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.<InvokeAsync>d__20.MoveNext()
    at  End of stack trace from previous location where exception was thrown ---
    at  System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
    at  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
    at  Microsoft.AspNetCore.Builder.RouterMiddleware.<Invoke>d__4.MoveNext()
    at  End of stack trace from previous location where exception was thrown ---
    at  System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
    at  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
    at  Microsoft.VisualStudio.Web.BrowserLink.BrowserLinkMiddleware.<ExecuteWithFilter>d__7.MoveNext()
    at  End of stack trace from previous location where exception was thrown ---
    at  System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
    at  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
    at  Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.<Invoke>d__7.MoveNext()


Get this bounty!!!

#StackBounty: #web-development #api #web-services #analytics Analytics API to gather data for display in own product

Bounty: 50

I am developing a web app which has users include a javascript snippet on their site, I want to track analytics related to that widget e.g. how often did I user click a button on that widget.

Now, I could just ping back to my server, dump all that data in a Redis and synchronize that data with my sql database at regular intervals.
However, I am wondering whether there is some service out there where I can simply dump events in different buckets and read from it through their API.
Thanks in advance.


Get this bounty!!!