Esempio n. 1
0
    public async Task <ApiError> BuyFromOfferAsync(int buyerid, long quantity, OfferModel offer, bool oldestfirst)
    {
        var checkresult = await ValidateModelAsync(offer, true);

        if (!checkresult.Successful)
        {
            return(checkresult);
        }
        if (buyerid <= 0)
        {
            return(new(string.Format(Strings.Invalid, "buyer id")));
        }
        if (quantity == 0)
        {
            return(new(string.Format(Strings.Invalid, "quantity")));
        }
        OfferEntity entity = offer !;

        try
        {
            return(ApiError.FromDalResult(await _offerRepository.BuyFromOfferAsync(buyerid, quantity, entity, oldestfirst)));
        }
        catch (Exception ex)
        {
            return(ApiError.FromException(ex));
        }
    }
Esempio n. 2
0
    public async Task <ApiError> InsertAsync(OfferModel model)
    {
        var checkresult = await ValidateModelAsync(model);

        if (!checkresult.Successful)
        {
            return(checkresult);
        }
        OfferEntity entity = model !;

        try
        {
            var result = await _offerRepository.InsertAsync(entity);

            if (result.Successful)
            {
                model.Id = entity.Id;
            }
            return(ApiError.FromDalResult(result));
        }
        catch (Exception ex)
        {
            return(ApiError.FromException(ex));
        }
    }
Esempio n. 3
0
        public async Task AddResourceAsync(string token, Personal personal)
        {
            NullCheck.ThrowIfNull <Personal>(personal);

            OfferEntity offerEntity = await _queryHelper.RetrieveOfferFromTokenAsync(token);

            await InsertAsync(offerEntity.id, personal);
        }
Esempio n. 4
0
        public async Task AddResourceAsync(string token, Device device)
        {
            NullCheck.ThrowIfNull <Device>(device);

            OfferEntity offerEntity = await _queryHelper.RetrieveOfferFromTokenAsync(token);

            await InsertAsync(offerEntity.id, device);
        }
Esempio n. 5
0
        public async Task AddResourceAsync(string token, Consumable consumable)
        {
            NullCheck.ThrowIfNull <Consumable>(consumable);

            OfferEntity offerEntity = await _queryHelper.RetrieveOfferFromTokenAsync(token);

            await InsertAsync(offerEntity.id, consumable);
        }
 protected object[] Take(OfferEntity offer)
 {
     return(new object[] {
         "@EmpID", offer.EmpID,
         "@SupID", offer.SupID,
         "@OffDate", offer.OffDate,
     });
 }
Esempio n. 7
0
 public Provider Build(OfferEntity o)
 {
     NullCheck.ThrowIfNull <OfferEntity>(o);
     name         = o.name;
     organisation = o.organisation;
     phone        = o.phone;
     mail         = o.mail;
     ispublic     = o.ispublic;
     return(this);
 }
Esempio n. 8
0
        public async Task <string> InsertAsync(Offer offer, string region)
        {
            NullCheck.ThrowIfNull <Offer>(offer);

            var provider = offer.provider;

            //Build as entities

            var offerEntity        = new OfferEntity().Build(provider, region);
            var offerAddressEntity = new AddressEntity().build(provider.address);

            //Create the coordinates and store the address of the offer

            _addressMaker.SetCoordinates(offerAddressEntity);
            await offerAddressEntity.InsertAsync(_context);

            //Store the offer including the address id as foreign key, the token and a timestamp
            offerEntity.address_id = offerAddressEntity.Id;
            offerEntity.token      = createToken();
            offerEntity.timestamp  = DateTime.Now;
            await offerEntity.InsertAsync(_context);

            //create the entities for the resources, calculate their coordinates, give them the offer foreign key and store them
            //Update the original offer with the ids from the created entities (helps us for testing and if we want to do more stuff with the offer in future features)

            int offer_id = offerEntity.id;

            if (!(offer.consumables is null))
            {
                foreach (var c in offer.consumables)
                {
                    await InsertAsync(offer_id, c);
                }
            }
            if (!(offer.personals is null))
            {
                foreach (var p in offer.personals)
                {
                    await InsertAsync(offer_id, p);
                }
            }
            if (!(offer.devices is null))
            {
                foreach (var d in offer.devices)
                {
                    await InsertAsync(offer_id, d);
                }
            }

            //Give back only the token
            return(offerEntity.token);
        }
Esempio n. 9
0
 public static OfferModel ToDto(OfferEntity entity)
 {
     return(new OfferModel
     {
         OffID = entity.OffID,
         EmpID = entity.EmpID,
         EmpName = entity.EmpName,
         SupID = entity.SupID,
         SupName = entity.SupName,
         OffDate = entity.OffDate,
         OffStatus = entity.OffStatus,
         OffEnabled = entity.OffEnabled,
         EmpApprove = entity.EmpApprove
     });
 }
