Application
Represent a Wisej application session. Provides methods and events to manage the application in the context of the current session
The Application class exposes to the application everything it needs to interact with the session, the user's browser, and all system events. It is a static class but all the properties, methods, and events are isolated by session.
You can use it to:
  • Save custom data in the Application.Session object.
  • Read the server variables in the Application.ServerVariables collection.
  • Read the Default.json configuration in the Application.Configuration property.
  • Handle application's exceptions using the Application.ThreadException event.
  • Handle the session disposal using the Application.ApplicationExit event.
  • Manage session expiration with the Application.SessionTimeout event.
  • Detect changes in the client device profile using the Application.ResponsiveProfileChanged, see Responsive Properties.
  • Access the logged-in user through the Application.User and Application.UserIdentity properties.
  • Read the current Application.Url and the Application.StartupUrl to extract the arguments, or use Application.QueryString for the collection of the argument name and values in the URL.
  • Download files to the browser with Application.Download() or open them in the browser using Application.DownloadAndOpen().
  • Change the culture programmatically by setting the Application.CurrentCulture property.
  • Read the current theme using the Application.Theme property.
  • Manage the browser's cookies using Application.Cookies or Application.Browser.CookieStorage. See Cookies for more details.

Session Object

Application.Session is a dynamic object that can store any kind of object. You can use it as if it was a regular object like this:
C#
VB.NET
1
// save something in the session
2
Application.Session.MyName = "Wisej";
3
Application.Session.MyComplexDataObject = new TestApp.Data.EmployeesList();
4
5
// retrieve session variables.
6
string name = Application.Session.MyName;
7
TestApp.Data.EmployeesList data = Application.Session.MyComplexDataObject
Copied!
1
Option Strict Off
2
3
' save something in the session
4
Application.Session.MyName = "Wisej"
5
Application.Session.MyComplexDataObject = New TestApp.Data.EmployeesList()
6
7
' retrieve session variables.
8
Dim name = As String = Application.Session.MyName
9
Dim data As TestApp.Data.EmployeesList = Application.Session.MyComplexDataObject
Copied!
Notice that since Application.Session is a dynamic object you can just add any field. You are just limited by the name since it must be compilable. If you want to use a variable name with dots, dashes, or any non-compilable character, use it through the indexer:
C#
VB.NET
1
Application.Session.value = "Hello";
2
Application.Session["[email protected]"] = 12
3
string value = Application.Session["value"];
Copied!
1
Option Strict Off
2
3
Application.Session.value = "Hello"
4
Application.Session("[email protected]") = 12
5
Dim value as String = Application.Session("value")
Copied!
Option Strict Off
In VB.NET in order to use dynamic fields, you must have Option Strict Off. Otherwise, always use the Session with the (name) indexer.

Server Variables

All the server variables that are supported by the Web server are available in Application.ServerVariables. Some well known and common server variables are also available as properties of the Application class:
  • UserAgent is "HTTP_USER_AGENT"
  • UserHostAddress is "REMOTE_ADDR"
  • UserHostName is "REMOTE_HOST"
  • UserLanguages is "HTTP_ACCEPT_LANGUAGE" split by a comma
  • ServerName is "SERVER_NAME"
  • ServerPort is "SERVER_PORT" parsed into an integer
Different web servers add different server variables. Don't expect all the server variables to be always present.

Application Events

There are many global events exposed by the Application class. They let your code receive all sorts of notifications from the Wisej infrastructure.

Exception Handling

In addition to the regular exception handling that you have in your code, Wisej lets you handle any unhandled exception through the Application.ThreadException event.
Exceptions are suppressed simply by handling the Application.ThreadException event. Once you attach a handler, it is up to your code to log, show, do nothing, or rethrow the exception.

Session Events

There are three events that are relevant to the session management system in Wisej:
Name
Description
ApplicationStart
Fired after the application is started, after the Program.Main() method is executed. It is fired only once for each new session.
ApplicationExit
Fired when the session is expired and is being disposed. At this point, the session is not recoverable. This is similar to a desktop application being closed.
SessionTimeout
Fired when the session is about to time out due to user inactivity. You can suppress the default behavior setting e.Handled = true. Otherwise, Wisej will show the built-in SessionTimeoutForm.

