Quantcast
Channel: Latest blog entries - Embarcadero Community
Viewing all 1683 articles
Browse latest View live

ブックレビュー:まんがでわかる 理科系の作文技術

$
0
0

筑木です。自分の文章力が不足しているので、「まんがでわかる 理科系の作文技術」を購入して読了しました。

ベストセラーである「理科系の作文技術」のエッセンスを抜き出して、マンガで解説した本です。解説部分は普通の文章ですが簡潔に判りやすく解説しています。

内容のうち、以下の部分は自分にもかなり響きました。

  • 先に結論を記述する。
  • 余計な修飾をしない。
  • はっきりと言い切る。
  • 文書を読むターゲットを意識して不要な解説は削る。

まだ実践は出来ていないのですが、これらを意識して文章を書いていけるように精進しなければなりません。電子書籍でも販売されていますので、興味のある方は是非ともお手を取ってみてください。読んで損はしないはずです。

大型連休中は積ん読状態であった「理科系の作文技術」と「日本語の作文技術」を読破して自分の血肉にしてしたいと考えています。

2018年4月23日~5月4日までの月~金曜に毎日ブログを更新。Delphi / C++Builderに関する技術記事からエンジニアの日常まで、さまざまな話題を投稿します。お楽しみに!

日本人スタッフブログを一覧表示できる、こちらのページをブックマークしてください。


Read More

Delphi Blogs of the Month #59

$
0
0

I have already blogged specifically about the 10.2.3 release, the patches we delivered for it, and linked to the collection of related articles in the community site at https://community.embarcadero.com/blogs/tags/tag/10-2-3. In particular, the launch webinar reply is available at https://community.embarcadero.com/blogs/entry/10-2-3-webinar-replay. Not much else to add, if not that it has been very well received by the users.

Technical Blog Posts

Very interesting, focused suggestions in Positioning a Task Dialogue by David at http://www.davidghoyle.co.uk/WordPress/?p=1921

Media file meta-data on Android in Delphi by Craig at https://community.embarcadero.com/blogs/entry/media-file-meta-data-on-android-in-delphi

5-Minute-Snack: Understanding TWebRequest’s ContentFields and QueryFields with regard to MethodType by Holger at https://flixengineering.com/archives/649

Using CData’s Gmail connector in C++ Builder by Greg at https://cppthingsblog.wordpress.com/2018/04/09/using-cdatas-gmail-connector-in-c-builder/ (as it also applies to Delphi, almost identically)

Ready for Debate? Which Windows Framework and What About StackOverflow?

Two topics that could spawn a significant debate, I'm sure.

The first is I found it very interesting to read this article by respected technical author Tim Anderson on "Which .NET framework for Windows: UWP, WPF or Windows Forms?" at https://www.itwriting.com/blog/10182-which-net-framework-for-windows-uwp-wpf-or-windows-forms.html. I strongly believe VCL provides a better option than any of the current Microsoft framework, plus it clearly wins for a long-lived applications and has the highest degree of long time support and compatibility. A couple of comments hinted at VCL, nice. Anyway, Tim recently reiterated the question on Twitter, https://twitter.com/timanderson/status/981933828964003840.

The second good topic for a discussion is reading Nick's take on the status of StackOverflow, at http://www.codingindelphi.com/blog/in-which-i-pontificate-about-stackoverflow/. But read also this twitter thread by an internal : https://twitter.com/balpha/status/984839394829000706


Read More

Delphi で Google Vision API を使ってランドマーク認識して地図表示する

$
0
0

少々古い記事となるのですが日経ソフトウェア 2018年1月号を読んでいたら、「人工知能API」で画像認識プログラミング、という記事がありまして、Google Vision API や Microsoft Cognitive Service, Amazon Rekognition を利用してみる、というものでした。

記事を読んでみると、人工知能APIと言いつつも、やっていることは REST API に画像を投げて、クラウド側の機械学習モデルを使って判定させているだけでしたので、これは Delphi/C++Builder でもできそうです。

そこで、この記事を参考にしつつ Google Vision API を Delphi で利用する例をご紹介します。

お手元に書籍がございましたら、比較しつつ記事を読んでみてください。

なお Google は Vision API の既存の機械学習モデルをベースにカスタマイズ可能なサービス、Cloud AutoML を発表していますが、この記事には Cloud AutoML の内容は含めていません。


Read More

Enterprise Connectorsのインストール済みコンポーネントのバージョン一覧を得る

$
0
0

複数のPCに開発環境を作る場合は、使用するコネクタとバージョンを等しく揃えたい

Delphi/C++Builder/RAD Studio 向けの Enterprise Connectors を使うと、さまざまなクラウドのAPIやデータを SQL で操作できることは、様々な機会でご紹介してきたとおりです。

この Enterprise Connectors は、新しい接続先のサポートや機能の修正等を含めた新しいビルドが CData 社より年に数回リリースされています。

このため、複数の作業用PCを併用するケースでは、環境の構築時期にズレがあるとインストールされているコネクタのビルドが異なる可能性が懸念されます。このような不整合はコネクタの挙動の違いを引き起こすかもしれません。あるいは、環境ごとに、インストールの過不足があるかもしれません。そこでここでは Enterprise Connectors のインストール済みコネクタおよびバージョンの一覧を取得する方法を紹介いたします。

この記事では Windows 10 1709 Fall Creators Update の環境で動作を確認しましたが、Windows10 は年2回のアップデートが提供されますので、バージョンによってはスクリーンショット等が異なる可能性があることにご注意ください。


