Giter Club home page Giter Club logo

mars's Introduction

MARS-curiosity logo

Delphi REST Library

  1. Lightweight
  2. Easy and powerful
  3. 100% RESTful Web Service
  4. Delphi-like
  5. Advanced dataset support with FireDAC
  6. OpenAPI 3 support

More features ...

Installation

  1. Clone or download this project
  2. Add folders to RAD Studio Library Path
  3. Build All in the RAD Studio IDE
  4. Install two packages

More about the installation ...

Use the Code Luke!

Build REST server with MARS Curiosity is very easy. To run a simple REST server just create a new Console Application and use the following code:

program Mars1;

{$APPTYPE CONSOLE}

{$R *.res}

uses
  System.SysUtils,
  MARS.Core.Engine,
  MARS.http.Server.Indy,
  MARS.mORMotJWT.Token,
  MARS.Core.MessageBodyWriters,
  MARS.Core.Attributes,
  MARS.Core.MediaType,
  MARS.Core.Registry;

type
  [Path('helloworld')]
  THelloWorldResource = class
  public
    [GET, Produces(TMediaType.TEXT_PLAIN)]
    function SayHelloWorld: string;
  end;

function THelloWorldResource.SayHelloWorld: string;
begin
  Result := 'Hello World! Here is MARS Curiosity ...';
end;

var
  FEngine: MARS.Core.Engine.TMARSEngine;
  FServer: MARS.http.Server.Indy.TMARShttpServerIndy;
begin
  // ----------------------------------
  // Register a resource class
  MARS.Core.Registry.TMARSResourceRegistry.Instance.
    RegisterResource<THelloWorldResource>;
  // ----------------------------------
  // Build and configure the engine
  FEngine := MARS.Core.Engine.TMARSEngine.Create;
  FEngine.BasePath := '/rest';
  FEngine.Port := 8080;
  FEngine.AddApplication('DefaultAPI', '/default', ['*.THelloWorldResource']);
  FServer := MARS.http.Server.Indy.TMARShttpServerIndy.Create(FEngine);
  // ----------------------------------
  // Run the REST server
  FServer.Active := True;
  Writeln ('Server is running ...');
  Write ('Press Enter to stop ...');
  Readln;
  // ----------------------------------
  // Close the server
  FServer.Active := False;
  FreeAndNil(FServer);
  FreeAndNil(FEngine);
end.

Documentation

Forum

Official MARS Curiosity forum at Delphi-Praxis International: https://en.delphipraxis.net/forum/34-mars-curiosity-rest-library/

Contribution

It would be great if you would like to support this project. It's quite easy and you can became better Gitter then.

Thanks

Most of the code has been written by the author (Andrea Magni) with some significant contributions by Nando Dessena, Stefan Glienke and Davide Rossi. Some of my customers actually act as beta testers and early adopters. I want to thank them all for the trust and effort.

Related Links

Embarcadero Delphi is a modern, powerful and effective language and development tool. Learn more about it at the following links:

COPYRIGHTS

  • The Delphi stylized helmet icon is trademark of Embarcadero Technologies.

mars's People

Contributors

andrea-magni avatar asryzhkov avatar brov84 avatar daniela-zanini avatar davide675 avatar dennis1000 avatar dmlam avatar kitesoft avatar larsenbjorn avatar lgldsilva avatar meg02in avatar mferlini avatar nandod avatar ortuagustin avatar sguastoni avatar shaunroselt avatar siarsartori avatar stuartclennett avatar tino-teuber avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

mars's Issues

Add DELETEAsync

Add DELETEAsync to MARS.Client.CustomResource.pas

procedure DELETEAsync(
  const ABeforeExecute: TProc<TMemoryStream>{$ifdef DelphiXE2_UP} = nil{$endif};
  const ACompletionHandler: TProc<TMARSClientCustomResource>{$ifdef DelphiXE2_UP} = nil{$endif};
  const AOnException: TMARSClientExecptionProc{$ifdef DelphiXE2_UP} = nil{$endif};
  const ASynchronize: Boolean = True); overload;

Patch files attached.

MARS.Client.CustomResource.txt

[Internal] Short commit names

@andrea-magni ... you should give short names for your commits - this is well known good practice - especially useful when you working in the bash terminal or the windows cmd. See good articles about this:

When you have to add more info to commit description just add short title in the 1 line then empty line and then full description, something like that (it is form your last commit):