Threading

Use Application.ThreadBegin and Application.ThreadEnd to receive a notification every time Wisej starts a new thread processing code in your application, including Application.StartTask(). This event can be used to clear or initialize thread static variables using the advanced coding pattern below:
C#
1
// Reset the thread static.
2
Application.ThreadBegin += (s, e) =>
3
{
4
_test = null;
5
};
6
Application.ThreadEnd += (s, e) =>
7
{
8
_test = null;
9
};
10
11
// Session-static variable.
12
public static String Test
13
{
14
get
15
{
16
if (_test == null)
17
_test = Application.Session.test;
18
19
return _test;
20
}
21
set
22
{
23
value = value ?? string.Empty;
24
_test = value;
25
Application.Session.test = value;
26
}
27
}
28
29
[ThreadStatic]
30
private static string _test;
Copied!
The code above shows a static property that is backed by a [ThreadStatic] field. When the field is null, it is initialized from the value stored in the application's session object. When it's not null, it is returned immediately. This pattern allows the creation of very fast session statics that only access the session lookup object once.

Idle

Use the Application.Idle event to execute code after the current request is executed, and all the events have been dispatched but before the response is sent to the client.
You can achieve the same using the Application.Post() method (similar to Control.Invoke) to register a code block that will be executed at the end of the current request.

Event Filter

Wisej is indeed magic
With Application.AddEventFilter(filter) you can inject an object into the Wisej event pipeline and pre-process all the events that coming from the browser for all the controls in the application.
With Application.AddEventFilter(filter) you can inject add an object into the Wisej event pipeline and pre-process all the events that are coming from the browser for all the controls in the application.
All you need to do is implement the Wisej.Core.IEventFilter single method PreFilterEvent(e). You may also implement that IEventFilter interface in a control class and register a specific control as an event filter.
C#
VB.NET
1
// register an event filter
2
Application.AddEventFilter(new MyEventFilter());
3
4
// event filter class
5
class MyEventFilter : IEventFilter
6
{
7
public bool PreFilterEvent(WisejEventArgs e)
8
{
9
var name = e.Type;
10
var control = e.Target as Control;
11
12
// block all KeyDown events to all TextBox controls.
13
if (name == "keydown" && control is TextBox)
14
return true;
15
16
// let the default dispatching work
17
return false;
18
}
19
}
Copied!
1
'' register an event filter
2
Application.AddEventFilter(New MyEventFilter())
3
4
'' event filter class
5
Class MyEventFilter
6
Implements Wisej.Core.IEventFilter
7
8
Public Function PreFilterEvent(e As WisejEventArgs) As Boolean Implements IEventFilter.PreFilterEvent
9
10
Dim name As String = e.Type
11
Dim control As Control = e.Target
12
13
If name = "keydown" And TypeOf control Is TextBox Then
14
Return True
15
End If
16
17
Return False
18
19
End Function
20
21
End Class
Copied!
Return true to indicate that your code has handled the event and to stop Wisej from dispatching it any further, or return false to let Wisej continue dispatching the event.
Event filters are invoked in the same order they are added.

Cookies

There are two cookies objects in Wisej:
  1. 1.
    Application.Cookies is a collection of Cookie objects.
  2. 2.
    Application.Browser.CookieStorage connects the application to the browser's cookies.
