ra0o0f / arangoclient.net

ArangoDB .NET Client with LINQ support
Apache License 2.0
99 stars 37 forks source link

Cannot Simply Connect to Server...... #139

Open ahmedfarazdev opened 3 years ago

ahmedfarazdev commented 3 years ago

I cannot Understand the documentation to get connected to the server and work with a simple database plz Guide my with the sytax code example

Tridy commented 2 years ago

I am trying to see if there is a way of using LINQ with Arango, so I ended up there. I looked at the project tests and was able to connect to the database by creating HttpTransport and then a client like this:

[Fact]
public async Task CanQueryArango()
{
    HttpApiTransport transport = GetHttpTransport();
    ArangoDBClient client = new (transport);
    var products = await client.Document.GetDocumentsAsync<MyType>("MyCollection", new[] { "MyKey" });
    Assert.Single(products);
}

protected HttpApiTransport GetHttpTransport()
{
    var transport = HttpApiTransport.UsingBasicAuth(
        new Uri("ARANGO_ADDRESS_AND_PORT"),
        "ARANGO_DB",
        "root",
        "root");

    return transport;
}
aligin commented 2 years ago

First, you can use such snippet to connet to arango in ASP.NET Core. This snippet gives you the IConfiguration and Action<> methods to configure the ArangoDb context to use in the DI.

Create an extention to connect to ArangoDb.

namespace Monq
{
    public static class ArangoDbServiceCollectionExtensions
    {
        /// <summary>
        /// Register ArangoDb context in the DI.
        /// </summary>
        /// <param name="services">DI Services collection.</param>
        /// <param name="setupAction">The setup options method that configures the ArangoDb client connection.</param>
        /// <returns></returns>
        public static IServiceCollection AddArangoDbClient(this IServiceCollection services, Action<DatabaseSharedSetting> setupAction)
        {
            var dbOptions = new DatabaseSharedSetting();
            setupAction(dbOptions);
            services.Configure<IOptions<DatabaseSharedSetting>>(x => Options.Create(dbOptions));

            ArangoDatabase.ChangeSetting(setupAction);

            var serviceProvider = services.BuildServiceProvider();
            var logFactory = serviceProvider.GetRequiredService<ILoggerFactory>();
            var log = logFactory.CreateLogger("ArangoDbClient");

            ArangoDatabase.ChangeSetting(x => x.Logger.Log += (msg) => log.LogInformation(msg));

            services.AddScoped<IArangoDatabase>(_ => ArangoDatabase.CreateWithSetting());

            return services;
        }

        /// <summary>
        /// Register ArangoDb context in the DI from the IConfiguration.
        /// </summary>
        /// <param name="services">DI Services collection.</param>
        /// <param name="configuration">The IConfiguration section that configures the ArangoDb client connection.</param>
        /// <returns></returns>
        public static IServiceCollection AddArangoDbClient(this IServiceCollection services, IConfiguration configuration)
        {
            var dbOptions = new DatabaseSharedSetting();
            configuration.Bind(dbOptions);

            services.Configure<DatabaseSharedSetting>(configuration);

            var mapperConfig = new MapperConfiguration(cfg => cfg.AddProfile(typeof(ArangoDbProfile)));
            var mapper = mapperConfig.CreateMapper();
            void action(DatabaseSharedSetting dest) => mapper.Map(dbOptions, dest);

            return services.AddArangoDbClient(action);
        }
    }
}

In this example we use AutoMapper, so the profile will be

using ArangoDB.Client;
using AutoMapper;
namespace Monq
{
    public class ArangoDbProfile : Profile
    {
        public ArangoDbProfile()
        {
            CreateMap<DatabaseSharedSetting, DatabaseSharedSetting>();
        }
    }
}

Then in the Startup.cs you can use extension method AddArangoDbClient().

namespace Monq
{
    public class Startup
    {
        public Startup(IConfiguration configuration) => Configuration = configuration;

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddArangoDbClient(Configuration.GetSection(Connection));
        }

        public void Configure(IApplicationBuilder app)
        {
            // ...
        }
    }
}

Аfter the conneсtion you can use IArangoDatabase context in the controllers

namespace Monq
{
    [Route("api/cats")]
    public class CatsController : Controller
    {
        readonly IMapper _mapper;
        readonly IArangoDatabase _context;
        public CatsController(IMapper mapper, IArangoDatabase context)
        {
            _mapper = mapper;
            _context = context;
        }

        /// <summary>
        /// Get all cat types.
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<ActionResult<IEnumerable<CatTypeViewModel>>> GetAll([FromQuery] PagingModel paging)
        {
            var catTypes = await _context.Query<CatType>()
                .Select(catType => new CatTypeProjection()
                {
                    CatType = catType,
                    Icon = AQL.First(_context.Query<Icon>().Where(icon => icon.Id == catType.IconId)),
                    LifeCycle = AQL.First(_context.Query()
                        .Traversal<LifeCycle, AssociatedWith>(catType.HandleId)
                        .Depth(1, 1)
                        .OutBound()
                        .Edge(_context.NameOf<AssociatedWith>())
                        .Where(x => x.Vertex.UserspaceId == UserspaceId)
                        .Select(x => x.Vertex))
                })
                .Where(x => x.CatType.UserspaceId == UserspaceId || x.CatType.UserspaceId == SystemUserspaceId)
                .Sort(x => x.CatType.Id)
                .WithPaging(paging, HttpContext, defaultOrder: x => x.CatType.Id)
                .ToListAsync();

            return _mapper.Map<IEnumerable<CatTypeViewModel>>(catTypes).ToList();
        }
    }
}