Our collection of our articles about Programming examples

Programming examples

The top 25 Basic SQL Commands used in the MS-SQl Server T-SQL Language
The top 25 Basic SQL Commands used in the MS-SQl Server T-SQL Language Friday, April 7, 2023
By: Lisa Chen, UX/UI Designer
The top 25 Basic SQL Commands used in the MS-SQl Server T-SQL Language

SELECT - retrieves data from one or more tables.

INSERT - inserts new data into a table.

UPDATE - updates existing data in a table.

DELETE - deletes data from a table.

CREATE TABLE - creates a new table.

ALTER TABLE - modifies the structure of a table.

DROP TABLE - deletes a table.

CREATE VIEW - creates a virtual table that is based on the result set of a SELECT statement.

ALTER VIEW - modifies the definition of a view.

DROP VIEW - deletes a view.

CREATE INDEX - creates an index on one or more columns of a table.

DROP INDEX - deletes an index from a table.

CREATE PROCEDURE - creates a stored procedure.

ALTER PROCEDURE - modifies the definition of a stored procedure.

DROP PROCEDURE - deletes a stored procedure.

CREATE FUNCTION - creates a user-defined function.

ALTER FUNCTION - modifies the definition of a user-defined function.

DROP FUNCTION - deletes a user-defined function.

CREATE TRIGGER - creates a trigger that automatically executes in response to certain events.

ALTER TRIGGER - modifies the definition of a trigger.

DROP TRIGGER - deletes a trigger.

BEGIN TRANSACTION - starts a transaction.

COMMIT TRANSACTION - commits a transaction.

ROLLBACK TRANSACTION - rolls back a transaction.

SET - sets the value of a variable or configuration option.

How to connect to Word Online in VB.NET using the Microsoft Graph API and the Microsoft Authentication Library (MSAL)
How to connect to Word Online in VB.NET using the Microsoft Graph API and the Microsoft Authentication Library (MSAL) Wednesday, May 17, 2023
By: Karen Fischer, Office Support and documentation
How to connect to Word Online in VB.NET using the Microsoft Graph API and the Microsoft Authentication Library (MSAL)

First, make sure you have the following NuGet packages installed in your project:

Microsoft.Graph
Microsoft.Identity.Client
Then, you can use the following code to connect to Word Online:

Imports Microsoft.Graph

Imports Microsoft.Identity.Client


Module Module1


    Sub Main()


        ' Set the Graph API endpoint for Word Online

        Const wordOnlineEndpoint As String = "https://graph.microsoft.com/v1.0/me/drive/root:/Documents"


        ' Set the Azure AD app registration information

        Const appId As String = "<Your app ID goes here>"

        Const redirectUri As String = "http://localhost"

        Const tenantId As String = "<Your tenant ID goes here>"


        ' Create a PublicClientApplication object with the app registration information

        Dim pca As New PublicClientApplication(appId, $"https://login.microsoftonline.com/{tenantId}")


        ' Create a new GraphServiceClient object with an authentication provider that uses MSAL to get an access token

        Dim graphClient As New GraphServiceClient(New DelegateAuthenticationProvider(

            Async Function(requestMessage)

                Dim result = Await pca.AcquireTokenInteractive({"Files.ReadWrite"}) _

                    .ExecuteAsync()


                requestMessage.Headers.Authorization =

                    New System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", result.AccessToken)

            End Function))


        ' Get the list of files in the user's Word Online root folder

        Dim files = Await graphClient.Me.Drive.Root.ItemWithPath("Documents").Children.Request().GetAsync()


        ' Print the name of each file

        For Each file In files

            Console.WriteLine(file.Name)

        Next


    End Sub


End Module
In this example, we're using the GraphServiceClient class from the Microsoft.Graph namespace to make requests to the Microsoft Graph API. We're also using the PublicClientApplication class from the Microsoft.Identity.Client namespace to authenticate the user and get an access token for the API.
To use this code in your own application, you'll need to replace the appId and tenantId constants with your own Azure AD app registration information, and you may need to modify the wordOnlineEndpoint constant to point to a different location in the user's OneDrive for Business.

Connecting to the GARDENA Smart System with REST and JSON in ASP.NET
Connecting to the GARDENA Smart System with REST and JSON in ASP.NET Friday, July 7, 2023
By: Jeff Barley, Head of Development
Connecting to the GARDENA Smart System with REST and JSON in ASP.NET

