### Initial Project Setup with Yarn Source: https://github.com/sensenet/sn-client/blob/develop/CONTRIBUTING.md Commands to clone the sn-client repository, navigate into the directory, install project dependencies using yarn, build the TypeScript packages, and run the initial unit tests. ```Shell git clone https://github.com/SenseNet/sn-client.git cd sn-client yarn yarn build yarn test ``` -------------------------------- ### Running Example Application Scripts with Yarn Source: https://github.com/sensenet/sn-client/blob/develop/CONTRIBUTING.md Examples of using yarn aliases to easily run common scripts (`build:webpack`, `start`) for specific example applications included in the project, such as `dms`, `snapp`, and `storybook`. ```Shell yarn dms build:webpack yarn dms start yarn snapp start yarn storybook start ``` -------------------------------- ### Run sn-dms-demo Application Source: https://github.com/sensenet/sn-client/blob/develop/examples/sn-dms-demo/README.md Starts the sn-dms-demo application using the yarn workspace command. ```bash yarn workspace sn-dms-demo run start ``` -------------------------------- ### Install Dependencies with Yarn Source: https://github.com/sensenet/sn-client/blob/develop/examples/sn-dms-demo/README.md Installs all project dependencies for the monorepo using the yarn command. ```bash yarn ``` -------------------------------- ### Cypress E2E Test Suite Example (JavaScript) Source: https://github.com/sensenet/sn-client/blob/develop/apps/sensenet/cypress/CONTRIBUTING.md Demonstrates a basic Cypress test suite (describe) with setup (before) and individual test cases (it) for user handling, including login and logout actions using Cypress commands and selectors. ```JavaScript describe('User handling', () => { before(() => cy.clearCookies({ domain: null } as any)) it('should login with test user', () => { cy.visit('/') cy.get('input[name="repository"]').type(`${Cypress.env('repoUrl')}{enter}`) cy.get('[data-test="demo-button"]').click() }) it('should logout', () => { cy.login() cy.visit(pathWithQueryParams({ path: '/', newParams: { repoUrl: Cypress.env('repoUrl') } })) .get('.MuiToolbar-root .MuiAvatar-root+.MuiButtonBase-root.MuiIconButton-root') .click() .get('.MuiList-root li[role="menuitem"]') .contains('Log out') .click() cy.get('.MuiDialog-container .MuiDialogActions-root .MuiButton-containedPrimary').click() }) }) ``` -------------------------------- ### Install using Yarn (Bash) Source: https://github.com/sensenet/sn-client/blob/develop/packages/sn-list-controls-react/README.md Installs the @sensenet/list-controls-react package using the Yarn package manager. ```bash yarn add @sensenet/list-controls-react ``` -------------------------------- ### Install using NPM (Bash) Source: https://github.com/sensenet/sn-client/blob/develop/packages/sn-list-controls-react/README.md Installs the @sensenet/list-controls-react package using the NPM package manager. ```bash npm install @sensenet/list-controls-react ``` -------------------------------- ### Installing Node Fetch Package (Shell) Source: https://github.com/sensenet/sn-client/blob/develop/packages/gatsby-source-sensenet/README.md Installs the `node-fetch` package, which is used in the example configuration as the fetch method override for the `codeLogin` function. ```shell npm install node-fetch ``` -------------------------------- ### Installing @sensenet/client-utils Source: https://github.com/sensenet/sn-client/blob/develop/packages/sn-client-utils/README.md Provides commands to install the @sensenet/client-utils package using either Yarn or NPM package managers. ```bash # Yarn yarn add @sensenet/client-utils # NPM npm install @sensenet/client-utils ``` -------------------------------- ### Install Yarn Globally Source: https://github.com/sensenet/sn-client/blob/develop/examples/sn-dms-demo/README.md Installs the Yarn package manager globally using npm. ```bash npm i yarn -g ``` -------------------------------- ### Starting DMS for E2E Test Development Source: https://github.com/sensenet/sn-client/blob/develop/CONTRIBUTING.md Command to start the dms-demo application locally, specifically configured for developing end-to-end tests. This usually involves setting the NODE_ENV to 'test' and potentially enabling specific test-related features. ```Shell yarn start:dms:e2e ``` -------------------------------- ### Example Gatsby Source Plugin Configuration with Values (JavaScript) Source: https://github.com/sensenet/sn-client/blob/develop/packages/gatsby-source-sensenet/README.md Provides a complete example of the `gatsby-config.js` configuration for the `gatsby-source-sensenet` plugin, including example values for host, path, oDataOptions, and the `accessToken` function. ```javascript // In your gatsby-config.js const fetch = require('node-fetch') const { codeLogin } = require('@sensenet/authentication-oidc-react') const { configuration } = require('./configuration') module.exports = { plugins: [ { resolve: `gatsby-source-sensenet`, options: { host: 'https://dev.demo.sensenet.com', path: '/Root/Content/SampleWorkspace/Blog', oDataOptions: { select: 'all', expand: ['LeadImage'], metadata: 'no', }, accessToken: async () => { const authData = await codeLogin({ ...configuration, fetchMethod: fetch }) return authData.access_token }, }, }, ], } ``` -------------------------------- ### Installing @sensenet/client-core (Bash) Source: https://github.com/sensenet/sn-client/blob/develop/packages/sn-client-core/README.md Instructions for adding the @sensenet/client-core library to your project using either Yarn or NPM package managers. This is the first step to using the library. ```bash # Yarn yarn add @sensenet/client-core # NPM npm install @sensenet/client-core ``` -------------------------------- ### Installing @sensenet/controls-react (Bash) Source: https://github.com/sensenet/sn-client/blob/develop/packages/sn-controls-react/README.md Provides commands to install the @sensenet/controls-react library using either Yarn or NPM package managers. ```Bash # Yarn yarn add @sensenet/controls-react # NPM npm install @sensenet/controls-react ``` -------------------------------- ### Running Workspace Script with Yarn Source: https://github.com/sensenet/sn-client/blob/develop/CONTRIBUTING.md Example command demonstrating how to use `yarn workspace` to execute a specific script (like `test`) within a designated package or workspace (`@sensenet/redux`) within the monorepo. ```Shell yarn workspace @sensenet/redux test ``` -------------------------------- ### Installing @sensenet/authentication-jwt Package (Bash) Source: https://github.com/sensenet/sn-client/blob/develop/packages/sn-authentication-jwt/README.md These commands show how to install the @sensenet/authentication-jwt package using either Yarn or NPM package managers. This is the first step to integrating the JWT authentication service into your project. ```bash # Yarn yarn add @sensenet/authentication-jwt # NPM npm install @sensenet/authentication-jwt ``` -------------------------------- ### Installing @sensenet/redux (Bash) Source: https://github.com/sensenet/sn-client/blob/develop/packages/sn-redux/README.md Commands to install the @sensenet/redux package using either Yarn or NPM package managers. ```bash # Yarn yarn add @sensenet/redux # NPM npm install @sensenet/redux ``` -------------------------------- ### Installing sensenet Authentication OIDC React Package (Shell) Source: https://github.com/sensenet/sn-client/blob/develop/packages/gatsby-source-sensenet/README.md Installs the `@sensenet/authentication-oidc-react` package, which is required for programmatically generating access tokens for authentication with sensenet. ```shell npm install @sensenet/authentication-oidc-react ``` -------------------------------- ### Build Project Packages Source: https://github.com/sensenet/sn-client/blob/develop/examples/sn-dms-demo/README.md Builds all packages within the monorepo using the yarn build command. ```bash yarn build ``` -------------------------------- ### Install @sensenet/control-mapper with Yarn Source: https://github.com/sensenet/sn-client/blob/develop/packages/sn-control-mapper/README.md Installs the @sensenet/control-mapper package using the Yarn package manager. ```bash yarn add @sensenet/control-mapper ``` -------------------------------- ### Creating a sensenet Store (TypeScript) Source: https://github.com/sensenet/sn-client/blob/develop/packages/sn-redux/README.md A basic example showing how to create a sensenet store instance using a configured repository and a root reducer. ```typescript import { Store } from '@sensenet/redux' import { Repository } from '@sensenet/client-core' const repository = new Repository({ repositoryUrl: 'http://path-to-your-portal.com', }) const options = { repository, rootReducer: myReducer, } as Store.CreateStoreOptions const store = Store.createSensenetStore(options) ``` -------------------------------- ### Installing @sensenet/authentication-oidc-react Source: https://github.com/sensenet/sn-client/blob/develop/packages/sn-authentication-oidc-react/README.md Commands to add the @sensenet/authentication-oidc-react package to your project using either Yarn or NPM package managers. ```bash # Yarn yarn add @sensenet/authentication-oidc-react # NPM npm install @sensenet/authentication-oidc-react ``` -------------------------------- ### Install @sensenet/search-react with NPM (Bash) Source: https://github.com/sensenet/sn-client/blob/develop/packages/sn-search-react/README.md Installs the @sensenet/search-react package using the NPM package manager. This command adds the package as a project dependency. ```bash npm install @sensenet/search-react ``` -------------------------------- ### Creating Configuration File (JavaScript) Source: https://github.com/sensenet/sn-client/blob/develop/packages/gatsby-source-sensenet/README.md Provides an example structure for a `configuration.js` file. This file loads environment variables using `dotenv` and exports repository and OIDC client configuration details. ```javascript // Create a new file in root folder with the name configuration.js require('dotenv').config() exports.repositoryUrl = '' exports.configuration = { clientId: process.env.GATSBY_REACT_APP_CLIENT_ID || '', clientSecret: process.env.GATSBY_REACT_APP_CLIENT_SECRET || '', identityServerUrl: '', } ``` -------------------------------- ### Install @sensenet/hooks-react with NPM Source: https://github.com/sensenet/sn-client/blob/develop/packages/sn-hooks-react/README.md Use this command to install the @sensenet/hooks-react package into your project using the NPM package manager. ```bash npm install @sensenet/hooks-react ``` -------------------------------- ### Opening Cypress Test Runner Source: https://github.com/sensenet/sn-client/blob/develop/CONTRIBUTING.md Command to launch the Cypress graphical user interface (GUI) test runner, specifying the project directory (`examples/sn-dms-demo`) where the Cypress configuration and test files are located. ```Shell yarn cypress open -P examples/sn-dms-demo ``` -------------------------------- ### Installing @sensenet/redux-promise-middleware (Bash) Source: https://github.com/sensenet/sn-client/blob/develop/packages/sn-redux-promise-middleware/README.md Commands to add the @sensenet/redux-promise-middleware package to your project using either Yarn or NPM. ```bash # Yarn yarn add @sensenet/redux-promise-middleware # NPM npm install @sensenet/redux-promise-middleware ``` -------------------------------- ### Clone sensenet Client Monorepo Source: https://github.com/sensenet/sn-client/blob/develop/examples/sn-dms-demo/README.md Clones the sensenet client monorepo from the specified GitHub URL. ```bash git clone https://github.com/SenseNet/sn-client.git ``` -------------------------------- ### Install @sensenet/search-react with Yarn (Bash) Source: https://github.com/sensenet/sn-client/blob/develop/packages/sn-search-react/README.md Installs the @sensenet/search-react package using the Yarn package manager. This command adds the package as a project dependency. ```bash yarn add @sensenet/search-react ``` -------------------------------- ### Installing Dependencies (npm/Yarn) Source: https://github.com/sensenet/sn-client/blob/develop/examples/sn-react-typescript-boilerplate/README.md Commands to install all required project dependencies listed in the package.json file using either npm or Yarn. ```npm npm install ``` ```yarn yarn install ``` -------------------------------- ### Setting up sensenet Redux Promise Middleware (Typescript) Source: https://github.com/sensenet/sn-client/blob/develop/packages/sn-redux-promise-middleware/README.md Example demonstrating how to import the middleware and integrate it into a Redux store using `applyMiddleware`, providing a sensenet `Repository` instance. ```Typescript import { Repository } from '@sensenet/client-core' import { promiseMiddleware } from '@sensenet/redux-promise-middleware' const repository = new Repository({ repositoryUrl: 'https://mySensenetSite.com' }) ... const store = createStore( rootReducer, persistedState, applyMiddleware([promiseMiddleware(repository)]), ) ``` -------------------------------- ### Installing gatsby-source-sensenet Plugin (Shell) Source: https://github.com/sensenet/sn-client/blob/develop/packages/gatsby-source-sensenet/README.md This command installs the gatsby-source-sensenet plugin using npm, adding it as a dependency to your Gatsby project. This is the first step required to integrate sensenet data into your Gatsby site. ```Shell npm install gatsby-source-sensenet ``` -------------------------------- ### Installing @sensenet/editor-react package Source: https://github.com/sensenet/sn-client/blob/develop/packages/sn-editor-react/README.md These commands demonstrate how to install the @sensenet/editor-react package, which provides a rich text editor component for sensenet applications built with React. You can choose to use either Yarn or NPM. ```bash # Yarn yarn add @sensenet/editor-react ``` ```bash # NPM npm install @sensenet/editor-react ``` -------------------------------- ### Installing @sensenet/repository-events Package (Bash) Source: https://github.com/sensenet/sn-client/blob/develop/packages/sn-repository-events/README.md Instructions for adding the @sensenet/repository-events package to your project using either Yarn or NPM. ```bash # Yarn yarn add @sensenet/repository-events # NPM npm install @sensenet/repository-events ``` -------------------------------- ### Installing @sensenet/pickers-react Package (Bash) Source: https://github.com/sensenet/sn-client/blob/develop/packages/sn-pickers-react/README.md This snippet provides commands to install the @sensenet/pickers-react package using either Yarn or NPM package managers. It includes commands for both methods. ```bash # Yarn yarn add @sensenet/pickers-react # NPM npm install @sensenet/pickers-react ``` -------------------------------- ### Navigate to Monorepo Root Source: https://github.com/sensenet/sn-client/blob/develop/examples/sn-dms-demo/README.md Changes the current directory to the root folder of the cloned sensenet client monorepo. ```bash cd sn-client ``` -------------------------------- ### Installing @sensenet/query Package (Bash) Source: https://github.com/sensenet/sn-client/blob/develop/packages/sn-query/README.md Instructions on how to add the @sensenet/query package to your project using either Yarn or NPM package managers. ```bash # Yarn yarn add @sensenet/query # NPM npm install @sensenet/query ``` -------------------------------- ### Starting Development Server (npm/Yarn) Source: https://github.com/sensenet/sn-client/blob/develop/examples/sn-react-typescript-boilerplate/README.md Commands to launch the Webpack development server, which compiles the project and serves it locally, typically with hot-reloading. ```npm npm run start ``` ```yarn yarn start ``` -------------------------------- ### Installing Dotenv Package (Shell) Source: https://github.com/sensenet/sn-client/blob/develop/packages/gatsby-source-sensenet/README.md Installs the `dotenv` package, which is used to load environment variables from a `.env` file into `process.env`. ```shell npm install dotenv ``` -------------------------------- ### Example RichText JSON Structure Source: https://github.com/sensenet/sn-client/blob/develop/packages/gatsby-source-sensenet/README.md Provides an example of the JSON structure returned for a RichText field when the `richtexteditor: 'all'` option is enabled. This structure represents the content as an abstract syntax tree. ```JSON { "type":"doc", "content":[ { "type":"paragraph", "attrs":{ "textAlign":"center" }, "content":[ { "type":"text", "marks":[ { "type":"bold" } ], "text":"Lorem ipsum dolor sit amet ..." } ] } ] } ``` -------------------------------- ### Install @sensenet/icons-react using Yarn or NPM Source: https://github.com/sensenet/sn-client/blob/develop/packages/sn-icons-react/README.md Provides commands to add the @sensenet/icons-react package to a project using either Yarn or NPM package managers. This is the first step to integrate the library into your project. ```bash # Yarn yarn add @sensenet/icons-react # NPM npm install @sensenet/icons-react ``` -------------------------------- ### Installing @sensenet/default-content-types Package Source: https://github.com/sensenet/sn-client/blob/develop/packages/sn-default-content-types/README.md Install the @sensenet/default-content-types package using either Yarn or NPM, the two most common package managers for Node.js projects. This package is essential for utilizing the default content type definitions provided by sensenet. ```bash yarn add @sensenet/default-content-types ``` ```bash npm install @sensenet/default-content-types ``` -------------------------------- ### Install @sensenet/hooks-react with Yarn Source: https://github.com/sensenet/sn-client/blob/develop/packages/sn-hooks-react/README.md Use this command to add the @sensenet/hooks-react package to your project using the Yarn package manager. ```bash yarn add @sensenet/hooks-react ``` -------------------------------- ### Install sensenet Google Auth Package (Bash) Source: https://github.com/sensenet/sn-client/blob/develop/packages/sn-client-auth-google/README.md Commands to add the @sensenet/authentication-google package to your project using either Yarn or NPM package managers. ```bash yarn add @sensenet/authentication-google ``` ```bash npm install @sensenet/authentication-google ``` -------------------------------- ### Example .env File Content (Environment Variables) Source: https://github.com/sensenet/sn-client/blob/develop/packages/gatsby-source-sensenet/README.md Shows the format for defining the `GATSBY_REACT_APP_CLIENT_ID` and `GATSBY_REACT_APP_CLIENT_SECRET` environment variables within a `.env` file. ```text // In your .env file GATSBY_REACT_APP_CLIENT_ID= GATSBY_REACT_APP_CLIENT_SECRET= ``` -------------------------------- ### Implementing a Custom Logger Source: https://github.com/sensenet/sn-client/blob/develop/packages/sn-client-utils/README.md Provides an example of how to create a custom logger implementation by extending `AbstractLogger` and implementing the `addEntry` method. It also shows how to make it injectable. ```typescript import { AbstractLogger, Injectable, LeveledLogEntry } from '@sensenet/client-utils' @Injectable({ lifetime: 'singleton' }) export class MyCustomLogCollector extends AbstractLogger { private readonly entries: Array> = [] public getEntries() { return [...this.entries] } public async addEntry(entry: LeveledLogEntry): Promise { this.entries.push(entry) } constructor() { super() } } ``` -------------------------------- ### Retrieving a service instance from Injector (TypeScript) Source: https://github.com/sensenet/sn-client/blob/develop/packages/sn-client-utils/README.md Shows how to get an instance of a registered service from the injector using the getInstance method, providing the service class as an argument. ```TypeScript const service = myInjector.getInstance(MySercive) ``` -------------------------------- ### Install sensenet Document Viewer React Component Source: https://github.com/sensenet/sn-client/blob/develop/packages/sn-document-viewer-react/README.md Use Yarn or NPM to add the @sensenet/document-viewer-react package to your project dependencies. ```Bash yarn add @sensenet/document-viewer-react ``` ```Bash npm install @sensenet/document-viewer-react ``` -------------------------------- ### Setup Google Auth Provider (TypeScript) Source: https://github.com/sensenet/sn-client/blob/develop/packages/sn-client-auth-google/README.md Initializes the Google OAuth provider instance by calling addGoogleAuth, requiring a sensenet Repository, JwtService, and your Google client ID. ```typescript import { Repository } from '@sensenet/client-core'\nimport { JwtService } from '@sensenet/authentication-jwt'\nimport { addGoogleAuth } from '@sensenet/authentication-google'\n\nconst repo = new Repository()\nconst jwt = new JwtService(repo)\nconst googleOauthProvider = addGoogleAuth(jwt, { clientId: '' }) ``` -------------------------------- ### Example Configuration and Usage of AuthenticationProvider Source: https://github.com/sensenet/sn-client/blob/develop/packages/sn-authentication-oidc-react/README.md This TypeScript code snippet demonstrates how to configure UserManagerSettings for the AuthenticationProvider component, including sensenet-specific parameters like 'sensenet' scope and 'snrepo' extra query parameter. It also shows how to set up provider components (AuthProvider, RepositoryProvider) using React hooks and context to wrap the application, providing both authentication and sensenet repository access based on the authenticated user. ```typescript import { AuthenticationProvider, useOidcAuthentication, UserManagerSettings } from '@sensenet/authentication-oidc-react'; import { Repository } from '@sensenet/client-core'; import { RepositoryContext } from '@sensenet/hooks-react'; import React, { PropsWithChildren } from 'react'; import { BrowserRouter, useHistory } from 'react-router-dom'; export const repositoryUrl = 'https://my-service.sensenet.com/'; export const configuration: UserManagerSettings = { client_id: '7cYLChuhJxyGb7BS', //externalSPA clientId for dev.demo.sensenet.com automaticSilentRenew: true, redirect_uri: 'http://localhost:3000/authentication/callback', response_type: 'code', post_logout_redirect_uri: 'http://localhost:3000/', scope: 'openid profile sensenet', authority: 'https://is.my-service.sensenet.com/', silent_redirect_uri: 'http://localhost:3000/authentication/silent_callback', extraQueryParams: { snrepo: repositoryUrl }, }; export function AppProviders({ children }: PropsWithChildren<{}>) { return ( {children} ); } export const AuthProvider = ({ children }: PropsWithChildren<{}>) => { const history = useHistory(); return ( {children} ); }; export const RepositoryProvider = ({ children }: PropsWithChildren<{}>) => { const { oidcUser } = useOidcAuthentication(); if (!oidcUser) { return ; } return ( { children } ); }; ``` -------------------------------- ### Running End-to-End Tests with Yarn Source: https://github.com/sensenet/sn-client/blob/develop/CONTRIBUTING.md Command to execute the configured end-to-end tests for the dms-demo application using yarn, typically running tests headlessly in a CI environment or locally. ```Shell yarn test:dms:e2e ``` -------------------------------- ### Perform Google Login (TypeScript) Source: https://github.com/sensenet/sn-client/blob/develop/packages/sn-client-auth-google/README.md Provides an example asynchronous method to log in using the initialized Google OAuth provider, optionally accepting an idToken and handling potential errors. ```typescript // an example login method with an optional idToken:\nasync Login(idToken?: string){\n try {\n await googleOauthProvider.login(idToken);\n console.log('Logged in');\n } catch (error) {\n console.warn('Error during login', error);\n }\n} ``` -------------------------------- ### Combining Custom Reducers with sensenet Reducers (TypeScript) Source: https://github.com/sensenet/sn-client/blob/develop/packages/sn-redux/README.md Example of using Redux's `combineReducers` to merge the built-in sensenet reducers with custom application-specific reducers. ```typescript import { combineReducers } from 'redux' import { Reducers } from '@sensenet/redux' const sensenet = Reducers.sensenet const myReducer = combineReducers({ sensenet, listByFilter, }) ``` -------------------------------- ### Defining Injectable service Lifetime (TypeScript) Source: https://github.com/sensenet/sn-client/blob/develop/packages/sn-client-utils/README.md Explains how to specify the lifetime of an injectable service using the lifetime option in the @Injectable() decorator. Examples include 'transient', 'scoped', and 'singleton'. ```TypeScript @Injectable({ lifetime: 'transient', }) export class MySercive { /** ...service implementation... */ } ``` -------------------------------- ### Using Custom Cypress Login Command (JavaScript) Source: https://github.com/sensenet/sn-client/blob/develop/apps/sensenet/cypress/CONTRIBUTING.md Shows how to use a custom Cypress command cy.login() with an argument to authenticate as a specific user role (e.g., 'superAdmin') in an E2E test. ```JavaScript cy.login('superAdmin') ``` -------------------------------- ### Cypress User Configuration JSON Source: https://github.com/sensenet/sn-client/blob/develop/apps/sensenet/cypress/CONTRIBUTING.md Defines the structure for user roles and their credentials within the Cypress environment configuration (cypress.json), including clientId, clientSecret, and id for admin and developer roles. ```JSON "admin": { "clientId": "businesscat", "clientSecret": "", "id": "/Root/IMS/Public('businesscat')" }, "developer": { "clientId": "devdog", "clientSecret": "", "id": "/Root/IMS/Public('devdog')" } ``` -------------------------------- ### Subscribing to Authentication State and User Changes (TypeScript) Source: https://github.com/sensenet/sn-client/blob/develop/packages/sn-authentication-jwt/README.md These examples illustrate how to subscribe to observable streams provided by the jwtService to react to changes in the current user or the overall authentication state. This allows applications to update UI or logic based on authentication status. ```typescript jwtService.currentUser.subscribe((newUser) => { console.log('User changed. New user: ', newUser.LoginName) }) jwtService.state.subscribe((newState) => { console.log('Authentication state changed to', newState) }) ``` -------------------------------- ### Creating Repository Instance (@sensenet/client-core, TypeScript) Source: https://github.com/sensenet/sn-client/blob/develop/packages/sn-client-core/README.md Demonstrates how to instantiate the Repository object, which serves as the main entry point for interacting with the sensenet repository. It requires providing configuration options like the repository URL and default OData parameters. ```typescript import { Repository } from '@sensenet/client-core' const repository = new Repository({ repositoryUrl: 'https://my-sensenet-site.com', oDataToken: 'OData.svc', defaultSelect: ['DisplayName', 'Icon'], requiredSelect: ['Id', 'Type', 'Path', 'Name'], defaultMetadata: 'no', defaultInlineCount: 'allpages', defaultExpand: [], defaultTop: 1000, }) ``` -------------------------------- ### Initializing Logging with Injector Source: https://github.com/sensenet/sn-client/blob/develop/packages/sn-client-utils/README.md Explains how to set up the logging service using the `@sensenet-client-utils/inject` module. It shows how to create an `Injector` and register logger implementations like `ConsoleLogger`. ```typescript import { ConsoleLogger, Injector } from '@sensenet/client-utils' const myInjector = new Injector().useLogging(ConsoleLogger, Logger1, Logger2 /** ...your Logger implementations */) ``` -------------------------------- ### Implementing Disposable Resources with using/usingAsync Source: https://github.com/sensenet/sn-client/blob/develop/packages/sn-client-utils/README.md Demonstrates how to create disposable resources by implementing the Disposable interface and using the `using` or `usingAsync` helper functions for automatic cleanup. ```typescript class Resource implements Disposable { dispose() { // cleanup logics } } using(new Resource(), resource => { // do something with the resource }) usingAsync(new Resource(), async resource => { // do something with the resource, allows awaiting promises }) ``` -------------------------------- ### Building the Project (npm/Yarn) Source: https://github.com/sensenet/sn-client/blob/develop/examples/sn-react-typescript-boilerplate/README.md Commands to create a production-ready bundle of the application, typically optimized and saved to a designated output directory. ```npm npm run build ``` ```yarn yarn build ``` -------------------------------- ### Configuring sensenet Repository with OData Token (TypeScript) Source: https://github.com/sensenet/sn-client/blob/develop/packages/sn-redux/README.md Shows how to initialize a sensenet Repository instance with a specific repository URL and an OData service token for authentication. ```typescript const repository = new Repository.SnRepository({ RepositoryUrl: 'http://path-to-your-portal.com', ODataToken: 'MyODataServiceToken', }) ``` -------------------------------- ### Cloning the Repository (Git) Source: https://github.com/sensenet/sn-client/blob/develop/examples/sn-react-typescript-boilerplate/README.md Instructions to clone the newly created repository from a Git hosting service to your local machine. ```Shell git clone ``` -------------------------------- ### Creating a new Injector instance (TypeScript) Source: https://github.com/sensenet/sn-client/blob/develop/packages/sn-client-utils/README.md Demonstrates how to instantiate the Injector class to create a new dependency injection container. ```TypeScript const myInjector = new Injector() ``` -------------------------------- ### Configuring sensenet Store with Custom Reducer (TypeScript) Source: https://github.com/sensenet/sn-client/blob/develop/packages/sn-redux/README.md Demonstrates how to create a sensenet store by combining built-in sensenet reducers with custom reducers and configuring it with a sensenet repository instance. ```typescript import { Repository } from '@sensenet/client-core' import { Reducers, Store } from '@sensenet/redux' import { combineReducers } from 'redux' const sensenet = Reducers.sensenet const myReducer = combineReducers({ sensenet, }) const repository = new Repository({ repositoryUrl: 'http://path-to-your-portal.com', }) const options: Store.CreateStoreOptions = { repository, rootReducer: myReducer, } const store = Store.createSensenetStore(options) ``` -------------------------------- ### Tracing Method Calls with Trace Source: https://github.com/sensenet/sn-client/blob/develop/packages/sn-client-utils/README.md Demonstrates how to use the `Trace.method` utility to track the execution lifecycle of a method, including calls, finishes, and errors. It shows how to configure the tracer and dispose of it. ```typescript const methodTracer: Disposable = Trace.method({ object: myObjectInstance, // You can define an object constructor for static methods as well method: myObjectInstance.method, // The method to be tracked methodName: 'method', // Unique identifier for the method isAsync: true, // if you set to async, method finished will be *await*-ed onCalled: traceData => { console.log('Method called:', traceData) }, onFinished: traceData => { console.log('Method call finished:', traceData) }, onError: traceData => { console.log('Method throwed an error:', traceData) }, }) // if you want to stop receiving events methodTracer.dispose() ``` -------------------------------- ### Loading Content Collection (@sensenet/client-core, TypeScript) Source: https://github.com/sensenet/sn-client/blob/develop/packages/sn-client-core/README.md Illustrates how to fetch a collection of content items, such as children of a path or results of a query. It uses the repository.loadCollection method and demonstrates applying OData query and orderby parameters. ```typescript const portalUsers = await repository.loadCollection({ path: '/Root/IMS/BuiltIn/Portal', oDataOptions: { query: 'TypeIs:User', orderby: ['LoginName'], }, }) console.log('Count: ', portalUsers.d.__count) console.log('Users: ', portalUsers.d.results) ``` -------------------------------- ### Setting up JwtService with Repository (TypeScript) Source: https://github.com/sensenet/sn-client/blob/develop/packages/sn-authentication-jwt/README.md This snippet demonstrates how to initialize the JwtService with a sensenet Repository instance. It configures the service with options like selecting 'all' properties, a timeout of 5000ms, and setting the token persistence strategy to 'Expiration'. ```typescript import { TokenPersist } from '@sensenet/authentication-jwt' const repository = new Repository() const jwtService = new JwtService(repository, { select: 'all' }, 5000, TokenPersist.Expiration) ``` -------------------------------- ### Creating New Content (POST, @sensenet/client-core, TypeScript) Source: https://github.com/sensenet/sn-client/blob/develop/packages/sn-client-core/README.md Demonstrates how to create a new content item in the repository using an OData POST request via the repository.post method. It requires specifying the parent path, content type, and the initial content data. ```typescript const createdUser = await repository.post({ parentPath: 'Root/Parent', contentType: 'User', content: { Name: 'NewContent', /** ...additional content data */ }, }) ``` -------------------------------- ### Creating and Using a Scoped Logger Source: https://github.com/sensenet/sn-client/blob/develop/packages/sn-client-utils/README.md Illustrates how to create a logger instance with a predefined scope using the `withScope` method, which is useful for logging within specific services or modules. ```typescript const scopedLogger = myLogger.withScope('logger/test') scopedLogger.verbose({ message: 'FooBarBaz' }) ``` -------------------------------- ### Subscribing to Content Created Event (TypeScript) Source: https://github.com/sensenet/sn-client/blob/develop/packages/sn-repository-events/README.md Demonstrates how to initialize the Repository and EventHub and subscribe to the onContentCreated event using TypeScript. ```ts const repository = new Repository({}) const eventHub = new EventHub(repository) // subscribe to a Content Created event eventHub.onContentCreated.subscribe(createdContent => { console.log('New Content created:', createdContent) }) ``` -------------------------------- ### Adding Log Entry with Level Helper Method Source: https://github.com/sensenet/sn-client/blob/develop/packages/sn-client-utils/README.md Shows an alternative way to add a log entry using a level-specific helper method like `verbose`, providing message, scope, and optional data. This achieves the same result as `addEntry`. ```typescript myLogger.verbose({ message: 'My log message', scope: '@sensenet/client-utils/test', data: { foo: 1, bar: 42, }, }) ``` -------------------------------- ### Adding Log Entry with addEntry Source: https://github.com/sensenet/sn-client/blob/develop/packages/sn-client-utils/README.md Demonstrates how to add a log entry using the `addEntry` method of a logger instance, specifying level, message, scope, and optional data. ```typescript myLogger.addEntry({ level: LogLevel.Verbose, message: 'My log message', scope: 'logger/test', data: { foo: 1, bar: 42, }, }) ``` -------------------------------- ### Copying Content (@sensenet/client-core, TypeScript) Source: https://github.com/sensenet/sn-client/blob/develop/packages/sn-client-core/README.md Demonstrates performing a batch copy action on one or more content items using the repository.copy method. It accepts content IDs or paths and a target path for the copy destination. ```typescript const copyResult = await repository.copy({ idOrPath: [45, 'Root/Path/To/Content'], targetPath: 'Root/Target/Path', }) ``` -------------------------------- ### Creating a child Injector (TypeScript) Source: https://github.com/sensenet/sn-client/blob/develop/packages/sn-client-utils/README.md Shows how to create a child injector from an existing injector, useful for creating scoped contexts for services. ```TypeScript const childInjector = myInjector.createChild({ owner: 'myCustomContext' }) ``` -------------------------------- ### Loading Single Content Item (@sensenet/client-core, TypeScript) Source: https://github.com/sensenet/sn-client/blob/develop/packages/sn-client-core/README.md Shows how to retrieve a single content item from the repository using its path or ID. It demonstrates using the repository.load method and optionally providing OData options like expand and select to customize the response. ```typescript import { User } from '@sensenet/default-content-types' const user = await repository.load({ idOrPath: '/Root/IMS/BuiltIn/Portal/Visitor', // you can also load by content Id oDataOptions: { // You can provide additional OData parameters expand: ['CreatedBy'], select: 'all', }, }) console.log(user) // {d: { /*(...retrieved user data)*/ }} ``` -------------------------------- ### Initialize and Configure ControlMapper in TypeScript Source: https://github.com/sensenet/sn-client/blob/develop/packages/sn-control-mapper/README.md Demonstrates how to import, initialize, and configure the ControlMapper with a sensenet Repository instance and default controls, setting up custom implementations for specific field settings. ```typescript import { Repository } from '@sensenet/client-core' import { ControlMapper } from '@sensenet/control-mapper' const repository = new Repository({ /** repository settings */ }) const mapper = new ControlMapper(repository, ExampleDefaultControl, ExampleDefaultFieldControl) .setupFieldSettingDefault('NumberFieldSetting', setting => MyNumberFieldImplementation) .setupFieldSettingDefault('PasswordFieldSetting', setting => MyPasswordFieldImplementation) ``` -------------------------------- ### Running Tests (npm/Yarn) Source: https://github.com/sensenet/sn-client/blob/develop/examples/sn-react-typescript-boilerplate/README.md Commands to execute the project's test suite (e.g., Jest tests) and generate a test coverage report. ```npm npm run test ``` ```yarn yarn test ``` -------------------------------- ### Defining an Injectable service from a class (TypeScript) Source: https://github.com/sensenet/sn-client/blob/develop/packages/sn-client-utils/README.md Illustrates how to use the @Injectable() decorator on a class to register it as a service that can be injected. Constructor parameters are automatically resolved. ```TypeScript @Injectable({ /** Injectable options */ }) export class MySercive { /** ...service implementation... */ constructor(s1: OtherInjectableService, s2: AnotherInjectableService) {} } ``` -------------------------------- ### Dispatching sensenet CreateContent Action (TypeScript) Source: https://github.com/sensenet/sn-client/blob/develop/packages/sn-redux/README.md Demonstrates how to use the sensenet CreateContent action to add a new content item under a specified parent path. ```typescript import { Repository } from '@sensenet/client-core' import { Task } from '@sensenet/default-content-type' import { Actions } from '@sensenet/redux' const repository = new Repository({ repositoryUrl: 'http://path-to-your-portal.com', }) const parentPath = '/workspaces/Project/budapestprojectworkspace/tasks'; const content: Task = { Id: 123, DisplayName: 'My first task' }) dispatch(Actions.CreateContent(parentPath, content, 'Task')) ``` -------------------------------- ### Retrieving Logger Instance from Injector Source: https://github.com/sensenet/sn-client/blob/develop/packages/sn-client-utils/README.md Shows how to access the configured logger instance from an `Injector` after it has been initialized with logging services. ```typescript const myLogger = myInjector.logger ``` -------------------------------- ### Creating Remote File Node for LeadImage (JavaScript) Source: https://github.com/sensenet/sn-client/blob/develop/packages/gatsby-source-sensenet/README.md This JavaScript code snippet, intended for `gatsby-node.js`, implements `onCreateNode` to handle image references. It checks for 'sensenetBlogPost' nodes, uses `createRemoteFileNode` to download the image specified by the 'LeadImage.Path', and links the created image node to the blog post node. Requires `gatsby-source-filesystem` and `gatsby-transformer-sharp`. ```JavaScript exports.onCreateNode = async ({ node, actions: { createNode }, createNodeId, getCache }) => { if (node.internal.type === 'sensenetBlogPost') { const leadImageNode = await createRemoteFileNode({ url: `${node.LeadImage.Path}`, parentNodeId: node.Id.toString(), createNode, createNodeId, getCache, }) if (leadImageNode) { node.leadImage___NODE = leadImageNode.id ///connect to blog post node } } } ``` -------------------------------- ### Configuring gatsby-source-sensenet Plugin in Gatsby Source: https://github.com/sensenet/sn-client/blob/develop/packages/gatsby-source-sensenet/README.md Demonstrates how to add and configure the gatsby-source-sensenet plugin within the plugins array of your Gatsby project's gatsby-config.js file, specifying essential options like host, path, and authentication details. ```javascript // In your gatsby-config.js module.exports = { plugins: [ { resolve: `gatsby-source-sensenet`, options: { host: '', path: '', oDataOptions: '', accessToken: '', level: '' } } ] } ``` -------------------------------- ### Building a sensenet Query (TypeScript) Source: https://github.com/sensenet/sn-client/blob/develop/packages/sn-query/README.md Demonstrates how to use the Query builder to construct a complex sensenet query with type casting, filtering (equals, between, notEquals, contains), grouping, sorting, and pagination (top, skip). It also shows the resulting sensenet query string output. ```typescript const query = new Query( (q) => q .typeIs('Task') // adds '+TypeIs:Task' and Typescript type cast .and.equals('DisplayName', 'Unicorn') // adds +Title:Unicorn .and.between('ModificationDate', '2017-01-01T00:00:00', '2017-02-01T00:00:00') .or.query( (sub) => sub // Grouping .notEquals('Approvable', true) .and.notEquals('Description', '*alma*'), // Contains with wildcards ) .sort('DisplayName') .top(5) // adds .TOP:5 .skip(10), ) console.log(query.toString()) ``` ```text "TypeIs:Task AND DisplayName:'Unicorn' AND ModificationDate:{'2017-01-01T00\\:00\\:00' TO '2017-02-01T00\\:00\\:00'} OR (NOT(Approvable:'true') AND NOT(Description:'*alma*')) .SORT:DisplayName .TOP:5 .SKIP:10" ``` -------------------------------- ### Setting an explicit service instance in Injector (TypeScript) Source: https://github.com/sensenet/sn-client/blob/develop/packages/sn-client-utils/README.md Demonstrates how to manually provide a specific instance of a service to the injector using setExplicitInstance, overriding the default instance creation. ```TypeScript class MyService { constructor(public readonly foo: string) } myInjector.setExplicitInstance(new MyService('bar')) ``` -------------------------------- ### Configuring Gatsby Source Plugin with Access Token Function (JavaScript) Source: https://github.com/sensenet/sn-client/blob/develop/packages/gatsby-source-sensenet/README.md Shows how to configure the `gatsby-source-sensenet` plugin in `gatsby-config.js` using an asynchronous function for the `accessToken` option. This function uses `codeLogin` from `@sensenet/authentication-oidc-react` to fetch an access token. ```javascript // In your gatsby-config.js const fetch = require('node-fetch') const { codeLogin } = require('@sensenet/authentication-oidc-react') const { configuration } = require('./configuration') module.exports = { plugins: [ { resolve: `gatsby-source-sensenet`, options: { host: '', path: '', oDataOptions: '' accessToken: async () => { const authData = await codeLogin({ ...configuration, fetchMethod: fetch }) return authData.access_token } }, }, ], } ``` -------------------------------- ### Creating Pages from sensenetBlogPost Nodes (JavaScript) Source: https://github.com/sensenet/sn-client/blob/develop/packages/gatsby-source-sensenet/README.md This JavaScript code snippet, intended for `gatsby-node.js`, implements the `createPages` API. It queries all 'sensenetBlogPost' nodes, iterates through them, and uses the created 'slug' field to generate individual pages for each blog post using a specified template. ```JavaScript //In your gatsby-node.js exports.createPages = async ({ graphql, actions }) => { const { createPage } = actions const allSensenetBlogPost = await graphql(` { allSensenetBlogPost(limit: 1000) { edges { node { fields { slug } } } } } `) if (allSensenetBlogPost.errors) { console.error(allSensenetBlogPost.errors) throw new Error(allSensenetBlogPost.errors) } const blogPostTemplate = path.resolve('') allSensenetBlogPost.data.allSensenetBlogPost.edges.forEach(({ node }) => { const { slug } = node.fields createPage({ path: `/${slug}/`, component: blogPostTemplate, context: { slug, }, }) }) } ``` -------------------------------- ### Tracking Value Changes with ObservableValue Source: https://github.com/sensenet/sn-client/blob/develop/packages/sn-client-utils/README.md Shows how to create an `ObservableValue`, subscribe to its changes using `subscribe`, update the value with `setValue`, and dispose of observers or the observable itself. ```typescript const observableValue = new ObservableValue(0) const observer = observableValue.subscribe(newValue => { console.log('Value changed:', newValue) }) // To update the value observableValue.setValue(Math.random()) // if you want to dispose a single observer observer.dispose() // if you want to dispose the whole observableValue with all of its observers: observableValue.dispose() ``` -------------------------------- ### Importing View Control Components (TypeScript) Source: https://github.com/sensenet/sn-client/blob/develop/packages/sn-controls-react/README.md Demonstrates how to import specific View Control components (NewView, EditView, CommandButtons) from the @sensenet/controls-react library into a TypeScript/React application. ```TypeScript import { NewView, EditView, CommandButtons } '@sensenet/controls-react'; ... ``` -------------------------------- ### Executing Custom OData Action - sensenet Client - TypeScript Source: https://github.com/sensenet/sn-client/blob/develop/packages/sn-client-core/README.md Demonstrates how to call a custom OData action using the `repository.executeAction` method. It defines interfaces for the action's request body and return type, then executes the action on a specific content item with a POST method and a defined body. ```TypeScript interface CustomActionBodyType { Name: string Value: string } interface CustomActionReturnType { Result: any } const actionResult = await repository.executeAction({ idOrPath: 'Path/to/content', method: 'POST', name: 'MyOdataCustomAction', body: { Name: 'foo', Value: 'Bar', }, }) console.log(actionResult.Result) ``` -------------------------------- ### Basic Icon Usage with Default Material-UI Source: https://github.com/sensenet/sn-client/blob/develop/packages/sn-icons-react/README.md Demonstrates importing the Icon component and rendering a basic icon by name. The default icon type is material-ui if not explicitly specified. Requires importing the Icon component from the library. ```ts import { Icon } from '@sensenet/icons-react' ... ... ``` -------------------------------- ### Using SnDocumentViewer with Widgets Source: https://github.com/sensenet/sn-client/blob/develop/packages/sn-document-viewer-react/README.md Import the SnDocumentViewer and various widgets to create a functional document viewer interface with controls for thumbnails, zoom, rotation, saving, and annotations. ```JavaScript import { AddAnnotationWidget, AddHighlightWidget, AddRedactionWidget, DocumentTitlePager, LayoutAppBar, RotateActivePagesWidget, RotateDocumentWidget, ROTATION_MODE, SaveWidget, DocumentViewer as SnDocumentViewer, ToggleCommentsWidget, ToggleRedactionWidget, ToggleShapesWidget, ToggleThumbnailsWidget, ZoomInOutWidget, } from '@sensenet/document-viewer-react' } renderAppBar={() => (
)} /> ``` -------------------------------- ### Using Flaticon Material Design Icons with @sensenet/icons-react Source: https://github.com/sensenet/sn-client/blob/develop/packages/sn-icons-react/README.md Shows how to specify the Flaticon material design icon type using iconType.flaticon. Includes optional parameters like fontSize, color, and an onClick event handler. Requires importing both Icon and iconType. ```ts import { Icon, iconType } from '@sensenet/icons-react' ... myEventHandler(e.target)} > ... ``` -------------------------------- ### Querying Nested Children Nodes (GraphQL) Source: https://github.com/sensenet/sn-client/blob/develop/packages/gatsby-source-sensenet/README.md This GraphQL query demonstrates how to traverse the content tree by querying nested children nodes. It fetches 'sensenetBlog', its 'sensenetBlogPost' children, and 'sensenetFolder' children, further nesting to fetch 'sensenetImage' children within folders. ```GraphQL query MyQuery { sensenetBlog { childrenSensenetBlogPost { Name DisplayName } childrenSensenetFolder { Name DisplayName childrenSensenetImage { Name DisplayName } } } } ``` -------------------------------- ### Using FontAwesome Icons with @sensenet/icons-react Source: https://github.com/sensenet/sn-client/blob/develop/packages/sn-icons-react/README.md Demonstrates how to specify the FontAwesome icon type using iconType.fontawesome. Includes optional parameters like fontSize, color, and an onClick event handler. Requires importing both Icon and iconType. ```ts import { Icon, iconType } from '@sensenet/icons-react' ... myEventHandler(e.target)} > ... ``` -------------------------------- ### Retrying Operations with Retrier Source: https://github.com/sensenet/sn-client/blob/develop/packages/sn-client-utils/README.md Illustrates how to use the `Retrier` utility to repeatedly attempt an asynchronous function until it succeeds, reaches a retry limit, or times out. Configuration options like retries, interval, and timeout are shown. ```typescript const funcToRetry: () => Promise = async () => { const hasSucceeded = false // ... // custom logic // ... return hasSucceeded } const retrierSuccess = await Retrier.create(funcToRetry) .setup({ Retries: 3, RetryIntervalMs: 1, timeoutMs: 1000, }) .run() ``` -------------------------------- ### Performing Login and Logout Operations (TypeScript) Source: https://github.com/sensenet/sn-client/blob/develop/packages/sn-authentication-jwt/README.md This code shows how to use the authentication service attached to the repository to perform login and logout operations. The login method requires a username and password, and both methods return a boolean indicating success. ```typescript const loginSuccess = await repository.authentication.login('username', 'password') const logoutSuccess = await repository.authentication.logout() ``` -------------------------------- ### Deleting Content (@sensenet/client-core, TypeScript) Source: https://github.com/sensenet/sn-client/blob/develop/packages/sn-client-core/README.md Shows how to delete a content item using the repository.delete method. It requires specifying the content's path or ID and can optionally perform a permanent deletion. ```typescript const deleteResult = await repository.delete({ idOrPath: 'Root/Path/To/Content/To/Delete', permanent: true, }) ```