Read More

Convertir Test de DUnit a DUnitX (Entrega 3)

$
0
0

Con este artículo pensaba completar esta serie referente a pruebas unitarias y a los Frameworks más utilizados en Delphi para realizarlas, pero el tema de conversión y migración de test entre DUnit y DUnitX se ha alargado más de lo esperado, así que para no generar una entrada muy larga y mezclar temas he decidido "partirla" en dos".

De esta forma dejo para la siguiente el Framework DUnitX en profundidad y en esta me he centrado en explicaros cómo migrar los test existentes que tengamos desarrollados en DUnit.

En las últimas versiones de Delphi, DUnitX es el framework que se recomienda usar desde Embarcadero. Veremos que es más flexible y parametrizable que DUnit, aunque si hemos trabajado con DUnit, DUnitX nos será muy familiar en su mayoría de aspectos (es una evolución de DUnit, NUnit y algunos otros...).

Si ya hemos trabajado con DUnit antes que con DUnitX (como hemos hecho en las entradas del blog) podemos "migrar" nuestros test de forma sencilla, ya que existen determinadas Units ya creadas para adaptar nuestros test existentes.

CONVERTIR TEST DESDE DUNIT A DUNITX

El proceso de conversión podéis seguirlo desde la DocWiki de Embarcadero en este enlace. De todas formas vamos a repasarlo utilizando el proyecto de test que hemos creado en las entradas anteriores.

Nos vamos a basar en los primeros test que hicimos en la segunda entrada, generados con DUnit. Así que cogeremos como proyecto base el que incluye los test realizados con DUnit. A continuación os dejo el enlace de descarga.

<Descarga del código fuente del proyecto>

Para convertir el test seguiremos los siguientes pasos:

1) Crear un nuevo proyecto de DUnitX.

Hay que decir que lo que podemos aprovechar es la unit donde hemos implementado los test, pero el proyecto hay que crearlo desde cero.

Para ello, desde el menú de File/New/Other Seleccionaremos un nuevo projecto de DUnitX. DUnitX_Project

La siguiente ventana nos preguntará algunos parámetros sobre el proyecto. En este caso nos interesa no marcar, el check de “Create Test Unit”, pues nuestra unit ya está creada con DUnit y lo que deseamos es reaprovechar los Test creados.

TestCase_Wizard1

Finalizamos el asistente y ya tendremos nuestro proyecto creado.

2) Añadir las units de funcionalidad y de test.

Una vez que el proyecto está creado, añadimos las 2 units que teníamos en el proyecto anterior.

  • UClass.TAritmeticaBasica.pas
  • Test.UClass.TAritmeticaBasica.pas

Protecto_Test_ConvertLa primera es la unit con la funcionalidad que deseamos probar y la segunda la unit con los test creados en DUnit y que tendremos que adaptar. Nuestro proyecto ahora queda de esta manera que vemos en la imagen.

3) Modificar el test para adaptarlo.

3.1) Como primer paso, en la unit donde tenemos implementados los test hay que modificar el uses de:

TestFramework

Y sustituirlo por este otro (DUnitX):

DUnitX.TestFramework,DUnitX.DUnitCompatibility.

3.2) Al registrar el Test cambiar la línea de registro:

RegisterTest(TestTAritmeticaBasica.Suite);

Por esta otra:

TDUnitX.RegisterTestFixture(TestTAritmeticaBasica);

Con estos dos simples cambios si ejecutamos nuestro proyecto de test, ahora podemos ver que siguen funcionando y cumpliendo su función. Al realizar un Run, podremos ver una imagen similar a esta:

Resultado_Test_DUnitX Frente a la que veíamos con DUnit: Resultado_Test_Dunit

Aunque el resultado visual es diferente, nos interesa que los datos que nos aparecen son equivalentes. Si modificamos un poco nuestro código para generar algún error (y poder ver así cómo se ven resultados erróneos) podremos obtener algo como esto:

Test_error_DUnitX

Finalizo aquí esta entrada. Justo debajo os pongo el código del proyecto "modificado" para que podáis hacer pruebas con él. He cambiado un par de test para que fallen y de esa forma podáis ver los diferente resultados.

<Descarga del código fuente del proyecto>

Como siempre sugerencias, comentarios, peticiones, y demás son bienvenidas.

Hasta la próxima.


Read More

ECMAScriptやPHPのような連想配列

$
0
0

連想配列は[キーか]ら連想される内容(Value)をプログラムで登録しておき、必要なときに[キー]から検索した内容(Value)を取得できるデータコンテナです。ECMAScript(JavaScript)では変数にJSONを入力すると連想配列として扱うことができます。

 

JavaScript言語

var l_associative = { 'りんご': 'ゴリラ' };

console.log(l_associative.りんご);

> ゴリラ

 

PHP言語

<?php

$l_associative = array('りんご'=>'ゴリラ');

print_r("ANSER = ".$l_associative['りんご']."\n");

?>

このように、連想配列はさまざまなプログラム言語で利用されています。C++での連想配列は標準ライブラリのmapが使用できます。一般的に連想コンテナといわれています。では、C++Builder VCLアプリケーションのプロジェクトで標準ライブラリのmapを使って試してみましょう。

メインフォーム上にKeyを入力するTEditとボタンのOnClickイベントで結果表示するValue側のTEditを用意しました。

 

Button1を選択しオブジェクトインスペクタのイベントタブからOnClick項目をダブルクリックしイベントハンドラを作成します。