Added raise an exception when none Message Body Writer is selected

regression: 
    given I removed the primitive types fallback in favor of a more uniform MBW implementation (see commit e90626798fc9bd430868743264cd30c7c64b529d), no content serialization happens when no MBW matches the request (i.e. no MBW are registered in the system). This leads to situation like the one described in #40.
    With the current commit, I am raising an exception if the invoked REST method is actually a function and no MBW are selected for response serialization.

Continuous Integration for MARS

It will great to implement CI solution integrated with GitHub project. MARS Curiosity could be example of the success story for the vendor and it will be extremely useful for the author. We (ma and Andrea) started such discussion in different topic. I'm going to copy all important parts of that bellow ...

can't compile MARS.DelphiRazor package in Delphi Berlin

after installing DelphiRazor package from Marco Cantu or yours, got the same fatal compile error: it is a DelphiRazor package error: can't find RlxRazor.pas, I think it is more RlxLocales.pas. It is in the source directory of DelphiRazor and it is added in the library directory.

TMARSClient Async AuthEndorsement

Hi,

Using Async calls when AuthEndorsement set to cookie (default) will not correctly authenticate.

So 2 suggestions:

1.) Add LClient.AuthEndorsement := TMARSAuthEndorsement.AuthorizationBearer; to all Async calls

2.) Perform a check of AuthEndorsement and raise an exception if set to cookies to help with usage?

Also, thanks for this library; it's fantastic

More detailed exception message is required

If you remove MARS.mORMotJWT.Token from uses section then REST server returning the exception:

Internal server error: [EMARSException] Token injection failed in MARSActivation

No guidance what to do. Something like:

Please add MARS.mORMotJWT.Token unit to uses section

POST error when content type charset = utf-8

  1. Run EKON22 Demo
  2. Send POST request with utf-8
curl -X POST -H "Content-Type: application/json;charset=utf-8" 
  -d "{\"Firstname\":\"Zażółć gęślą jaźń\",\"Lastname\":\"X\",\"DateOfBirth\":\"2000-01-24\"}"
  -v "http://localhost:8080/rest/default/helloworld/recordAge"
  1. Error: EConvertError: Format UTF8: Type cannont be determined invalid or incompatible argument

procedure TMARSIndyClient.AssignTo should clone IOHandler

I have found issues arise if a mix of Sync and Async calls are made; an initial fix is to add DELETEAsync as per issue #26

I have found by commenting out the following line in procedure TMARSIndyClient.AssignTo(Dest: TPersistent) resolves the issue.

LDestClient.HttpClient.IOHandler := HttpClient.IOHandler;

Should the IOHandler not be transferred or cloned.

The way IOHandler works in indy, is if it is not set the IOHandler will be NIL the first time an AssignTo is called, however once a HTTP request (not ASYNC in MARS) is made the IOHandler will have an internal IOHandler.

Indy Connect Code

image

Rest.Json

Hi I get rest.json dcu not found when building. Is this because i am using Delphi EX2

regards
ettienne

Linux demos don't compiles

i've created a new project with MarsCMD and the LinuxDaemon and Apache Module don't compile with "web.Multireq not found" error. (in mars.cors.attributes)

I commented the unit and all it's ok.
TIA
Bob

Issue with returning a TJsonObject

I'm getting an the following error when trying to call a resource which returns a TJsonObject with the latest MARS repo. The error is

Project JsonDataObjectsVCL.exe raised exception class EMARSHttpException with message 'MessageBodyWriter not found for method HelloWorld of resource THelloWorldResource'.

This occurs with the MARS JsonDataObjects demo server under 10.3.

To Reproduce
Steps to reproduce the behavior:

  1. Run the JsonDataObjects server
  2. Open a broser and navigate to "http://localhost:8080/rest/default/helloworld"

Configuration -

  • OS: Windows 10
  • Client: Chrome browser
  • Version Delphi 10.3

TMarsClientCustomResource Async

Propose to change exceptions handled in Async events also Synchronized? or an option

procedure(AError: Exception)
               begin
               AOnException(AError);
               {if Assigned(AOnException) then
                 begin
                   if ASynchronize then
                     TThread.Synchronize(nil
                       , procedure
                         begin
                           AOnException(AError);
                         end
                     )
                   else
                     AOnException(AError);
                 end;}
               end);

Example as an option