The GARDENA Smart System, developed by Husqvarna Group, provides innovative solutions for managing and controlling your garden and outdoor devices. To integrate and interact with the GARDENA Smart System, developers can leverage the Husqvarna Group's Open API, which offers a convenient way to access and control various smart devices using RESTful web services and JSON data format.

In this guide, we will show ypou how to connect to the GARDENA smart system using ASP.NET, a popular framework for building web applications. By utilizing the power of RESTful APIs and JSON, we can seamlessly communicate with GARDENA devices, retrieve information, and perform actions remotely.

What to do first:

Obtaining API credentials (client ID and client secret) at

https://developer.husqvarnagroup.cloud/

Implementing the authentication flow to obtain an access token.

Now you can:

Retrieving a list of available devices and their properties.

Controlling device states, such as turning on/off or adjusting settings.

Monitoring device status and retrieving real-time data.

Handling JSON Data:

Parsing JSON responses from the GARDENA API.

Serializing JSON data to send requests and update device settings.

Posible Common Use Cases:

Creating schedules for automated device operations.

Managing device groups and zones for efficient control.

Handling events and notifications from the GARDENA system.

Note: Before starting the implementation, make sure to register as a developer and obtain API credentials from the Husqvarna Group's developer portal. Familiarity with ASP.NET, RESTful APIs, and JSON will be helpful throughout the development process.

 

 Private Sub doAuth2()


        Dim clientId As String = "xxxxxx-xxx-xxxx-xxxx-xx"

        Dim clientSecret As String = "xxxxx-xxxx-xxxx-xxxx-xxxxxxxxxx"

        Dim accessToken As String = GetAccessToken(clientId, clientSecret)

        Dim LocationID As String = "xxxxxxx-xxxx-xxxx-xxx-xxxxxxxx"


        Response.Write(accessToken)

        Response.Write(GetLanMoverList(accessToken, clientId))

        Response.Write(GetLocations(accessToken, LocationID, clientId))

        'End If

    End Sub


    Private Function GetAccessToken(clientId As String, clientSecret As String) As String

        Dim tokenEndpoint As String = "https://api.authentication.husqvarnagroup.dev/v1/oauth2/token"



        Dim redirectUri As String = "https://localhost:44306/"


        Dim request As HttpWebRequest = CType(WebRequest.Create(tokenEndpoint), HttpWebRequest)

        request.Method = "POST"

        Dim postData As String = String.Format("grant_type=client_credentials&client_id={0}&client_secret={1}&redirect_uri={2}", clientId, clientSecret, redirectUri)

        Dim byteArray As Byte() = Encoding.UTF8.GetBytes(postData)

        request.ContentType = "application/x-www-form-urlencoded"

        request.ContentLength = byteArray.Length



        Dim dataStream As Stream = request.GetRequestStream()

        dataStream.Write(byteArray, 0, byteArray.Length)

        dataStream.Close()


        Dim response As WebResponse = request.GetResponse()

        dataStream = response.GetResponseStream()

        Dim reader As New StreamReader(dataStream)

        Dim responseFromServer As String = reader.ReadToEnd()


        Dim serializer As New JavaScriptSerializer()

        Dim tokenData As Dictionary(Of String, Object) = serializer.Deserialize(Of Dictionary(Of String, Object))(responseFromServer)


        If tokenData.ContainsKey("access_token") Then

            Return tokenData("access_token").ToString()

        Else

            Return ""

        End If

    End Function

    Private Function GetLanMoverList(Token As String, clientId As String) As String


        Dim tokenEndpoint As String = "https://api.amc.husqvarna.dev/v1/mowers"

        Dim X_Api_Key As String = clientId

        Dim Token_var As String = "Bearer " + Token

        Dim Authorization_Provider As String = "husqvarna"


        Dim request As HttpWebRequest = CType(WebRequest.Create(tokenEndpoint), HttpWebRequest)

        request.Method = "GET"

        request.Headers.Add("Authorization", Token_var)

        request.Headers.Add("X-Api-Key", X_Api_Key)

        request.Headers.Add("Authorization-Provider", Authorization_Provider)



        Dim response As WebResponse = request.GetResponse()

        Dim dataStream As Stream = response.GetResponseStream()

        Dim reader As New StreamReader(dataStream)

        Dim responseFromServer As String = reader.ReadToEnd()


        reader.Close()

        dataStream.Close()

        response.Close()


        Return responseFromServer

    End Function

    Private Function GetLocations(Token As String, LocationID As String, clientid As String) As String


        Dim tokenEndpoint As String = "https://api.smart.gardena.dev/v1/locations" + "/" + LocationID

        Dim X_Api_Key As String = clientid

        Dim Token_var As String = "Bearer " + Token

        Dim Authorization_Provider As String = "husqvarna"


        Dim request As HttpWebRequest = CType(WebRequest.Create(tokenEndpoint), HttpWebRequest)

        request.Method = "GET"

        request.Headers.Add("Authorization", Token_var)

        request.Headers.Add("X-Api-Key", X_Api_Key)

        request.Headers.Add("Authorization-Provider", Authorization_Provider)



        Dim response As WebResponse = request.GetResponse()

        Dim dataStream As Stream = response.GetResponseStream()

        Dim reader As New StreamReader(dataStream)

        Dim responseFromServer As String = reader.ReadToEnd()


        reader.Close()

        dataStream.Close()

        response.Close()


        ' Parse the JSON string into a JsonDocument

        Dim jsonDocumentVar As JsonDocument = JsonDocument.Parse(responseFromServer)

        Dim locationIdVar As String = jsonDocumentVar.RootElement.GetProperty("data").GetProperty("id").GetString()

        Dim locationName As String = jsonDocumentVar.RootElement.GetProperty("data").GetProperty("attributes").GetProperty("name").GetString()


        Return responseFromServer

    End Function