You can read the cookies from the browser either using the Application.Cookies collection or directly through the CookieStorage. The Application.Cookies collection is populated when the application starts up. It receives all the cookies that are available on the browser.
Adding, changing, deleting, reading cookies is all done using the Application.Cookies collection:
C#
VB.NET
1
// save a cookie
2
Application.Cookies.Add("another.cookie", "Wisej");
3
4
// read a cookie
5
var value = Application.Cookies["my-cookie"];
Copied!
1
'' save a cookie
2
Application.Cookies.Add("another.cookie", "Wisej")
3
4
'' read a cookie
5
Dim value as String = Application.Cookies("my-cookie")
Copied!
Remember that when using the Cookies collection cookies are loaded from the browser only once when the application is loaded (or refreshed) and updated back in the browser only after the request is completed. Adding a cookie to the collection doesn't save it to the browser until the current execution is completed.
As an alternative, you can use the Application.Browser.CookieStorage object. It's not a collection and it doesn't contain any cookie information. It's a connection to the browser's storage and lets you read and write cookies directly from/to the browser:
C#
VB.NET
1
// request the value of a cookie and receive it in a callback
2
Application.Browser.CookieStorage.GetValue<string>("my-cookie", (value) => {
3
4
// do something with the string value
5
6
});
7
8
// read the value of a cookie and await for it
9
var value = await Application.Browser.CookieStorage<string>("my-cookie");
Copied!
1
'' request the value of a cookie and receive it in a callback
2
Application.Browser.CookieStorage.GetValue(Of String)("my-cookie",
3
Sub(value)
4
'' do something with the string value
5
End Sub)
6
7
' read the value of a cookie and await for it
8
Dim value As String = Await Application.Browser.CookieStorage.GetValueAsync(Of String)("my-cookie")
Copied!

Browser Object

Consider the Application.Browser object as a representation of the individual user's browser window through the Wisej.Core.ClientBrowser class. Wisej initializes and updates the object with all sorts of information regarding the user's browser:
  • Device is a string that identifies the device type: "Mobile", "Tablet" or "Desktop".
  • CultureInfo is the primary culture defined in the browser matched to a CultureInfo instance
  • Type is a string that identifies the browser type.
  • ScreenSize is the size of the user's device screen.
  • Size instead is the size of the browser window.
Refer to the API documentation for the full list of properties.

Features

The Browser.Feature object is a dynamic object that defines the features that are supported by the browser. It's an ever changing list that depends on the browser and the features that Wisej detects at startup. Currently, it is implemented like this:
JavaScript
1
features: {
2
worker: ("Worker" in window),
3
webSocket: ("WebSocket" in window),
4
arrayBuffer: ("ArrayBuffer" in window),
5
notification: ("Notification" in window),
6
geolocation: ("geolocation" in navigator),
7
serviceWorker: ("serviceWorker" in navigator),
8
speechSynthesis: (window.speechSynthesis) != null,
9
fullScreen: this.platform.isFullScreenSupported(),
10
browserStorage: this.platform.isBrowserStorageSupported(),
11
speechRecognition: (window.speechRecognition || window.webkitSpeechRecognition || window.mozSpeechRecognition) != null
12
}
Copied!
To test if a browser supports a specific feature, simply check the field name: i.e. Application.Browser.Features.speechRecognition == true.

UserData