Esempio n. 10
0
        public async Task MarkDeviceAsDeletedAsync(string token, int deviceId, string reason)
        {
            NullCheck.ThrowIfNull <string>(token);
            NullCheck.ThrowIfNull <string>(reason);

            if (reason.Trim().Length == 0)
            {
                throw new ArgumentException(FailureCodes.InvalidReason);
            }

            // Get device from database
            var query =
                from o in _context.offer as IQueryable <OfferEntity>
                join d in _context.device on o.id equals d.offer_id
                where token == o.token && d.id == deviceId
                select new { d, o };

            var foundDevices = await query.ToListAsync();

            if (foundDevices.Count == 0)
            {
                throw new DataNotFoundException(FailureCodes.NotFoundConsumable);
            }

            DeviceEntity deviceEntity = foundDevices[0].d;
            OfferEntity  offerEntity  = foundDevices[0].o;

            deviceEntity.is_deleted = true;
            await deviceEntity.UpdateAsync(_context);

            await new ChangeEntity()
            {
                change_type      = ChangeEntityChangeType.DeleteResource,
                element_id       = deviceEntity.id,
                element_type     = ChangeEntityElementType.Device,
                element_category = deviceEntity.category,
                element_name     = deviceEntity.name,
                diff_amount      = deviceEntity.amount,
                reason           = reason,
                timestamp        = DateTime.Now,
                region           = offerEntity.region
            }.InsertAsync(_context);
        }
Esempio n. 11
0
    public async Task <ApiError> UpdateAsync(OfferModel model)
    {
        var checkresult = await ValidateModelAsync(model, true);

        if (!checkresult.Successful)
        {
            return(checkresult);
        }
        OfferEntity entity = model !;

        try
        {
            return(ApiError.FromDalResult(await _offerRepository.UpdateAsync(entity)));
        }
        catch (Exception ex)
        {
            return(ApiError.FromException(ex));
        }
    }
Esempio n. 12
0
        public async Task MarkPersonalAsDeletedAsync(string token, int personalId, string reason)
        {
            NullCheck.ThrowIfNull <string>(reason);

            if (reason.Trim().Length == 0)
            {
                throw new ArgumentException(FailureCodes.InvalidReason);
            }

            // Get personal from database
            var query =
                from o in _context.offer as IQueryable <OfferEntity>
                join p in _context.personal on o.id equals p.offer_id
                where token == o.token && p.id == personalId
                select new { p, o };

            var foundPersonals = await query.ToListAsync();

            if (foundPersonals.Count == 0)
            {
                throw new DataNotFoundException(FailureCodes.NotFoundPersonal);
            }

            PersonalEntity personalEntity = foundPersonals[0].p;
            OfferEntity    offerEntity    = foundPersonals[0].o;

            personalEntity.is_deleted = true;
            await personalEntity.UpdateAsync(_context);

            await new ChangeEntity()
            {
                change_type      = ChangeEntityChangeType.DeleteResource,
                element_id       = personalEntity.id,
                element_type     = ChangeEntityElementType.Personal,
                element_category = personalEntity.qualification,
                element_name     = null,
                diff_amount      = 1,
                reason           = reason,
                timestamp        = DateTime.Now,
                region           = offerEntity.region
            }.InsertAsync(_context);
        }
Esempio n. 13
0
        public async Task ChangeDeviceAmountAsync(string token, int deviceId, int newAmount, string reason)
        {
            NullCheck.ThrowIfNull <string>(token);

            // Get device from database
            var query =
                from o in _context.offer as IQueryable <OfferEntity>
                join d in _context.device on o.id equals d.offer_id
                where token == o.token && d.id == deviceId
                select new { d, o };

            var foundDevices = await query.ToListAsync();

            if (foundDevices.Count == 0)
            {
                throw new DataNotFoundException(FailureCodes.NotFoundDevice);
            }

            DeviceEntity device = foundDevices[0].d;
            OfferEntity  offer  = foundDevices[0].o;

            // If amount has not changed: do nothing
            if (device.amount == newAmount)
            {
                return;
            }

            int diffAmount = Math.Abs(newAmount - device.amount);

            // If amount has increased: no reason required
            if (device.amount < newAmount)
            {
                device.amount = newAmount;
                await device.UpdateAsync(_context);

                // Add log
                await new ChangeEntity()
                {
                    change_type      = "INCREASE_AMOUNT",
                    element_id       = device.id,
                    element_type     = "device",
                    element_category = device.category,
                    element_name     = device.name,
                    diff_amount      = diffAmount,
                    reason           = reason,
                    timestamp        = DateTime.Now,
                    region           = offer.region
                }.InsertAsync(_context);

                return;
            }

            NullCheck.ThrowIfNull <string>(reason);

            // If amount has decreased: ensure that a reason is provided
            if (reason.Trim().Length == 0)
            {
                throw new ArgumentException(FailureCodes.InvalidReason);
            }
            if (newAmount < 1)
            {
                throw new ArgumentException(FailureCodes.InvalidAmountDevice);
            }
            device.amount = newAmount;
            await device.UpdateAsync(_context);

            // Add log
            await new ChangeEntity()
            {
                change_type      = "DECREASE_AMOUNT",
                element_id       = device.id,
                element_type     = "device",
                element_category = device.category,
                element_name     = device.name,
                diff_amount      = diffAmount,
                reason           = reason,
                timestamp        = DateTime.Now,
                region           = offer.region
            }.InsertAsync(_context);
        }