procedure TMARSClientCustomResource.POSTAsync(
  const ABeforeExecute: TProc<TMemoryStream>;
  const ACompletionHandler: TProc<TMARSClientCustomResource>;
  const AOnException: TMARSClientExecptionProc;
  const ASynchronize: Boolean;  const ASynchronizeException: Boolean);

Package MARS

Hi Andrea ...

I need to create a server in a package, however I can not compile because of the error "[dcc32 Error] E2223 $ DENYPACKAGEUNIT 'Web.WebBroker' can not be put into a package". I saw that the unit MARS.http.Server.Indy does uses idHTTPWebBrokerBridge, but MARS.http.Server.Indy is not part of any of the packages listed below:
MARS.Utils
MARS.CORE
MARS.mORMot
MARS.ReadersAndWriters
MARS.FireDAC

Without the use of package I can usually use the TMARShttpServerIndy unit.

Can you help me with this?

Thank you!

TMS Web

Writing javascript without bugs using delphi is a timesaver. Combined with MARS simple and structured backend for basic CRUD operations, it would be a boon and groundbreaking in itself.

Improve IDE Wizard

In the ./Source/IDE Wizard/ folder there are Delphi package. This package after compilation and registration in the RAD Studio adds new project Delphi wizard. This wizard is available through IDE->File->New->Other. It requires lot of care and improvements to be ready for an official shipment.

See:
https://github.com/andrea-magni/MARS/tree/master/Source/IDE%20Wizard

Andrea Magni wrote about this:

The IDE wizard actually needs some love as at some point I preferred the MARSCmd approach. I lack knowledge to make the IDE wizard fair enough. So, yes, if anyone is capable then just go ahead, thanks!

We need anybody with RAD Studio Open Tool API knowledge to upgrade this or at least to support us. Who wants to enlist?

Abstract from MARS' underlying http layer (Indy, WebBroker)

It would be nice to have a chance to move MARS from Indy/WebBroker http layer to other http server implementations.

A viable option is to abstract from Web.HttpApp data structures (TWebRequest and TWebResponse) in order to support even http frameworks implementing their own data structures to model http request and response.

I am looking to DelphiCrossSocket project as first new http framework to interact with.
Some work on MARS side has already been done in the develop branch.

THTTP.Net Client Async Crashes on Android and Delphi RIO 10.3.1

This is posted to help anyone else they might stumble across the issue so they don't waste hours like I did. The issue is not with MARS but effects MARS using HTTP.NET on Android and Delphi 10.3.1

Your application will crash randomly with Seg Faults, Bus errors.

TNetHttpClient can't work in multithread under android (RSP-23742)
https://quality.embarcadero.com/browse/RSP-23742

Patch System.Net.HttpClient.pas with

THTTPClientExt = record
--
case Integer of
0: (
FPreemptiveAuthentication: Boolean;
FSecureFailureReasons: THTTPSecureFailureReasons;
FAutomaticDecompression: THTTPCompressionMethods
);
1: (
_pad: array[0 .. 7] of Byte
);
end;

MARS runs like a linux apache module

Hi,
I installed MARS on linux UBUNTU 18.04 server like a module and works fine with "Hello World" sample

I tried to access a MySQL database but I received a "internal server error" without explain

I tried like a console application and works fine ... I can read the database and display the data

One problem maybe is the .ini file
in the console mode I put the file into same folder of application and ok.

in module mode, I tried to put the file into module folder but I think is wrong

Someone tried this scenario?

thanks!
Antonello

MARSCmd may fail while renaming files from a template

MARSCmd strategy to rename files is weak and fails if a file (full file name) has more than a single replacement taking place.
Example:
File from template
%MARS%\Demos\MARSTemplate\bin\MARSTemplateClient\AndroidManifest.xml
should become
%MARS%\Demos\NEW_NAME_HERE\bin\NEW_NAME_HEREClient\AndroidManifest.xml

but move operation fails as the NEW_NAME_HEREClient folder may not exists yet.
Thanks to Stuart Clennet for pointing this out: https://en.delphipraxis.net/topic/362-error-during-execute-in-marscmd/

Authentication

Hello, I would like to know how to change the value of JWT_SECRET_PARAM_DEFAULT without having to directly change the value of the counter.

The way you are here:

_{TMARSToken}