Browser.UserData is also a dynamic object that is populated by Wisej at startup. It allows a web application to save and send custom data to the Wisej application before it is loaded. It is mostly useful to process a POST request, and OAuth2 and other Single Sign On (SSO) systems.
For example, if another system redirects the user to your Wisej web application using a POST request because it is also sending some data, you cannot receive the POSTed data in Program.Main() because the Wisej application is started in an Ajax request.
In cases like this, change your Default.html page into a Default.aspx page (don't forget to change it also in Default.json), read the POSTed data in the code behind and save it to a JavaScript variable named Wisej.userData.
ASP.NET (C#)
1
<% @Page Language="C#" %>
2
3
<!DOCTYPE html>
4
5
<html>
6
<head>
7
<title>Wisej.ReceivePostData</title>
8
<meta charset="utf-8" />
9
<meta http-equiv="X-UA-Compatible" content="IE=Edge;IE=11" />
10
<script src="wisej.wx"></script>
11
</head>
12
<body>
13
14
<script>
15
<%
16
var name = Request.Form["Name"];
17
var lastname = Request.Form["LastName"];
18
%>
19
Wisej.userData = {
20
name: "<%=name%>",
21
lastName: "<%=lastname%>"
22
};
23
</script>
24
25
</body>
26
</html>
Copied!
The sample startup page above receives "Name" and "LastName" from a POST request, saves them into a JavaScript object and saves the object in Wisej.userData. It will be available to the Wisej application as a dynamic object in Application.Browser.UserData.

Browser Storage

Access the browser's storage system using the Application.Brower object. All the storages have the same methods and work exactly the same. You can read, write, and enumerate the values either using a callback or the async/await pattern. All methods are asynchronous because they all interact with the browser directly.
There are three storages supported:
Storage
Description
The stored data is saved across browser sessions.
The stored data is cleared when the page session ends. A page session lasts as long as the browser is open, and survives over page reloads and restores.
Cookies are saved with the browser and are cleared depending on their expiration, scope, etc.

Favicon & Title

Wisej projects already include a default favicon.ico file at the root. That is the icon that the browser shows on the tab page and in the page's overview. However, being a file, once you create it it's difficult to change dynamically.
The Application class allows your application to change both, the favicon and the title of the page, dynamically at any time through these properties:
  • Application.FavIcon. Changes the favicon using an Image object.
  • Application.FavIconSource. Changes the favicon using a source string: a URL, embedded resource, or theme icon.
  • Application.Title. Changes the title of the application in the browser.

Printing

You can print (print preview in the browser and then print), any page, window, dialog, or specific control. it's quite easy, simply use Application.Print() or Application.Print(control).
The first will print the entire surface of the browser.
Full print. Includes the main page and any floating window.
The second allows you to specify a control to isolate and print. You can indicate a window or just a data grid, an image, a panel, etc...
Isolated control print.

Download

The Application class also allows your application to download a file to the users browser, or to download & open a file in the browser in any tab. There are two overloaded methods:
  • Application.Download(). Takes a file, a stream, or an image and an optional filename to send to the browser.
  • Application.DownloadAndOpen(). Takes the same arguments as Download() plus a string indicating the name of the target tab where the browser should open the file after downloading it.

Sounds

Play sounds on the user's browser using the Application.Play() method and overloads:
  • Application.Play(MessageBoxIcon). Plays a predefined sound that matches the MessageBoxIcon value.
  • Application.Play(url). Plays the sound in the specified .wav file. It can also be a data URL.
The Beep() VB.NET extension uses Application.Play() with a predefined base64 URL.

JavaScript

Use Application.Eval() and Application.Call(), or Application.EvalAsync() and Application.CallAsync() to invoke JavaScript code or functions in the global context.
See also:

JavaScript Loading

Application.LoadPackages() and Application.LoadPackagesAsync() loads a list of .js or .css files in the order they are passed to the method and in sequence. Each file is loaded only after the previous is loaded, allowing the loading of dependencies.
Each entry has the following properties:
  • Name. Unique name of the .js or .css file to load. It's used to cache the file on the client and loads it only once even if Application.LoadPackages() is called multiple times, or if a Widget class loads the same file.
  • Source. Is the URL from where to load the file.
  • Integrity. Is the optional hash code used to verify that the file hasn't been tampered with. See https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script.
LoadPackages() takes a callback method as the last optional argument with a boolean result parameter. Wisej calls this method passing true when all the packages have been loaded successfully, or false if any package fails to load.
LoadPackagesAsync() is the same as LoadPackages() but instead of using a callback to notify the application, it's an awaitable method.
C#
VB.NET
1
Application.LoadPackages(new[] {
2
3
new Widget.Package(){
4
Name="jquery",
5
Source = "https://code.jquery.com/jquery-3.5.1.min.js",
6
Integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0="
7
}
8
}, (result) => {
9
10
// result is true if all the packages have been
11
// loaded successfully,
12
13
});
Copied!
1
Application.LoadPackages({
2
New Widget.Package With {
3
.Name = "jquery",
4
.Source = "https://code.jquery.com/jquery-3.5.1.min.js",
5
.Integrity = "sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0="
6
}
7
}, Sub(result)
8
9
' result Is true if all the packages have been
10
' loaded successfully,
11
12
End Sub
13
)
Copied!
Last modified 8d ago