#Code Snippet

0 Followers · 298 Posts

Code snippet is a programming term for a small region of re-usable source code, machine code, or text.

Question Yone Moreno · Jan 28, 2021

Hello,

We would need some help,

Our aim is to send an image as binary data using a REST Service

Currently we do the following:

1 We get from the external system a binary image in our REST Operation

2 We encode it to Base64

set linea=""
    while (tResponse.Data.AtEnd = 0) {
        set linea = linea_$system.Encryption.Base64Encode(tResponse.Data.Read(57))
    }

3 We send it to the Process in a Response Message:

4
0 1086
Question Yone Moreno · Jan 27, 2021

Hello,

We would need some help, please;

We would like to handle when we have a date with hours:

20201204090000

And when we have it without the hours part, as follows:

20201204

For the first case we used:

##class(Ens.Util.Time).ConvertDateTime(source.{ORCgrp(1).RXA:DateTimeStartofAdministratio},"%Y%m%d%H%M%S","%d/%m/%Y",,.tSC)

For the second one we wrote:

##class(Ens.Util.Time).ConvertDateTime(source.{ORCgrp(1).RXA:DateTimeStartofAdministratio},"%Y%m%d","%d/%m/%Y",,.tSC)

 

However each way only works for one case

How could we handle both cases with just a line of code?

We have read:

1
0 434
Question Scott Roth · Jan 13, 2021

I have a case where our EMR is sending data, but not all the values needed for the Ancillary are valued properly and causes that message to error/halt processing on the Ancillary system, not ideal but its what they do. I would expect them to still process the message except that 1 field, but they don't.

I want to add validation to make sure certain fields are valued correctly for the Vendor. 

So I add some statements to take those items that don't pass this validation out to a batch file with headers.

9
0 1074
Discussion Eduard Lebedyuk · Jan 10, 2021
To start the year let's have a round of CodeGolf!
You know the drill. Shortest solution wins.Print a size ascending range of Diamonds using the numbers 1 to 9, ranging from size 1 to size N, each diamond separated by a blank line.
A size 1 diamond should look like this, a single centered 1:
1
With the size N=9 diamond looking like this:
1
121
12321
1234321
123454321
12345654321
1234567654321
123456787654321
12345678987654321
123456787654321
1234567654321
12345654321
123454321
1234321
12321
19
0 588
Question David Reche · Feb 16, 2016

Hello,

I am trying to use %ZEN.proxyObject to send out in JSON format so I do:

    set tProxyRequest = ##class(%ZEN.proxyObject).%New()
    set tProxyRequest.notanumber = "28001"
    set tProxyRequest.aboolean = "true"
    
    set tBody = ##class(%GlobalCharacterStream).%New()
    do ##class(Ens.Util.JSON).ObjectToJSONStream(tProxyRequest,.tBody,"aelotwu")
    w tBody.Read()

and I get:

{
        "aboolean":"true",
        "notanumber":28001
}

But I want this:

{
        "aboolean":true,
        "notanumber":"28001"
}

Help please !

10
0 1575
Question Alice Shrestha · Nov 27, 2020

Hi,

I seem to be able to execute sqlproc using the convention defined here https://docs.intersystems.com/latest/csp/docbook/Doc.View.cls?KEY=GSQL_… provided the package/folder is a single level. As, soon I have a nested folder structure I get an error while trying to execute this. 

For instance, 

select id, Utils.Users_getRole(id) roles from users.users

works fine while, 

select id, com.xyz.utils.Users_getRole(id) from users.users
does not work and gives,  "User defined SQL function ... does not exist"

I am on Cache 2017. Is there a workaround to making this work? 

3
0 194
Question Ahmad Bukhtiar · Nov 19, 2020

I have multiple files with different columns, first 9 values are fixed, so i want to ignore the first value, and next 8 values i want to combine into one value using ^ sign

Current Format

|||||||||||^^||||||^^|||||||||||||||||
|||||||||||^^||||^^|||||||||||||||||||||||
|||||||||||^^|||^^||||||||

Desired Format

^^^^^^|||^^||||||^^|||||||||||||||||
^^^^^^|||^^||||^^|||||||||||||||||||||||
^^^^^^|||^^|||^^||||||||

Reading each line from the file use below code.

#dim line as %String = tInput.ReadLine(, .status)

"here i was to put some string function to change format of the data in line variable"

11
0 995
Article Eduard Lebedyuk · Dec 3, 2019 1m read

One of the most useful features in Studio is code snippets.

Here's how to add snippets to VSCode.

Here's a generalized instructions.

1. Go to File - Preferences - User Snippets and choose objectscript.

2. Add your snippet, here's an example:

