Translate

Thursday, April 28, 2022

Golang - Converting from Java and JSP to Golang and a Template

I'm working on converting a Java web application to Golang. Converting the JSP to a template was fairly straight forward.
In Java, I have this function to load the form:

@RequestMapping("/valueinputDateLoadAD")
public ModelAndView valueinputDateLoadAD() {
	Map myModel = new HashMap();
	myModel.put("page", "ldap/dateLoadAD/");
	myModel.put("label1", "Filter:");
	myModel.put("title", "Last update date in the form YYYYMMDD or Res. ID");
	myModel.put("input1_title", "AD Last Update Date or Res. ID");
	return new ModelAndView("input2Form", myModel);
}

The JSP form:

<form action="${page}" name="form1" id="form1" method="POST" target="iframename" onsubmit="event.stopPropagation(); event.preventDefault();">
<table id="input2" style="vertical-align: middle;">
  <tr>
	<td></td><td colspan="3"><b>${title}</b></td>
  </tr>
  <tr>
	<td style="text-align: right;">${label1}</td>
	<td><input style="min-width: 300px;" id="value1" type="text" name="value1" title="${input1_title}" maxlength="60" onkeydown="if (event.keyCode == 13) document.getElementById('input2search').click()"/></td>
	<td>  </td>
	<td><input type="button" id="input2search" value="   Go   " onclick="event.stopPropagation(); event.preventDefault();loadBySubmit2('form1');"/>
	<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>
	</td>
  </tr>
</table>
</form>


In Golang, I have this structure and function to load the template:

type StrcP1 struct {
	Page      string
	Label1    string
	Title     string
	In1_Title string
}
func valueinputDateLoadAD(w http.ResponseWriter, req *http.Request) { logger.NLog.Info().Msg("valueinputDateLoadAD called") strcP := StrcP1{Page: "dateLoadADGroup", Label1: "Filter:", Title: "Last update date in the form YYYYMMDD or Res. ID", In1_Title: "AD Last Update Date or Res. ID"} tmpl, err := template.ParseFiles("_resources/html/form/input2Form.html") if err != nil { logger.NLog.Error().Err(err).Msg("valueinputDateLoadAD: file parse error") http.Error(w, "Something went wrong", http.StatusInternalServerError) return } err = tmpl.Execute(w, strcP) if err != nil { logger.NLog.Error().Err(err).Msg("valueinputDateLoadAD: template execute error") http.Error(w, "Something went wrong", http.StatusInternalServerError) } }

And this is my template:

<form action="{{.Page}}" name="form1" id="form1" method="POST" target="iframename" onsubmit="event.stopPropagation(); event.preventDefault();">
<table id="input2" style="vertical-align: middle;">
  <tr>
	<td></td><td colspan="3"><b>{{.Title}}</b></td>
  </tr>
  <tr>
	<td style="text-align: right;">{{.Label1}}</td>
	<td><input style="min-width: 300px;" id="value1" type="text" name="value1" title="{{.In1_Title}}" maxlength="60" onkeydown="if (event.keyCode == 13) document.getElementById('input2search').click()"/></td>
	<td>  </td>
	<td><input type="button" id="input2search" value="   Go   " onclick="event.stopPropagation(); event.preventDefault();loadBySubmit2('form1');"/>
	</td>
  </tr>
</table>
</form>

Friday, April 8, 2022

Golang - Working with active directory date attributes

Some simple functions I wrote to convert AD date attributes to dates as stings.


//Converts a string passed in with the millisecond count to the date in the form yyyy-MM-dd HH:mm:ss as a string
func convertStringToDate64(strDate string) (string, error) {
	uD, err := strconv.ParseInt(strDate, 0, 64)
	if err == nil {
		return time.Unix((uD/(10000000))-11644473600, 0).Format("2006-01-02 15:04:05"), nil
	}
	return "", nil
}

//Converts a string passed in the form yyyyMMddHHmmss.0Z to the date in the form yyyy-MM-dd HH:mm:ss as a string
func convertStringToDateZ(strDate string) (string, error) {
	uD, err := time.Parse("20060102150405", strings.Replace(strDate, ".0Z", "", 1))
	if err == nil {
		return uD.Format("2006-01-02 15:04:05"), nil
	}
	return "", nil
}

Tuesday, April 5, 2022

Golang - Query Salesforce by using the Salesforce API

I've been learning how to query Salesforce by using the Salesforce API. Here is a simple example that uses the Salesforce query from my last post to query a custom object for values from two related tables. I am using the simpleforce package.

1 - Function to connect to Salesforce:


var (
	SfURL      = "https://mysite.my.salesforce.com/" //Custom or instance URL, for example, 'https://na01.salesforce.com/'
	SfUser     = "me@email.org"           //User name of the Salesforce account                                                                                    //"Username of the Salesforce account."
	SfPassword = "MyPassword"                         //Password of the Salesforce account.
	SfToken    = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"            //Security token, could be omitted if Trusted IP is configured.
)

func CreateClient() *simpleforce.Client {
	client := simpleforce.NewClient(SfURL, simpleforce.DefaultClientID, simpleforce.DefaultAPIVersion)
	if client == nil {
		// handle the error
		fmt.Println("Unable to create client.")
		return nil
	}

	err := client.LoginPassword(SfUser, SfPassword, SfToken)
	if err != nil {
		// handle the error
		fmt.Println("Unable to log in.")
		fmt.Println(err)
		return nil
	} else {
		fmt.Println("SF logged in!")
	}
	// Do some other stuff with the client instance if needed.

	return client
}


2 - Function to query Salesforce. I pass in the query from my last blog post, "Select Project__r.Name, Geographic_Area__r.Country_Code__c from Project_Geographic_Area__c"

//Query Salesforce using the passed in SOQL script
func GetByS(strQ string) {
	client := CreateClient()
	result, err := client.Query(strQ) // Note: for Tooling API, use client.Tooling().Query(q)
	if err != nil {
		// handle the error
		fmt.Println(err)
		return
	}

	for _, record := range result.Records {
		// access the record as SObjects.
		fmt.Println(record)
		//Example 1
		ifvP := record.InterfaceField("Project__r") //get the interface
		strP := ifvP.(map[string]interface{})["Name"] //get the string
		fmt.Println("Project:", strP)
		//Eample 2
		strC := record.InterfaceField("Geographic_Area__r").(map[string]interface{})["Country_Code__c"] //get the string from the interface
		fmt.Println("Country", strC)
	}
}


Salesforce - SOQL query for values from relate objects

Unlike TSQL, SOQL does not use joins on related tables (objects). Instead, the related object is referenced directly in the query by replacing the 'c' at the end of the custom object name with 'r'. In the following example I have three custom objects, Project_Geographic_Area__c, Project__c, and Geographic_Area__c. The Project_Geographic_Area__c has a foreign key field, Project__c, to the Project__c table, and a foreign key field, Geographic_Area__c, to the Geographic_Area__c table. I want to query Salesforce for the Name field from the Project__c table and the Country__Code__c field from the Geographic_Area__c table. So, replacing the ‘c’ with an ‘r’ in the names of our related tables and appending the field names, the resulting query is “Select Project__r.Name, Geographic_Area__r.Country_Code__c from Project_Geographic_Area__c.”