Translate

Monday, August 29, 2022

Golang - "no required module provides package" error

We all make simple mistakes every now and then. In my case, I missplelled a file name, so the file extension was not ".go". It took me some time to figure out because of the error message.

Tuesday, June 7, 2022

Math - My Collatz Conjecture Proof

While doing some math courses on Coursera, I came accross the Colatz conjecture and decided to give a try at the proof. I show that the Collatz function is equal to te function f(n) = 3n + b, where n is the number and b is the least significant bit (LSB).
Link to my proof.

Monday, May 23, 2022

jQuery - AJAX to change the value in an Input box

I made a form with two input boxes, one with an id of vaue2 and another with an id of value3. The value in the value3 input gets loaded with a value from the database when I tab from value2 to value3. This is the form:

<form action="{{.Page}}" name="form1" id="form1" method="POST" target="iframename" onsubmit="event.stopPropagation(); event.preventDefault();">
<table id="input4Form" style="vertical-align: middle;">
	<tr>
		<td></td><td colspan="4"><b>{{.Title}}</b></td>
	</tr>
	<tr>
		<td style="text-align: right;">{{.Label1}}</td>
		<td><input id="value1" type="text" name="value1" title="{{.In1_Title}}" maxlength="60" onkeydown="if (event.keyCode == 13) document.getElementById('input2search').click()"/></td>
		<td>  </td>
		<td style="text-align: right">{{.Label2}}</td>
		<td><input id="value2" type="text" name="value2" title="{{.In2_Title}}" maxlength="60" onkeydown="if (event.keyCode == 13) document.getElementById('input2search').click()"/></td>
		<td>  </td>
		<td style="text-align: right">{{.Label3}}</td>
		<td><input id="value3" type="text" name="value3" title="{{.In3_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>
<script type="text/javascript">
	document.getElementById('value2').addEventListener('keydown', getdefAD);
	document.getElementById('value1').focus();

	function getdefAD(val1){	
		if (val1.keyCode == 9) {
			$.post('erp/getDefaultValue?attr=' + $("input#value2").val() +'&id=' + $("input#value1").val(), function(data) {
			if (data) $("input#value3").val(data);
   		});	
		}
	}
</script>

This is the response handler to return a value from the database:

//Get default value for attribute
func getDefaultValue(w http.ResponseWriter, r *http.Request) {
	sA := "attr"
	sP := r.URL.Query().Get(sA)
	sA = "id"
	sI := r.URL.Query().Get(sA)
	if dataAccess.IsStringInSlice(sP, dataAccess.SlcAD_Default) {
		sR := dataAccess.GetERPADDefault(sP, sI)
		fmt.Fprintf(w, "%s", sR)
	} else {
		//sR = dataAccess.GetERPADDefault(sP, sI)
		//fmt.Fprintf(w, "%s", sR)
		// fmt.Println("Not found")
		return
	}
}

Saturday, May 7, 2022

Golang - Display Active Directory thumbnailPhoto attribute as HTML IMG

I'm working on an application to list all of the active directory attributes that are set for a user. The application uses "encoding/base64" and "github.com/go-ldap/ldap". To display the tumbnai imag, I used this HTML:

"<div style='width:400px;'><img src='data:image/jpg;base64," + b64.StdEncoding.EncodeToString(attrE.ByteValues[0]) + "'/></div>"

This is the code that iterates through all of the returned AD attributes and creates the HTML text:

var sHTML string
var sA []string
for _, entry := range strcAttrs.Entries {
	for _, attr := range entry.Attributes {
		sA = append(sA, attr.Name)
	}
}
sort.Strings(sA)
for _, attE := range sA {
	for _, entry := range strcAttrs.Entries {
		for _, attrE := range entry.Attributes {
			if attrE.Name == attE {
				if ldapAccess.IncSlcStdAttrs(attrE.Name) {
					sHTML = sHTML + "<span style='text-decoration: bold; background-color: green'>"
				} else {
					sHTML = sHTML + "<span style='text-decoration: bold;'>"
				}
				sHTML = sHTML + "attribute: " + attrE.Name + "</span><br />"
				var attr string = ""
				for _, attr = range attrE.Values {
					if ldapAccess.Include(attrE.Name) {
						if ldapAccess.IsDate64(attrE.Name) {
							sHTML = sHTML + "Date: " + ldapAccess.ConvertStringToDate64(attr)
						} else {
							if ldapAccess.IsDateZ(attrE.Name) {
								sHTML = sHTML + "Date: " + ldapAccess.ConvertStringToDateZ(attr)
							} else {
								sHTML = sHTML + attr
							}
						}
					} else {
						if (attrE.Name) == "thumbnailPhoto" {
							sHTML = sHTML + "<div style='width:400px;'><img src='data:image/jpg;base64," + b64.StdEncoding.EncodeToString(attrE.ByteValues[0]) + "'/></div>"
						} else {

							sHTML = sHTML + "Not Displayed"
						}
					}
					sHTML = sHTML + "<br/>"
				}
			}
		}
	}
	sHTML = sHTML + "<br/>"
}

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)
	}
}