constructor TMARSToken.Create (const AToken: string; const AParameters: TMARSParameters);
begin
   Create (
     AToken
   , AParameters.ByName (JWT_SECRET_PARAM, JWT_SECRET_PARAM_DEFAULT) .AsString
   , AParameters.ByName (JWT_ISSUER_PARAM, JWT_ISSUER_PARAM_DEFAULT) .AsString
   , AParameters.ByName (JWT_DURATION_PARAM, JWT_DURATION_PARAM_DEFAULT) .AsExtended
   );
end;_

I would like to change the JWT_SECRET_PARAM_DEFAULT and JWT_ISSUER_PARAM_DEFAULT values.

I tried inheriting from the TMARSToken class, but I could not get TMARSmORMotJWTToken.LoadJWTToken to use my key to validate authentication.

Packages/101Berlin/MARSClient.CoreDesign.dproj has incorrect dcu output folder

Package outputs to Lib250 instead of Lib240.
Simple Patch:

diff -r Packages/101Berlin/MARSClient.CoreDesign.dproj: bd3a5102 Packages/101Berlin/MARSClient.CoreDesign.dproj: Working Tree
51c51
<         <DCC_DcuOutput>..\..\Lib250\$(Platform)\$(Config)</DCC_DcuOutput>
---
>         <DCC_DcuOutput>..\..\Lib240\$(Platform)\$(Config)</DCC_DcuOutput>

TJSONObjectHelper.ReadDateTimeValue ignores ADefault argument

Describe the bug
Passing a value as default value for ReadDateTimeValue has no effects.

To Reproduce
Steps to reproduce the behavior:

  1. Have a TJSONObject somewhere
  2. include MARS.Core.JSON to have the TJSONObjectHelper available
  3. AObj.ReadDateTimeValue('WhateverField', -1) defaults to 0 instead of -1 when WhateverField is not included in the JSON representation

Methods from child classes are not registered

It appears that Mars only registers REST methods in the registered class, not the ones that appear in parent classes.

This code works:

  [Produces(TMediaType.APPLICATION_JSON)]
  [Path('test')]
  TTest= class
  protected
    function DoDefault: String; virtual;
  public
    [GET]
    function Default: String;
  end;

...

  function TTest.DoDefault: String;
  begin
    Result := 'Works!';
  end;

  function TTest.Default: String;
  begin
    Result := DoDefault;
  end;
...

  initialization
    TMARSResourceRegistry.Instance.RegisterResource<TTest>;  

This code returns no GET handler:

  [Produces(TMediaType.APPLICATION_JSON)]
  [Path('test')]
  TTest= class
  protected
    function DoDefault: String; virtual;
  public
    [GET]
    function Default: String;
  end;

  TTestChild= class
  protected
    function DoDefault: String; override;
  end;

  function TTest.Default: String;
  begin
    Result := DoDefault;
  end;

...

  function TTestChild.DoDefault: String;
  begin
    Result := 'Doesn''t Work!';
  end;

...

  initialization
    TMARSResourceRegistry.Instance.RegisterResource<TTestChild>;  

Is it possible to register with Mars attributes in parent classes?

Resource Not Found handling

if (BasePath <> '') and (BasePath <> TMARSURL.URL_PATH_SEPARATOR) then
begin
if not LURL.MatchPath(BasePath) then
raise EMARSEngineException.Create(
Format('Bad request [%s] does not match engine URL [%s]', [LURL.URL, BasePath])
, 404
);
if LURL.HasPathTokens(2) then
LApplicationPath := TMARSURL.CombinePath([LURL.PathTokens[0], LURL.PathTokens[1]]);
end;

When server do not find resource then it throwing the exception (as shown above) ... why? Generally REST Servers are only responding with

HTTP 404 Not found
Content-Type: application/json; charset=UTF-8

{"status":"error", "message": "Unsuported resource. Service denied to respond."}

or something similar

What is the difference? When you are using some Web Browsers to test MARS Server (I check just Chrome) they are asking for favicon.ico and when server is run with the debugger mode you will receive this exception in the IDE - it looks that something is wrong but it isn't (bad perception)

GetDesiredEncoding(AActivation) - Not enough parameters

Hi Andrea Magni,

I am try to build your demo in RAD Studio 10.2 but following error after successfully install your component.

[dcc32 Error] MARS.JsonDataObjects.ReadersAndWriters.pas(56): E2035 Not enough actual parameters
[dcc32 Fatal Error] Server.Resources.pas(20): F2063 Could not compile used unit 'MARS.JsonDataObjects.ReadersAndWriters.pas'