Case insensitive replace on a string
Case insensitive replace on a string Tuesday, July 25, 2023
By: Lisa Chen, UX/UI Designer
Case insensitive replace on a string

I am confident that everyone is well acquainted with the replace function, a remarkable tool that effortlessly substitutes all instances of a given string with another string. However, it is worth noting that this function can also be employed to achieve the same outcome while disregarding the case sensitivity of the comparison string.

Dim mystring as string = "One Two Three"
mystring = replace(mystring,"two","TWO", 1,,CompareMethod.Text)

The aforementioned code effectively substitutes the occurrence of the term "Two" within the string with the uppercase variant "TWO", despite the fact that the string being compared is provided in lowercase format.

Example of how you can connect to the OpenAI API using VB.NET
Example of how you can connect to the OpenAI API using VB.NET Sunday, March 5, 2023
By: Michael Brown, Quality Assurance and Software Engineer
Example of how you can connect to the OpenAI API using VB.NETImports System.Net.Http

Imports System.Text.Json

Public Class OpenAI_API_Client

    Private _apiKey As String

    Private _httpClient As HttpClient

    Private _baseUrl As String = "https://api.openai.com/v1"

    Public Sub New(apiKey As String)

        _apiKey = apiKey

        _httpClient = New HttpClient()

        _httpClient.DefaultRequestHeaders.Authorization = New System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", _apiKey)

    End Sub

    Public Async Function GetCompletion(prompt As String, model As String) As Task(Of String)

        Dim requestBody As New With {

            .prompt = prompt,

            .model = model,

            .max_tokens = 50,

            .temperature = 0.5,

            .n = 1,

            .stop = Nothing

        }

        Dim requestBodyJson = JsonSerializer.Serialize(requestBody)

        Dim response = Await _httpClient.PostAsync($"{_baseUrl}/completions", New StringContent(requestBodyJson, Encoding.UTF8, "application/json"))

        response.EnsureSuccessStatusCode()

        Dim responseBody = Await response.Content.ReadAsStringAsync()

        Dim responseObject = JsonSerializer.Deserialize(Of Object)(responseBody)

        Dim choices = responseObject("choices")(0)

        Return choices("text")

    End Function

End Class


To use this class, you can create an instance of the OpenAI_API_Client class with your API key and then call the GetCompletion method with the prompt and model name to generate text completion:

Dim client As New OpenAI_API_Client("<your-api-key>")

Dim prompt = "Once upon a time"

Dim model = "text-davinci-002"