イベントハンドラのメソッドの上にmapを利用するためのインクルードを1行記述します。

#include <map>

イベントハンドラの中は下記のように記述します。

void __fastcall TForm1::Button1Click(TObject *Sender)

{

        std::map<String, String> l_associative;

        l_associative.insert(std::make_pair<String, String>("りんご", "ゴリラ"));

        l_associative["赤"] = "きつね";

        //結果をValue側に設定する

        Edit2->Text        = l_associative[Edit1->Text];

}

 コード中のl_associativeと言う変数が連想コンテナです。insert()関数を使った登録と直接Keyを指定した入力方法2つ書いています。l_associativeの中を呼び出す場合l_associative[キー]です。

 

実行すると下記のように、Edit1で「赤」を入力しボタンをクリックすると「きつね」とEdit2に表示されました。



 

2018年4月23日~5月4日までの月~金曜に毎日ブログを更新。Delphi / C++Builderに関する技術記事からエンジニアの日常まで、さまざまな話題を投稿します。お楽しみに!

日本人スタッフブログを一覧表示できる、こちらのページをブックマークしてください。


Read More

10.2.3 C++ Hotfix for an issue with a 4KB or larger stack allocation

$
0
0

In 10.2.3, there is an issue affecting methods using the fastcall calling convention that allocate 4KB or more on the stack inside the method. The stack allocation could result in the 'this' pointer containing an incorrect value.  This was reported as:

  • RSP-20171
  • RSP-20297 and RSP-20173 (duplicate reports)

You can download the hotfix from CodeCentral.

Technical info

For those interested in the technical details, when the stack grows, it might need to grow into a new page, and 4KB is the size of a page on Windows and so by definition will cause this to occur. When the compiler sees a 4KB or larger stack allocation it calls a method to ensure the next page(s) are committed. 

We have always had one RTL method to handle this, _chkstk, and in 10.2.3, we introduced a new version, _chkstk_noalloc. This new method ensures that the esp register is left unchanged; if not, while your app would be fine, the debugger could get confused and think it was in a recursive method. We fixed this issue in 10.2.3. This hotfix addresses a related issue where the eax register was not being restored correctly, which for a fastcall method manifests as the 'this' pointer.

Make sure you rebuild and relink your projects against the 10.2.3 RTL, since if you mix old and new RTLs you will get an unresolved external against this new method. Upgrading to 10.2.3 and this hotfix solves some debugging scenarios that were problematic in earlier releases, and enables debugging of method parameters and other items in a method with a very large allocation.

 


Read More

C++ Free Compiler Updated to 10.2.3

$
0
0

Embarcadero has had a free download of our C++ compiler and RTL (capable of making Win32 apps) for many years, going back into the Borland days. (In fact, Idera as a company likes providing free tools - check out some of the others here.) We aim to keep that free compiler up to date, and so we updated it from the frankly ancient classic "Borland" v5.5 compiler to the 10.2 Berlin compiler in July 2016.

I'm pleased to announce that we've just updated it again, with the compiler from 10.2.3 Tokyo. You can download it here!

This download includes:

  • Our Clang-enhanced compiler for Win32. Today's update has improved this further:
    • bcc32c, compatible with the classic compiler's command-line interface
    • New! bcc32x, the same compiler with a Clang command line interface
  • The Dinkumware STL
  • Our RTL
  • Miscellaneous command-line tools, such as the librarian (tlib), resource compiler, and others.

Is the Command-line Compiler Right for Me? 

This is just the command-line compiler and tools; it is not a full IDE.  You'll need a text editor to write programs.  It is suitable for building Win32 apps from scratch, such as a WinMain() application.