Error appear in MARS.JsonDataObjects.ReadersAndWriters.pas unit as appears above as well, kindly fix it.

Best Regards
Fiaz

ISAPI body parms are empty

ISAPI dll projects will not provide any data in body parameters; example below (and attached) will create 2 files in c:\windows\temp for an ISAPI project. Both should contain the same data, however body-param.txt will be empty. Compiling as a standalone EXE body param works fine.

type
[Path('helloworld')]
THelloWorldResource = class
protected
[context]
Request: TWebRequest;
public
[GET, Produces(TMediaType.TEXT_PLAIN)]
function SayHelloWorld: string;
[POST]
procedure POST([BodyParam] body: string);
end;

procedure THelloWorldResource.POST(body: string);
var
LStringList: TStringList;
begin
LStringList := TStringList.Create;
try
LStringList.Add(body); // Empty in ISAPI project
LStringList.SaveToFile(TPath.GetTempPath + 'body-param.txt');
LStringList.Clear;
LStringList.Add(Request.Content);
LStringList.SaveToFile(TPath.GetTempPath + 'body-content.txt');
finally
FreeAndNil(LStringList);
end;
end;

Uploading ISAPITest.zip…

Possibly another UTF-8 issue

Hi Andrea,

Today I upgraded to the latest version of Indy and MARS and I started to have some data corruption coming from the server. It appeared that my UTF-8 were returning data which was encoded slightly different than before.

I've spent some time on it and found that the following small change fixes the issue for me.

procedure TMARShttpServerIndy.DoCommandGet(AContext: TIdContext;
  ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo);
var
  LRequest: TIdHTTPAppRequest;
  LResponse: TIdHTTPAppResponse;
begin
  inherited;
  // added these 2 lines...
  if AResponseInfo.CharSet = '' then
    AResponseInfo.CharSet := 'ISO-8859-1';

Now my UTF-8 resources return the data encoded correctly. I tried to run your unit tests but unfortunately don't have DUnitX - Do you think this will break anything?

I think I only use a small part of MARS so I'm not sure of the implications this may have but it seems to fix the issues I have seen today.

Kind regards,
Graham

TStringReader causes an additional CRLF (on Win) to be appended to strings

When the TStringReader is matched to provide a string value (i.e. using reading a FormParam into a string variable), an additional end line is appended to the actual value.
This depends on the internal implementation of TStringReader and should not happen.

Steps to reproduce the behavior:

  1. Using a fresh new project
  2. Try to POST against the Token resource
  3. Authentication always fails because even if you provide the correct password an endline is appended to the actual value

"Range check error" on MacOS & iOS client

Hi,
when a MARS client call a POST method of a applyupdate resource ... like this:

function PostDelta([BodyParam] const ADeltas: TArray<TFDMemTable>)
  : TArray<TMARSFDApplyUpdatesRes>;

the function return this error: "Range check error"
to get around the problem just return an empty array like this:

result := []

This issue happen only when the client is MacOS or iOS

Antonello

Issue with Unicode (Arabic characters)

Hi Andrea,

My REST server needs to be able to return Arabic text for some of my customers. However, the only way I have been able to do this is to add in the following line to MARS.Core.Activation

        // 3 - fallback (raw)
        else
        begin
          Response.ContentType := TMediaType.CHARSET_UTF8_DEF;    // << inserted this line

          if (LMethodResult.Kind in [tkString, tkUString, tkChar, {$ifdef DelphiXE2_UP}tkWideChar,{$endif} tkLString, tkWString])  then

Without this, the unicode characters are not preserved when setting "Response.Content".

Can you confirm if this is a bug? And/or if this is an acceptable fix.

Many thanks for your great work on this!

Kind regards,
Graham

EKON 22 Demo sending TMyRecord via CURL

I was testing a new EKON 22 demo and found small issue. I'm sending:

curl -X POST -H "Content-Type: application/json" -d "{'Firstname':'Bogdan','Lastname':'Polak','DateOfBirth':'2001-01-10'}" -v "http://localhost:8080/rest/default/helloworld/recordAge"

and response is

< HTTP/1.1 200 OK
< Connection: close
< Content-Type: application/json
< Content-Length: 107
< Date: Mon, 12 Nov 2018 19:49:39 GMT
<
{"Name":" ","Seconds":-543749917,"Minutes":62520289,"Hours":1042004,"Days":43416,"Months":1426,"Years":118}* Closing connection 0