"SQL Statement": {
    "prefix": ["sql"],
    "body": ["#dim rs As %SQL.ISelectResult",
            "set rs = ##class(%SQL.Statement).%ExecDirect(,\"SELECT * FROM\")",
            "while rs.%Next() {",
            "\twrite rs.ID, !",
            "}"]
}

In here:

  • prefix - what you need to type for the snippet to appear
  • body - snippet body
1
5 785
Question Salma Sarwar · Oct 6, 2020

Hi

I would like to create a new message of a particular type and append various segments programmatically.  I have started with the following snippet.  What I am currently finding difficult is to define a segment of a particular segment structure.  I would like to append a pid segment of 2.3.1 to my message.  I know I could you the importfromstring but I wanted to know whether there was a better way of achieving this.

Set tOutputMessage = ##class(EnsLib.HL7.Message).%New()
Set target.DocType="2.3.1:DFT_P03"

#Dim tPID As EnsLib.HL7.Segment

tPID.SegTypeName ="PID"

2
0 830
Article Timothy Leavitt · Aug 27, 2020 7m read

Introduction

In a previous article, I discussed patterns for running unit tests via the  InterSystems Package Manager. This article goes a step further, using GitHub actions to drive test execution and reporting. The motivating use case is running CI for one of my Open Exchange projects, AppS.REST (see the introductory article for it here). You can see the full implementation from which the snippets in this article were taken on GitHub; it could easily serve as a template for running CI for other projects using the ObjectScript package manager.

Features demonstrated implementation include:

0
2 929
Question Ewan Whyte · Aug 3, 2020

Hi, I want to INSERT a customerID and customerName to a table if the customerID does not exist. Or UPDATE if they've changed their name.
I've reviewed the documentation (https://docs.intersystems.com/irislatest/csp/docbook/Doc.View.cls?KEY=R…) and have confused myself with the INSERT OR UPDATE statement. Rather than using two individual statements , is there a way to get it in one?

What I have at the moment doesn't do anything. In fact it errors.

I intend to use this within a code block in a DTL.

3
0 588
Question Yone Moreno · Jun 16, 2020

Hello,

We would like to learn how would you approach this task.

We would need to check every day a set of folders which are outside our server (in fact we could see them as if they were "inside" the server), then we need to check for modified or created files in the last day, and move all the ones which match the criteria to just one folder in our server.

We have thought about doing the following:

1) Create a task to run it each day:

5
0 743
Question Yone Moreno · Jun 15, 2020

Hello,

We would need to iterate all over the OBXs list and get their OBX3 CE1 to determine if it is the lab result we need to send to the output system.

We wonder how could we achieve this in a foreach component inside a Bussiness Process.

We think we would need to use a foreach because of it is needed to generate a message, for each one of the OBX which have the OBX3 CE1 that the output systems uses for the lab results.

So then we would need to use a foreach and then inside a transform and a call

We have already been able to output all tbe OBX3 CE1 to the log as follows:

1
0 669
Question Yone Moreno · Apr 30, 2020

Hello,

We would need to convert a message from the following class:

Class Mensajes.Request.Laboratorio.HL7Request Extends Ens.Request [ ClassType = persistent, ProcedureBlock ]
{Parameter RESPONSECLASSNAME = "Mensajes.Response.Laboratorio.ACKResponse";

Property mensaje As %XML.GlobalCharacterStream(CONTENT = "MIXED");

Property idPeticion As %String(MAXLEN = "");

Property ExpedienteUsuario As %String(MAXLEN = "");

Property MessageId As %String(MAXLEN = "");Property ContentType As %String(MAXLEN = "");

to a Request message which is composed by hl7 segments:

1
0 979
Article Evgeny Shvarov · May 11, 2016 1m read

Hi!

I believe the simplest is (to work with csv delimited by ";"):


set file = ##class(%File).%New( "data.csv" )
    set sc = file.Open( "R" ) 
    if $$$ISERR(sc) quit    ; or do smth

    while 'file.AtEnd {
        set str=file.ReadLine() 
        for i=1:1:$length( str, ";" ) {
            set id=$piece( str, ";" ,i ) 
            write !, id  // or do smth
        }
    }
    do file.Close()

Possible options:

different variants of error handling with sc code.

Embrace while loop into try/catch block.

And what's yours?

16
0 7195
Article Jenna Makin · Nov 9, 2015 1m read

The attached code package provides a simple implementation of a web service client that utilizes the USPS Shipping API to normalize  an address.

This code requires the developer to obtain a USPS Shipping API user ID which can be obtained from the USPS shipping API website.  The assigned User Id can either be passed into the web service call as a parameter or can be coded as a parameter into the Request object.

1
0 484
Article Gevorg Arutiunian · Aug 31, 2018 1m read

This code snippet changes all passwords in a system to a specified string. The two literal strings at the beginning of the snippet can be adjusted to edit the system or password string. The class method "test" runs the code:


Class eduardlebedyuk.changePasswords Extends %RegisteredObject
{
	ClassMethod test()
	{
        set ns = $namespace
	    zn "%SYS"
	    set NewPass = "NewPassString"
	    set rs=##Class(%ResultSet).%New("Security.Users:List")
	    set st = rs.Execute()
	    while rs.Next() { set st=$SYSTEM.Security.ChangePassword(rs.Get("Name"),NewPass)}
        zn ns
	}
}
7
0 851
Article Jose-Tomas Salvador · Apr 25, 2018 2m read

What if you could serialize/deserialize objects in whatever format: JSON, XML, CSV,...; attending different criteria: export/import some properties and not others, transform values in this or that way before exporting/importing,...; and all of this without having to change the class definition? Wouldn't that be great??

4
4 2722
Question Larry Pinsky · Feb 28, 2020

I have a code block in a BPL.  I have the below SQL and code.  All variables have been declared and set.  When I run the SQL, if there are no values returned, I get 100 for the value of SQLCODE when I perform the FETCH, which is correct.  If values are returned, I get a -400 error when I perform the first FETCH.  I've investigated, but cannot find the reason for a -400 error.  Hoping someone out here understands this and knows what's wrong.

2
0 2037
Question Kevin Furze · Jan 15, 2020

cache 2017.2.1 (Build 801_3)

when I look into the "sql statements" ( sql page of the management portal ) I have lots of old statements with a lot of them frozen. many of them are %sqlcq routines (I believe these are the SLQ's I run when testing/running random SQL queries in the sql page. )

I can clearly see where I can click on an individual query and untick an individual query to unfreeze it. or delete it. but thats a painful slow process. I can't see anywhere to delete/change multiple queries

2
0 271
Discussion Evgeny Shvarov · Aug 31, 2019

Hi Developers!

Often we need to use relatively small arrays with constants, static arrays in algorithms, etc where we need to do something with each element of an array. There are several ways to deal with it in ObjectSctipt. 

Previously I used to use globals, locals, PPG for this but not so long time ago figured out that %List is a way too handy.

Indeed, suppose we have an array of months and need to set up and use it in our code.

15
1 690
Article Timothy Leavitt · Dec 16, 2019 6m read

I've been having a blast with the Advent of Code puzzles this year - though I'll be heading into a busy span of time with family soon and will probably drop off toward the end. (At least, that's what always seems to happen - it's a good thing, though!)

I had a whole plane ride to play around with Day 13 and wanted to share some fun terminal tricks. I'm not planning to post my solutions on GitHub until the end of the year, but this is just visualization fun - not relevant to solving your own puzzle input (although visualization definitely helps for debugging) wink

2
0 558
Article Peter Steiwer · Dec 12, 2019 2m read

What is a portlet?

The simple answer is: a custom widget. A portlet can exist by itself on a DeepSee dashboard, it can be used along side standard DeepSee widgets, or along side other portlets. The rendering of the custom widget is completely user defined. This means you can embed a web page, create a form to perform any sort of action needed based on the data on your dashboard, use third party charting libraries, or simply display data from outside of a DeepSee cube.

How to get started

1
0 558
Article Pravin Barton · Mar 28, 2019 2m read

ObjectScript has at least three ways of handling errors (status codes, exceptions, SQLCODE, etc.). Most of the system code uses statuses but exceptions are easier to handle for a number of reasons. Working with legacy code you spend some time translating between the different techniques. I use these snippets a lot for reference. Hopefully they're useful to others as well.

5
23 3886
Question Flávio Lúcio Naves Júnior · Oct 21, 2019

Hello Everyone,

I'm want to know, what is more common for your company to use, the abbreviation syntax or the complety name of commands, and why?

Ex. 

S VAR=10 / D FUNC^ROUTINE F 1:1:1000

Set VAR=10 / Do Func^Routine / For 1:1:1000

set var=10 / do func^routine / for 1:1:1000

Here in my company, we are familiar with the abbreviation syntax, because to spell is more faster.

35
0 1117
Article Joel Solon · Oct 30, 2019 4m read

A few years ago, I was teaching the basics of our %UnitTest framework during Caché Foundations class (now called Developing Using InterSystems Objects and SQL). A student asked if it was possible to collect performance statistics while running unit tests. A few weeks later, I added some additional code to the %UnitTest examples to answer this question. I’m finally sharing it on the Community.

2
2 714
Question Yone Moreno · Oct 13, 2019

We have in DB two books, first is loaned because it has the Friend ID, and the other is in the shelf.

I execute a class query to get all loaned books:

    Query BooksLoaned() As %SQLQuery
    {
        SELECT *
        FROM Library.Book
        WHERE Friend IS NOT NULL
    }
 

Which I have tested throught the portal:

My task is to retrieve all the loaned books and return them in an array. Method code:

6
0 486