Pesquisar

Pergunta
· Ago. 12

Need help with file upload.csp

I am trying to use upload.csp as a template for choosing a CDV file to process. I am calling it from a zen page using this:
<button caption="Import Client Consultation Extract" 
       controlStyle="width:500px; height:100px; font-size:1.5em;"
         onclick="zenPage.importExtract();"/>

ClientMethod importExtract() [ Language = javascript ]
{
    // Open CSP popup to upload the CSV
    //alert('importExtract called.');
    zenPage.launchPopupWindow(zenLink('Upload.CSP'),'Upload Client Consultation extract',
                              'status,scrollbars,resizable,width=750,height=250');
}

I have increased the size of the text and buttons and I have added code to process the contents of the selected file into a global that will be processed further in the next step. The only problem is, I can't get the code to call back to the parent zen page and close the popup. I also wanted to add an "Exit" button so the user can close the popup without choosing a file if needed for some reason. What I have developed isn't working.

I am hoping someone would take some time to look this over and give me some solutions.

Here is the upload.csp as I have altered it.

<!-- Copyright (c) 2001 InterSystems Inc. ALL RIGHTS RESERVED. -->
<csp:class description="Upload Client Consultations file.">
<html> <head>
<H1>Upload Client Consultation extract file</H1>
</head> <body bgcolor="#CCCCFF"> <!-- HTML Form to submit the file. You must specify the enctype="multipart/form-data" -->
<!-- for this to work -->
<form enctype="multipart/form-data" method="post" action="upload.csp" style="font-size: 20px">
Choose Client Consultation file: <input type=file size=30 name=FileStream style="width: 500px; height: 40px; font-size:18px;">
<style="font-size: 20px;">
<ul>
  <input type="submit" value="Upload file" style="width: 100px; height: 40px; font-size: 18px;">
  <button onclick="exitPopup();" style="width: 100px; height: 40px; font-size: 18px;"> Exit </button>
</ul>
<p>
</form> <!-- As form is submitted to this page look to see if we have the stream in the %request object -->
<csp:if condition='($data(%request.MimeData("FileStream",1)))'>
<ul>
<script language="Cache" runat="server">
&js<alert('Choose file click');>
New bytes,lc
Set bytes=%request.MimeData("FileStream",1).Read()
Set bytes=##class(%CSP.Utils).DecodeData(bytes)
If $Data(^G2W.Import("UploadedCSV")) Kill ^G2W.Import("UploadedCSV")
For lc=1:1:$L(bytes,"_$c(13,10)_") {
Set D=$TR($Piece(bytes,"_$c(13,10)_",lc),$C(187,191,239))
Set ^G2W.Import("UploadedCSV",lc)=$ZCONVERT(D, "I", "HTML")
}
</script>
</ul>
</csp:if>
</body>
<script language = "JavaScript" >
 function exitPopup() {
alert('Made it to exitPopup');
opener.processImport();
window.close();
}
</script>
</html>
 

I do realize this is to choose a file on the client side (my laptop). This is what I want. The file will not be on the server (my desktop).

Thank you for your time.

8 Comments
Discussão (8)2
Entre ou crie uma conta para continuar
Anúncio
· Ago. 12

VS Code release July 2025 (version 1.103)

Visual Studio Code releases new updates every month with new features and bug fixes, and the July 2025 release is now available.

Enhancements include revamped tool picker and expanded tool limits for MCPs, Chat GPT-5 integration and chat checkpoints, and multi-branch Git worktrees plus coding agent session management to improve productivity.

If you need help migrating from InterSystems Studio to VS Code, or want to advance your knowledge of VS Code, take a look at the training courses George James Software offers > georgejames.com/vscode-training/

Updates in version 1.103 include -

MCP:

Chat:

Productivity:

The release also includes contributions from our very own @John Murray through pull requests that address open issues. Find out more about these features in the release notes here > https://code.visualstudio.com/updates/v1_103

For those with VS Code, your environment should auto-update. You can manually check for updates by running Help > Check for Updates on Linux and Windows or running Code > Check for Updates on macOS.

Discussão (0)1
Entre ou crie uma conta para continuar
Artigo
· Ago. 12 7min de leitura

Using LIKE with Variables and Patterns in SQL

Over the years, I’ve noticed that certain SQL questions come up repeatedly on the InterSystems Developer Community, especially about using the LIKE predicate in different contexts. Common variations include:

and many more derivatives. So, I decided to write an article that focuses on how LIKE works in InterSystems IRIS SQL, especially when used with variables in Embedded SQL, Dynamic SQL, and Class Queries, while touching on pattern escaping and special character searches.

First of all, I'd like to mention that InterSystems IRIS SQL offers most of the capabilities available in other relational DBMS that implement a later version of the SQL standard. But at the same time, it's important to mention that apart from relational access, in IRIS you can also use other models to get the same data, for example, object or document models. 

On this note, let's look at the LIKE predicate and how this tool is used in SQL for pattern matching. 

Basic info

Firstly, let's look at some basics. The LIKE predicate is used in a WHERE (or HAVING) clause of a SELECT, UPDATE, or DELETE statement to filter records based on whether a column's values match a specified pattern. The basic syntax is as follows:

SELECT column1, column2
  FROM table_name
 WHERE column_name LIKE pattern;

The pattern can include literal characters and two primary wildcard characters:

  • % (percent sign): represents zero, one, or multiple characters. For example, 'A%' matches any string starting with 'A', '%Z' matches any string ending with 'Z', and '%XY%' matches any string containing 'XY'.
  • _ (underscore): represents a single character. For example, 'A_C' matches 'ABC', 'AEC', etc., but not 'AC' or 'ABBC'.

For example, the following query retrieves all names from the Employees table that start with "Jo":

SELECT Name
  FROM Employees
 WHERE Name LIKE 'Jo%';

And this query retrieves all names that have an "a" as the second character:

SELECT Name
  FROM Employees
 WHERE Name LIKE '_a%';

It's crucial to understand that LIKE performs pattern matching, not equality. While 'ABC' LIKE 'ABC' evaluates to true, it's generally more efficient to use the = operator for exact string matches ('ABC' = 'ABC'). LIKE excels when you need fuzzy matching or searches for substrings.

Include a special character in a search phrase (escape clause)

I find the ESCAPE clause to be quite handy when you need to use a wildcard character, e.g. %, in your LIKE statement, and want it actually to mean a percentage sign. In this case, you can use the ESCAPE clause to define an escape character. Any character immediately following the escape character in the pattern is treated as a literal character, not a wildcard. For example, if you have the following data:

INSERT INTO Post.Promos(name, description) VALUES('Test 1', 'This is 40% discount')
INSERT INTO Post.Promos(name, description) VALUES('Test 2', 'This is 50% discount')
INSERT INTO Post.Promos(name, description) VALUES('Test 3', 'This is 10% discount')
INSERT INTO Post.Promos(name, description) VALUES('Test 4', 'some description')

and you wish to find all Promos that have a "50% discount" phrase in the description, you can use the following query:

SELECT Name
  FROM Post.Promos
 WHERE Description LIKE '%50\% discount' ESCAPE '\'

In this example, \ is defined as the escape character, so the system will treat the % sign as a literal, not a wildcard, and will look for a discount with a description that contains the literal phrase "50% discount".

Find special characters

If you need to look for several special characters or to find all of them in a string, you can't use a LIKE predicate, you need to use %MATCHES. It matches a value with a pattern string containing literals, wildcards, and ranges. Beware that a pattern should be specified in Logical format, regardless of the %SelectMode setting. So if you want to find all values that contain any special character, you can use %MATCHES to look for them like this:

SELECT * 
  FROM Post.Promos p
 WHERE p.description %MATCHES '*[!”%#$&”()*+,-./:;<=>?@\%\_]*'

This finds any description containing at least one of the listed symbols. You can use the ESCAPE clause to specify the escape character, but by default it's set to "\", so you can omit it as is done in my example. 

The query above will return three rows with 40%, 50% and 10% discount and not 'some description'.

Also, this predicate follows the general rules of pattern matching of IRIS. For example, for a placeholder, you will use "?" and not "_":

SELECT * 
  FROM Post.Promos p
 WHERE p.name %MATCHES '???? [0-9]'

This will look for all names that consist of any four characters, a space, and a numerical digit.

While I'm on the topic of patterns, there's also a predicate %PATTERN that allows you to match a pattern of character type codes and literals to the data values. So, to perform the same search as above, you can write the following query:

SELECT * 
  FROM Post.Promos p
 WHERE p.name %PATTERN '1U.L1" "1N'

This matches:

1U — 1 uppercase letter
.L — lowercase letters
1" " — 1 space
1N — 1 numerical digit

Using variables with LIKE

Now it's time to look at how you can use variables in your queries. There are three ways you can use a SQL statement in your Object Script code: Embedded SQL, Dynamic SQL, and writing a class query.

Embedded SQL

To pass a value into an Embedded SQL statement, you should use a named parameter (or, in other terms, input and/or output host variables), meaning that it has to have a name. For example, if we still wish to find all Promos with a 50% discount, we will write the following query:

 set param = "50\% discount"
 &sql(DECLARE C1 CURSOR FOR
       SELECT Name
         INTO :nameout
         FROM Post.Promos
        WHERE Description LIKE '%'_:param_'%' ESCAPE '\')
 &sql(OPEN C1)
       QUIT:(SQLCODE'=0)
 &sql(FETCH C1)
 WHILE (SQLCODE = 0) {
     WRITE nameout,!
    &sql(FETCH C1) }
  &sql(CLOSE C1)

Its input host variable is param, and it equals "50% discount". To make the query understand that % is a part of the parameter and not a placeholder for any length of characters, I use the ESCAPE clause.

Also, don't misplace double and single quotation marks:

  • In SQL, you use the former to mark a field that is a reserved name, for example, "Group". You use the latter to observe any string.
  • In ObjectScript, you use the former to observe the string, and the latter has nothing to do with strings at all, it's an unary operator NOT.

When using parameters, you don't need to put a single quotation mark inside the double quotation mark

set param = " '50\% discount ' " 

to show the compiler that it's a string or anything to this effect. In this case, the engine will look for single quotes as part of the search string,

The output host variable in the example above is "nameout," where the value of the Name column will be placed, and it can be used later in the code.

Dynamic SQL

Starting with version 2015.2, Dynamic SQL can accept a literal value input to a query in two ways:

  • input parameters specified at execution time using the “?” character
  • input host variables specified at prepare time

The second approach will follow the same idea as in Embedded SQL above:

 set param = "50\% discount"
 set myquery = 3
 set tStatement = ##class(%SQL.Statement).%New()
 set myquery(1) = "SELECT Name"
 set myquery(2) = "FROM Post.Promos"
 set myquery(3) = "WHERE Description LIKE '%'_:param_'%' ESCAPE '\'"
 set qStatus = tStatement.%Prepare(.myquery)
 set tResult = tStatement.%Execute()
 while tResult.%Next() {
	 write tResult.Name, !
 }

with the exception that you don't need the output host variables because the %SQL.StatementResult (result type of tStatement.%Execute()) will have all the properties that reference columns in the SELECT statement.

In the first approach, you put the question mark in place of a parameter, and then when calling %Execute(), you need to provide values for the parameters in the same order as the "?" in your statement:

 set param = "50\% discount"
 set myquery = 3
 set tStatement = ##class(%SQL.Statement).%New()
 set myquery(1) = "SELECT Name"
 set myquery(2) = "FROM Post.Promos"
 set myquery(3) = "WHERE Description LIKE '%'_?_'%' ESCAPE '\'"
 set qStatus = tStatement.%Prepare(.myquery)
 set tResult = tStatement.%Execute(param)
 while tResult.%Next() {
	 write tResult.Name, !
 }

Class Query

The input host variables are used in Class Queries following the same rules as in Embedded and Dynamic SQL:

Query GetDiscount(param As %String) As %SQLQuery [ SqlProc ]
{
SELECT Name FROM Post.Promos
 WHERE (Description LIKE '%'_:param_'%' ESCAPE '\')
}

When calling the query, you provide parameters in the same order as they are written in the method signature:

SELECT *
  FROM Post.Promos_GetDiscount('50\% discount')

I hope this article answers at least some of the popular questions that crop up from time to time.

If you're interested in a more in-depth article about performance considerations and best practices, or if you have any comments, don't hesitate to leave them in the comments section below.

2 Comments
Discussão (2)2
Entre ou crie uma conta para continuar
Anúncio
· Ago. 12

[Video] App de Navegação como Orquestração de Serviços no HealthShare com Single Sign-On para aplicativos de terceiros

Olá Comunidade,

Aproveitem o novo video no InterSystems Developers YouTube:

⏯ HealthShares Nav App as a Service Orchestrator with Single SignOn for 3rd Party Apps @ Global Summit 2024

Este vídeo apresenta a história de um cliente da região de Mayenne, na França, onde o Health Share é usado como uma plataforma unificada para coordenar o atendimento em sete hospitais e provedores municipais para 300.000 pacientes. Ele destaca como o Health Share integra serviços de terceiros com autenticação e autorização integradas, permitindo acesso fácil para diferentes profissionais de saúde por meio de login único e diversos métodos de login seguros.

Apresentadores:
🗣 @Florence Cureau, Sales Engineer, InterSystems 
🗣 @Francois Le Floch , Senior Solutions Engineer, InterSystems

Registe-se em nosso canal no YouTube InterSystems Developers para ficar atualizado!

Discussão (0)1
Entre ou crie uma conta para continuar
Anúncio
· Ago. 12

Récompense d’août pour les articles sur Global Masters

Salut, Communauté des Développeurs !

Nous avons lancé une toute nouvelle activité sur Global Masters : La récompense pour les articles !
C’est votre chance de partager votre expertise, d’aider vos collègues développeurs et, bien sûr, de gagner des points en le faisant.

👉 Participez à la récompense d’août pour les articles sur Global Masters

Plus tôt, nous avions lancé le défi Soumettez une idée pour un article — où les membres de Global Masters pouvaient proposer de sujets pour les articles, tutoriels, guides pratiques, et plus encore. Nous avons reçu un grand nombre d’idées fantastiques !

👉 Désormais, une fois par mois, nous publierons une liste de 10 sujets très demandés par la communauté.
Vous pourrez choisir un sujet dans la liste, écrire un article dessus et gagner une récompense de 🏆 5 000 points lorsque l’article sera approuvé.


🏆 Récompense d’août pour les articles

Période : du 7 au 31 août
Date limite pour publier un article et envoyer le lien via Global Masters : 31 août

Sujets d’août :

  1. Bonnes pratiques de codage pour les développeurs ObjectScript débutants. Exemples pratiques : comment utiliser les objets dynamiques – bonnes pratiques, comment utiliser les globals, etc.
  2. Création de tables SQL pour les tables relationnelles.
  3. Expériences avec l’utilisation d’outils de copilote avec ObjectScript (en particulier si vous obtenez de bons résultats !).
  4. InterSystems API Manager – étapes de configuration et d’utilisation.
  5. Bonnes pratiques pour concevoir des classes %Persistent dans InterSystems IRIS. Guide pour structurer efficacement les classes persistantes, incluant des conseils sur l’indexation, les relations et la validation afin d’assurer performance et maintenabilité.
  6. Utiliser Docker pour moderniser les environnements InterSystems hérités — montrer comment mettre en conteneur des applications InterSystems IRIS pour le développement local, les tests et le déploiement, y compris la configuration et les bases de l’orchestration.
  7. « Comment utiliser Studio et VS Code efficacement pour le développement InterSystems » — astuces et guide de configuration pour les développeurs passant à VS Code avec l’extension InterSystems ObjectScript.
  8. Modèles avancés de mise en œuvre FHIR avec InterSystems IRIS.
  9. Explication des propriétés d’opération comme Stay connected, Connect timeout, Reconnect retry, Response timeout, Read timeout. Détailler ce que chacune signifie et comment elles interagissent.
  10. Diagnostic et résolution des erreurs courantes d’InterSystems ObjectScript.

P.S. Si vous trouvez qu’un article à jour existe déjà sur un sujet proposé, envoyez-nous simplement le lien, marquez-le comme « Existant » et gagnez 30 points pour nous avoir aidés à l’identifier.


Règles à suivre :

  • L’article doit respecter les >>Directives générales de la Communauté des Développeurs<< et ne doit pas être rédigé par une IA.
  • Taille minimale : 400 mots (les liens et le code ne sont pas comptés dans la limite).
  • L’article doit porter sur les produits et services InterSystems.
  • L’article doit être rédigé en anglais (y compris pour le code, les captures d’écran, etc.).
  • L’article doit être 100 % nouvel.
  • L’article ne peut pas être une traduction d’un article déjà publié dans d’autres communautés.
  • L’article doit contenir uniquement des informations correctes et fiables sur la technologie InterSystems.
  • Des articles sur le même sujet mais avec des exemples différents provenant d’auteurs distincts sont acceptés.
Discussão (0)1
Entre ou crie uma conta para continuar