Esempio n. 14
0
 public static OfferModel?FromEntity(OfferEntity entity) => entity is null ? null : new()
Esempio n. 15
0
        public async Task <bool> UpdateThroughputAsync(string correlationId, int throughput)
        {
            try
            {
                // 1. Get collection
                CollectionEntity collectionEntity = null;

                var client = UpdateHttpClientWithHeader("GET", "colls", $"dbs/{DatabaseName}/colls/{CollectionName}");
                {
                    var uri      = new Uri($"{BaseUri}/dbs/{DatabaseName}/colls/{CollectionName}");
                    var response = await client.GetAsync(uri);

                    var responseContent = await response.Content.ReadAsStringAsync();

                    if (response.IsSuccessStatusCode)
                    {
                        collectionEntity = JsonConverter.FromJson <CollectionEntity>(responseContent);
                        if (collectionEntity == null)
                        {
                            throw new NotFoundException(correlationId, "NotFound", $"Unable to find collection '{CollectionName}'. Response Content: {responseContent}");
                        }
                        Logger.Trace(correlationId, $"UpdateThroughputAsync: Found collection '{CollectionName}'.");
                    }
                    else
                    {
                        throw new ConnectionException(correlationId, "ConnectFailed", $"Error while getting info about collection '{CollectionName}'. Response Content: {responseContent}");
                    }
                }

                // 2. Retrieve offer of collection (throughput)
                OfferEntity offerEntity = null;
                client = UpdateHttpClientWithHeader("POST", "offers", "");
                {
                    client.DefaultRequestHeaders.Add("x-ms-documentdb-isquery", "True");

                    var uri      = new Uri($"{BaseUri}/offers");
                    var value    = new { query = $"SELECT * FROM root WHERE (root[\"offerResourceId\"] = \"{collectionEntity.ResourceId}\")" };
                    var response = await client.PostAsync(uri, value, new NoCharSetJsonMediaTypeFormatter());

                    var responseContent = await response.Content.ReadAsStringAsync();

                    if (response.IsSuccessStatusCode)
                    {
                        var searchOffersEntity = JsonConverter.FromJson <SearchOffersEntity>(responseContent);
                        offerEntity = searchOffersEntity?.Offers?.FirstOrDefault();
                        if (offerEntity == null || offerEntity.Content == null)
                        {
                            throw new NotFoundException(correlationId, "NotFound", $"Unable to find offer of collection '{CollectionName}'. Response Content: {responseContent}");
                        }

                        Logger.Trace(correlationId, $"UpdateThroughputAsync: The current throughput of collection '{CollectionName}' is: '{offerEntity?.Content?.OfferThroughput}'.");
                    }
                    else
                    {
                        throw new ConnectionException(correlationId, "ConnectFailed", $"Error while getting offer of collection '{CollectionName}'. Response Content: {responseContent}");
                    }
                }

                // 3. Verify existing throughput
                if (throughput.Equals(offerEntity.Content.OfferThroughput))
                {
                    Logger.Trace(correlationId, $"UpdateThroughputAsync: Skip to update throughput of collection '{CollectionName}' with the same throughput: '{throughput}'.");
                    return(await Task.FromResult(true));
                }

                // 4. Update offer (new throughput)
                offerEntity.Content.OfferThroughput = throughput;
                client = UpdateHttpClientWithHeader("PUT", "offers", $"{offerEntity.Id.ToLower()}");
                {
                    var uri      = new Uri($"{BaseUri}/offers/{offerEntity.Id.ToLower()}");
                    var response = await client.PutAsJsonAsync(uri, offerEntity);

                    var responseContent = await response.Content.ReadAsStringAsync();

                    if (response.IsSuccessStatusCode)
                    {
                        var resultOfferEntity = JsonConverter.FromJson <OfferEntity>(responseContent);
                        Logger.Trace(correlationId, $"UpdateThroughputAsync: The updated throughput of collection '{CollectionName}' is: '{resultOfferEntity?.Content?.OfferThroughput}'.");
                    }
                    else
                    {
                        throw new ConnectionException(correlationId, "ConnectFailed", $"Error while updating throughput of collection '{CollectionName}'. Response Content: {responseContent}");
                    }
                }
            }
            catch (Exception exception)
            {
                Logger.Error(correlationId, exception, $"UpdateThroughputAsync: Failed to update throughput to '{throughput}' of the collection '{CollectionName}' in the CosmosDB database '{DatabaseName}'.");
                return(await Task.FromResult(false));
            }

            return(await Task.FromResult(true));
        }
 public Offer(OfferEntity entity)
 {
     hero   = entity.RowKey;
     seller = entity.PartitionKey;
     price  = Convert.ToDouble(entity.Price);
 }
Esempio n. 17
0
 internal Offer(OfferEntity entity)
 {
     _backingField = entity;
 }