Giter VIP home page Giter VIP logo

glpi_dotnet's Introduction

GLPI API

Signin

  • appkey see in settings api /front/config.form.php
  • EAuthorizationType.UserToken - for authentication from user token. See in the user settings /front/preference.php in Remote access keys
  • EAuthorizationType.LoginPassInBase64 - for use LDAP and internal auth and other method; Session continue ~ 20 min
await using Client client = new Client("http://localhost:5555/apirest.php/","appkey");

necessary to use

await client.InitSession(
    "glpiClientToken",
    EAuthorizationType.UserToken,
    true);
  • I recommend using a user token to avoid leaking user data

or

await client.InitSession(
    Client.ConvertToBase64("log", "pass"), 
    EAuthorizationType.LoginPassInBase64,
    true);
  • log and pass any type auth

Get Ticket

  • If you need 1 element from the dashboard descendants, then you only need to specify the ID in the parameters
  • If you need to make a special collection, then don't use ID
  • If you need to get all the elements then use an overload without parameters
Ticket? tic = await Ticket.GetItemAsync(client, new Parameter
{
    id = 1
});
IEnumerable<Ticket>? tics = await Ticket.GetItemsAsync(client);
IEnumerable<Ticket>? ticsWithParameters = await Ticket.GetItemsAsync(client, new Parameter
{
    order = Parameter.EOrder.DESC,
    range = new Range(0, 9)
});
  • In the last example, returning the last 10 tickets.

Get with criteria

ResponseSearch? searchTickets = await Ticket.GetItemsAsync(client, new[]
        {
            Criteria.Create<Ticket>((int) EFieldTicket.TicketStatus,
                false,
                Criteria.ESearchType.equals,
                $"{(int) Ticket.EStatus.Await}")            
        });
  • Search for tickets based on a given criterion.
  • For each heir, the dashboard has its own listing. For tickets this is EFieldTicket.
  • To initialize the criterion, use the static Create method.
 Criteria.Create<Ticket>((int) EFieldTicket.TicketStatus,
                false,
                Criteria.ESearchType.equals,
                $"{(int) Ticket.EStatus.Await}")

or

 Criteria.Create((int) EFieldTicket.TicketStatus,
                false,
                typeof(Ticket),
                Criteria.ESearchType.equals,
                $"{(int) Ticket.EStatus.Await}")
  • Argument 1 int:
    • field identifier. It can be obtained from the enumeration I wrote above.
  • Argument 2 bool:
    • it indicates different types. For example, if you are building a query for computers and want to sort by monitors, then in the meta field you need to indicate false, in other cases true.
  • Argument 3 ESearchType:
    • for the accuracy of the request, you need to know which parameter is suitable for the field. You can find it (for tickets):
IEnumerable<SearchOption> searchOptions = await Ticket.ListSearchOptionsAsync(client);
  • Argument 4 int and conversion to string (for enum) or string:
    • takes a value to search for; if this is an enumeration, then you need to use the int data type.

Get Ticket from ResponseSearch

responseSearchTickets.Data
            .Select(s => s.FirstOrDefault().Value)
            .AsParallel()
            .Select(p => Ticket.GetItemAsync(client,
                new Parameter
                {
                    id = (long) p
                }).Result)
            .ToList();

responseSearchTickets was obtained from the previous example. In s.FirstOrDefault().Value contains EFieldTicket.TicketStatus (ticket id). At the same time I download tickets by ID.

Get Ticket from ResponseSearch and Parameter

ResponseSearch? responseSearch = await Ticket.GetItemsAsync(client,
new Parameter
{
    is_deleted = false,
    range = new Range(0, 9),
    sort = (int)EFieldTicket.TicketId
},
new Criteria[]
{
    Criteria.Create<Ticket>
    (
      (int) EFieldTicket.TicketStatus,
      false,
      Criteria.ESearchType.equals,
      $"{(int)Ticket.EStatus.Await}"
    )
});
  • In the parameters:
    • is_deleted = false (sorting will ignore deleted objects)
    • range: from 0 to 9 (10 objects) will be taken into account in sorting
    • sorting: the number of the field by which sorting will be performed.
  • In the criteria (search for tickets whose status is equal to Await)
  • In the final: loading 10 non-deleted tickets, sorted by their ID, that are in Await status