118 years is quite a lot. :-) I checked that is since data zero, means 1899-12-30. Is there something wrong or I was missing something?

I was trying different date formats: 2001-01-10T00:00:00.000+02:00, 2001-01-10T00:00:00, 2001-01-10Z00:00:00 but the response is still the same

Server does not accept absolute-form for request-target

According to the http 1.1 spec, clients must send the request-target in the origin-form (absolute-path + optional query), eg:
GET /where?q=now HTTP/1.1

But the next section specifies that servers must also accept the absolute-form, in the interests of forward compatibility, eg:
GET http://www.example.org/pub/WWW/TheProject.html HTTP/1.1

A client that we interface with always sends absolute-form requests, contrary to the standard, but our MARS-based server fails to process these requests, also contrary to the standard.

We've found that in this case the url constructed by MARS has the host/port duplicated into the path (we're using TMARShttpServerIndy - I haven't tested other configurations). This can be demonstrated with a request such as:
curl -v localhost:8080 --request-target http://localhost:8080/default/helloworld

We're using an OnBeforeHandleRequest event handler as follows to work around this issue - could this support for either origin-form or absolute-form be integrated into MARS?

Engine.OnBeforeHandleRequest := function(Engine: TMARSEngine; URL: TMARSURL;
  Request: TWebRequest; Response: TWebResponse; var Handled: Boolean): Boolean
var
  URI: TIdURI;
begin
  // reconstruct the raw http request-target passed from client to server
  URI := TIdURI.Create(Request.RawPathInfo);
  URI.Params := Request.Query;

  // http 1.1 spec requires that the request-target sent by client is in the
  // origin-form (absolute-path + query), but also requires servers to accept
  // the absolute-form (full absolute-uri)
  if URI.Protocol = '' then
    URI.Protocol := 'http';
  if URI.Host = '' then
    URI.Host := Request.Host;
  if URI.Port = '' then
    URI.Port := IntToStr(Request.ServerPort);

  // set url for mars engine and continue with request
  URL.URL := URI.GetFullURI;
  Result := True;
end;

MARS Pascal Style Guide is mandatory

To not speed (in the future) a lot of time for unproductive discussions we have to define this repo Style Guide. At the beginning we can start with formatting in the uses section (which is now important) and improve other sections in the future.

Discussion about README.md

  1. There are two copies of the README.md - should be synchronized
  1. Map of the functionalities and concepts is totally unreadable - especially in the PNG format, but with PDF is still difficult to read, you have to zoom in a lot. Maybe change it into the hierarchical list will be better
  2. MARS image is beautiful, but it uses so much place important for ket message. Maybe you can consider to move it to the bottom of the file
  3. In the JavaScript libraries are important source code examples in the README file. Something like that:
type
  [Path('helloworld')]
  TSampleResource = class
  public
    [GET, Produces(TMediaType.TEXT_PLAIN)]
    function SayHelloWorld: string;
  end;

function TSampleResource.SayHelloWorld: string;
begin
  Result := 'Hello World!';
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
  TMARSResourceRegistry.Instance.RegisterResource<TSampleResource>;
  FEngine := TMARSEngine.Create;
  FEngine.BasePath := '/rest';
  FEngine.Port := 8080;
  FEngine.AddApplication('DefaultApp', '/default', ['ServerResources. TSampleResource']);
  FServer := TMARShttpServerIndy.Create(FEngine);
  FServer.Active := True;
end;

procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction);
begin
  if Assigned(FServer) then
  begin
    FServer.Active := False;
    FreeAndNil(FServer);
    FreeAndNil(FEngine);
  end;
end;

can't compile packages in /MARS/Packages/10Seattle folder

The MARS / Packages / 10Seattle folder contains MARSClient.dpk and MARSServer.dpk. Compiler errors with Delphi 10 Seattle.

I have changed search path ....\Source\Core in ....\Source
I also removed MARS.Core.Request.pas from MARSServer package.
Still compiler errors.

Missing conditional defines?

Hi Andrea,

There appear to be 2 references to TJsonBool in MARS.Core.JSON which are not wrapped in a {$ifdef Delphi10Seattle_UP}

This prevents compiling in XE8 (and I assume earlier versions)

I've added the missing defines and will test here.

Kind regards,
Graham

const tkWideChar not exist in XE7

