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.

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.