Dim completion = Await client.GetCompletion(prompt, model)

Console.WriteLine(completion)

This example uses the System.Net.Http namespace to make HTTP requests to the OpenAI API and the System.Text.Json namespace to serialize and deserialize JSON data./div>

How you can connect to OneDrive using VB.NET
How you can connect to OneDrive using VB.NET Sunday, March 5, 2023
By: Tom Breen, Customer support and PM
How you can connect to OneDrive using VB.NETImports Microsoft.Identity.Client
Imports Microsoft.Graph
Imports Microsoft.Graph.Auth

Public Class OneDrive_Client
Private _graphClient As GraphServiceClient
Public Async Function AuthenticateAndConnect(clientId As String, tenantId As String, username As String, password As String, scopes As String()) As Task
Dim publicClientApp As IPublicClientApplication = PublicClientApplicationBuilder _
.Create(clientId) _
.WithAuthority(AzureCloudInstance.AzurePublic, tenantId) _
.Build()
Dim authProvider As UsernamePasswordProvider = New UsernamePasswordProvider(publicClientApp, scopes, username, password)
_graphClient = New GraphServiceClient(authProvider)
End Function

Public Async Function ListDriveItems() As Task(Of List(Of DriveItem))
Dim driveItems = Await _graphClient.Me.Drive.Root.Children.Request().GetAsync()
Return driveItems.ToList()
End Function
End Class

To use this class, you can create an instance of the OneDrive_Client class and call the AuthenticateAndConnect method with your client ID, tenant ID, username, password, and the desired scopes for the application. Then, you can call the ListDriveItems method to retrieve a list of DriveItems from your OneDrive:

Dim client As New OneDrive_Client()
Dim clientId = ""
Dim tenantId = ""
Dim username = ""
Dim password = ""
Dim scopes = {"https://graph.microsoft.com/.default"}
Await client.AuthenticateAndConnect(clientId, tenantId, username, password, scopes)
Dim driveItems = Await client.ListDriveItems()
For Each item In driveItems
Console.WriteLine(item.Name)
Next

This example uses the Microsoft Graph SDK to access the OneDrive API and the Microsoft Identity Client SDK to authenticate the user. You need to create a Microsoft Azure AD application and obtain a client ID and tenant ID to use this example.

Java script to get the weather from a free weather service
Java script to get the weather from a free weather service Monday, March 27, 2023
By: Jason Clarkson, Sales and customer Relations
Java script to get the weather from a free weather service

To get the weather from a free weather service in JavaScript, you can use the fetch API to make an HTTP request to the weather service's API endpoint and parse the JSON response. Here is an example code snippet:

const apiKey = 'your_api_key_here';
const city = 'your_city_here';
const apiUrl = `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}`;

fetch(apiUrl)
.then(response => response.json())
.then(data => {
const temperature = data.main.temp;
const description = data.weather[0].description;
console.log(`The temperature in ${city} is ${temperature} degrees Celsius with ${description}.`);
})
.catch(error => console.error(error));

In this example, we're using the OpenWeatherMap API, which requires an API key to use. Replace your_api_key_here with your actual API key. Also, replace your_city_here with the name of the city you want to get the weather for. The API returns the temperature in Kelvin, so we convert it to Celsius in the console output.

Javascript example how to use opemap on a web page
Javascript example how to use opemap on a web page Monday, March 27, 2023
By: Lisa Chen, UX/UI Designer
Javascript example how to use opemap on a web page

OpenLayers is a popular JavaScript library for displaying maps and integrating with OpenMap. Here's an example of how to use OpenLayers to display a map with OpenMap tiles on a web page:

// create a new map
const map = new ol.Map({
target: 'map',
layers: [
new ol.layer.Tile({
source: new ol.source.OSM()
})
],
view: new ol.View({
center: ol.proj.fromLonLat([0, 0]),
zoom: 2
})
});

In this example, we're using the latest version of OpenLayers from the OpenLayers CDN. We create a new map with a single layer consisting of OpenMap tiles using the ol.source.OSM() constructor. We set the initial view to be centered on coordinates [0, 0] and zoomed out to level 2.

You can customize the map by adding additional layers, markers, popups, and more using the OpenLayers API. Be sure to check the OpenLayers documentation for more information on how to use this library.