Can't compile Authorization demo in XE7, in line {$ifdef DelphiXE6_UP}tkWideChar, {$endif} the const tkWideChar not exist, must be tkWChar i think

ClientSide BeforeInvoke hooks do not fire when using regular component-based approach

You can set an anonymous method to get called before each client side request.
The mechanism is implemented in TMARSCustomClient by the RegisterBeforeExecute and the like methods.

Unfortunately, this works using the non-component based approach with MARS client classes but not when using regular component instance calls (MyClient.Get/Post/...).

Regression bug - Empty response from console MARS server

  1. With console server and just simple helloword now response is empty. Just try my simple console server (copied bellow). VCL application MARS server is workin fine then it something with console version.
  2. Maybe it good idea to add some simple acceptance tests uses DUnitX: just run server, then call some requests with TIdHTTP or with TRESTClient and verify the response. We can start with manual test execution at the beginning. However, such tests should be executed automatically just after each commit. It requires RAD Studio IDE accessible in the cloud Windows machine and add some online hooks to GitHub. Maybe you can ask for cloud hosting?
uses
  System.SysUtils,
  MARS.Core.Engine,
  MARS.http.Server.Indy,
  MARS.mORMotJWT.Token,
  MARS.Core.Attributes,
  MARS.Core.MediaType,
  MARS.Core.Registry;

type
  [Path('helloworld')]
  THelloWorldResource = class
  public
    [GET, Produces(TMediaType.TEXT_PLAIN)]
    function SayHelloWorld: string;
  end;

function THelloWorldResource.SayHelloWorld: string;
begin
  Result := 'Hello World! Zażółć gęślą jaźń';
end;

var
  FEngine: MARS.Core.Engine.TMARSEngine;
  FServer: MARS.http.Server.Indy.TMARShttpServerIndy;
begin
  // ----------------------------------
  // Register resource class
  MARS.Core.Registry.TMARSResourceRegistry.Instance.
    RegisterResource<THelloWorldResource>;
  // ----------------------------------
  // Build and configure the engine
  FEngine := MARS.Core.Engine.TMARSEngine.Create;
  FEngine.BasePath := '/rest';
  FEngine. ThreadPoolSize := 5;
  FEngine.Port := 8080;
  FEngine.AddApplication('DefaultAPI', '/default', ['*.THelloWorldResource']);
  FServer := MARS.http.Server.Indy.TMARShttpServerIndy.Create(FEngine);
  // ----------------------------------
  // Run REST server
  FServer.Active := True;
  Writeln ('Server is running ...');
  Writeln ('Open web page:');
  Writeln ('http://localhost:8080/rest/default/helloworld/');
  Write ('Press Enter to stop ...');
  Readln;
  // ----------------------------------
  // Close the server
  FServer.Active := False;
  FreeAndNil(FServer);
  FreeAndNil(FEngine);
end.

How to change the response to charset utf-8

In the following code:

type
  [Path('helloworld')]
  THelloWorldResource = class
  public
    [GET, Produces(TMediaType.TEXT_PLAIN)]
    function SayHelloWorld: string;
  end;
function THelloWorldResource.SayHelloWorld: string;
begin
  Result := 'Hello World! Zażółć gęślą jaźń';
end;

How to change the response from iso to utf-8?

pointer error when trying to pass a FireDac DataSet from a MarsDataResource

This is working with sources from october 29 but not with those from december 3 (message returning by server: 'internal pointer error'):
type
[Path('/maindata')]
TMainDataResource = class(TMARSFDDataModuleResource)
FDConnection1: TFDConnection;
FDGUIxWaitCursor1: TFDGUIxWaitCursor;
oneEmployee: TFDQuery;
allEmployee: TFDQuery;
country: TFDQuery;
sales: TFDQuery;
private
protected
[Context]
FD: TMarsFireDac;
public
[GET, Path('/employee'), Produces(TMediaType.APPLICATION_JSON_FIREDAC)]
function oneEmployeeQuery: TFDDataSet;
end;

implementation
{%CLASSGROUP 'Vcl.Controls.TControl'}
{$R *.dfm}

uses
MARS.Core.Registry;

{ TMainDataResource }
function TMainDataResource.oneEmployeeQuery: TFDDataSet;
begin
FD.InjectMacroValues(TFDAdaptedDataSet(oneemployee).Command);
FD.InjectParamValues(TFDAdaptedDataSet(oneemployee).Command);
Result := oneEmployee;
end;

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.