Frapid.WebApi.DataAccess.FormRepository.BulkImportAsync C# (CSharp) Method

BulkImportAsync() public method

public BulkImportAsync ( object>.List items ) : Task>
items object>.List
return Task>
        public async Task<List<object>> BulkImportAsync(List<Dictionary<string, object>> items)
        {
            if (!this.SkipValidation)
            {
                if (!this.Validated)
                {
                    await this.ValidateAsync(AccessTypeEnum.ImportData, this.LoginId, this.Database, false).ConfigureAwait(false);
                }

                if (!this.HasAccess)
                {
                    Log.Information(
                        $"Access to import entity \"{this.FullyQualifiedObjectName}\" was denied to the user with Login ID {this.LoginId}.");
                    throw new UnauthorizedException("Access is denied.");
                }
            }

            var result = new List<object>();
            int line = 0;
            using (var db = DbProvider.GetDatabase(this.Database))
            {
                try
                {
                    await db.BeginTransactionAsync().ConfigureAwait(false);

                    items = this.Crypt(items);

                    foreach (var item in items)
                    {
                        line++;

                        item["audit_user_id"] = this.UserId;
                        item["audit_ts"] = DateTimeOffset.UtcNow;
                        item["deleted"] = false;

                        var primaryKeyValue = item[this.PrimaryKey];

                        if (primaryKeyValue != null)
                        {
                            result.Add(primaryKeyValue);
                            var sql = new Sql("UPDATE " + this.FullyQualifiedObjectName + " SET");

                            int index = 0;

                            foreach (var prop in item.Where(x => !x.Key.Equals(this.PrimaryKey)))
                            {
                                if (index > 0)
                                {
                                    sql.Append(",");
                                }

                                sql.Append(Sanitizer.SanitizeIdentifierName(prop.Key) + "=@0", prop.Value);
                                index++;
                            }


                            sql.Where(this.PrimaryKey + "=@0", primaryKeyValue);

                            await db.NonQueryAsync(sql).ConfigureAwait(false);
                        }
                        else
                        {
                            string columns = string.Join(",",
                                item.Where(x => !x.Key.Equals(this.PrimaryKey))
                                    .Select(x => Sanitizer.SanitizeIdentifierName(x.Key)));

                            string parameters = string.Join(",",
                                Enumerable.Range(0, item.Count - 1).Select(x => "@" + x));
                            var arguments =
                                item.Where(x => !x.Key.Equals(this.PrimaryKey)).Select(x => x.Value).ToArray();

                            var sql = new Sql("INSERT INTO " + this.FullyQualifiedObjectName + "(" + columns + ")");
                            sql.Append("SELECT " + parameters, arguments);

                            sql.Append(FrapidDbServer.AddReturnInsertedKey(this.Database, this.PrimaryKey));

                            result.Add(await db.ScalarAsync<object>(sql).ConfigureAwait(false));
                        }
                    }

                    db.CommitTransaction();

                    return result;
                }
                catch (Exception ex)
                {
                    db.RollbackTransaction();
                    string errorMessage = $"Error on line {line}. {ex.Message} ";
                    throw new DataAccessException(errorMessage, ex);
                }
            }
        }

Usage Example

Esempio n. 1
0
        public async Task<List<object>> BulkImportAsync(string schemaName, string tableName, [FromBody] JArray collection)
        {
            var items = this.ParseCollection(collection);

            if(items == null ||
               items.Count.Equals(0))
            {
                return null;
            }

            try
            {
                var repository = new FormRepository(schemaName, tableName, this.AppUser.Tenant, this.AppUser.LoginId, this.AppUser.UserId);
                return await repository.BulkImportAsync(items).ConfigureAwait(false);
            }
            catch(UnauthorizedException)
            {
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden));
            }
            catch(DataAccessException ex)
            {
                throw new HttpResponseException
                    (
                    new HttpResponseMessage
                    {
                        Content = new StringContent(ex.Message),
                        StatusCode = HttpStatusCode.InternalServerError
                    });
            }
#if !DEBUG
            catch
            {
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError));
            }
#endif
        }