How to use @bentley/bentleyjs-core - 10 common examples

To help you get started, we’ve selected a few @bentley/bentleyjs-core examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github imodeljs / imodeljs / test-apps / agent-test-app / src / QueryAgent.ts View on Github external
private async _extractChangeSummary(changeSetId: string) {
        const accessToken: AccessToken = await this._tokenStore!.getAccessToken();
        if (!this._iModelDb) {
            // Open a new local briefcase of the iModel at the specified version
            this._iModelDb = await IModelDb.open(actx, accessToken, this._projectId!, this._iModelId!, OpenParams.pullOnly(AccessMode.Exclusive), IModelVersion.asOfChangeSet(changeSetId));
        } else {
            // Update the existing local briefcase of the iModel to the specified version
            await this._iModelDb.pullAndMergeChanges(actx, accessToken, IModelVersion.asOfChangeSet(changeSetId));
        }

        // Extract summary information about the current version of the briefcase/iModel into the change cache
        const changeSummaryIds: Id64String[] = await ChangeSummaryManager.extractChangeSummaries(actx, accessToken, this._iModelDb!, { currentVersionOnly: true });
        Logger.logTrace(QueryAgentConfig.loggingCategory, `Extracted summary information from change set "${changeSetId}"`);

        // Attach a change cache file to the iModel to enable querying the change summary
        ChangeSummaryManager.attachChangeCache(this._iModelDb);

        // Find the change summary that was just created
        assert(changeSummaryIds.length === 1);
        const changeSummary: ChangeSummary = ChangeSummaryManager.queryChangeSummary(this._iModelDb!, changeSummaryIds[0]);

        /*
        * Query the change summary to gather up all the content
        */
        const changeContent = { id: changeSummary.id, changeSet: changeSummary.changeSet, instanceChanges: {} };

        Logger.logTrace(QueryAgentConfig.loggingCategory, `   Description: ${changeSummary.changeSet.description}`);
        Logger.logTrace(QueryAgentConfig.loggingCategory, `   Push Date: ${new Date(changeSummary.changeSet.pushDate).toLocaleString()}`);
        Logger.logTrace(QueryAgentConfig.loggingCategory, `   User Created: ${changeSummary.changeSet.userCreated}`);
github imodeljs / imodeljs / test-apps / agent-test-app / src / QueryAgent.ts View on Github external
changeContent.instanceChanges = this._iModelDb!.withPreparedStatement("SELECT ECInstanceId FROM ecchange.change.InstanceChange WHERE Summary.Id=? ORDER BY ECInstanceId", (stmt: ECSqlStatement): any[] => {
            stmt.bindId(1, changeSummary.id);
            const instanceChanges = new Array();
            while (stmt.step() === DbResult.BE_SQLITE_ROW) {
                const row = stmt.getRow();

                const instanceChange: any = ChangeSummaryManager.queryInstanceChange(this._iModelDb!, Id64.fromJSON(row.id));
                switch (instanceChange.opCode) {
                    case ChangeOpCode.Insert: {
                        // Get the instance after the insert
                        const rows: any[] = this._iModelDb!.executeQuery(ChangeSummaryManager.buildPropertyValueChangesECSql(this._iModelDb!, instanceChange, ChangedValueState.AfterInsert));
                        assert(rows.length === 1);
                        instanceChange.after = rows[0];
                        break;
                    }
                    case ChangeOpCode.Update: {
                        // Get the instance before the update
                        let rows: any[] = this._iModelDb!.executeQuery(ChangeSummaryManager.buildPropertyValueChangesECSql(this._iModelDb!, instanceChange, ChangedValueState.BeforeUpdate));
                        assert(rows.length === 1);
                        instanceChange.before = rows[0];
                        // Get the instance after the update
                        rows = this._iModelDb!.executeQuery(ChangeSummaryManager.buildPropertyValueChangesECSql(this._iModelDb!, instanceChange, ChangedValueState.AfterUpdate));
                        assert(rows.length === 1);
github imodeljs / imodeljs / plugins / geo-photo / src / ProjectSharePhotoTree.ts View on Github external
public async updateTags(requestContext: AuthorizedClientRequestContext, contextId: GuidString, psFile: PSPhotoFile): Promise {
    try {
      const tags = await psFile.readTagsFromJpeg();
      if (tags === undefined) {
        Logger.logWarning(loggerCategory, "Jpeg does not have any geographic location", () => ({ ...psFile.psFile }));
        return undefined;
      }
      await this.saveTags(requestContext, contextId, psFile, tags);
      return tags;
    } catch (error) {
      // tslint:disable-next-line:no-console
      console.log(`Error ${error} attempting to read tags of ${psFile.name}`);
      return undefined;
    }
  }
github imodeljs / imodeljs / plugins / geo-photo / src / JpegTagReader.ts View on Github external
case 6:
          // console.log('Thumbnail image format is JPEG');
          if (thumbTags.has("JpegIFOffset") && thumbTags.has("JpegIFByteCount")) {
            // extract the thumbnail
            const tOffset = tiffStart + (thumbTags.get("JpegIFOffset") as number);
            const tLength = thumbTags.get("JpegIFByteCount") as number;

            if (tOffset + tLength > dataView.byteLength)
              Logger.logWarning(loggerCategory, "Cannot extract thumbnail blob");
            else
              thumbTags.set("blob", Buffer.from(dataView.buffer, tOffset, tLength));
          }
          break;

        case 1:
          Logger.logWarning(loggerCategory, "Thumbnail image format is TIFF, which is not implemented.");
          break;
        default:
          Logger.logWarning(loggerCategory, "Unknown thumbnail image format", () => ({ format: thumbTags.get("Compression") }));
      }
    } else if (thumbTags.get("PhotometricInterpretation") === 2) {
      Logger.logWarning(loggerCategory, "Thumbnail image format is RGB, which is not implemented.");
    }
    return thumbTags;
  }
github imodeljs / imodeljs / plugins / geo-photo / src / JpegTagReader.ts View on Github external
// Data format is ordinary JPEG format, starts from 0xFFD8 and ends by 0xFFD9. It seems that
    // JPEG format and 160x120pixels of size are recommended thumbnail format for Exif2.1 or later.

    if (thumbTags.has("Compression")) {
      // console.log('Thumbnail image found!');

      switch (thumbTags.get("Compression") as number) {
        case 6:
          // console.log('Thumbnail image format is JPEG');
          if (thumbTags.has("JpegIFOffset") && thumbTags.has("JpegIFByteCount")) {
            // extract the thumbnail
            const tOffset = tiffStart + (thumbTags.get("JpegIFOffset") as number);
            const tLength = thumbTags.get("JpegIFByteCount") as number;

            if (tOffset + tLength > dataView.byteLength)
              Logger.logWarning(loggerCategory, "Cannot extract thumbnail blob");
            else
              thumbTags.set("blob", Buffer.from(dataView.buffer, tOffset, tLength));
          }
          break;

        case 1:
          Logger.logWarning(loggerCategory, "Thumbnail image format is TIFF, which is not implemented.");
          break;
        default:
          Logger.logWarning(loggerCategory, "Unknown thumbnail image format", () => ({ format: thumbTags.get("Compression") }));
      }
    } else if (thumbTags.get("PhotometricInterpretation") === 2) {
      Logger.logWarning(loggerCategory, "Thumbnail image format is RGB, which is not implemented.");
    }
    return thumbTags;
  }
github imodeljs / imodeljs / core / backend / src / BriefcaseManager.ts View on Github external
private static openBriefcase(requestContext: AuthorizedClientRequestContext, contextId: GuidString, iModelId: GuidString, changeSetId: GuidString, pathname: string, openParams: OpenParams, briefcaseId: number): BriefcaseEntry | undefined {
    const nativeDb = new IModelHost.platform.DgnDb();
    const res = nativeDb.openIModel(pathname, openParams.openMode);
    if (DbResult.BE_SQLITE_OK !== res)
      throw new IModelError(res, `Cannot open briefcase at ${pathname}`, Logger.logError, loggerCategory, () => ({ iModelId, pathname, openParams }));

    const briefcase = new BriefcaseEntry(contextId, iModelId, changeSetId, pathname, openParams, briefcaseId);
    briefcase.setNativeDb(nativeDb); // Note: Sets briefcaseId, currentChangeSetId in BriefcaseEntry by reading the values from nativeDb
    assert(briefcase.isOpen);

    // Validate the briefcase
    let isValidBriefcase: boolean = true;
    if (briefcase.currentChangeSetId !== briefcase.targetChangeSetId) {
      if (openParams.syncMode === SyncMode.FixedVersion) {
        Logger.logError(loggerCategory, "Briefcase found is invalid (is not of required version). Deleting it to allow retries", () => briefcase.getDebugInfo());
        isValidBriefcase = false;
      } else {
        if (nativeDb.hasUnsavedChanges() || nativeDb.hasSavedChanges())
          Logger.logWarning(loggerCategory, "Briefcase found with local changes, but is not of required version. Ignoring required version", () => briefcase.getDebugInfo());
        else
          isValidBriefcase = false; // Invalidate the briefcase to refetch it
      }
    }
    if (briefcase.briefcaseId !== briefcaseId) {
      Logger.logError(loggerCategory, "Briefcase found is invalid (does not have the expected briefcase id). Deleting it to allow retries", () => ({ expectedBriefcaseId: briefcaseId, ...briefcase.getDebugInfo() }));
github imodeljs / imodeljs / core / backend / src / rpc-impl / IModelReadRpcImpl.ts View on Github external
public async getModelProps(tokenProps: IModelTokenProps, modelIdsList: Id64String[]): Promise {
    const iModelToken = IModelToken.fromJSON(tokenProps);
    const modelIds = new Set(modelIdsList);
    const iModelDb: IModelDb = IModelDb.find(iModelToken);
    const modelJsonArray: ModelProps[] = [];
    for (const id of modelIds) {
      try {
        // TODO: Change iModelDbModels.getModelJson to return a ModelProps object, rather than a string.
        const modelProps: any = JSON.parse(iModelDb.models.getModelJson(JSON.stringify({ id })));
        assert("modeledElement" in modelProps, "iModelDb.models.getModelJson must return a ModelProps object");
        modelJsonArray.push(modelProps);
      } catch (error) {
        if (modelIds.size === 1)
          throw error; // if they're asking for more than one model, don't throw on error.
      }
    }
    return modelJsonArray;
  }
github imodeljs / imodeljs / core / frontend / src / render / primitives / mesh / MeshBuilder.ts View on Github external
public addTriangle(triangle: Triangle): void {
    // Prefer to avoid adding vertices originating from degenerate triangles before we get here...
    assert(!triangle.isDegenerate);

    const onInsert = (_vk: TriangleKey) => this.mesh.addTriangle(triangle);
    this.triangleSet.insertKey(triangle, onInsert);
  }
}
github imodeljs / imodeljs / core / frontend / src / render / webgl / glsl / Clipping.ts View on Github external
function addClippingPlanes(prog: ProgramBuilder, maxClipPlanes: number) {
  assert(maxClipPlanes > 0);
  const frag = prog.frag;
  const vert = prog.vert;

  addEyeSpace(prog);
  prog.addUniform("u_numClips", VariableType.Int, (program) => {
    program.addGraphicUniform("u_numClips", (uniform, params) => {
      const doClipping = true; // set to false to visualize pre-shader culling of geometry...
      const numClips = (doClipping && params.target.hasClipVolume) ? params.target.clips.count : 0;
      assert(numClips > 0 || !doClipping);
      uniform.setUniform1i(numClips);
    });
  });

  addModelViewMatrix(vert);

  if (System.instance.capabilities.supportsTextureFloat) {
github imodeljs / imodeljs / core / ecschema-metadata / src / Exception.ts View on Github external
case ECObjectsStatus.InvalidEnumValue: return this._appendMessage("ECObjectsStatus.InvalidEnumValue");
      case ECObjectsStatus.InvalidModifier: return this._appendMessage("ECObjectsStatus.InvalidModifier");
      case ECObjectsStatus.InvalidMultiplicity: return this._appendMessage("ECObjectsStatus.InvalidMultiplicity");
      case ECObjectsStatus.InvalidPrimitiveType: return this._appendMessage("ECObjectsStatus.InvalidPrimitiveType");
      case ECObjectsStatus.InvalidSchemaItemType: return this._appendMessage("ECObjectsStatus.InvalidSchemaItemType");
      case ECObjectsStatus.InvalidStrength: return this._appendMessage("ECObjectsStatus.InvalidStrength");
      case ECObjectsStatus.InvalidStrengthDirection: return this._appendMessage("ECObjectsStatus.InvalidStrengthDirection");
      case ECObjectsStatus.InvalidRelationshipEnd: return this._appendMessage("ECObjectsStatus.InvalidRelationshipEnd");
      case ECObjectsStatus.InvalidType: return this._appendMessage("ECObjectsStatus.InvalidType");
      case ECObjectsStatus.MissingSchemaUrl: return this._appendMessage("ECObjectsStatus.MissingSchemaUrl");
      case ECObjectsStatus.UnableToLocateSchema: return this._appendMessage("ECObjectsStatus.UnableToLocateSchema");
      case ECObjectsStatus.ClassNotFound: return this._appendMessage("ECObjectsStatus.ClassNotFound");
      case ECObjectsStatus.SchemaContextUndefined: return this._appendMessage("ECObjectsStatus.SchemaContextUndefined");
      case ECObjectsStatus.DifferentSchemaContexts: return this._appendMessage("ECObjectsStatus.DifferentSchemaContexts");
      default:
        assert(false);
        /* istanbul ignore next */
        return this._appendMessage("Error " + this.errorNumber.toString());
    }
  }