<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Asad Bukhari on Medium]]></title>
        <description><![CDATA[Stories by Asad Bukhari on Medium]]></description>
        <link>https://medium.com/@asad_bukhari?source=rss-980e4cdd8af6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*-6HKyv7AFtLpMNMPXlsCHA.jpeg</url>
            <title>Stories by Asad Bukhari on Medium</title>
            <link>https://medium.com/@asad_bukhari?source=rss-980e4cdd8af6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 11:07:18 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@asad_bukhari/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Building a Local RAG Pipeline with Chroma, Jina Embeddings, and Mistral]]></title>
            <link>https://medium.com/@asad_bukhari/building-a-local-rag-pipeline-with-chroma-jina-embeddings-and-mistral-10b2f610ec4c?source=rss-980e4cdd8af6------2</link>
            <guid isPermaLink="false">https://medium.com/p/10b2f610ec4c</guid>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[mistral]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[chromadb]]></category>
            <category><![CDATA[ollama]]></category>
            <dc:creator><![CDATA[Asad Bukhari]]></dc:creator>
            <pubDate>Thu, 10 Jul 2025 09:09:46 GMT</pubDate>
            <atom:updated>2025-07-10T09:09:46.895Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Retrieval-Augmented Generation (RAG)</strong> is a powerful technique that goes beyond relying solely on what a model has been trained on. Instead, it retrieves relevant information from your own data sources and feeds it into the model at runtime. This makes the output more accurate, domain-specific, and grounded in your data — without the need to retrain the model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Dphhr4pi_UYZ4okOVP7v1Q.png" /><figcaption>RAG — Augementing context with external source</figcaption></figure><p>While cloud-based options exist, sometimes you just want something that runs <strong>fully offline</strong>, gives you <strong>complete control</strong>, and is <strong>more cost-effective</strong> — especially when working with sensitive data or running frequent queries.</p><p>In this post, I’ll walk you through how to set up a local RAG pipeline using:</p><ul><li><a href="https://www.trychroma.com/">ChromaDB</a> for vector storage and search</li><li>Jina Embeddings v2 for semantic encoding</li><li><a href="https://ollama.com/library/mistral">Mistral</a> via <a href="https://ollama.com/">Ollama</a> for local language generation</li><li><a href="https://www.python.org/downloads/">Python</a> for implementation</li></ul><p>Let’s start by getting Mistral running locally.</p><h3>Step 1: Pull and Run Mistral with Ollama</h3><p>First, install Ollama for your operating system.</p><p>Once installed, pull and run the <strong>Mistral</strong> model with:</p><pre>ollama pull mistral<br>ollama run mistral</pre><p>By default, Ollama exposes a local REST API at: <a href="http://localhost:11434/">http://localhost:11434</a></p><p>You can interact with Mistral using a POST request to:</p><pre>POST http://localhost:11434/api/generate</pre><p>This API accepts a JSON payload like:</p><pre>{<br>  &quot;model&quot;: &quot;mistral&quot;,<br>  &quot;prompt&quot;: &quot;Your question here&quot;,<br>  &quot;stream&quot;: false<br>}</pre><h3><strong>Step 2: Install Required Packages</strong></h3><p>Before running the code, make sure you have the necessary Python libraries installed:</p><pre>pip install sentence-transformers chromadb requests</pre><h3>Step 3: Implementation</h3><p>With Mistral running, let’s build the rest of the RAG pipeline. Create a file RAG_Sample.py</p><pre>import chromadb<br>from sentence_transformers import SentenceTransformer<br>import requests</pre><p>This function sends your query and context to the Mistral model running locally.</p><pre>def ask_mistral(prompt: str) -&gt; str:<br>    response = requests.post(<br>        &quot;http://localhost:11434/api/generate&quot;,<br>        json={&quot;model&quot;: &quot;mistral&quot;, &quot;prompt&quot;: prompt, &quot;stream&quot;: False}<br>    )<br>    return response.json().get(&quot;response&quot;, &quot;&quot;).strip()</pre><p>Ingest Documents into Chroma after generating embeddings.</p><pre>chroma_client = chromadb.PersistentClient(path=&quot;./chroma_db&quot;)<br>collection = chroma_client.get_or_create_collection(name=&quot;jina_docs&quot;)<br><br>model = SentenceTransformer(&quot;jinaai/jina-embeddings-v2-base-en&quot;, trust_remote_code=True)<br>model.max_seq_length = 1024<br><br>texts = [<br>    &quot;After Obama, Jeo Biden was the president of United State ?&quot;,<br>    &quot;After Jeo Biden, Donald Trump is the President of the United States.&quot;,<br>    &quot;Till today July 03, 2025 Donald Trump is still the president.&quot;,<br>]<br><br>embeddings = model.encode(texts).tolist()<br>ids = [f&quot;doc_{i}&quot; for i in range(len(texts))]<br><br>collection.add(<br>    documents=texts,<br>    embeddings=embeddings,<br>    ids=ids<br>)</pre><p>We run a semantic search and flatten the result set to prepare the context.<br>Then Build a Prompt with context and get the answer.</p><pre>query = &quot;List the last three presidents of United States?&quot;<br>query_embedding = model.encode([query]).tolist()<br><br>results = collection.query(query_embeddings=query_embedding, n_results=2)<br>retrieved_docs_lists = results[&quot;documents&quot;]<br>all_docs = sum(retrieved_docs_lists, [])  # flatten<br><br>context = &quot;\n&quot;.join(all_docs)<br><br>prompt = f&quot;Answer the question using the context below:\n\nContext:\n{context}\n\nQuestion: {query}\nAnswer:&quot;<br>answer = ask_mistral(prompt)<br><br>print(f&quot;\nPrompt: {query}\n&quot;)<br>print(f&quot;\nAnswer: {answer}\n&quot;)</pre><p>Run it using Python</p><pre>python.exe RAG_Sample.py</pre><p>You will get the output like:</p><pre>Prompt: List the last three presidents of United States?<br><br>Answer: Barack Obama, Joe Biden, and Donald Trump (in that order)<br>are the last three Presidents of the United States</pre><ul><li><strong>No internet dependency</strong></li><li><strong>Fully local</strong> and private setup</li><li><strong>Fast vector search</strong> with Chroma</li><li><strong>Strong open-source LLM</strong> via Mistral</li></ul><p>This is a great starting point for custom bots, documentation search, or domain-specific Q&amp;A systems.</p><h3>Conclusion</h3><p>RAG doesn’t have to be complicated — or cloud-based. With tools like Chroma, Jina embeddings, and Mistral via Ollama, you can build a fast, flexible, and <strong>fully local AI assistant</strong> in just a few lines of Python.</p><p>For complete source code: <a href="https://github.com/asadhasnain/AI/tree/master/RAG">https://github.com/asadhasnain/AI/tree/master/RAG</a></p><p>If you’re experimenting with open-source LLM stacks, this is a solid foundation.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=10b2f610ec4c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reading Element Properties in iTwin.js with getElementProps]]></title>
            <link>https://medium.com/@asad_bukhari/reading-element-properties-in-itwin-js-with-getelementprops-f2443696014c?source=rss-980e4cdd8af6------2</link>
            <guid isPermaLink="false">https://medium.com/p/f2443696014c</guid>
            <category><![CDATA[bentley]]></category>
            <category><![CDATA[digital-twin]]></category>
            <category><![CDATA[itwin-platform]]></category>
            <category><![CDATA[itwinjs]]></category>
            <dc:creator><![CDATA[Asad Bukhari]]></dc:creator>
            <pubDate>Mon, 30 Jun 2025 10:47:51 GMT</pubDate>
            <atom:updated>2025-06-30T10:47:51.574Z</atom:updated>
            <content:encoded><![CDATA[<p>Working with iModels often requires not just querying element IDs, but also diving deeper into the <strong>metadata and properties</strong> attached to those elements. While ECSqlReader lets you stream elements from a BriefcaseDb, using getElementProps() allows you to <strong>read full properties</strong> of any element.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/292/0*RF1VlhqzZ7ckhsdm.png" /></figure><p>In this post, we’ll explore the use of BriefcaseDb.elements.getElementProps.</p><p>If you’re new to working with briefcases or querying elements using ECSqlReader, I recommend checking out my previous post:</p><p><a href="https://medium.com/@asad_bukhari/querying-elements-in-itwin-js-using-ecsqlreader-99fd29c09b17">Querying Elements in iTwin.js Using ECSqlReader</a></p><h3>Step-by-Step Guide</h3><p>We assume you already have an initialized BriefcaseDbexplained in my <a href="https://medium.com/@asad_bukhari/itwin-js-node-js-application-handling-imodel-briefcases-with-ease-3e07bb65344e">iTwin.js: Node.js Application Handling iModel Briefcases with Ease</a>. how you can query all Element IDs from the BisCore.Element and then read properties using getElementProps:</p><pre>const readElements = async (briefcaseDb: BriefcaseDb): Promise&lt;void&gt; =&gt; {<br>  const query = `SELECT ECInstanceId FROM BisCore.Element`; <br>  const ecSqlReader: ECSqlReader = briefcaseDb.createQueryReader(query);<br><br>  while (await ecSqlReader.step()) {<br>    const elementId = ecSqlReader.current.ECInstanceId;<br><br>    // Get properties of the current element<br>    const elementProps = briefcaseDb.elements.getElementProps(elementId);<br><br>    console.log(`Element ${elementId}:`, JSON.stringify(elementProps, null, 2));<br>  }<br>}</pre><h3>Conclusion</h3><p>getElementProps is a lightweight, flexible way to inspect element metadata in your iModel. We just paired it with ECSqlReader for efficient iteration over large datasets.</p><p>Find the complete source code on GitHub: <a href="https://github.com/asadhasnain/iTwinjsStarterKit/tree/master/CRUD/ElementProperties">iTwinjsStarterKit</a></p><h3>References:</h3><p><a href="https://www.itwinjs.org/reference/core-backend/imodels/imodeldb/imodeldb.elements/getelementprops/">iTwin.js: getElementProps</a></p><p><a href="https://www.itwinjs.org/reference/core-backend/imodels/imodeldb/imodeldb.elements/trygetelementprops/">iTwin.js: tryGetElementProps</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f2443696014c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Querying Elements in iTwin.js Using ECSqlReader]]></title>
            <link>https://medium.com/@asad_bukhari/querying-elements-in-itwin-js-using-ecsqlreader-99fd29c09b17?source=rss-980e4cdd8af6------2</link>
            <guid isPermaLink="false">https://medium.com/p/99fd29c09b17</guid>
            <category><![CDATA[itwinjs]]></category>
            <category><![CDATA[digital-twin-services]]></category>
            <category><![CDATA[itwin-platform]]></category>
            <category><![CDATA[digital-twin-technology]]></category>
            <category><![CDATA[digital-twin]]></category>
            <dc:creator><![CDATA[Asad Bukhari]]></dc:creator>
            <pubDate>Fri, 27 Jun 2025 12:14:49 GMT</pubDate>
            <atom:updated>2025-06-27T12:16:15.534Z</atom:updated>
            <content:encoded><![CDATA[<p>In this post, we’ll walk through how to use <a href="https://www.itwinjs.org/reference/core-common/imodels/ecsqlreader/">ECSqlReader</a>to query Element IDs from an iModel using a BriefcaseDb. If you&#39;re new to working with briefcases, make sure to check out my earlier post: <a href="https://medium.com/@asad_bukhari/itwin-js-node-js-application-handling-imodel-briefcases-with-ease-3e07bb65344e">iTwin.js: Node.js Application Handling iModel Briefcases with Ease</a>. Here, we’ll build on that foundation and focus specifically on how to use ECSqlReader for querying element data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/292/1*-LET0NsofKPN20gFhJ2vDQ.png" /></figure><h3>What is ECSqlReader?</h3><p>ECSqlReader allows you to run EC SQL queries directly against your BriefcaseDb. It provides a lightweight cursor that can iterate over results <strong>asynchronously</strong>, making it suitable for large datasets without loading everything into memory.</p><h3>Step-by-Step Guide</h3><p>We assume you already have an initialized BriefcaseDbexplained in my <a href="https://medium.com/@asad_bukhari/itwin-js-node-js-application-handling-imodel-briefcases-with-ease-3e07bb65344e">iTwin.js: Node.js Application Handling iModel Briefcases with Ease</a>. how you can query all Element IDs from the BisCore.Element schema:</p><pre>const queryElements = async (briefcaseDb: BriefcaseDb): Promise&lt;Id64String[]&gt; =&gt; {<br>  const query = `SELECT ECInstanceId FROM BisCore.Element`;<br>  const elementIds: Id64String[] = [];<br><br>  const ecSqlReader: ECSqlReader = briefcaseDb.createQueryReader(query);<br><br>  while (await ecSqlReader.step()) {<br>    elementIds.push(ecSqlReader.current.ECInstanceId);<br>  }<br><br>  return elementIds;<br>}</pre><ul><li>createQueryReader(query) creates a cursor to read rows one at a time.</li><li>ecSqlReader.step() advances the cursor. Each call loads the next row.</li><li>ecSqlReader.current provides access to the current row&#39;s values—in this case, ECInstanceId.</li><li>We collect all IDs into an array and return them.</li></ul><h3>Conclusion</h3><p>ECSqlReader is a powerful and flexible way to query elements directly from an iModel. It gives you better control, especially when working with large data or custom queries.</p><p>If you’re already using BriefcaseDb, adding ECSqlReader to your toolkit can help you build more efficient and tailored solutions.</p><p>Find the complete source code on GitHub: <a href="https://github.com/asadhasnain/iTwinjsStarterKit/tree/master/CRUD/QueryElements">iTwinjsStarterKit</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=99fd29c09b17" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Speed Up Your iTwin App Development with Ready-to-Use Layouts]]></title>
            <link>https://medium.com/@asad_bukhari/speed-up-your-itwin-app-development-with-ready-to-use-layouts-590df01579f4?source=rss-980e4cdd8af6------2</link>
            <guid isPermaLink="false">https://medium.com/p/590df01579f4</guid>
            <category><![CDATA[digital-twin]]></category>
            <category><![CDATA[itwinjs]]></category>
            <category><![CDATA[itwin-platform]]></category>
            <category><![CDATA[bentley-systems]]></category>
            <dc:creator><![CDATA[Asad Bukhari]]></dc:creator>
            <pubDate>Thu, 24 Apr 2025 10:28:36 GMT</pubDate>
            <atom:updated>2025-04-24T10:28:36.362Z</atom:updated>
            <content:encoded><![CDATA[<p>When you’re building iTwin-based applications, chances are you care about two things early on:</p><ol><li>Clean, maintainable layouts</li><li>Consistency in layout</li><li>Not reinventing the UI skeleton every time</li></ol><p>That’s where <a href="https://www.npmjs.com/package/@itwin/itwinui-layouts-react">@itwin/itwinui-layouts-react</a> fits perfectly. It gives you predefined regions—header, side nav, content, tools, bottom bar—so you can focus on delivering features, not fixing layout bugs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-vdbuM5iGUIGE8m2qEizgA.png" /><figcaption>iTwinUI Application Layout Sample</figcaption></figure><p>In this quick post, I’ll walk you through just how easy it is to spin up a modern layout using iTwinUI components.</p><h3>Create a React project</h3><p>If you haven’t already, set up a React project. You can use tools like <a href="https://vitejs.dev/">Vite</a> for a fast development experience. For more details you can refer to blog <a href="https://medium.com/@asad_bukhari/kickstart-your-itwin-js-frontend-with-itwinui-276d9ae03977">Kickstart Your iTwin.js Frontend with iTwinUI</a></p><pre>npm create vite@latest itwinui-sample-layout -- --template react-ts</pre><pre>cd itwinui-sample-layout<br>npm install</pre><p>Delete all the tsx and css files under source folder.</p><h3>Install iTwinUI packages</h3><p>Run the following command to add @itwin/itwinui-react package to your project (I am also installing @itwin/itwinui-icons-react just to use in my sample):</p><pre>npm install @itwin/itwinui-react @itwin/itwinui-layouts-react @itwin/itwinui-icons-react</pre><h3>Setup the Layout</h3><p>This is a minimal layout setup from @itwin/itwinui-layouts-react that works well as a starting point for most iTwin apps.</p><pre>// App.tsx<br>import &#39;@itwin/itwinui-layouts-css/styles.css&#39;;<br>import { PageLayout } from &#39;@itwin/itwinui-layouts-react&#39;;<br>import { Button, Surface } from &#39;@itwin/itwinui-react&#39;;<br><br>import MainHeader from &#39;./Header/MainHeader&#39;;<br>import { SideNavigationBar } from &#39;./Navigation/SideNavigationBar&#39;;<br>import ThemeButton from &#39;./Theme/ThemeButton&#39;;<br><br>export default function App() {<br>  return (<br>    &lt;PageLayout&gt;<br>      &lt;PageLayout.Header&gt;<br>        &lt;MainHeader /&gt;<br>      &lt;/PageLayout.Header&gt;<br><br>      &lt;PageLayout.SideNavigation&gt;<br>        &lt;SideNavigationBar /&gt;<br>      &lt;/PageLayout.SideNavigation&gt;<br><br>      &lt;PageLayout.Content padded&gt;<br>        &lt;PageLayout.TitleArea&gt;<br>          &lt;div&gt;My iTwin Application&lt;/div&gt;<br>        &lt;/PageLayout.TitleArea&gt;<br><br>        &lt;PageLayout.ToolsArea<br>          left={&lt;Button&gt;Edit&lt;/Button&gt;}<br>          right={&lt;Button&gt;Draw&lt;/Button&gt;}<br>        /&gt;<br><br>        &lt;Surface elevation={1}&gt;<br>          &lt;div&gt;Content&lt;/div&gt;<br>        &lt;/Surface&gt;<br>      &lt;/PageLayout.Content&gt;<br><br>      &lt;PageLayout.BottomBar&gt;<br>          &lt;div&gt;Buttom Bar&lt;/div&gt;<br>      &lt;/PageLayout.BottomBar&gt;<br>    &lt;/PageLayout&gt;<br>  );<br>}</pre><p>This layout covers a full app scaffold with following regions:</p><ul><li><strong>Header</strong> – Where you drop in your iTwin, iModel , and profile dropdown.</li><li><strong>SideNavigation</strong> – A vertical nav for switching between difference services.</li><li><strong>Content</strong> – The heart of your app: it holds your title, tool buttons, and main surface.</li><li><strong>BottomBar</strong> – Great for things like theme toggles, build info, or support links.</li></ul><p><strong>Check out the complete source code here: </strong><a href="https://github.com/asadhasnain/iTwinjsStarterKit/tree/master/UI/itwinui-layouts/layout-sample-page">iTwin Layout Sample on GitHub</a></p><p><strong>Conclusion</strong></p><p>Layout is usually the first place we trip over ourselves in frontend work. With @itwin/itwinui-layouts-react, the skeleton is taken care of. You&#39;re free to focus on the twin data, business rules, and tools that matter.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=590df01579f4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kickstart Your iTwin.js Frontend with iTwinUI]]></title>
            <link>https://medium.com/@asad_bukhari/kickstart-your-itwin-js-frontend-with-itwinui-276d9ae03977?source=rss-980e4cdd8af6------2</link>
            <guid isPermaLink="false">https://medium.com/p/276d9ae03977</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[itwinjs]]></category>
            <category><![CDATA[digital-twin]]></category>
            <category><![CDATA[bentley-systems]]></category>
            <dc:creator><![CDATA[Asad Bukhari]]></dc:creator>
            <pubDate>Wed, 16 Apr 2025 13:30:32 GMT</pubDate>
            <atom:updated>2025-04-16T13:30:32.060Z</atom:updated>
            <content:encoded><![CDATA[<p>When building iTwin.js-based frontend applications, <strong>iTwinUI</strong> is hands down the best UI library available. It empowers developers to focus on solving real problems, while taking care of consistent styling, accessibility, theming, and responsive layout.</p><p>In this blog post, we’ll walk step-by-step through setting up a React project using iTwinUI. By the end, you’ll have a styled app with a theme switcher and ready-to-use components.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/396/1*PcO0a3G8v6JsNDTUQFqg-A.png" /></figure><p>In my future blogs, I’ll be using iTwinUI extensively — so let’s explore it together from the start.</p><h3>Step by Step: Setup iTwinUI and React</h3><h4>1. Create a React project</h4><p>If you haven’t already, set up a React project. You can use tools like <a href="https://vitejs.dev/">Vite</a> for a fast development experience:</p><pre>npm create vite@latest itwinui-basics -- --template react-ts<br><br>cd itwinui-basics<br>npm install</pre><p>Delete all the tsx and css files under source folder.</p><h4>2. Install iTwinUI packages</h4><p>Run the following command to add @itwin/itwinui-react package to your project (I am also installing @itwin/itwinui-icons-react just to use in my sample):</p><pre>npm install @itwin/itwinui-react @itwin/itwinui-icons-react</pre><h4>3. Create a main entry point (main.tsx)</h4><pre>// main.tsx<br>import * as React from &#39;react&#39;;<br>import { createRoot } from &#39;react-dom/client&#39;;<br>import &#39;@itwin/itwinui-react/styles.css&#39;;<br>import &#39;./styles.css&#39;;<br>import { AppWithWrapper } from &#39;./AppWithWrapper&#39;;<br><br>const rootElement = document.getElementById(&#39;root&#39;)!;<br>const root = createRoot(rootElement);<br><br>root.render(<br>  &lt;React.StrictMode&gt;<br>    &lt;AppWithWrapper /&gt;<br>  &lt;/React.StrictMode&gt;,<br>);</pre><p>We import the iTwinUI styles, our own styles, and wrap the app in AppWithWrapper.</p><h4>4. Add Styles (styles.css)</h4><p>This sets a clean baseline and ensures the toggle button is always accessible.</p><pre>/* styles.css */<br>* {<br>  box-sizing: border-box;<br>}<br><br>body {<br>  margin: 0;<br>}<br><br>.theme-toggle {<br>  position: fixed;<br>  top: 0;<br>  right: 0;<br>}<br><br>.app-wrapper {<br>  height: 100dvh;<br>  padding: 2rem 1rem;<br>  overflow: auto;<br>}</pre><h4>5. Theme Switcher Wrapper (AppWithWrapper.tsx)</h4><p>This component wraps your entire application with a <strong>theme toggle</strong> — super handy for dark mode lovers!</p><pre>// AppWithWrapper.tsx<br>import { ThemeProvider, IconButton } from &#39;@itwin/itwinui-react&#39;;<br>import * as React from &#39;react&#39;;<br>import App from &#39;./App&#39;;<br><br>export const AppWithWrapper = () =&gt; {<br>  const [theme, setTheme] = React.useState&lt;&#39;light&#39; | &#39;dark&#39;&gt;(() =&gt;<br>    matchMedia?.(&#39;(prefers-color-scheme: dark)&#39;).matches ? &#39;dark&#39; : &#39;light&#39;<br>  );<br><br>  return (<br>    &lt;ThemeProvider className=&#39;app-wrapper&#39; theme={theme}&gt;<br>      &lt;IconButton<br>        className=&#39;theme-toggle&#39;<br>        styleType=&#39;borderless&#39;<br>        aria-label=&#39;Toggle theme&#39;<br>        onClick={() =&gt; setTheme(theme === &#39;light&#39; ? &#39;dark&#39; : &#39;light&#39;)}<br>      &gt;<br>        {theme === &#39;light&#39; ? &#39;🌞&#39; : &#39;🌙&#39;}<br>      &lt;/IconButton&gt;<br>      &lt;App /&gt;<br>    &lt;/ThemeProvider&gt;<br>  );<br>};</pre><h4>5. Use iTwinUI Components (App.tsx)</h4><p>This App component includes several iTwinUI common components: a button, checkbox, radio buttons, an input field, and a search box — all ready to go with iTwinUI’s styling.</p><pre>// App.tsx<br>import { Button, Checkbox, LabeledInput, Radio, SearchBox } from &#39;@itwin/itwinui-react&#39;;<br><br>export default function App() {<br>  return (<br>    &lt;&gt;<br>      &lt;Button&gt;Default&lt;/Button&gt;<br>      &lt;Checkbox label=&#39;Checkbox&#39; defaultChecked /&gt;<br>      &lt;Radio name=&#39;Options&#39; label=&#39;Option 1&#39; defaultChecked /&gt;<br>      &lt;Radio name=&#39;Options&#39; label=&#39;Option 2&#39; /&gt;<br>      &lt;LabeledInput label=&#39;Label&#39; placeholder=&#39;Placeholder&#39; message=&#39;Hint message&#39; /&gt;<br>      &lt;SearchBox inputProps={{ placeholder: &#39;Search...&#39; }} /&gt;<br>    &lt;/&gt;<br>  );<br>}</pre><h4>6. Run and build</h4><p>Build and start the app.</p><pre>npm run build<br>npm run start</pre><h4>Conclusion</h4><p>That’s all you need to get started with iTwinUI! With minimal setup, you get a polished, professional UI that adheres to accessibility and design best practices. Here is the complete sample code: <a href="https://github.com/asadhasnain/iTwinjsStarterKit/tree/master/UI/itwinui-basics">https://github.com/asadhasnain/iTwinjsStarterKit/tree/master/UI/itwinui-basics</a></p><p>This is just the beginning — in future posts, I’ll explore more advanced layouts, form handling, dialog components, and integrating iTwin.js tools.</p><p>Stay tuned! And happy coding with iTwinUI.</p><h4>References:</h4><p><a href="https://itwinui.bentley.com/">https://itwinui.bentley.com/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=276d9ae03977" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[iTwin.js: Node.js Application Handling iModel Briefcases with Ease]]></title>
            <link>https://medium.com/@asad_bukhari/itwin-js-node-js-application-handling-imodel-briefcases-with-ease-3e07bb65344e?source=rss-980e4cdd8af6------2</link>
            <guid isPermaLink="false">https://medium.com/p/3e07bb65344e</guid>
            <category><![CDATA[itwin-platform]]></category>
            <category><![CDATA[bentley-systems]]></category>
            <category><![CDATA[digital-twin]]></category>
            <category><![CDATA[digital-twin-technology]]></category>
            <category><![CDATA[itwinjs]]></category>
            <dc:creator><![CDATA[Asad Bukhari]]></dc:creator>
            <pubDate>Thu, 27 Mar 2025 10:28:20 GMT</pubDate>
            <atom:updated>2025-03-27T10:28:48.004Z</atom:updated>
            <content:encoded><![CDATA[<p>In this blog, we will explore how to build a Node.js application that using iTwin.js to download and process a <strong>briefcase</strong>. This guide is designed for developers looking to work with large-scale infrastructure data while maintaining synchronization across different users and systems.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/292/1*W1JNq5Iq1uEhvtfm0TxDzA.png" /><figcaption>iTwin.js Node Application</figcaption></figure><h3>Understanding Briefcases in iTwin.js</h3><p>A <strong>Briefcase</strong> in iTwin.js represents a local copy of an iModel, allowing editing and synchronization with the <strong>iModel Hub</strong>.</p><p>For mode details about Digital Twin terms refer to my blog <a href="https://medium.com/@asad_bukhari/understanding-terms-itwin-itwin-plaform-imodelhub-imodel-briefcases-and-changesets-a2b63166dc32">Understanding terms iTwin, iTwin Plaform, iModelHub, iModel, Briefcases, and Changesets</a></p><h3>Step-by-Step Guide</h3><h3>Step 1: Setup a Sample Node.js Project</h3><p>Set up a sample Node.js Project by using the steps listed in my blog <a href="https://medium.com/@asad_bukhari/authorizing-with-itwin-js-using-node-cli-10b4746fed31">Authorizing Node CLI using iTwin.js.</a></p><h3>Step 2: Create iTwin and iModel</h3><ol><li>Go to <a href="https://developer.bentley.com/"><strong>Bentley Developer Portal</strong> </a>&gt; <strong>Profile</strong> &gt; <strong>My iTwins</strong>.</li><li>Create a new <strong>iTwin Project</strong>, or use an already existing one.</li><li>After creating the iTwin project, create an <strong>iModel</strong>.</li><li>You can select an existing <strong>Bentley Sample iModel</strong> or create an <strong>Empty iModel</strong>. In this example, we will use the <strong>Stadium iModel</strong> template.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*QNh0gtrZceN4D3nG889pyQ.png" /><figcaption>Create Stadium Sample iModel</figcaption></figure><p>Once the iModel is created, use the <strong>Copy IDs</strong> option to copy the iTwin and iModel ID.</p><h3>Step 3: Configure the .env File</h3><p>Before running the application, create a .env file and define the necessary configurations:</p><pre>LOG_LEVEL=Error<br>CLIENT_ID=[Set your client id]<br>ITWIN_ID=[Set your iTwin id]<br>IMODEL_ID=[Set your iModel id]<br>MY_SERVICE_TMP_DIR=./tmp</pre><h3>Step 4: Implement Logging (Optional)</h3><p>Logging is an essential part of debugging and monitoring application performance. The following script initializes logging in the backend:</p><pre>//BackendLogger.ts<br><br>import { Logger, LoggerLevelsConfig } from &quot;@itwin/core-bentley&quot;;<br>import config from &quot;./Logger.config.json&quot;;<br><br>export function initializeLogging(logLevel: string = &quot;Error&quot;): void {<br>  Logger.initializeToConsole();<br><br>  // Configure log levels by category<br>  if (&quot;loggerConfig&quot; in config) {<br>    config.loggerConfig.defaultLevel = logLevel;<br>    Logger.validateProps(config.loggerConfig);<br>    Logger.configureLevels(config.loggerConfig as LoggerLevelsConfig);<br>  }<br>}</pre><h3>Step 5: Download and Read Elements</h3><p>Create/update the index.ts file using BriefcaseManager, IModelHost, and BriefcaseDb from @itwin/core-backend.</p><p>Every iTwin.js backend must call <a href="https://www.itwinjs.org/reference/core-backend/imodelhost/imodelhost/startupstatic/">IModelHost.startup</a>. <a href="https://www.itwinjs.org/learning/backend/imodelhost/">IModelHost</a> initializes the necessary components to access iModels and serve iTwin.js service.</p><p>Using <a href="https://www.itwinjs.org/reference/core-backend/imodels/briefcasemanager/downloadbriefcasestatic/">BriefcaseManager.downloadBriefcase</a>, download a new briefcase from iModelHub for the supplied iModelId.</p><p>Once the briefcase is downloaded, use <a href="https://www.itwinjs.org/reference/core-backend/imodels/briefcasedb/openstatic/">BriefcaseDb.open</a> to open it and list all the elements inside.</p><p>Here is the complete code snippet, reading .env file, intializing logger, authorizing, start iModelHost, downloading and listing the elements.</p><pre>/**<br> * @file index.ts<br> * @description This file initializes the iModelHost, downloads a briefcase, processes its elements, and releases the briefcase.<br> * It uses environment variables for configuration and performs authentication using NodeCliAuthorizationClient.<br> */<br><br>import { BriefcaseDb, BriefcaseManager, IModelHost, KnownLocations } from &quot;@itwin/core-backend&quot;;<br>import { Logger } from &quot;@itwin/core-bentley&quot;;<br>import { RequestNewBriefcaseProps } from &quot;@itwin/core-common&quot;;<br>import { BackendIModelsAccess } from &quot;@itwin/imodels-access-backend&quot;;<br>import { NodeCliAuthorizationClient } from &quot;@itwin/node-cli-authorization&quot;;<br>import * as dotenv from &quot;dotenv&quot;;<br>import path from &quot;path&quot;;<br>import { initializeLogging } from &quot;./BackendLogger&quot;;<br><br>// Load environment variables from .env file<br>dotenv.config();<br><br>const clientId = process.env.CLIENT_ID || &quot;&quot;;<br>const iTwinId = process.env.ITWIN_ID || &quot;&quot;;<br>const iModelId = process.env.IMODEL_ID || &quot;&quot;;<br>const LogLevel = process.env.LOG_LEVEL || &quot;Error&quot;;<br><br>if (!clientId || !iTwinId || !iModelId) {<br>  throw new Error(&quot;Must specify a valid configuration with CLIENT_ID, ITWIN_ID, and IMODEL_ID&quot;);<br>}<br><br>const authClient = new NodeCliAuthorizationClient({ clientId, scope: &quot;itwin-platform&quot; });<br>let accessToken: string = &quot;&quot;;<br><br>/**<br> * Initializes the iModelHost with the specified cache directory and authorization client.<br> * @async<br> * @function startupIModelHost<br> * @returns {Promise&lt;void&gt;}<br> */<br>const startupIModelHost = async (): Promise&lt;void&gt; =&gt; {<br>  let cacheDir = process.env.MY_SERVICE_CACHE_DIR;<br>  if (!cacheDir) {<br>    const tempDir = process.env.MY_SERVICE_TMP_DIR || KnownLocations.tmpdir;<br>    cacheDir = path.join(tempDir, &quot;iModelJs_cache&quot;);<br>  }<br><br>  await IModelHost.startup({ cacheDir, authorizationClient: authClient, hubAccess: new BackendIModelsAccess() });<br>};<br><br>/**<br> * Downloads a briefcase, processes its elements, and releases the briefcase.<br> * @async<br> * @function downloadAndProcessBriefcase<br> * @returns {Promise&lt;void&gt;}<br> */<br>const downloadAndProcessBriefcase = async (): Promise&lt;void&gt; =&gt; {<br>  const requestNewBriefcaseProps: RequestNewBriefcaseProps = {<br>    iTwinId: iTwinId, <br>    iModelId: iModelId,<br>  };<br><br>  const localBriefcaseProps = await BriefcaseManager.downloadBriefcase(requestNewBriefcaseProps);<br>  const briefcaseDb = await BriefcaseDb.open({ fileName: localBriefcaseProps.fileName, readonly: true });<br><br>  Logger.logInfo(&quot;Backend.BriefcaseManager&quot;, `Opened Briefcase Id: ${briefcaseDb.briefcaseId}`);<br><br>  const idSet = briefcaseDb.queryEntityIds({ from: &quot;BisCore.Element&quot; });<br><br>  idSet.forEach(id =&gt; {<br>    const element = briefcaseDb.elements.getElement(id);<br>    Logger.logInfo(&quot;Backend.BriefcaseManager&quot;, `Element Id: ${element.id}, ClassName: ${element.className}`);<br>  });<br><br>  briefcaseDb.close();<br>  await BriefcaseManager.releaseBriefcase(accessToken, localBriefcaseProps);<br>};<br><br>/**<br> * Main function to execute the process of signing in, initializing logging, starting up iModelHost,<br> * downloading and processing the briefcase, and signing out.<br> * @async<br> * @function main<br> * @returns {Promise&lt;void&gt;}<br> */<br>(async (): Promise&lt;void&gt; =&gt; {<br>  try {<br>    console.log(&quot;Starting browser based sign in...&quot;);<br><br>    await authClient.signIn();  // Sign in to iTwin.js<br>    accessToken = await authClient.getAccessToken();<br><br>    initializeLogging(LogLevel);<br>    await startupIModelHost();<br>    await downloadAndProcessBriefcase();<br><br>    await authClient.signOut(); // Sign out of iTwin.js<br>  } catch (error) {<br>    console.error(&quot;Error during execution:&quot;, error);<br>  }<br>})();</pre><h3>Conclusion</h3><p>In this blog, we walked through the setup and execution of a Node.js application that interacts with iTwin.js to download and process a briefcase. Find the complete source code on GitHub: <a href="https://github.com/asadhasnain/iTwinjsStarterKit/tree/master/Connections/Backend/BriefcaseManager">iTwinjsStarterKit</a></p><p>This serves as a foundational guide for developers looking to build scalable infrastructure applications using iTwin.js.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3e07bb65344e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding terms iTwin, iTwin Plaform, iModelHub, iModel, Briefcases, and Changesets]]></title>
            <link>https://medium.com/@asad_bukhari/understanding-terms-itwin-itwin-plaform-imodelhub-imodel-briefcases-and-changesets-a2b63166dc32?source=rss-980e4cdd8af6------2</link>
            <guid isPermaLink="false">https://medium.com/p/a2b63166dc32</guid>
            <category><![CDATA[itwin]]></category>
            <category><![CDATA[itwin-platform]]></category>
            <dc:creator><![CDATA[Asad Bukhari]]></dc:creator>
            <pubDate>Fri, 14 Mar 2025 13:10:11 GMT</pubDate>
            <atom:updated>2025-03-19T06:41:39.555Z</atom:updated>
            <content:encoded><![CDATA[<p>When working with iTwin.js, it’s essential to grasp few core concepts that form the foundation of digital twin ecosystem. In this post, we’ll explore six fundamental terms: <strong>iTwin</strong>,<strong> iTwin Platform</strong>, <strong>iModelHub</strong>, <strong>iModel</strong>, <strong>Briefcases</strong>, and <strong>Changesets</strong>.</p><h3>1. What is an iTwin?</h3><p>An <strong>iTwin</strong> is Bentley’s standard for infrastructure digital twins. It is a digital representation of a physical asset or system, such as a building, bridge, or rail network. An iTwin enables collaboration by aggregating data from multiple sources, including design applications, IoT sensors, and reality data etc.</p><p>Think of an iTwin as a <strong>collection or list of data sources</strong> relevant to a project. Some of these data sources, are hosted on the <strong>iTwin Platform</strong>, while others may reside in external systems.</p><h3>2. What is the iTwin Platform?</h3><p>The <strong>iTwin Platform</strong> is a cloud-based ecosystem of APIs, tools, and services designed to create and manage digital twins, known as <strong>iTwins</strong>. The iTwin Platform helps you unlock the full potential of your asset’s digital twin.</p><h3>3. What is an iModel?</h3><p>An <strong>iModel</strong> is a <strong>distributed relational database</strong>, designed to support a common cloud format with a schema defined by <a href="https://www.itwinjs.org/bis/guide/intro/overview/"><strong>BIS (Base Infrastructure Schema)</strong></a>. It is designed to hold information about a single infrastructure asset. Unlike traditional CAD or BIM files, iModels support incremental updates and enable collaborative workflows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/723/1*D-Sm9T-nThF8dncPILdaZQ.png" /><figcaption>iModel — data sync from different sources/formats</figcaption></figure><p><strong>Key features of iModels:</strong></p><ul><li><strong>Lightweight and efficient:</strong> Designed for optimal cloud storage and retrieval.</li><li><strong>Immutable history:</strong> Every modification is recorded as a versioned change, maintaining a comprehensive audit trail.</li></ul><h3>4. What is iModelHub?</h3><p><strong>iModelHub</strong> is a cloud service that serves as the backbone for iTwin.js applications. It coordinates concurrent access to iModels and manages changes through a system of Changesets, ensuring data integrity and facilitating collaborative workflows. It is the <strong>control center for iModels</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/723/1*H-T03Q1CPnB9LrZQrh3dNg.png" /><figcaption>iModelHub — <em>Image courtesy of iTwin.js org</em></figcaption></figure><h3>5. What is a Briefcase?</h3><p>A <strong>Briefcase</strong> is a local copy of an iModel that users can acquire to work with the iModel. Users can make changes to their copy of the iModel and then push them as a single Changeset file into iModelHub.</p><h3>6. What is a Changeset?</h3><p>A <strong>Changeset</strong> is a recorded set of modifications made to an iModel in a Briefcase. It contains incremental changes such as new elements, property updates, and deletions. Changesets form a linear timeline of iModel changes, ensuring a structured and traceable history.</p><h3>Wrapping Up</h3><p>Understanding <strong>iTwin</strong>,<strong> iTwin Platform</strong>, <strong>iModelHub</strong>, <strong>iModel</strong>, <strong>Briefcases</strong>, and <strong>Changesets</strong> is crucial when developing applications with iTwin.js. These concepts form the backbone of Bentley’s iTwin ecosystem, enabling seamless collaboration, version-controlled updates, and efficient digital twin management.</p><p>If you’re just starting with iTwin.js, exploring how these components interact in real-world workflows will help you build scalable and high-performance digital twin applications.</p><p>Do you have any questions or specific topics you’d like to explore further? Let’s discuss in the comments!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a2b63166dc32" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Secure React + TypeScript + iTwin.js SPA with CRA]]></title>
            <link>https://medium.com/@asad_bukhari/building-a-secure-react-typescript-itwin-js-spa-with-cra-0e2d5dfd6d7f?source=rss-980e4cdd8af6------2</link>
            <guid isPermaLink="false">https://medium.com/p/0e2d5dfd6d7f</guid>
            <category><![CDATA[itwinjs]]></category>
            <category><![CDATA[itwin-platform]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[create-react-app]]></category>
            <dc:creator><![CDATA[Asad Bukhari]]></dc:creator>
            <pubDate>Fri, 07 Mar 2025 05:50:36 GMT</pubDate>
            <atom:updated>2025-03-07T05:51:06.567Z</atom:updated>
            <content:encoded><![CDATA[<p>Setting up a new React app with create-react-app (CRA) can be challenging due to errors or excessive boilerplate from existing templates. The itwin-auth-spa template simplifies this by generating a minimal, well-structured setup for integrating authentication with iTwin.js.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/352/1*VC0E2AHTn1n65xz4iP3Umw.png" /></figure><p>With this guide, you’ll quickly scaffold a secure React application using TypeScript, CRA, and iTwin.js authentication.</p><h3>Prerequisites</h3><p>Before getting started, make sure you have:</p><ul><li><a href="https://nodejs.org/en"><strong>Node.js</strong></a> (LTS version recommended)</li></ul><h3>Step 1: Create a New iTwin.js SPA with Authentication</h3><p>Run the following command to set up a React app with TypeScript, iTwin.js, and authentication:</p><pre>npx create-react-app my-itwin-app --template itwin-auth-spa</pre><p>This command does the following:</p><ul><li>Sets up a React app with TypeScript and iTwin.js authentication enabled.</li><li>Installs the necessary dependencies.</li><li>Provides a minimal starting template to start with iTwin.js Application.</li></ul><h3>Step 2: Build and Run the App</h3><p>To build and start the app, run:</p><pre>npm run build<br>npm start</pre><h3>Conclusion</h3><p>By following these steps, you’ve created a secure React + TypeScript SPA with iTwin.js authentication. This setup provides a scalable foundation for integrating authentication while keeping the codebase clean and manageable.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0e2d5dfd6d7f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Enhancing iTwin.js Logging with Bunyan and Seq for Better Observability]]></title>
            <link>https://medium.com/@asad_bukhari/enhancing-itwin-js-logging-with-bunyan-and-seq-for-better-observability-bc0f54db9707?source=rss-980e4cdd8af6------2</link>
            <guid isPermaLink="false">https://medium.com/p/bc0f54db9707</guid>
            <category><![CDATA[digital-twin]]></category>
            <category><![CDATA[itwinjs]]></category>
            <category><![CDATA[seq]]></category>
            <category><![CDATA[itwin-platform]]></category>
            <dc:creator><![CDATA[Asad Bukhari]]></dc:creator>
            <pubDate>Fri, 28 Feb 2025 09:50:41 GMT</pubDate>
            <atom:updated>2025-02-28T09:52:27.432Z</atom:updated>
            <content:encoded><![CDATA[<p>Effective logging is crucial for monitoring and debugging modern applications. In iTwin.js applications, leveraging structured logging can significantly improve the observability of backend services. This blog explores how to integrate <a href="https://github.com/trentm/node-bunyan">Bunyan</a> and <a href="https://datalust.co/seq">Seq</a> with <a href="https://www.itwinjs.org/">iTwin.js</a> — the library for developing infrastructure digital twin applications — to establish a efficient logging mechanism.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/419/1*IPNEk7ff0vmW3VFjUcuX9A.png" /><figcaption>Seq integration with iTwin.js</figcaption></figure><h3>Why Use Bunyan and Seq?</h3><p><strong>Bunyan</strong> is a high-performance, JSON-based logger for Node.js that provides structured logs. <strong>Seq</strong> is a structured logging server that allows real-time search and analysis of logs with a rich query interface. Integrating these tools enhances log management by enabling structured logging with minimal performance overhead.</p><p>Here are the steps to implement logging in an iTwin.js application using Bunyan and Seq.</p><h3>1. Setup Seq and Project</h3><ul><li><a href="https://datalust.co/download">Download</a>, Install and run Seq. For more details, refer to the Seq <a href="https://docs.datalust.co/docs/getting-started">Getting Started documentation</a>.</li><li>Setup a Node.js project or copy it from here: <a href="https://github.com/asadhasnain/iTwinjsStarterKit/tree/master/Templates/node-template">iTwinjsStarterKit Node Template</a></li></ul><h3>2. Install Dependencies</h3><p>To get started, install the required dependencies:</p><pre>npm install bunyan bunyan-seq @itwin/core-bentley dotenv<br>npm install --save-dev @types/bunyan</pre><h3>3. Configure Logging</h3><p>Create a Logger.config.json file with the following content to define log levels:</p><pre>{<br>  &quot;loggerConfig&quot;: {<br>     &quot;defaultLevel&quot;: &quot;${LOG_LEVEL}&quot;,<br>     &quot;categoryLevels&quot;: [<br>         {&quot;category&quot;: &quot;Logging.SeqIntegrated&quot;, &quot;logLevel&quot;: &quot;Trace&quot;}<br>     ]<br>   }<br>}</pre><p>Create a BackendLogger.ts file to initialize logging:</p><pre>import { Logger, LoggerLevelsConfig } from &quot;@itwin/core-bentley&quot;;<br>import bunyan from &quot;bunyan&quot;;<br>import seq from &quot;bunyan-seq&quot;;<br>import config from &quot;./Logger.config.json&quot;;<br><br>/**<br> * Creates and configures the Bunyan logger.<br> */<br>function createBunyanLogger(): bunyan {<br>  return bunyan.createLogger({<br>    name: process.env.APP_NAME || &quot;SeqLogger&quot;,<br>    streams: [<br>      {<br>        stream: process.stdout,<br>        level: process.env.LOG_LEVEL?.toLowerCase() as bunyan.LogLevel || &quot;error&quot;,<br>      },<br>      seq.createStream({<br>        serverUrl: process.env.SEQ_URL || &quot;http://127.0.0.1:5341&quot;,<br>        apiKey: process.env.SEQ_API_KEY || &quot;&quot;,<br>        level: process.env.LOG_LEVEL?.toLowerCase() as bunyan.LogLevel || &quot;error&quot;<br>      })<br>    ]<br>  });<br>}<br><br>/**<br> * Initializes logging for the application.<br> */<br>export function initializeLogging(logLevel: string = &quot;Error&quot;): void {<br><br>  const bunyanLogger = createBunyanLogger();<br><br>  const bunyanLogFunction = (category: string, message: string, meta: any, level: string) =&gt; {<br>    switch (level.toLowerCase()) {<br>      case &quot;error&quot;:<br>        bunyanLogger.error({ category, ...meta }, message);<br>        break;<br>      case &quot;warn&quot;:<br>        bunyanLogger.warn({ category, ...meta }, message);<br>        break;<br>      case &quot;info&quot;:<br>        bunyanLogger.info({ category, ...meta }, message);<br>        break;<br>      case &quot;trace&quot;:<br>        bunyanLogger.trace({ category, ...meta }, message);<br>        break;<br>      default:<br>        bunyanLogger.info({ category, ...meta }, message);<br>        break;<br>    }<br>  };<br><br>  /*<br>   Note: The initialize will set the default log level to undefined and category to empty <br>   Its important to set the default log level and configure after calling initialize<br>   */<br>  Logger.initialize(<br>    (category, message, meta) =&gt; bunyanLogFunction(category, message, meta, &quot;error&quot;),<br>    (category, message, meta) =&gt; bunyanLogFunction(category, message, meta, &quot;warn&quot;),<br>    (category, message, meta) =&gt; bunyanLogFunction(category, message, meta, &quot;info&quot;),<br>    (category, message, meta) =&gt; bunyanLogFunction(category, message, meta, &quot;trace&quot;)<br>  );<br><br>  if (&quot;loggerConfig&quot; in config) {<br>    config.loggerConfig.defaultLevel = logLevel;<br>    Logger.validateProps(config.loggerConfig);<br>    Logger.configureLevels(config.loggerConfig as LoggerLevelsConfig);<br>  }<br>}</pre><p><strong>Note:</strong> The Logger initialize will set the default log level to undefined and category to empty. Its important to set the default log level and configure after calling initialize.</p><h3>4. Initialize Logging</h3><p>Create/Modify index.ts file to load environment variables and initialize logging:</p><pre>import { Logger } from &quot;@itwin/core-bentley&quot;;<br>import * as dotenv from &quot;dotenv&quot;;<br>import { initializeLogging } from &quot;./BackendLogger&quot;;<br><br>// Load environment variables from .env file<br>dotenv.config();<br><br>/**<br> * Main function initializing logging<br> * @async<br> * @function main<br> * @returns {Promise&lt;void&gt;}<br> */<br>(() =&gt; {<br><br>  initializeLogging(process.env.LOG_LEVEL);<br><br>  Logger.logError(&quot;Logging.SeqIntegrated&quot;, &quot;Logging Seq Error&quot;);<br>  Logger.logWarning(&quot;Logging.SeqIntegrated&quot;, &quot;Logging Seq Warning&quot;);<br>  Logger.logInfo(&quot;Logging.SeqIntegrated&quot;, &quot;Logging Seq Info&quot;);<br>  Logger.logTrace(&quot;Logging.SeqIntegrated&quot;, &quot;Logging Seq Trace&quot;);<br><br>})();</pre><h3>5. Define Environment Variables</h3><p>Create/update .env file to specify logging configurations:</p><pre>APP_NAME=SeqIntegratedLogger<br>LOG_LEVEL=Trace<br>SEQ_URL=http://127.0.0.1:5341<br>SEQ_API_KEY=your-seq-api-key</pre><p>You can generate SEQ_API_KEY from Seq admin API keys.</p><h3>6. Build and Run the application</h3><p>Build and run the application</p><pre>npm run build<br>npm run start</pre><p>Now, you should be able to find the logs in Seq.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3HG4KfLOZjXit2rz-jc3dw.png" /><figcaption>Seq Logs</figcaption></figure><h3>Conclusion</h3><p>By integrating Bunyan and Seq with iTwin.js, you can achieve powerful, structured logging for your backend services. This setup not only enhances debugging but also provides deep insights into application performance.<br>For a full working example, visit the GitHub repository: <a href="https://github.com/asadhasnain/iTwinjsStarterKit/tree/master/Common/Logging/SeqIntegrated">SeqIntegrated Logging Sample</a>.</p><p>Try implementing this in your iTwin.js project and take your logging capabilities to the next level!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bc0f54db9707" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Step-by-Step Guide: Implementing Logging in iTwin.js Applications]]></title>
            <link>https://medium.com/@asad_bukhari/step-by-step-guide-implementing-logging-in-itwin-js-applications-28ce949d68a8?source=rss-980e4cdd8af6------2</link>
            <guid isPermaLink="false">https://medium.com/p/28ce949d68a8</guid>
            <category><![CDATA[digital-twins-technology]]></category>
            <category><![CDATA[itwinjs]]></category>
            <category><![CDATA[itwin-platform]]></category>
            <category><![CDATA[digital-twin]]></category>
            <dc:creator><![CDATA[Asad Bukhari]]></dc:creator>
            <pubDate>Thu, 20 Feb 2025 11:56:52 GMT</pubDate>
            <atom:updated>2025-04-08T00:15:28.134Z</atom:updated>
            <content:encoded><![CDATA[<p>Logging is essential in iTwin.js applications for debugging, monitoring, and auditing purposes. In this guide, we will walk through setting up and configuring logging step by step.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/441/1*e8r0IXrptZu8zfw4VwUVUA.png" /><figcaption>iTwin.js Console Logger</figcaption></figure><h3>Step 1: Setting Up the Project</h3><p>To get started, you can use the iTwin.js Starter Kit as a template. Clone the following repository and create a copy of the node-template:</p><pre>git clone https://github.com/asadhasnain/iTwinjsStarterKit.git<br>cd iTwinjsStarterKit/Templates/node-template</pre><p>This will set up the necessary project structure to proceed with logging integration.</p><h3>Step 2: Setting Up Environment Variables</h3><p>Create a .env file in your project root to store configurable logging levels:</p><pre>LOG_LEVEL=Error</pre><h3>Step 3: Installing Dependencies</h3><p>Ensure you have the necessary dependencies installed and @itwin/core-bentely:</p><pre>npm install<br>npm install @itwin/core-bentley</pre><h3>Step 4: Creating the Logger Configuration File</h3><p>Create a Logger.config.json file to define logging levels:</p><pre>{<br>    &quot;loggerConfig&quot;: {<br>       &quot;defaultLevel&quot;: &quot;${LOG_LEVEL}&quot;,<br>       &quot;categoryLevels&quot;: [<br>           {&quot;category&quot;: &quot;Logging.ConsoleLogger&quot;, &quot;logLevel&quot;: &quot;Trace&quot;}<br>       ]<br>     }<br>}</pre><h3>Step 5: Initializing Console Logging</h3><p>Create a BackendLogger.ts file to configure and initialize logging:</p><pre>import { Logger, LoggerLevelsConfig } from &quot;@itwin/core-bentley&quot;;<br>import config from &quot;./Logger.config.json&quot;;<br><br>/**<br> * Initializes logging for the application.<br> */<br>export function initializeLogging(logLevel: string = &quot;Error&quot;): void {<br>  Logger.initializeToConsole();<br><br>  if (&quot;loggerConfig&quot; in config) {<br>    config.loggerConfig.defaultLevel = logLevel;<br>    Logger.validateProps(config.loggerConfig);<br>    Logger.configureLevels(config.loggerConfig as LoggerLevelsConfig);<br>  }<br>}</pre><h3>Step 6: Integrating Logging in the Application</h3><p>Modify index.ts to load environment variables and initialize logging:</p><pre>import * as dotenv from &quot;dotenv&quot;;<br>import { initializeLogging } from &quot;./BackendLogger&quot;;<br>import { Logger } from &quot;@itwin/core-bentley&quot;;<br><br>// Load environment variables from .env file<br>dotenv.config();<br><br>/**<br> * Main function initializing logging<br> * @async<br> * @function main<br> * @returns {Promise&lt;void&gt;}<br> */<br>(() =&gt; {<br>  initializeLogging(process.env.LOG_LEVEL);<br><br>  Logger.logInfo(&quot;main&quot;, &quot;Print this line if default logging is set to Info or lower&quot;);<br>  Logger.logInfo(&quot;Logging.ConsoleLogger&quot;, &quot;Logging initialized&quot;);<br>})();</pre><h3>Step 7: Running the Application</h3><p>Build and run your application:</p><pre>npm run build<br>npm start</pre><p>You should see logs based on the configured log level.</p><h3>Best Practices</h3><ul><li>Use Logger.logTrace, Logger.logInfo, Logger.logWarning, Logger.logError, and Logger.logExceptionappropriately.</li><li>Avoid logging sensitive data.</li><li>Configure different log levels for different environments (e.g., Debug for local, Error for production).</li></ul><h3>Conclusion</h3><p>By following this step-by-step guide, you have successfully set up structured logging in an iTwin.js application. This ensures better observability and debugging capabilities for your project.</p><p>For the complete source code, check out the <strong>Logging/ConsoleLogger </strong>project under the Common folder on GitHub: <a href="https://github.com/asadhasnain/iTwinjsStarterKit"><strong>iTwinjsStarterKit</strong></a>. For more detailed learning, refer to the official iTwin.js documentation on logging: <a href="https://www.itwinjs.org/learning/common/logging/">iTwin.js Logging Guide</a></p><p>Have you tried implementing Logging with iTwin.js? Share your experience in the comments below!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=28ce949d68a8" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>