Example 2: Basic Usage
This example file is broken up into 8 key functionalities that are subsequently called in the main method. Each sub-chapter is named after its respective method which aims to help navigating the example and this explanation.
1. Time Series Definition
Section titled “1. Time Series Definition”Defining time series is a key operation of the API. The following methods not only show how to create one, but also properly organize, read and write them. Most of these operations require to be called on an ITsm object as shown in example 1.
Iterating Over Repositories
Section titled “Iterating Over Repositories”To get a list of all available repositories, call the tsm.Repositories.Find() method. Keep in mind that to access data of the returned list, an await foreach() loop must be used as shown in the IteratingOverRepositories() method.
Creating a Time Series
Section titled “Creating a Time Series”The following objects are created to define the time series:
- name
- description
- function
- interval
Putting these parameters along with a boolean value that defines the Function and Cyclicality into the tsm.TimeSeries.Create() method creates a time series.
Saving a Time Series
Section titled “Saving a Time Series”To preserve the created time series, the repository that it’s supposed to be saved into must first be loaded using the tsm.Repositories.Load(String) method. In this example, the repository TSM_Example_Repository is used. In this example a unit store is also instantiated by calling GetUnitStore() on the repository.
Next, a new time series is created following the approach described earlier. The only difference is the inclusion of the unit parameter, which is initialized by invoking References.Create(unit) on the UnitStore object. To manage time series within a repository, it needs to be accessed by calling the time series store via GetTimeSeriesStore() from the ITsmRepository class. Finally, the saving process is completed by calling the Save() method on the time series store, passing in the newly created time series object as a parameter.
Finding and Iterating Over Time Series
Section titled “Finding and Iterating Over Time Series”To search for time series with partial or imprecise information, accessing the time series store is necessary once again. A SearchParameter object can be created using the SearchParameters.Create() method, which allows searching time series by any of their properties. In this example, time series are filtered by their description field.
To retrieve the matching results, the Find(ITimeSeriesSearchParameter) method should be called on the time series store, passing in the search parameter object. To access the actual time series from the returned references, calling Resolve().ConfigureAwait(false) and extracting the value is required. It’s important to use the await keyword with these method calls as demonstrated in the example, since they return asynchronous results.
Updating a Time Series
Section titled “Updating a Time Series”Updating an existing time series first requires creating or retrieving a time series object, following the same pattern described for creating a time series. This example demonstrates a complete update workflow by first creating a time series with a unique name, saving it to the repository, modifying it, and then persisting those changes.
The process begins with creating a time series in the same fashion as before. To modify it, the desired properties of the time series object should be updated directly. In this example, the description is changed to “New and improved”. To persist these changes to the repository, the SaveOrUpdate() method must be called on the time series store, passing in the time series reference. The SaveOrUpdate() method ensures that changes are properly synchronized with the repository.
Note that all repository operations are asynchronous, requiring the use of the await keyword when calling these methods.
Deleting a Time Series
Section titled “Deleting a Time Series”In this example a time series is created and accessed in the same way as before. It is then deleted by calling timeSeriesStore.Delete() with the exact time series name as a string parameter. In this case the name is directly extracted via timeSeries.Name.
2. Time Series Data
Section titled “2. Time Series Data”Another crucial functionality of this API is obviously the extraction and usage of data in a given time series. To achieve this, it is required to create and save time series, which was explained above and will be skipped entirely for the following chapters.
Creating Time Series Data
Section titled “Creating Time Series Data”The data object is instantiated as an ITimeSeriesDataCollection<T>, where T determines the type definition applied to every data point stored within the collection. To fill it, the method TimeSeriesData.CreateCollection<T> is invoked on the ITsm object.
It requires the following parameters:
- an interval (using
ITsmobject) - a boolean value flagging the data as cyclic
- a unit (using the unit store)
- a time zone (using
ITsmobject) - a list of data points (using
ITsmobject)
Individual data points are constructed by calling the TimeSeriesData.Create<T>() method on an ITsm object. Parameters of this method are:
- the point of time on which the value is placed of the C#
DateTimeOffsettype. - the value itself
- the flag of the value
The return value is an object of the type ITimeSeriesData<T> where T is the type of the data values. With that a list of data points can be created as such:
var datapoints = new List<ITimeSeriesData<double>>{ tsm.TimeSeriesData.Create<double>(start.AddHours(1), 7.0, Flag.Estimated()), tsm.TimeSeriesData.Create<double>(start.AddHours(1), 2.0, Flag.Valid()), tsm.TimeSeriesData.Create<double>(start.AddHours(2), 23.0, Flag.Missing()) // Additional datapoints};In case of the example data points are created using a streamed iteration from 0 to 100 but any list of ITimeSeriesData<T> works.
Writing Time Series Data
Section titled “Writing Time Series Data”To access a time series data store, the method GetTimeSeriesDataStore(), which takes a time series store as a parameter, must be invoked on the repository. By simply calling timeSeriesDataStore.Write(data), where data is a ITimeSeriesData<T> list as before the data is written to the time series.
Reading Time Series Data
Section titled “Reading Time Series Data”A ReadingOptions object of the timeSeriesDataStore is used to define the time span of the data that should be outputted. In case of the example, values from hour 10 to 20 after the starting point are included.
Placing the ReadingOptions as a parameter to the Read<T>() method of the time series data store will return an asynchronous list of the ITimeSeriesData type. The result must be awaited to access the individual data points.
3. Historization
Section titled “3. Historization”This chapter focuses solely on how to create and handle time series with historization enabled. For background on what historization is and what it is used for, see Audit and Historization.
Enabling and Reading Historization
Section titled “Enabling and Reading Historization”To create a time series object with historization and audit enabled these two additional parameters have to be set:
preserveHistoricData: true,preserveAuditLog: trueThe time series data is saved to a repository in exactly the same way as before. The point in time at which Write(data) was called is saved automatically. Any additional data inputs that cover the same time span do not overwrite existing data but are saved to another audit time stamp and can be accessed.
After the second dataset is saved to the time series a new parameter historicDateTime becomes relevant in the definition of a ReadingOptions object. It can take the form of a DateTimeOffsetAtOrBefore type and its defined by the method Create(DateTimeOffset, boolean). The parameters the audition date and whether or not it is exact. In the example a point in time just after the Write() operation is saved and used to read the first iteration of the data.
To view the currently valid data values it is not even necessary to add a historicDateTime parameter and the time series can be treated as though it does not have historization enabled.
4. Quotation
Section titled “4. Quotation”Quotation works in much the same way as historization. See Quotations for more on what quotations are and what they are used for.
Enabling and Reading Quotation
Section titled “Enabling and Reading Quotation”Once more the time series is created using a new parameter to enable quotation:
quotation: trueBy its nature, the time stamp associated with the quotation time series is not saved automatically and must be defined separately. This is done by first creating a new date of the DateTimeOffset() type which is then used as a parameter in the WritingOptions.CreateQuotationOptions() method of the ITimeSeriesData class. Saving the data to a time series once again requires calling the Write() method of the time series data store, but in this case with two parameters, the first of which is the just defined WritingOptions object and the data field comes second.
The DateTimeOffsetAtOrBefore object is parameterized by a date of the DateTimeOffset type and a boolean which flags whether or not it is exact.
The ReadingOption can now once again be inserted into the Read<T> method to receive an asynchronous list of data points.
5. Units
Section titled “5. Units”Unit operation require access to the unit store class. This is simply achieved by calling GetUnitStore() on a repository.
Saving a New Unit
Section titled “Saving a New Unit”A new unit object is instantiated using Units.Create() on an ITsm instance and passing a symbol (string) and an Interval Transformation as parameters. To check whether or not a unit already exists the method TryLoad(String symbol) is awaited. If not, the unit is saved by invoking Save(unit) on the unit store.
Finding Units
Section titled “Finding Units”A list of unit references can be created by calling Find() on the unit store. To gain access to the actual value of the unit, two steps need to be taken as shown in the example:
var resolvedUnitReferenceResult = (await unitReference.TryResolve().ConfigureAwait(false));if (!resolvedUnitReferenceResult.GetValueOrError(out var resolvedUnitReference, out var resolvedUnitReferenceError)) throw resolvedUnitReferenceError; // Handle Errorvar unit = resolvedUnitReference.Value;The TryResolve() method returns a result object to the given unit reference. A resolved unit reference can then be extracted out of the result by calling GetValueOrError(). This function takes two out-parameters as inputs, one of which will be assigned a value and the other null, depending on whether or not the dereferencing was successful or not.
This two-step process (dereferencing followed by result extraction) gives users more flexibility in handling errors.
The same result can be achieved like this, which does not give the user a way of accessing the resolved unit reference error:
var resolvedUnit = await unitReference.Resolve().ConfigureAwait(false);var unit = resolvedUnit.Value;Loading a Unit
Section titled “Loading a Unit”The demonstrated method TryLoad() in the unit store searches for a unit with the exact symbol passed as a parameter. This returns a single object that can be dereferenced and extracted in the same way as before.
Deleting a Unit
Section titled “Deleting a Unit”Deleting is achieved by calling Delete() on the unit store, passing the exact symbol of the Unit as a parameter.
6. Constant Unit Conversions
Section titled “6. Constant Unit Conversions”See Units and Conversions for more about constant unit conversions.
Saving a New Constant Unit Conversion
Section titled “Saving a New Constant Unit Conversion”At first three new units are created using the method described earlier. A new unit conversion can be constructed by invoking ConstantUnitConversions.Create() on the ITsm object. The parameters used in the first example are:
- The unit that should be converted
- The unit that should be converted into
- The factor of conversion
This information is enough to perform this simple unit conversion. When converting from a rate unit to its cumulative equivalent, however, an integration interval is required. This is exemplified by the conversion from ampere (A) to ampere hours (Ah). The integrationInterval parameter of the type IInterval is created and set as shown in the example.
After gaining access to the unit conversion store a check is performed whether or not the unit conversion already exists by invoking TryLoad(). If a unit conversion with the same identifier already exists, the storage information of the original object is transferred to the new object so that the old one can be overwritten if necessary. This is then done by calling SaveOrUpdate() on the constant unit conversion store.
Find All Unit Conversions
Section titled “Find All Unit Conversions”To find all unit conversions in a repository the method Find() is called on the constant unit conversion store. The resulting list can once again be iterated through by an await foreach() loop.
Load a Constant Unit Conversion
Section titled “Load a Constant Unit Conversion”Much in the same way as loading a unit, the conversion has to be loaded by calling TryLoad(String identifier). Then it is tried to get the value of the returned Result object. If this is successful a reference to the conversion unit is returned. This reference can then in turn be dereferenced by using GetValueOrError() which, if successful, grants access to the attributes of the conversion.
Delete a Constant Unit Conversion
Section titled “Delete a Constant Unit Conversion”To delete a conversion the method Delete(String identifier) is simply called on the constant unit conversion store.
Reading Data with Constant Unit Conversions
Section titled “Reading Data with Constant Unit Conversions”To read a time series in a different unit than it was written, all that has to be done is to make sure a suitable conversion from the time series unit to the target unit exists and add the target unit as a parameter in the reading options object. The rest is exactly the same as reading a time series as described earlier.
7. Time-Dependent Unit Conversions
Section titled “7. Time-Dependent Unit Conversions”Firstly, two functions are called to create objects needed for the later operations. The first one creates a new time series, gives it the unit “USD/EUR” and assign data to it, which indicates the conversion between the two currencies at a given time. The second function simply creates and saves a time series that will later be converted.
Assigning a Conversion Time Series to a Time Series
Section titled “Assigning a Conversion Time Series to a Time Series”This is achieved by calling SaveAssignment() on the ITsm object, passing the two time series that were just created as parameters.
Saving a Conversion Time Series as Default Conversion Time Series
Section titled “Saving a Conversion Time Series as Default Conversion Time Series”In order to use a conversion time series without having to creating a new one each time explicitly calling it, a default conversion time series can be saved to the repository. To do this, the time dependent unit conversion store has to be accessed from the repository. Then, invoking the Save() method on it, the conversion time series is now saved to the repository for future use.
Finding Conversion Time Series Assigned to a Time Series
Section titled “Finding Conversion Time Series Assigned to a Time Series”To get a list of conversion time series that are explicitly assigned to a time series, the Find() method is called on the time dependent unit conversion store, passing the time series that has assigned conversions as a parameter.
Finding Default Conversion Time Series
Section titled “Finding Default Conversion Time Series”Essentially the same as finding the conversions to a time series, with the only difference that Find() is called without any parameters.
Finding All Conversion Time Series
Section titled “Finding All Conversion Time Series”This is the combination of the last two methods in the example. By calling FindAll() instead of Find(), again with a time series as a parameter, a list of conversions assigned to the passed time series and all default conversion time series is returned.
Deleting a Time Series from Default Conversion Time Series
Section titled “Deleting a Time Series from Default Conversion Time Series”To remove a conversion time series from the pool of default conversions, the method Delete(timeSeries) is called on the time dependent unit conversion store.
Unassigning a Conversion Time Series from a Time Series
Section titled “Unassigning a Conversion Time Series from a Time Series”Works the same way as assigning, but instead of SaveAssignment(), DeleteAssignment() is called on the ITsm object. Once again passing the conversion time series that should be unassigned and the affected time series as parameters.
Reading Data with Time Dependent Unit Conversions
Section titled “Reading Data with Time Dependent Unit Conversions”If a suitable conversion time series exists, data can be retrieved as usual but with the target unit added as a parameter in the definition of the readingOptions object.
8. Formulas
Section titled “8. Formulas”Performing and Reading a Calculation Without Storing the Results
Section titled “Performing and Reading a Calculation Without Storing the Results”By creating formula time series, calculations involving one or many time series can be performed and read. In order to avoid filling the database with calculations that are rarely used, so-called ad hoc formulas are used.
The formula text is turned into a formula object by calling Formulas.Create() on the ITsm object. Everything else is done through its Calculator property, which provides two factories:
CalculationOptions.Create()defines how the time series referenced inside the formula are read and harmonized. It takes a boolean flagging the data as cyclic, a function and an interval, and optionally an interval transformation, a unit, a time zone and a start of time.ReadingOptions.Create()defines the form in which the result is returned.
Both are passed to the Calculate<T>() method of the calculator, where T is the value type of the result:
var result = await tsm.Calculator.Calculate<double>( formula, calculationOptions, readingOptions, defaultRepositoryName: "TSM_Example_Repository");The defaultRepositoryName parameter names the repository used to resolve those references in the formula that do not specify one themselves.
The returned ITimeSeriesDataCollection<T> is iterated with an await foreach() loop. Neither the formula nor the result is written to the repository.