var ticks = responseSearch?.Data
.Select(s => (long) s.FirstOrDefault().Value)
.AsParallel()
.Select(q => Ticket.GetItemAsync(client, new Parameter
{
    id = q
}).Result)
.ToList();

Upload Document

ManifestFileUpload? result = await Document.Upload(client, new ManifestFile("file.png", "newImage.png"));

or

ManifestFileUpload? result = await Document.Upload(client, new ManifestFile(new MemoryStream(),"fileFromStream.png", "newImageFromStream.png"));

Download Document

if (!Equals(result, null))
{
    var streamFile = Document.Download(client, result.Id);
    await using FileStream fs = new FileStream(result.upload_result.Files.FirstOrDefault().Display, FileMode.CreateNew, FileAccess.Write);
    await (await streamFile).CopyToAsync(fs);
}

Create Ticket

string ticItem = await Ticket.AddItemAsync(client, new Ticket
{
    Content = "This is a new ticket"
});

string ticItems = await Ticket.AddItemsAsync(client, new Ticket[]
{
    new ()
    {
        Content = "Help me! From 1 room",
        IdLocation = 2
    },
    new ()
    {
        Content = "<div><h3>Help me! From 2 room</h3></div>",
        IdLocation = 3
    }
});

Update Ticket

In the tic receives a ticket with ID 2. We update the location ID and ticket status on the closed using the UpdateItemAsync method; the same for several tickets

Ticket? tic = await Ticket.GetItemAsync(client,new Parameter
{
    id = 2
});

tic.IdLocation = 4;
tic.Status = Ticket.EStatus.Close;

string updateTic = await Ticket.UpdateItemAsync(client, tic);

var tics = (await Ticket.GetItemsAsync(client, new Parameter
{
    is_deleted = true
})).ToList();

tics.ForEach(tic => tic.IsDeleted = false);

string updateTicks = await Ticket.UpdateItemAsync(client, tics);

Delete Ticket

  • Argument 3 bool: isForcePurge (default false)
    • If the itemtype have a trashbin, you can force purge (delete finally)
  • Argument 4 bool: isHistory (default true)
    • Set to false to disable saving of deletion in global history
Ticket? tic = await Ticket.GetItemAsync(client,new Parameter
{
    id = 2
});

if(!Equals(tic, null))
    await Ticket.DeleteItemAsync(client, tic, true, false);
  • If the ticket exists, it can be deleted.

WebHook with plugin the Webhook

const string adr = "http://localhost:5533/"; 
client.InitListener(new[]
{
    new Listening(
        string.Join(string.Empty, adr, "createtic"),
        "POST",
        (result, id) => Task.CompletedTask),
        Guid.NewGuid().ToString()
    new Listening(
        string.Join(string.Empty, adr, "updatetic"),
        HttpMethod.Put.Method,
        (result, id) => Task.CompletedTask),
    new Listening(
        string.Join(string.Empty, adr, "deltic"),
        HttpMethod.Delete.Method,
        ResponseObj, 
        typeof(Ticket))
});
  • Argument 1 string: http listening address with port if needed
  • Argument 2 string: http method. Default put or post
  • Argument 3 Func<string?,string?,Task> or Func<objeck?,string?,Task>: a function whose
    • 1 argument is a string or an object;
    • 2 optional parameter: listener identifier,
    • and output is used for async.
  • Argument 4 string: optional parameter. Listener ID
  • If you use an object in the 3rd argument, then for deserialization you must specify the type of the object, otherwise it will default to a string
private Task ResponseObj(object? result, string? id)
{
    Ticket? tic = result as Ticket;
    return Task.CompletedTask;
}
await client.DisposableListener();

Closing the client can be done in two ways

  • use using
await using Client client = new Client("http://localhost:5555/apirest.php/","appkey");

or

  • use DisposeAsync()
Client client = new Client("http://localhost:5555/apirest.php/","appkey");
await client.DisposeAsync();
If you used a InitListener, then always use DisposableListener()

glpi_dotnet's People

Contributors

kirkinmur1561 avatar s1032142155 avatar

Watchers

 avatar

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.