We hope it will be useful for students or anyone learning C++ or for teachers (but don't forget we have an academic license of the entire C++Builder product, plus our free Starter Edition); for those who maintain libraries that need to be tested or compatible with a wide range of compilers; for those who've used earlier versions of our products; or anyone for whom a free and powerful compiler is a useful tool.

Download the free C++ compiler here!

About C++Builder

When you want to add the benefits of a fully featured IDE and toolchain, choose C++Builder for cross-platform development.  It includes compilers for Win32, Win64, iOS, Android, and macOS, as well as cross-platform database, enterprise, UI, and web frameworks. Use one codebase and one set of libraries. Design a UI once and specialize it natively per platform or per device, just like subclassing code. Accelerate your development: spend time coding, not struggling with the UI or the platform.

C++Builder comes with a FREE 30 Day Trial.


Read More

App Home Screen Navigation - FireMonkey UI Templates

$
0
0

Providing your application menu on the home/main screen is a popular design pattern used in many applications today. It is especially useful in mobile applications where screen real estate is limited. Home screen navigation can be used by itself to serve as the main application menu, or used in conjunction with a slide-in drawer and/or additional toolbar navigation.

Home screen navigation provides all the key application functionality at a glance on one screen. Providing a good user experience in your application is not only important for user adoption, but also to get accepted in the iOS App Store and Android Google Play Store. For more information on cross-platform design patterns, watch our webinar replay on UX excellence. 

While you can always create your own customized home navigation screens from scratch, as detailed in this blog post, it can be time consuming. Using these new layouts will reduce development time while providing ample opportunities to customize for your own application.  UI tweaks are easy and fast, and application styles can be quickly expanded or replaced with your own.

Generally speaking, home screen navigation designs include:

  • Glyph Buttons arranged in a grid like layout
  • Glyph Buttons can be annotated with text
  • May span over multiple screens
  • Most commonly used in mobile applications 

Delphi and RAD Studio 10.2.3 include 18 new FireMonkey UI templates, designed to highlight FMX's multi-device capabilities, showcase best practices, and help new users get started quicker. They showcase UI paradigms that mobile application developers need in today’s applications.

This blog post focuses on the three new home screen navigation GUI templates, available for download in GetIt (Tools > GetIt Package Manager > Sample Projects).

Each of the three templates uses one of the premium FireMonkey multi-platform styles.

 

Only the first template will be auto-opened after installing a GUI template, but you can access the other two templates by navigating to C: \ Users \ Public \ Documents \ Embarcadero \ Studio \ 19.0 \ Samples \ Object Pascal \ App Home Screens 

App Home Screen #1:

Shown in the IDE on an Android FireUI device 4" phone view. This GUI template includes built-in support for FireMonkey's Behavior Service. FireMonkey's Behavior Service is a service API that allows the framework and developer to query information about the device the app is running on to dynamically adjust itself for the form factor and platform. UI element locations are automatically adjusted for each type of target device (for example, the position of tabs on different mobile platforms)

Template running on the iOS Simulator.

 

App Home Screen #2:

Shown at design time in the IDE, and running on Windows.

 

   

Includes built-in support for slide-in drawer style navigation, using FireMonkey's TMultiView control. Template running on the iOS Simulator.

Key Benefits of slide-in drawer style navigation include: 

  • Main app menu is hidden by default, allowing you to take advantage of more screen real estate when building your application
  • Invoked by tapping on a menu button or swiping left/right, providing an intuitive user experience

 

App Home Screen #3:

You can easily change the background overlay color by changing the fill color for the rectangle. 

 

You can easily change the image opacity of the background image.

 

Home Screen Navigation, Template #3 running on Windows. Includes built-in support for slide-in drawer style navigation, using FireMonkey's TMultiView control.

 


Read More

Webinar Replay: C++ Software Security Sins

$
0
0

In the world of software development, we are up against new cyber security threats each day, and the risks and consequences of un-secure software is too great to be unaware of.  

Join presenter, Mary Kelly, to address the key security sins related to C++ applications, how they happen and how to resolve them.

Here is the webinar replay :

Buffer Overruns

The following is a snippet of a common “old school” buffer overrun:

void bufFunc (char *str)
{
     char buffer[10];
     strcpy (buffer, str);
}

int  _tmain(int argc, _TCHAR* argv[])
{
     char string [16];
     printf (“Input some data : ”);
     gets(string);
     bufFunc (string);
     printf (“Additional data here : ”);
}

When dealing with buffer overflows, here are a few common fixes:

  • Comment your code
  • Use the C++ Standard Library and STL
  • Use libraries that check bounds
  • For buffer overruns or overflows, there is a popular method called fuzz testing. Fuzz Testing or fuzzing as it’s known in many circles is a testing technique by which you test your inputs with generated semi-randomized values helping with stability and performance of your applications. I mentioned one fuzzing library that I use called libFuzzer.

Format String Problems

void vulnerable ()
{
     char buffer[60];
     if (fgets (buffer, sizeof (buffer), stdin) == NULL)
     return;
     printf(buffer);
}
void notVulnerable ()
{
     char buffer[60];
     if (fgets (buffer, sizeof (buffer), stdin) == NULL)
     return;
     printf (“%s”, buffer);
}

Recommended fixes:

  • Don’t pass user input directly as the format string to formatting functions
  • Use fixed format strings, or format strings from a trusted source
  • Keep an eye on compiler warnings and errors
  • When necessary to use format strings, use : printf("%s", user_input)
  • Even better, use don’t use the printf family of functions if you can avoid it, use stream operations

Integer Overflows

Integer overflow occurs when the result of an operation is larger than the allowed max max value for the data type of an operation and can cause crashes, logic errors, escalation of privileges, and execution of arbitrary code.

Some easy fixes you can do:

  • Study and understand your code.  Do a little bit of math!
  • Check all calculations used to determine that your memory allocations and array indexes can’t overflow.
  • Use unsigned variables for array offsets and sizes for memory allocation
  • Pay attention to your compiler warnings
  • Check for truncation and sign issues when working with size_t

Array new and delete

When you write new in your applications, you are creating unmanaged objects, and you are then required to call delete later on if you don’t want to risk leaks. So don’t use new and delete at all, as this is considered a C++ bad practices. Better yet, working in modern C++ allows you to use smart pointers and Standard library container classes that make it easier to match every new with exactly one delete.

Poor copy constructor and assignment declarations

In C++, a copy constructor is called when a new variable will be created from an object. If you don’t create a copy constructor, then your compiler generates a copy constructor. This sounds great! But if you don’t properly set up your constructor, then the errors replicate.

class PrtHolder
{
public:
     PtrHolder(void* p) : m_ptr(p)
     {
     }
     ~PtrHolder()
     {
            delete m_ptr;
     }
private:
     void* m_ptr;
};

When your class controls resources, you should declare a private copy constructor and assignment operator with no implementation, this way if a class external to the class with your private declaration attempts to invoke one of these, then you will get a compiler error about invoking a private method. Even if you accidentally call one internally, then you will get a link error.

Pointer initialization

Foo* pFoo;
if (GetFooPtr ( &pFoo ) )
{
     // some code
}
// If pFoo is uninitialized, this is exploitable
pFoo -> Release();

There are a few methods to use when wanting to avoid pointer problems. Use these steps in C++:

  • Initialize pointers when you declare them - Kind of a no brainer, but a great way to make your application a little easier to debug instead of worrying about some previously used pointer value
  • Zero pointers out after use
  • To avoid memory leaks, allocate memory from the heap and return it at the same abstraction level.
  • Return blocks to the heap while your pointers are still in scope
  • Make sure that the types of pointers match

Lack of STL knowledge

Know the standards to C++. There is an awesome group of people out there who make up rules regarding the evolution of the C++ language. Since C++11, there has been an uptick in features that help to avoid many pitfalls surrounding security of your C++ code.  My recommendation for learning more about the C++ STL or the C++ Standard Library is to check out www.cplusplus.com or cppreference.com.

Useful Resources

I usually like to recommend a few books or resources in my webinars and this one is no different. For learning about Software Security or ways to solve these “sins” with an emphasis on C++ applications, check out the following:

Writing Secure Code, Second Edition by Michael Howard and David LeBlanc

24 Deadly Software Security Sins: Programming Flaws and How to Fix Them by Michael Howard, David LeBlanc, John Viega

Software Security: Building Security In by Gary McGraw

Effective C++: 55 Specific Ways to Improve Your Programs and Designs (3rd Edition) by Scott Meyers

STL Tutorial and Reference Guide by David Musser


Read More

Google Book APIを使ってISBNコードから書籍情報を取得する

$
0
0

筑木です。今回はWebAPIへのアクセスの例として、Google Books APIsを使ってISBNコードから書籍情報を取得してみます。

応用として、TCameraComponentとZXingを使って画像のバーコードから書籍のISBNコードを読み取り、Google Books APIsで書籍情報を取得、それをDBに登録して蔵書管理アプリみたいなものが作れます。

Google Books APIsにISBNコードを投げてその結果を取得するのは、TRESTRequest、TRESTClient、TRESTResponseを使えば非常に簡単です。
このようにフォームにUIであるTEdit,TLabel,TMemo,TImageと、Google Books APIsとやりとりをするためのTRESTRequest、TRESTClient、TRESTResponse、TIdHTTPを配置します。

配置したTRESTRequestのClientとResponseプロパティにそれぞれTRESTClient、TRESTResponseを設定します。

実際にAPIを呼び出してみましょう。TRESTRequestとTRESTClientにパラメータを設定し、Executeメソッドを呼ぶだけです。

procedure TForm1.Button1Click(Sender: TObject);
begin
  RESTRequest1.ResetToDefaults;
  RESTClient1.ResetToDefaults;
  RESTResponse1.ResetToDefaults;

  RESTClient1.BaseURL := 'https://www.googleapis.com/';
  RESTRequest1.Resource := 'books/v1/volumes?q=isbn:{ISBN}';
  RESTRequest1.Params.AddItem('ISBN', Edit1.Text, TRESTRequestParameterKind.pkURLSEGMENT);
  RESTRequest1.Execute;
end;

APIの詳細は以下のURLを参照してください。今回は単純にパラメータとしてISBNコードを渡すだけです。

https://developers.google.com/books/docs/v1/reference/

RESTRequestのAfterExecuteイベントが発生すると結果が取得できますので、戻ってきたJSONをパースします。
JSONの書式は以下のURLを参照してください。
https://developers.google.com/books/docs/v1/reference/volumes

procedure TForm1.RESTRequest1AfterExecute(Sender: TCustomRESTRequest);
var
  BookInfo : TJSONValue;
  BookItems : TJSONArray;
  Authors : TJSONArray;
  ThumbnailURL : string;
  ItemCount : integer;
  i : Integer;
  ImageStream : TMemoryStream;
begin
  BookInfo := RESTResponse1.JSONValue;

  // 項目をクリア
  Edit2.Text := '';
  Edit3.Text := '';
  Memo1.Text := '';
  Edit4.Text := '';
  Image1.Bitmap.Clear(claWhite);

  // アイテム数取得
  ItemCount := BookInfo.GetValue('totalItems');

  if ItemCount > 0 then
  begin
    // 結果をパースする。
    BookItems := BookInfo.GetValue('items');
    with BookItems.Items[0] do
    begin
      // 題名
      Edit2.Text := GetValue('volumeInfo.title');

      // 副題
      Edit3.Text := GetValue('volumeInfo.subtitle');

      // 著者
      Authors := GetValue('volumeInfo.authors');
      for I := 0 to Authors.Count - 1 do
      begin
        Memo1.Lines.Add(Authors.Items[i].GetValue());
      end;

      // 出版日
      Edit4.Text := GetValue('volumeInfo.publishedDate');

      // 書影のサムネイル
      ThumbnailURL := GetValue('volumeInfo.imageLinks.thumbnail');
      ImageStream := TMemoryStream.Create;
      IdHTTP1.Get(ThumbnailURL, ImageStream);
      Image1.Bitmap.LoadFromStream(ImageStream);
    end;
  end;
end;

書影のサムネイルはTIdHTTPを使って改めて取得します。結果はTMemoryStreamに保存してTImageに設定するだけです。


クラウド系のサービスはリクエスト結果がJSONで帰ってくることが多いのですが、Delphi/C++Builderのコンポーネントを使えば簡単に結果のパースが可能です。古いDelphiやC++BuilderのバージョンではJSONなどのパースも自前で行うか、フリーのライブラリを使う必要がありますが、最新のバージョンでは手軽にWeb サービスを利用できるようになっています。

2018年4月23日~5月4日までの月~金曜に毎日ブログを更新。Delphi / C++Builderに関する技術記事からエンジニアの日常まで、さまざまな話題を投稿します。お楽しみに!

日本人スタッフブログを一覧表示できる、こちらのページをブックマークしてください。


Read More

Google Book APIを使ってISBNコードから書籍情報を取得する

$
0
0

筑木です。今回はWebAPIへのアクセスの例として、Google Books APIsを使ってISBNコードから書籍情報を取得してみます。

応用として、TCameraComponentとZXingを使って画像のバーコードから書籍のISBNコードを読み取り、Google Books APIsで書籍情報を取得、それをDBに登録して蔵書管理アプリみたいなものが作れます。

Google Books APIsにISBNコードを投げてその結果を取得するのは、TRESTRequest、TRESTClient、TRESTResponseを使えば非常に簡単です。
このようにフォームにUIであるTEdit,TLabel,TMemo,TImageと、Google Books APIsとやりとりをするためのTRESTRequest、TRESTClient、TRESTResponse、TIdHTTPを配置します。

配置したTRESTRequestのClientとResponseプロパティにそれぞれTRESTClient、TRESTResponseを設定します。

実際にAPIを呼び出してみましょう。TRESTRequestとTRESTClientにパラメータを設定し、Executeメソッドを呼ぶだけです。

procedure TForm1.Button1Click(Sender: TObject);
begin
  RESTRequest1.ResetToDefaults;
  RESTClient1.ResetToDefaults;
  RESTResponse1.ResetToDefaults;

  RESTClient1.BaseURL := 'https://www.googleapis.com/';
  RESTRequest1.Resource := 'books/v1/volumes?q=isbn:{ISBN}';
  RESTRequest1.Params.AddItem('ISBN', Edit1.Text, TRESTRequestParameterKind.pkURLSEGMENT);
  RESTRequest1.Execute;
end;

APIの詳細は以下のURLを参照してください。今回は単純にパラメータとしてISBNコードを渡すだけです。

https://developers.google.com/books/docs/v1/reference/

RESTRequestのAfterExecuteイベントが発生すると結果が取得できますので、戻ってきたJSONをパースします。
JSONの書式は以下のURLを参照してください。
https://developers.google.com/books/docs/v1/reference/volumes

procedure TForm1.RESTRequest1AfterExecute(Sender: TCustomRESTRequest);
var
  BookInfo : TJSONValue;
  BookItems : TJSONArray;
  Authors : TJSONArray;
  ThumbnailURL : string;
  ItemCount : integer;
  i : Integer;
  ImageStream : TMemoryStream;
begin
  BookInfo := RESTResponse1.JSONValue;

  // 項目をクリア
  Edit2.Text := '';
  Edit3.Text := '';
  Memo1.Text := '';
  Edit4.Text := '';
  Image1.Bitmap.Clear(claWhite);

  // アイテム数取得
  ItemCount := BookInfo.GetValue<Integer>('totalItems');

  if ItemCount > 0 then
  begin
    // 結果をパースする。
    BookItems := BookInfo.GetValue<TJSONArray>('items');
    with BookItems.Items[0] do
    begin
      // 題名
      Edit2.Text := GetValue<String>('volumeInfo.title');

      // 副題
      Edit3.Text := GetValue<String>('volumeInfo.subtitle');

      // 著者
      Authors := GetValue<TJSONArray>('volumeInfo.authors');
      for I := 0 to Authors.Count - 1 do
      begin
        Memo1.Lines.Add(Authors.Items[i].GetValue<String>());
      end;

      // 出版日
      Edit4.Text := GetValue<String>('volumeInfo.publishedDate');

      // 書影のサムネイル
      ThumbnailURL := GetValue<String>('volumeInfo.imageLinks.thumbnail');
      ImageStream := TMemoryStream.Create;
      IdHTTP1.Get(ThumbnailURL, ImageStream);
      Image1.Bitmap.LoadFromStream(ImageStream);
    end;
  end;
end;

書影のサムネイルはTIdHTTPを使って改めて取得します。結果はTMemoryStreamに保存してTImageに設定するだけです。


クラウド系のサービスはリクエスト結果がJSONで帰ってくることが多いのですが、Delphi/C++Builderのコンポーネントを使えば簡単に結果のパースが可能です。古いDelphiやC++BuilderのバージョンではJSONなどのパースも自前で行うか、フリーのライブラリを使う必要がありますが、最新のバージョンでは手軽にWeb サービスを利用できるようになっています。

2018年4月23日~5月4日までの月~金曜に毎日ブログを更新。Delphi / C++Builderに関する技術記事からエンジニアの日常まで、さまざまな話題を投稿します。お楽しみに!

日本人スタッフブログを一覧表示できる、こちらのページをブックマークしてください。


Read More

10.2.3 C++ 4KB以上のスタック割り当てに関する問題のホットフィックス

$
0
0

この記事は、DAVID MILLINGTONによる10.2.3 C++ Hotfix for an issue with a 4KB or larger stack allocationの抄訳です。

 

10.2.3では、メソッド内のスタックに4KB以上を割り当てる fastcall呼び出し規約を使用するメソッドに影響を与える issueがあります。スタックの割り当てによって、 'this'ポインタに不正な値が格納される可能性があります。

これは次のように報告されました:

  • RSP-20171
  • RSP-20297 、RSP-20173 (duplicate reports)

CodeCentralからホットフィックスをダウンロードできます

 

技術情報

技術的な詳細に関しましては、“Stack Grows”すると、新しいページに増やす必要があり(4KBはWindows上のページのサイズ)定義すると発生します。コンパイラが4KB以上のスタック割り当てを認識すると、次のページが確実にコミットされるようにメソッドを呼び出します。

 

これを処理するRTLメソッドは、常に1つの_chkstkしか持たないので10.2.3では新しいバージョン_chkstk_noallocを導入しました。この新しい方法は、espレジスタが変更されないように確保します。そうでない場合、ユーザーアプリケーションは大丈夫ですがデバッガはConfusedする可能性があり、再帰メソッドであったと考えられます。しかし、この問題は10.2.3で修正されました。このホットフィックスでは、eaxレジスタが正しく復元されない問題などの関連を解決します。fastcallメソッドの場合、 'this'ポインタとして現れます。

 

古いRTLと新しいRTLを混在させると、この新しいメソッドに対して未解決の外部が発生するため、プロジェクトを再構築して10.2.3 RTLと再リンクするようにしてください。10.2.3にアップグレードし、このホットフィックスは、以前のリリースで問題だったいくつかのデバッグシナリオを解決し、非常に大きな割り当てを持つメソッドのメソッドパラメータやその他の項目のデバッグを有効にします。

 


Read More

Removing the Community toolbar

$
0
0

The RAD Studio IDE contains a toolbar allowing you to log on to Community, and see messages sent to you by other users, questions and answers, and other notifications.

Recent website upgrades have caused issues with this toolbar for some users (now resolved), and we plan to remove the toolbar altogether in an upcoming version of RAD Studio.

If you have encountered issues, you can disable it in your current version of RAD Studio. The following assumes you are using RAD Studio 10.3. Adjust the version numbers appropriately if you are using an earlier version.

Disabling the Community toolbar

There are three methods you can use. Note that all of these modify your system, and you should take care and make appropriate backups.

Removing the package

This method is the most straightforward and easy.

  1. Close the IDE
  2. In Explorer, navigate to C:\Program Files (x86)\Embarcadero\Studio\19.0\bin
  3. Locate ‘CommunityToolbar250.bpl’
  4. Rename it to ‘CommunityToolbar250.bpl.old’
  5. Start the IDE.

Editing the registry

Editing the registry can damage your system. Take care.

  1. Close the IDE
  2. Open the registry editor (regedit)
  3. Navigate to HKEY_CURRENT_USER\Software\Embarcadero\BDS\19.0\Known IDE Packages
  4. Locate the entry, ‘$(BDS)\Bin\CommunityToolbar250.bpl’ with a value of ‘Embarcadero Community Toolbar Package’
  5. Edit the string value (not the name, but the textual description of the package), and prepend two underscores, so that the value is ‘__Embarcadero Community Toolbar Package’
  6. Start the IDE.

Using a special tool

There is an IDE addin to manage the packages the IDE loads. You can find it on CodeCentral here. This is unofficial, so regard its use as at your own risk.

Build and install this into RAD Studio, and use it to disable the Community Toolbar package.

Community integration

It's important to us that the Delphi and C++Builder community is visible to you, as part of that community. We recently added upcoming events to the Welcome screen, to make these much more visible and easy to register for. Often these are run by members of our community and we encourage you to join - these also have a live Q&A in which you can ask questions and have them answered, too. In terms of our Community site, we're evaluating its role within the IDE itself. Feel free to send us feedback (you can email me at david dot millington at embarcadero.com); we value your feedback, like hearing from you and will take your thoughts into account.

 


Read More

C++でLINQを使う

$
0
0

C++で面白いライブラリがあったので紹介します。

LINQって何?

LINQ(統合言語クエリ)はC#の機能でコンテナに対してクエリを発行して結果を抽出します。 詳細はMSDNのドキュメントを参照してください。 https://docs.microsoft.com/ja-jp/dotnet/csharp/linq/

LINQ for C++

LINQ for C++はこの、LINQをC++で使用できるようにしたライブラリです。

https://archive.codeplex.com/?p=cpplinq

使い方も簡単で、GitHubで公開されているヘッダファイルをインクルードするだけです。

https://github.com/mrange/cpplinq

では、実際に使ってみましょう。

#pragma hdrstop
#pragma argsused

#ifdef _WIN32
#include <tchar.h>
#else
  typedef char _TCHAR;
  #define _tmain main
#endif

#include <stdio.h>
#include <iostream>
#include "CppLinq/cpplinq.hpp"    


int computes_a_sum ()
{
  using namespace cpplinq;
  int ints[] = {3,1,4,1,5,9,2,6,5,4};

  return
      from_array (ints)
    >>  where ([](int i) {return i%2 ==0;})     // 偶数を抽出する
    >>  sum ()                                  // 抽出した値を合計する
    ;
}


int _tmain(int argc, _TCHAR* argv[])
{
  std::cout << computes_a_sum() << std::endl;

  return 0;
}

 

C++Builderでビルドしてみますが、C++11の機能を使っているので、[プロジェクト|オプション|C++コンパイラ]で「従来のBorlandコンパイラの使用」のチェックを外してください。

実行結果です。

このように配列から偶数を抽出してその合計が出力されました。新しいC++コンパイラを使用することによって沢山のライブラリも使用できるようになりました。コンパイラ自体も10.2.3のが公開されていますので、是非ともお試し下さい。

 

 

2018年4月23日~5月4日までの月~金曜に毎日ブログを更新。Delphi / C++Builderに関する技術記事からエンジニアの日常まで、さまざまな話題を投稿します。お楽しみに!

日本人スタッフブログを一覧表示できる、こちらのページをブックマークしてください。


Read More

My Blog is Having Serious Hiccups, Let's Plan a Move

$
0
0

You might have seen my blog has had a few issues recently. It is a very old application written in Delphi and running on a totally outdated Linux VM, hosted by a newer and more robust server. But the reality is, it is fairly fragile. First it had a kernel crash, caused by a bad out-of-memory issue, than on reboot it was low on disk space and things went a bit bonkers. It is working now, but not sure how much it will remain online.

I have already done a significant part of the development of a new simple custom engine, still in Delphi, using some of the newest technologies. I have a database where I can migrate all of the data. Nothing will get lost in terms of URLs and content (or so I hope -- there are over 12 years of content and over 1,400 post on this blog). So over the coming week I'll spend some extra time (it is my  personal time) on the migration. I plan making a parallel site available for early testing (initially read only, maybe even without comments) and over time I'll move everything there.

While I'll be working on it, I plan offering a fairly detailed description of the work involved both in the migration and in building the new site. While I don't plan open sourcing the engine, I can certainly share a lot of the technologies and the code being used. Stay tuned. And if the blog crashes badly again, sorry, I might just end up surfacing the new site.


Read More

3D Credits Scroll with Delphi

$
0
0

A little fun with Delphi for today’s Star Wars day!

3D Credits Scroll with Delphi - May The Fourth

This is a pretty simple 3D form with a 3D layout at an angle, and then a 2D layout with text and images is animated up the 3D layout. The only code is populating the labels as the animation kicks off automatically.

3D Scroll - MayTheFourth-StructureDownload the code and run the full credit scroll, or change the message to share with your friends. It is FireMonkey, and while I only tested it on Windows, it should work on Android, iOS, macOS, and even Linux if you are running FMX Linux.

CreditScroll3D Source for 10.2.3 Delphi

May the Fourth be with You!


Read More

【追加開催決定!】エンタープライズモバイル開発ワークショップ

$
0
0

【6月8日(金)追加開催決定!】エンタープライズモバイル開発ワークショップ 「業務システムと連携するアプリ開発を体験」

4月に新設したエンタープライズモバイル開発ワークショップ。4月開催が終了し、5月は早い段階で満席となりましたので、6月に追加開催を決定!【先着8名】となり、6月も満席が予想されますので、お申込みはお早めに。

開催概要

スマートフォンやタブレットが普及する中、これらを活用して現場でITを活用し、業務を効率化したいという要求が高まっています。しかし、多くのモバイル向け開発ツールでは、企業システムと連携するための機能が用意されておらず、肝心の企業データの活用のために多くの労力を割かざるを得ません。

エンバカデロが提供するエンタープライズ向けモバイル開発機能を用いれば、コンポーネントによる効率的な開発によりデータ連携が可能。企業データを活用したモバイルアプリの開発を迅速に行えます。このワークショップでは、エンタープライズモバイル開発を実現するDelphi / C++Builderを用いて、企業データとの連携を実際の開発シナリオに基づいて実装し、効率的な開発手法を体験できます。企業向けモバイル開発を検討している方に最適のセミナーです。

日時・詳細

セミナー名:エンタープライズモバイル開発ワークショップ 「業務システムと連携するアプリ開発を体験」

日程:6月8日(金)14時~17時

会場:エンバカデロ飯田橋オフィス セミナールーム(東京・飯田橋)地図

定員:8名(先着順)

参加費:無料(事前登録制)

お申込み:登録フォームより事前にご登録ください

※開発環境、機材は弊社で準備いたします。パソコンなどの持ち込みは必要ありません。

内容:

  • 企業システムとモバイルを連携させるしくみ
  • コンポーネントによる連携の手法
  • ビジュアル操作によるユーザーインターフェイス設計
  • コンポーネントを用いたデータ連携の演習
  • 開発マシンからモバイルデバイスのリモートデバッグ
  • アプリケーションの配布

こんな方におすすめ

  • 企業のシステム開発責任者/技術リーダー
  • 企業のモバイル開発責任者/技術リーダー
  • 既存システム資産を抱える情報システム部門
  • 企業システムでモバイルの活用を提案したいシステム開発企業(SI)
  • モバイルの活用を推進したい企画/研究部門

 

RAD Studio 無料トライアル版


Read More

RAD Studio 10.2.3 iOS 11.3 Patch available

$
0
0

Earlier this week we released a patch for Delphi, C++Builder and RAD Studio 10.2.3 that adds support for building iOS 11.3 applications for Development, App Store, Ad Hoc or In-House Distribution.

This patch fixes the following publicly reported issues:

Click here to download the patch. 


Read More

RAD Studio / Delphi / C++Builder 10.2.3 iOS 11.3パッチリリース

$
0
0

この記事は、Sarina DuPontによるRAD Studio 10.2.3 iOS 11.3 Patch availableの抄訳です。

 

今週初めにRAD Studio / Delphi / C++Builder 10.2.3用パッチをリリースしました。

これはiOS 11.3アプリ開発, App Store, Ad Hoc or In-House Distributionのビルドサポートです。

このパッチは、公表されている以下のIssueを修正しています:

パッチをダウンロードするには、ここをクリックしてください。

 

 


Read More
Viewing all 1683 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>