Recent Content
Filter IC Dimension by Entity Property
A common requirement for reporting is to be able to filter the IC dimension by some property that exists only on the original Entity members. This can be achieved with a custom Member List defined in a Finance business Rule. Select Case api.FunctionType ' MemberListHeaders support is optional but good practice Case Is = FinanceFunctionType.MemberListHeaders Dim mListHeaders As New List(Of MemberListHeader) ' add the name of your list: mListHeaders.Add(New MemberListHeader("withText1")) Return mListHeaders ' Here we do the real work Case Is = FinanceFunctionType.MemberList If args.MemberListArgs.MemberListName.XFEqualsIgnoreCase("withText1") Then ' this list of members will be populated later Dim ICs As New List(Of Member) ' amend parameters as necessary here Dim dimensionName as String = "CorpEntities" Dim memberFilter as String = "E#Root.Base.Where(Text1 <> '')" ' filter the Entity dimension by some criteria Dim entities As List(Of MemberInfo) = brapi.Finance.Members.GetMembersUsingFilter(si, _ brapi.Finance.Dim.GetDimPk(si, dimensionName), _ memberFilter, _ True) ' retrieve IC members corresponding to the selected Entity members ' and push them into output list For Each entityMInfo As MemberInfo In entities if entityMInfo.getEntityProperties().isIC then ICs.Add(brapi.Finance.Members.GetMember(si, dimtypeId.IC, entityMInfo.Member.Name)) end if Next ' wrap with the MemberList object and return Return New MemberList(New MemberListHeader("withText1"), ICs) This can then be referenced in CubeViews and elsewhere like this:Aggregating a tagged set of accounts (e.g. Balance Sheet only)
This is an example to obtain values for a Cash Flow formula for all accounts tagged with a certain Text1 field. For every Account tagged CF_AR (Cash Flow - Accounts Receivable) and evaluating the Flow member Activity Calc, if the Activity Calc and the Account Tag in UD1 match, the number is added to the data buffer. Values are then sign-flipped by multiplying them by -1. There are two main approaches, depending on the version you're working with. For releases 6.0 and later, we can leverage GetDataBufferUsingFormula to produce performant code that is easy to read. For older releases, we have to use a more complex approach via the Eval function. GetDataBufferUsingFormula - v6.0 and above ' retrieve the account ID once, outside the loop, to avoid multiple lookups Dim cfArId as Integer = api.Members.GetMemberId(DimType.Account.Id, "CF_AR") ' create the result buffer Dim targetBuf As New DataBuffer() ' retrieve source data, limited to tagged accounts with a complex filter Dim sourceBuf As DataBuffer = api.Data.GetDataBufferUsingFormula( _ "RemoveNoData(FilterMembers(F#ActivityCalc, [A#BalanceSheet.Base.Where(Text1 = CF_AR)]))") ' loop through each cell For Each cell As DataBufferCell In sourceBuf.DataBufferCells.Values ' copy cell into new one, so we can safely tweak it Dim newCell As New DataBufferCell(cell) ' change the account newCell.DataBufferCellPk.AccountId = cfArId ' Stuff cell into target buffer. ' The last parameter ensures multiple values are summed up, ' rather than replacing each other targetBuf.SetCell(si, newCell, True) Next ' assign target buffer to a variable we can reference in Calculate api.Data.FormulaVariables.SetDataBufferVariable("myBuf", targetBuf, False) ' actually save the buffer into the database, against the target destination, while flipping signs. api.Data.Calculate("A#CF_AR:F#CF_Activity = $myBuf * -1") Note: this sample aims to strike a balance between code complexity, flexibility, and performance. More performant approaches are possible: you could modify the Flow ID also, and flip sign, inside the loop; then just saving results with api.Data.SetDataBuffer, rather than going through a Calculate call. That would be less flexible to integrate with other requirements though (e.g. performing other operations before saving, which can be easily done in Calculate but not with buffer objects). Eval - v.5.x and below Formula The Calculate call is straightforward. Notice the second parameter; that must be the name of our Helper Function. api.Data.Calculate("A#CF_AR:F#CF_Activity = EVAL(F#ActivityCalc) * -1", AddressOf onEvalDataBuffer) Helper Function This can be reused over and over, so it might be better placed in a shared Business Rule for ease of maintenance. Private Sub OnEvalDataBuffer(ByVal api As FinanceRulesApi, ByVal evalName As String, ByVal eventArgs As EvalDataBufferEventArgs) Dim cfAccountId As Integer = api.Members.GetMemberId(DimType.Account.Id, "CF_AR") Dim cfFlowId As Integer = api.Members.GetMemberId(DimType.Flow.Id, "CF_Activity") 'Retrieve the target accounts, and keep their IDs in a Dictionary Dim ms As String = "A#BalanceSheet.Base.Where(Text1 = CF_AR)" Dim members As List(Of MemberInfo) = _ api.Members.GetMembersUsingFilter( _ api.Pov.AccountDim.DimPk, ms, Nothing) Dim memberlookup As New Dictionary(Of Integer, Object) If Not members Is Nothing Then For Each memInfo As MemberInfo In members memberlookup.Add(memInfo.Member.MemberId, Nothing) Next End If 'Loop over cells that match our "TEXT1" account filter Dim resultCells As New Dictionary(Of DataBufferCellPk, DataBufferCell) For Each sourceCell As DataBufferCell In eventArgs.DataBuffer1.DataBufferCells.Values ' Ignore NoData cells and where the account is not tagged If(Not sourceCell.CellStatus.IsNoData) And _ memberLookup.ContainsKey(sourceCell.DataBufferCellPk.AccountId) Then ' We don't assign the original cell object to output buffer, ' but an edited copy Dim cashflowCell As New DataBufferCell(sourceCell) cashflowCell.DataBufferCellPk.AccountId = cfAccountId cashflowCell.DataBufferCellPk.FlowId = cfFlowId Dim existingCell As DataBufferCell = Nothing If resultCells.TryGetValue(cashflowCell.DataBufferCellPk, existingCell) Then 'Since there is already a cell in the dictionary, ' replace it with the aggregated amount. existingCell.CellAmount = existingCell.CellAmount + sourceCell.CellAmount Else 'Add this dataCell to the new dictionary. resultCells.Add(cashflowCell.DataBufferCellPk, cashflowCell) End If End If Next 'Assign the new list of DataCells to the result. eventArgs.DataBufferResult.DataBufferCells = resultCells End Sub2likes0CommentsDashboard: Open Dashboard File Resource
Open a Dashboard file resource and retrieve its raw contents. Note: This snippet is for OneStream 7.4 and above. Previous releases can use similar logic, just without the WorkspaceID machinery. ' *** parameters to customize to your needs ' Specify the name of the dashboard file we want to retrieve Dim fileResourceName As string = "FileName.txt" ' Specify the name of the Workspace containing it Dim workspaceName as String = "My Workspace" ' set this to True if your Dashboard is in the System pane Dim isSystemLevel as Boolean = False ' *** end parameters ' the following chunk will find the ID of the workspace containing the file Dim workspaceID = Guid.Empty If not workspaceName.XFEqualsIgnoreCase("Default") then Dim workspaceID as Guid = BRApi.Dashboards.Workspaces.GetWorkspaceIDFromName( _ si, isSystemLevel, workspaceName) end if ' Now we retrieve the FileResource object, representing our file Dim fileResource As DashboardFileResource = BRApi.Dashboards.FileResources.GetFileResource( _ si, isSystemLevel, workspaceID, fileResourceName) ' If the file contains text, you can retrieve it right away with the following line. ' NOTE: if it's some other type (zip, image, etc), you will need different handling. Dim fileContent As String = system.Text.Encoding.UTF8.GetString(fileResource.FileBytes)1like0CommentsFinance: Return on Capital Employed
This formula calculates a financial ratio that measures a company's profitability and the efficiency with which its capital is employed. The main financial logic in the formula is EBIT / (Total Assets - Total Liabilities) Return api.Data.GetDataCell( _ "Divide(A#[YourEBITAccount], A#[YourTotalAssetsAccount] - A#[YourTotalLiabilitiesAccount])")1like0CommentsFinance: Annualized Revenue
This Dynamic Calc formula calculates Annualized Revenue, by taking 3 months of Total Revenue, dividing it down to a monthly amount, then multiplying it by 12. ' "Prior Scenario" must be stored as Text1 property in current Scenario Dim priorScenario As String = api.Scenario.Text(1) Dim objTimeMemberSubComponents As TimeMemberSubComponents = BRApi.Finance.Time.GetSubComponentsFromName( _ si, api.Pov.Time.Name) Dim periodNum As String = "M" & objTimeMemberSubComponents.Month.ToString Select Case periodNum Case "M1" Return api.Data.GetDataCell( _ "((A#TOTREV:U1#Top:V#Periodic:I#Top" & _ $" + A#TOTREV:U1#Top:V#Periodic:I#Top:S#{priorScenario}:T#PovPrior1" & _ $" + A#TOTREV:U1#Top:V#Periodic:I#Top:S#{priorScenario}:T#PovPrior2)" & _ " / 3) * 12") Case "M2" Return api.Data.GetDataCell( _ "((A#TOTREV:U1#Top:V#Periodic:I#Top" & _ " + A#TOTREV:U1#Top:V#Periodic:I#Top:T#PovPrior1" & _ $" + A#TOTREV:U1#Top:V#Periodic:I#Top:S#{priorScenario}:T#PovPrior2)" & _ " / 3) * 12") Case Else Return api.Data.GetDataCell( _ "((A#TOTREV:U1#Top:V#Trailing3MonthTotal:I#Top / 3) * 12)") End Select0likes0CommentsDashboard: Get or Set Literal Parameter
Literal Parameters are, effectively, application-wide variables that can be used to drive Dashboards and Cube Views. Their values can be set or retrieved in code as shown below. From version 7.3 onwards, they are contained in a Workspace. That means that the relevant calls now require the ID of the Workspace where the Parameter is located. Note that the ID of Default Workspace is an empty Guid. Note: Literal Parameters are effectively shared between all users; which means that, if a Dashboard Action triggered by "User1" modifies a Literal Parameter value, "User2" will also receive the changed value in any Dashboards they are using (at the first refresh). OneStream Version 7.3+ Dim parameterName As String = "MyParameterName" ' if Parameter lives in Dashboards under "System" tab, set this to True Dim isSystemLevel as Boolean = False ' retrieve workspace ID. If it's Default Workspace, you can just use Guid.Empty instead Dim workspaceID As Guid = BRApi.Dashboards.Workspaces.GetWorkspaceIDFromName( _ si, isSystemLevel, workspaceName) ' --- Set literal parameter value Dim newValue As String = "New Literal Value" BRApi.Dashboards.Parameters.SetLiteralParameterValue( _ si, isSystemLevel, workspaceID, parameterName, newValue) ' --- Retrieve literal parameter value Dim pValue as String = BRApi.Dashboards.Parameters.GetLiteralParameterValue( _ si, isSystemLevel, workspaceID, parameterName) OneStream Version 7.2 and below Dim parameterName As String = "MyParameterName" ' if Parameter lives in Dashboards under "System" tab, set this to True Dim isSystemLevel as Boolean = False ' --- Set literal parameter value Dim newValue As String = "New Literal Value" BRApi.Dashboards.Parameters.SetLiteralParameterValue( _ si, isSystemLevel, parameterName, newValue) ' --- Retrieve literal parameter value Dim pValue as String = BRApi.Dashboards.Parameters.GetLiteralParameterValue( _ si, isSystemLevel, parameterName)0likes0CommentsExtender: Auto Update Member Property
This snippet will modify a Member property that can vary by Scenario Type and/or Time. Just pass the relevant ScenarioType ID or Time member ID to set it in a more specific way; it will then appear as a "Stored Item" in the interface. Note: SaveMemberInfo does not create entries in Audit tables, which means the Audit Metadata report will not contain anything related to this operation. For this reason, we do not recommend to use this snippet outside of implementation activities or in production environments. 'Get the MemberInfo object for the member you want to update, in this example an Account. Dim objMemberInfo As MemberInfo = BRApi.Finance.Members.GetMemberInfo( _ si, DimType.Account.Id, "<Member Name>", True) ' Retrieve member properties so we can modify them. Dim accountProperties As AccountVMProperties = objMemberInfo.GetAccountProperties() ' change the Account Type accountProperties.AccountType.SetStoredValue(AccountType.Revenue.Id) ' change default Text1 value ' if you want to set it for a specific ScenarioType and/or time, ' use the relevant values in the first 2 parameters accountProperties.Text1.SetStoredValue( _ ScenarioType.Unknown.Id, DimConstants.Unknown, "<UpdatedValue>") 'Save the member and its properties. Dim isNew As TriStateBool = TriStateBool.TrueValue BRApi.Finance.MemberAdmin.SaveMemberInfo(si, objMemberInfo, False, True, False, isNew)Extender: Rename a dimension
This snippet will rename a dimension. Note: RenameDim does not create entries in Audit tables, which means the Audit Metadata report will not contain anything related to this operation. For this reason, we do not recommend to use this snippet outside of implementation activities or in production environments. Note: renaming a dimension might break references in exported artefacts. Dim originalDim As String = "Original Dimension Name" '<-- Dimension name to be changed Dim updatedDim As String = "New Dimension Name" '<-- Updated Dimension name Dim objDimPk As DimPk = BRApi.Finance.Dim.GetDimPk(si, originalDim) BRApi.Finance.Dim.RenameDim(si, objDimPk, originalDim, updatedDim)0likes0CommentsExtender: Auto Create Member
This snippet will create a new Account member, including setting some properties that can vary by Scenario Type and/or Time. Note: SaveMemberInfo does not create entries in Audit tables, which means the Audit Metadata report will not contain anything related to this operation. For this reason, we do not recommend to use this snippet outside of implementation activities or in production environments. 'Create a new MemberInfo object with its child objects. Dim objMemberPk As New MemberPk(DimType.Account.Id, DimConstants.Unknown) 'Update Dim Name accordingly Dim objDim As OneStream.Shared.Wcf.Dim = BRApi.Finance.Dim.GetDim(si, "<Dimension Name>") 'Create New Member Dim objMember As New Member(objMemberPk, _ "<New Member Name>", "<Member Description>", objDim.DimPk.DimId) 'Create VaryingMemberProperties object Dim objProperties As New VaryingMemberProperties( _ objMemberPk.DimTypeId, objMemberPk.MemberId, DimConstants.Unknown) 'Create new member info object for new member Dim objMemberInfo As New MemberInfo( _ objMember, objProperties, Nothing, objDim, DimConstants.Unknown) 'Modify some member properties. Account dimension, in this example. Dim accountProperties As AccountVMProperties = objMemberInfo.GetAccountProperties() accountProperties.AccountType.SetStoredValue(AccountType.Revenue.Id) accountProperties.Text1.SetStoredValue( _ ScenarioType.Unknown.Id, DimConstants.Unknown, "MyNewText1Value") 'Save the member and its properties. Dim isNew As TriStateBool = TriStateBool.TrueValue BRApi.Finance.MemberAdmin.SaveMemberInfo(si, objMemberInfo, True, True, False, isNew)Extender: User Inactivity Email
This Extender can be executed in a Data Management step to automate emailing details of an auto-expiring account to the related user. Imports System Imports System.Data Imports System.Data.Common Imports System.IO Imports System.Collections.Generic Imports System.Globalization Imports System.Linq Imports Microsoft.VisualBasic Imports System.Threading Imports System.Windows.Forms Imports OneStream.Shared.Common Imports OneStream.Shared.Wcf Imports OneStream.Shared.Engine Imports OneStream.Shared.Database Imports OneStream.Stage.Engine Imports OneStream.Stage.Database Imports OneStream.Finance.Engine Imports OneStream.Finance.Database '** IMPORTANT! Update "InactiveEmailNotification" in line below ' with actual name of the Extender business rule you created Namespace OneStream.BusinessRule.Extender.InactiveEmailNotification Public Class MainClass Public Function Main(ByVal si As SessionInfo, ByVal globals As BRGlobals, ByVal api As Object, ByVal args As ExtenderArgs) As Object '--------------------------------------------------------------------------------------- 'Description: User Expiration Warning ' 'Usage: Sends an email to users prior their account auto expire date. ' This Snippet should replace an entire rule as it includes non-standard Imports [Lines 1-18] ' 'Notes: Administrator must set the following values prior to use: ' BusinessRuleName [Line 20] ' EmailConnectionName [Line 58] ' UserWarningThreshold [Line 61] ' EmailTitle [Line 64] ' EmailMessage [Line 68-75] ' EmailList [Line 78] ' 'Created By: OneStream Software 'Date Created: 09-15-2020 '--------------------------------------------------------------------------------------- Try Select Case args.FunctionType Case Is = ExtenderFunctionType.Unknown Me.EmailNotification(si) Case Is = ExtenderFunctionType.ExecuteDataMgmtBusinessRuleStep Me.EmailNotification(si) End Select Return Nothing Catch ex As Exception Throw ErrorHandler.LogWrite(si, New XFException(si, ex)) End Try End Function #Region "General Helpers" Public Sub EmailNotification(ByVal si As SessionInfo) Try 'Specify the email connection (Defined in Application Server setup) Dim emailConnectionName As String = "OneStreamEmail" 'Enter number of days prior to user expiration that warning will be sent. ' Email will only be sent if "Remaining Allowed Inactivity" is less than or equal to threshold days. Dim userWarningThreshold As Double = 20 'Define the the email title to be sent. The value [days] will be updated during processing. Dim emailTitle As String = "OneStream User ID Expiration - [days] day warning" 'Define the the email body to be sent. ' [user] & [days] will automatically be replaced, during processing, ' with the OneSteam Username & number of days till expiration. Dim emailMessage As New Text.StringBuilder emailMessage.AppendLine("Attention: [user]") emailMessage.AppendLine("") emailMessage.AppendLine("Your login for OneStream will expire in [days] due to inactivity." emailMessage.AppendLine("Please login as soon as possible.") emailMessage.AppendLine("") ' replace xxx in text below with relevant email address emailMessage.AppendLine("If you require assistance, please contact xxxx .") emailMessage.AppendLine("") emailMessage.AppendLine("Thank you.") emailMessage.AppendLine("The Support Team") 'Define any additional email addresses to include other than the user that is expiring. ' All emails will be listed in the "To: field" of the email. Dim emailList As New List(Of String) ' Uncomment following lines if necessary and update with relevant addresses. 'emailList.Add("emailaddress1@customer.com") 'emailList.Add("emailaddress2@customer.com") ' If you need more addresses, just add more lines like the ones above 'Account Expiration Warning Me.ValidateUserExpiration(si, emailConnectionName, _ userWarningThreshold, emailTitle, emailMessage.ToString, emailList) Catch ex As Exception Throw ErrorHandler.LogWrite(si, New XFException(si, ex)) End Try End Sub Public Sub ValidateUserExpiration(ByVal si As SessionInfo, ByVal emailConnectionName As String, _ ByVal userWarningThreshold As Double, ByVal emailTitle As String, ByVal emailMessage As String, ByVal emailList As List(Of String)) Try Dim dtResults As New DataTable Using dbConnApp As DbConnInfo = BRAPi.Database.CreateApplicationDbConnInfo(si) Dim ds As DataSet = BRApi.Database.ExecuteMethodCommand( _ dbConnApp, XFCommandMethodTypeID.Users, "{}", "Users", Nothing) If Not ds Is Nothing Then Dim dt As DataTable = ds.Tables(0).Copy Dim userID As Guid = Guid.Empty Dim userName As String = String.Empty Dim remainingDays As Double = 0 Dim updatedEmailList As New List(Of String) Dim updatedEmailTitle As String = String.Empty Dim updatedEmailMessage As String = String.Empty Dim objUserInfoAndStatus As UserInfoAndStatus = BRApi.Security.Admin.GetUserAndStatus( _ si, si.UserName) For Each dr As DataRow In dt.Rows 'Filter out inactive users and users without a defined email address If(dr(4).ToString().XFContainsIgnoreCase("TRUE")) And (Not String.IsNullOrEmpty(dr(7).ToString)) Then 'Get UserName and UserInfoAndStatus userName = dr(1) objUserInfoAndStatus = BRApi.Security.Admin.GetUserAndStatus(si, userName) If objUserInfoAndStatus.LogonStatus.GetNumDaysOfRemainingAllowedInactivity <= userWarningThreshold Then remainingDays = objUserInfoAndStatus.LogonStatus.GetNumDaysOfRemainingAllowedInactivity 'Reset email list for next user updatedemailList.Clear updatedemailList.AddRange(emailList) 'Add user to email list updatedemailList.Add(dr(6).ToString) 'Replace [days] & [user] values in email EmailTitle and EmailMessage updatedEmailTitle = emailTitle.Replace( _ "[days]", ConvertHelper.ToInt32(remainingDays)) updatedEmailMessage = emailMessage.Replace( _ "[days]", ConvertHelper.ToInt32(remainingDays)) updatedEmailMessage = updatedEmailMessage.Replace( _ "[user]", userName) 'Send the email using a worker background thread Dim mailThread As New SendMailThread(si, _ emailConnectionName, updatedemailList, _ updatedEmailTitle, updatedEmailMessage, Nothing) mailThread.Start End If End If Next End If End Using Catch ex As Exception Throw ErrorHandler.LogWrite(si, New XFException(si, ex)) End Try End Sub #End Region #Region "Constants and Enumerations" 'String Messages Public m_MsgNoEmailConnection As String = "Cannot Send Notifications: Email Connection must be specified." #End Region Public Class SendMailThread #Region "Module Level Variables" Private Const m_ThreadNamePrefix As String = "XF Send Mail Thread" Private m_SI As SessionInfo = Nothing Private m_MailConnectionName As String = String.Empty Private m_ToEmailAddresses As New List(Of String) Private m_Subject As String = String.Empty Private m_Body As String = String.Empty Private m_AttachmentFilePaths As New List(Of String) Private m_WorkerThread As Thread #End Region #Region "Constructor" Public Sub New(ByVal si As SessionInfo, ByVal mailConnectionName As String, _ ByVal toEmailAddresses As List(Of String), ByVal subject As String, _ ByVal body As String, ByVal attachmentFilePaths As List(Of String)) 'Copy the input parameters so the background thread can access them. m_SI = si m_MailConnectionName = mailConnectionName m_ToEmailAddresses = toEmailAddresses m_Subject = subject m_Body = body m_AttachmentFilePaths = attachmentFilePaths End Sub #End Region #Region "Public Methods" Public Sub Start() Try 'Create the Background Thread m_WorkerThread = New Thread(AddressOf Me.WorkerThreadMethod) 'We don't want this worker thread to keep the process from being shut down. m_WorkerThread.IsBackground = True 'Naming thread to provide a unique recognizable marker when debugging. m_WorkerThread.Name = m_ThreadNamePrefix & " " & Guid.NewGuid().ToString("N") XFWcfOperationInvoker.SetCultureInfoForUserToThread(m_SI, m_WorkerThread) m_WorkerThread.Start() Catch ex As Exception Throw ErrorHandler.LogWrite(m_SI, New XFException(m_SI, ex)) End Try End Sub #End Region #Region "Private Methods" Private Sub WorkerThreadMethod() Try 'Send the email BRApi.Utilities.SendMail(m_SI, m_MailConnectionName, m_ToEmailAddresses, m_Subject, m_Body, m_AttachmentFilePaths) Catch ex As Exception 'Important: do not re-throw the exception from this worker thread since it will be processed by .NET as an unhandled exception. 'Even if an exception could be processed normally, it couldn't be sent back to the client via WCF because the client isn't 'waiting for a WCF method to complete and the client might not not even be logged on anymore. Try BRApi.ErrorLog.LogError(m_SI, ex) Catch End Try End Try End Sub #End Region End Class End Class End Namespace1like0Comments