<?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 The Tech Platform on Medium]]></title>
        <description><![CDATA[Stories by The Tech Platform on Medium]]></description>
        <link>https://medium.com/@thetechplatform?source=rss-f458f38f5c02------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*R1HQCbgLzj0YidFzDWlyaA.png</url>
            <title>Stories by The Tech Platform on Medium</title>
            <link>https://medium.com/@thetechplatform?source=rss-f458f38f5c02------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 11:14:38 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@thetechplatform/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[Build Your Own Copilot (Jarvis) with Copilot Studio ]]></title>
            <link>https://thetechplatform.medium.com/build-your-own-copilot-jarvis-with-copilot-studio-70531acb5423?source=rss-f458f38f5c02------2</link>
            <guid isPermaLink="false">https://medium.com/p/70531acb5423</guid>
            <category><![CDATA[microsoft-copilot]]></category>
            <category><![CDATA[copilot-studio]]></category>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[microsoft]]></category>
            <category><![CDATA[microsoft-365]]></category>
            <dc:creator><![CDATA[The Tech Platform]]></dc:creator>
            <pubDate>Thu, 29 Aug 2024 04:52:06 GMT</pubDate>
            <atom:updated>2024-08-29T04:52:06.663Z</atom:updated>
            <content:encoded><![CDATA[<iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F65xn6MNkohA%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D65xn6MNkohA&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F65xn6MNkohA%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/67b618b964c526c901cb30a45879cfee/href">https://medium.com/media/67b618b964c526c901cb30a45879cfee/href</a></iframe><p>This post is for an amazing initiative by wedoAI 2024.</p><p>Follow them on their website <a href="https://wedoai.ie/">https://wedoai.ie/</a> and learn more.</p><p>Join me for an exciting session where we delve into the world of Copilot Studio. This revolutionary platform empowers developers to build their custom coding assistants inspired by the capabilities of Copilot. Whether you’re a seasoned developer looking to streamline your workflow or a curious enthusiast eager to explore the possibilities of AI-driven development tools, this session is for you.</p><figure><img alt="Microsoft Copilot Studio" src="https://cdn-images-1.medium.com/max/935/1*m5GsTbbn9Qs7fJ4rB65q_Q.png" /></figure><p>Throughout this interactive session, participants will:</p><h4><strong>1. Introduction to Copilot Studio:</strong></h4><p>Gain a comprehensive understanding of Copilot Studio and how it empowers developers to create personalized coding assistants. Learn about the underlying AI technologies and the philosophy behind Copilot Studio’s design.</p><h4><strong>2. Designing Your Assistant:</strong></h4><p>Explore the intuitive interface of Copilot Studio as we guide you through the process of designing your own coding assistant. From defining coding preferences to customizing language models, discover how to tailor your assistant to suit your unique coding style and requirements.</p><h4><strong>3. Training Your Assistant:</strong></h4><p>Dive into the training process as we demonstrate how to teach your assistant to understand context, identify patterns, and generate relevant code suggestions. Learn best practices for optimizing training data and fine-tuning your assistant’s performance.</p><h4><strong>4. Integrating with Your IDE:</strong></h4><p>Explore seamless integration options that allow you to leverage your custom coding assistant directly within your preferred integrated development environment (IDE), whether it’s Visual Studio Code, Visual Studio, or others. Discover how to enhance your coding experience and boost productivity with intelligent assistance at your fingertips.</p><h4><strong>5. Advanced Features and Use Cases:</strong></h4><p>Delve deeper into advanced features and use cases of Copilot Studio, such as collaboration tools, version control integration, and plugin development. Gain insights into how developers around the world are leveraging custom coding assistants to accelerate their workflows and unlock new possibilities.</p><p>By the end of this session, participants will be equipped with the knowledge and tools to embark on their journey of building and customizing their own Copilot-inspired coding assistants with Copilot Studio. Whether you’re looking to streamline your development process, explore AI-driven coding assistance, or push the boundaries of innovation, Copilot Studio offers limitless opportunities to unleash your creativity and elevate your coding experience.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=70531acb5423" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Progressive Web Apps with Power Apps: A Step-by-step Guide]]></title>
            <link>https://thetechplatform.medium.com/building-progressive-web-apps-with-power-apps-a-step-by-step-guide-f43cc4b47386?source=rss-f458f38f5c02------2</link>
            <guid isPermaLink="false">https://medium.com/p/f43cc4b47386</guid>
            <category><![CDATA[powerapps]]></category>
            <category><![CDATA[web-app-development]]></category>
            <category><![CDATA[pwa]]></category>
            <category><![CDATA[web-app-developers]]></category>
            <category><![CDATA[microsoft-365]]></category>
            <dc:creator><![CDATA[The Tech Platform]]></dc:creator>
            <pubDate>Sat, 10 Aug 2024 11:03:01 GMT</pubDate>
            <atom:updated>2024-08-10T11:03:01.614Z</atom:updated>
            <content:encoded><![CDATA[<p>In today’s digital landscape, Progressive Web Apps (PWAs) have a powerful solution for delivering and engaging user experiences across various devices and platforms. Combining the best features of web and mobile applications, PWAs offer fast, reliable, and immersive interactions, regardless of network conditions.</p><figure><img alt="Building Progressive Web Apps with Power Apps" src="https://cdn-images-1.medium.com/max/562/0*EzD73gKcr-2LT7YL.png" /></figure><p>This guide will walk you through the steps of building a Progressive Web App using <a href="https://www.thetechplatform.com/post/powerapps-toggle-yes-no">Power Apps</a>. Whether you’re a seasoned developer or just starting, these step-by-step instructions will help you create a PWA that enhances user engagement and accessibility.</p><p>Read: <a href="https://www.thetechplatform.com/post/a-guide-to-build-power-pages-with-salesforce-data">A guide to build Power Pages with Salesforce Data</a></p><p><strong>Progressive Web Apps (PWAs)</strong> are web applications that use modern web capabilities to deliver an app-like experience to users. They are designed to work on any platform using a standards-compliant browser, including desktop and mobile devices. Key features of PWAs include:</p><ul><li>PWAs can work offline or on low-quality networks.</li><li>They adapt to different screen sizes and orientations.</li><li>PWAs provide a user experience similar to native apps, including smooth animations and interactions.</li><li>They can send push notifications to engage users.</li><li>Users can install PWAs on their home screen without needing an app store.</li></ul><h3>Power Apps and Progressive Web Pages</h3><p><a href="https://www.thetechplatform.com/post/how-to-use-a-filter-in-powerapps-collection">Power Apps</a> is a suite of apps, services, connectors, and a data platform that provides a rapid application development environment to build custom apps for your business needs. It allows users to create applications with minimal coding, leveraging a drag-and-drop interface and pre-built templates. Power Apps can connect to various data sources, including Microsoft 365, Dynamics 365, SQL Server, and others, making it a versatile tool for creating business solutions.</p><p>Using Power Apps to create PWAs offers several advantages:</p><ul><li><strong>Ease of Use</strong>: Power Apps’ intuitive interface allows users to create and customize PWAs without extensive coding knowledge.</li><li><strong>Integration with Microsoft Ecosystem</strong>: Power Apps seamlessly integrates with other Microsoft services, such as Azure, SharePoint, and Teams, enhancing functionality and data connectivity.</li><li><strong>Cost-Effective Development</strong>: Building PWAs with Power Apps can be more cost-effective than developing separate native apps for different platforms.</li><li><strong>Rapid Deployment</strong>: Power Apps enable rapid development and deployment of PWAs, allowing businesses to quickly respond to changing needs and opportunities.</li><li><strong>Enhanced User Experience</strong>: Combining the app-like experience of PWAs with the powerful features of Power Apps results in highly engaging and functional applications.</li><li><strong>Scalability</strong>: Power Apps and PWAs can scale to meet the needs of businesses of all sizes, from small startups to large enterprises.</li></ul><h3>Steps for Creating Progressive Web Pages (PWA) in Power Apps</h3><h4>STEP 1: Enable PWA in Power Apps</h4><p>Navigate to the Power Pages and choose the desired site. Click “<strong>Edit</strong>” to access the site’s editing mode.</p><figure><img alt="Building Progressive Web Apps with Power Apps 1" src="https://cdn-images-1.medium.com/max/888/0*ChdD8uPZmYVCV3GJ.png" /></figure><p>In the left panel, locate the “<strong>Set up</strong>” workspace. Select “<strong>Progressive web applications</strong>”.</p><figure><img alt="Building Progressive Web Apps with Power Apps 2" src="https://cdn-images-1.medium.com/max/420/0*LskI0R823D0zkDhb.png" /></figure><p>Toggle the “<strong>Enable PWA</strong>” to activate the PWA feature.</p><figure><img alt="Building Progressive Web Apps with Power Apps 3" src="https://cdn-images-1.medium.com/max/888/0*puih0aU830fIXIsD.png" /></figure><h4>STEP 2: Customize the PWA</h4><p>Now, enter the following information:</p><ol><li><strong>Display Name: </strong>PWA portal name that will appear on mobile and app store.</li><li><strong>App Store Description:</strong> A brief description of PWA for app store listing.</li><li><strong>Start page: </strong>The initial page is displayed when PWA is opened.</li><li><strong>Splash screen background color</strong>: The background color for the loading screen.</li><li><strong>App icon: </strong>An Image for your App</li></ol><figure><img alt="Building Progressive Web Apps with Power Apps 4" src="https://cdn-images-1.medium.com/max/888/0*7c2Umu1RMeu7_VU0.png" /></figure><h4>STEP 3: Define Offline behavior</h4><p>PWAs allow users to continue navigating your site offline or without an internet connection. You can designate specific pages to remain accessible (in read-only mode) offline, while a custom message can be displayed for your site that isn’t available offline.</p><p>Under the More settings section, click “<strong>Define offline pages</strong>”.</p><figure><img alt="Building Progressive Web Apps with Power Apps 5" src="https://cdn-images-1.medium.com/max/420/0*PeEIsOV4T_8MlS8E.png" /></figure><p>Select the specific pages within your site that should be accessible when the device is offline (read-only). Click <strong>Save.</strong></p><figure><img alt="Building Progressive Web Apps with Power Apps 6" src="https://cdn-images-1.medium.com/max/888/0*SMSh8MzeGr9myQoy.png" /></figure><p>To customize the appearance of offline pages, navigate to the “<strong>Pages</strong>” workspace and select “<strong>Default offline pages.</strong>”</p><figure><img alt="Building Progressive Web Apps with Power Apps 7" src="https://cdn-images-1.medium.com/max/888/0*iS2T21m6Csxpozh4.png" /></figure><h4>STEP 4: Distribute the Progressive Web App</h4><p>Once your app is ready, you can distribute the app</p><ol><li>Using a browser</li><li>Using an app store.</li></ol><p><strong>Using a browser</strong></p><p>Once the PWA is enabled, users can pin the Power Pages site to their device’s home screen for easy access. This method is supported across all platforms (Android, iOS, Chromebook, Windows) and devices (mobile, desktop, tablet).</p><p><strong>Using an app store</strong></p><p>Create an app package to distribute your PWA through app stores. We partner with PWABuilder, a platform that generates app packages compatible with different app stores.</p><p>Here are the steps to create an app package:</p><p>Under More Settings, click “<strong>Create app package</strong>”.</p><figure><img alt="Building Progressive Web Apps with Power Apps 8" src="https://cdn-images-1.medium.com/max/888/0*yGlHfspAp5fdQwFx.png" /></figure><p>A dialog box will appear. Click “<strong>Open PWA builder</strong>”.</p><figure><img alt="Building Progressive Web Apps with Power Apps 9" src="https://cdn-images-1.medium.com/max/617/0*byr_Ut0XajySS_Wz.png" /></figure><p>You’ll be redirected to the PWABuilder website to create an app package suitable for various app stores. The generated package includes the necessary files for app store submission and a step-by-step guide to complete the process.</p><h4>STEP 5: Update Android Certificate</h4><p>If necessary, update the Android certificate by accessing the “<strong>Update the Android certificate</strong>” option under <strong>More Settings</strong>.</p><figure><img alt="Building Progressive Web Apps with Power Apps 11" src="https://cdn-images-1.medium.com/max/888/0*68xSFXnbukdDnHB-.png" /></figure><p>Enter the following information:</p><ol><li>Package title</li><li>SHA-256 cert fingerprint</li></ol><figure><img alt="Building Progressive Web Apps with Power Apps 10" src="https://cdn-images-1.medium.com/max/709/0*RxSgydCn_JHgBfZJ.png" /></figure><p>Click<strong> Update </strong>to complete the process.</p><h3>Use Cases and Examples</h3><p>Here are some real-world examples of PWA’s created with Power Apps:</p><p><strong>Employee Self-Service Portal</strong>:</p><ul><li><strong>Company</strong>: A large retail chain</li><li><strong>Solution</strong>: Created a PWA using Power Apps to provide employees access to schedules, payroll information, and company announcements. The app works offline, allowing employees to check their schedules without internet access.</li><li><strong>Benefits</strong>: Improved employee engagement and reduced administrative workload.</li></ul><p><strong>Field Service Management</strong>:</p><ul><li><strong>Company</strong>: A utility services provider</li><li><strong>Solution</strong>: Developed a PWA for field technicians to access job details, report issues, and update job statuses in real time. The app includes offline capabilities to ensure technicians can work in areas with poor connectivity.</li><li><strong>Benefits</strong>: Increased efficiency and accuracy in field operations.</li></ul><p><strong>Customer Feedback App</strong>:</p><ul><li><strong>Company</strong>: A hospitality business</li><li><strong>Solution</strong>: Implemented a PWA to collect customer feedback through surveys and forms. The app can be installed on customers’ devices and works offline, ensuring feedback can be collected anytime.</li><li><strong>Benefits</strong>: Enhanced customer satisfaction and valuable insights for business improvement.</li></ul><h3>Conclusion</h3><p>The combination of Power Apps and PWAs presents a powerful opportunity for businesses to enhance their digital presence and improve operational efficiency. By leveraging the strengths of both platforms, you can create robust, user-friendly applications that meet the demands of today’s digital landscape.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f43cc4b47386" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Best Practices to Manage Apache Spark Libraries in Microsoft Fabric]]></title>
            <link>https://thetechplatform.medium.com/best-practices-to-manage-apache-spark-libraries-in-microsoft-fabric-e83a2cf12673?source=rss-f458f38f5c02------2</link>
            <guid isPermaLink="false">https://medium.com/p/e83a2cf12673</guid>
            <category><![CDATA[microsoft-fabric]]></category>
            <category><![CDATA[apache]]></category>
            <category><![CDATA[apache-spark]]></category>
            <category><![CDATA[best-practices]]></category>
            <category><![CDATA[microsoft-365]]></category>
            <dc:creator><![CDATA[The Tech Platform]]></dc:creator>
            <pubDate>Sat, 03 Aug 2024 10:44:48 GMT</pubDate>
            <atom:updated>2024-08-03T10:44:48.649Z</atom:updated>
            <content:encoded><![CDATA[<p>Apache Spark is a powerful open-source framework for big data processing and analytics. When working with Spark in Microsoft Fabric, efficient library management becomes crucial. Properly handling libraries ensures smooth development workflows, minimizes duplication, and enhances overall code quality. This article will explore best practices for managing Spark libraries within the Fabric environment.</p><p><strong>In case you missed: </strong><a href="https://www.thetechplatform.com/post/task-flows-in-microsoft-fabric-a-comprehensive-guide"><strong>Task Flows in Microsoft Fabric: A Comprehensive Guide</strong></a></p><p>Library management in Microsoft Fabric handles libraries within Fabric environments, particularly when working with <strong>Apache Spark</strong>. When you work with Apache Spark, libraries provide essential functionality beyond the core Spark components.</p><ol><li>Offers additional tools, algorithms, and utilities that enhance your data processing capabilities.</li><li>When libraries are well-maintained, they are optimized for execution speed, memory usage, and resource utilization.</li><li>Libraries can be reused across different projects, notebooks, and experiments. You avoid redundant installations and ensure consistent usage.</li><li>When team members work on shared projects, the same libraries ensure reproducibility.</li><li>It prevents version conflicts that might arise due to different library versions being used with different workloads.</li></ol><p>Microsoft Fabric provides managed environments specifically designed for data engineering tasks.</p><ol><li><strong>Role in Data Engineering: </strong>Microsoft Fabric offers Spark runtimes, Jupyter Notebooks, and other tools. These environments serve as isolated workspaces where data engineers can develop, experiment, and analyze data. Each Microsoft Fabric environment is isolated, allowing multiple users to work independently without interfering with each other’s libraries or configurations.</li><li><strong>Customization:</strong> Fabric environments can be customized with specific libraries. You can install the exact packages needed for your data engineering workflows. Whether it’s Python libraries, machine learning frameworks, or specialized tools, MicrosoftFabric will set up your environment just right.</li><li><strong>Scalability: </strong>Microsoft Fabric seamlessly scales to handle large datasets and complex computations. Whether processing terabytes of data or running intricate machine learning pipelines, Microsoft Fabric provides the necessary resources.</li></ol><h3>Types of Libraries</h3><p>Below are three types of libraries you can manage in Microsoft Fabric:</p><ol><li>Built-in Libraries</li><li>Public Libraries</li><li>Custom Libraries</li></ol><h4>1. Built-in Libraries:</h4><p>Built-in libraries come preinstalled with Microsoft Fabric Spark runtimes. These foundational libraries provide essential functionality out of the box.</p><p>Here are some examples:</p><p><strong>Python Packages</strong>:</p><ul><li><a href="https://www.thetechplatform.com/post/python-numpy-for-data-science"><strong>NumPy</strong></a>: A powerful library for numerical computing, providing support for arrays, matrices, and mathematical functions.</li><li><a href="https://www.thetechplatform.com/post/13-important-pandas-function-used-in-data-science"><strong>Pandas</strong></a>: Used for data manipulation, analysis, and cleaning. It offers data structures like DataFrames.</li><li><a href="https://www.thetechplatform.com/post/data-visualization-with-matplotlib"><strong>Matplotlib</strong></a>: A popular plotting library for creating visualizations.</li></ul><p><strong>Java Libraries</strong>:</p><ul><li><strong>Apache Commons</strong>: A collection of reusable Java components for various tasks, including utilities, data structures, and algorithms.</li></ul><p>Other Java libraries are specific to Spark’s ecosystem.</p><p>These Microsoft Fabric built-in libraries are the building blocks for data engineering and analysis tasks. They streamline development by providing commonly used tools right from the start.</p><h4>2. Public Libraries:</h4><p>Public libraries are essential components that provide reusable code and functionality for your data engineering tasks. These libraries are sourced from external repositories, with two primary sources supported by Fabric:</p><ul><li><strong>PyPI (Python Package Index)</strong>: A comprehensive repository of Python packages.</li><li><strong>Conda</strong>: A package manager and environment management system for various programming languages.</li></ul><p>Here are the steps to add Public Libraries to Your Microsoft Fabric Environment:</p><p><strong>STEP 1: Select a Source</strong>:</p><p>Choose either PyPI or Conda as the source for your library. Specify the name of the library you want to install.</p><p><strong>STEP 2: Specify the Version</strong>:</p><p>Provide the desired version of the library. Microsoft Fabric will fetch the specified version from the chosen repository.</p><p><strong>STEP 3: Auto-Completion and Direct Search</strong>:</p><p>Fabric offers auto-completion for popular libraries during the addition process. If the library you need isn’t auto-completed, search for it directly by entering its full name. You’ll see available versions for valid library names.</p><p><strong>STEP 4: Batch Upload Using YAML</strong></p><p>Fabric supports batch uploads of public libraries using a <strong>YAML (.yml) file</strong>. Create a YAML file specifying multiple public libraries and their versions. Upload the file to your environment, and Microsoft Fabric will extract and add the libraries to the list.</p><p><strong>STEP 5: Filtering and Updating Public Libraries</strong></p><p>Use the search box on the <strong>Public Libraries</strong> page to filter the list and find specific libraries. To update the version of an existing library:</p><ul><li>Navigate to your environment.</li><li>Open the <strong>Public Libraries</strong> section.</li><li>Choose the library and update its version.</li></ul><p><strong>STEP 6: Deleting and Viewing Dependencies</strong></p><p>Hover over a library row to reveal options:</p><ul><li><strong>Trash Icon</strong>: Delete the library.</li><li><strong>View Dependency</strong>: Explore the library’s dependencies.</li></ul><p><strong>STEP 7: Exporting to YAML</strong></p><p>Fabric allows you to export the full list of public libraries to a YAML file. Download this file to your local directory for reference.</p><h4>3. Custom Libraries:</h4><p>Custom libraries cater to specific needs and can be uploaded to your Microsoft Fabric environment. Common formats for custom libraries include:</p><ul><li><strong>Wheel (.whl)</strong>: Python package format for distribution.</li><li><strong>JAR (Java Archive)</strong>: Used for Java libraries.</li><li><strong>Tarballs (.tar.gz)</strong>: Common for R language packages.</li></ul><p>Custom libraries allow you to extend Fabric’s capabilities by adding domain-specific tools, proprietary algorithms, or project-specific code.</p><p><strong>Read: </strong><a href="https://www.thetechplatform.com/post/policies-to-manage-data-in-microsoft-fabric-s-sypanse-real-time-analytics"><strong>Policies to manage Data in Microsoft Fabric’s Synapse Real-Time Analytics</strong></a></p><h3>Best Practices to Manage Apache Spark Libraries in Microsoft Fabric</h3><h3>Best Practice 1: Setting Default Libraries</h3><p>Setting default libraries in <strong>Microsoft Fabric</strong> is a best practice for efficient library management in Apache Spark environments.</p><p><strong>Consistency and Streamlined Development</strong>:</p><ul><li>Default libraries ensure that all notebooks and Spark job definitions within the workspace start sessions with the same set of preinstalled libraries.</li><li>Developers don’t need to manually install required packages each time they create a new notebook or run a job.</li><li>This consistency streamlines development and reduces setup overhead.</li></ul><p><strong>Avoiding Version Conflicts</strong>:</p><ul><li>When multiple users collaborate in the same workspace, version conflicts can arise if everyone uses different library versions.</li><li>Setting default libraries ensures that everyone works with the same versions, minimizing compatibility issues.</li></ul><p><strong>Workspace-Wide Dependencies</strong>:</p><ul><li>Default libraries become part of the workspace settings.</li><li>All users benefit from these shared dependencies, making collaboration smoother.</li></ul><p>As an administrator of the workspace, you have the authority to configure default libraries for your Fabric environment. Here are the steps to create a new environment:</p><p><strong>STEP 1: Access the Microsoft Fabric Portal</strong></p><p>Navigate to the Microsoft Fabric portal. On the left panel, click on the “<strong>Workspace</strong>” option.</p><p><strong>STEP 2: Creation of a New Environment</strong></p><p>In the Microsoft Fabric Workspace section, locate and click the “<strong>+ New</strong>” button. A drop-down menu will appear. Select “<strong>Environment</strong>” from this list.</p><figure><img alt="Best Practices to Manage Apache Spark Libraries in Microsoft Fabric 1" src="https://cdn-images-1.medium.com/max/420/0*m2nCaxbxENoJqvmd.png" /></figure><p><strong>STEP 3: Name Your Environment</strong></p><p>A pop-up box will appear. Type your desired name in the provided field and click “<strong>Create</strong>” to proceed.</p><figure><img alt="Best Practices to Manage Apache Spark Libraries in Microsoft Fabric 2" src="https://cdn-images-1.medium.com/max/888/0*gMtJRkqyOs7aVWza.png" /></figure><p><strong>STEP 4: Configure Your Environment</strong></p><p>After naming your environment, you’ll be presented with three main options to configure your environment:</p><figure><img alt="Best Practices to Manage Apache Spark Libraries in Microsoft Fabric 3" src="https://cdn-images-1.medium.com/max/586/0*tyajZxJtw5LdEHut.png" /></figure><p><strong>STEP 5: Install Python Libraries</strong> :</p><p>Once the environment is set up, open a terminal or command prompt within the environment. Use the following commands to install Python packages:</p><ul><li>For <strong>pip</strong>:</li></ul><pre>pip install package_name</pre><ul><li>For <strong>conda</strong>:</li></ul><pre>conda install package_name</pre><p>Replace <strong>package_name</strong> with the actual name of the Python library you want to install.</p><p><strong>STEP 6: Include Java Libraries</strong></p><p>For Java libraries, you’ll need to include the appropriate JAR files. Upload the necessary JAR files to your environment. Configure your Spark jobs or notebooks to reference these JAR files as needed.</p><p><strong>STEP 7: Attach the Environment as Workspace Default</strong>:</p><p>Click Workspace in the left panel. Click (…) and select the <strong>Workspace Settings option.</strong></p><figure><img alt="Best Practices to Manage Apache Spark Libraries in Microsoft Fabric 4" src="https://cdn-images-1.medium.com/max/623/0*8MBCCit3GqRIw9Tn.png" /></figure><p>Under the <strong>Data Engineering/Science</strong> tab, select “<strong>Spark settings</strong>”. Go to<strong> the Environment</strong> section, and toggle on the “<strong>Set default environment</strong>”.</p><figure><img alt="Best Practices to Manage Apache Spark Libraries in Microsoft Fabric 6" src="https://cdn-images-1.medium.com/max/888/0*ha3UDHk3uM5qs-S_.png" /></figure><p>This ensures that notebooks and Spark job definitions within the workspace start sessions with the libraries installed in the default environment.</p><h3>Best Practice 2: Persistent Library Specification</h3><p>When you persist library specifications, you install the required libraries in a dedicated environment. This environment is then attached to specific code items (such as notebooks or Spark job definitions).</p><p>When you’re working within a notebook or defining a Spark job, you’ll find the <strong>Environment menu</strong> available in the <strong>Home</strong> tabs. This menu provides access to the environments you’ve set up in Fabric.</p><figure><img alt="Best Practices to Manage Apache Spark Libraries in Microsoft Fabric 7" src="https://cdn-images-1.medium.com/max/888/0*xRGXjWFSO9MarrwU.png" /></figure><p>Within the Environment menu, you’ll see a list of available environments. Choose the specific Microsoft Fabric environment associated with your notebook or Spark job. Once you select an environment, its configuration becomes effective for your current session. This includes the <strong>Spark compute settings</strong> ( cluster size, memory allocation, and cores) and the <strong>libraries</strong> configured within that environment. Libraries installed in the environment are now accessible for your Spark tasks.</p><p><strong>Benefits</strong>:</p><ul><li><strong>Efficiency and Time-Saving</strong>: You can avoid repetitive installations by installing libraries in a dedicated environment and attaching them to code items. Once the libraries are set up, they remain effective across all Spark sessions where the environment is attached. Developers no longer need to run installation commands every time they create a new notebook or execute a Spark job. This streamlined approach saves valuable time and effort.</li><li><strong>Granularity and Customization</strong>: Unlike workspace-level settings, this approach allows for finer granularity. You can attach the same environment to multiple code artifacts within a workspace. Attaching them to a common Microsoft Fabric environment ensures consistency for subsets of notebooks or Spark job definitions that require the same libraries. You can tailor environments to specific project needs.</li><li><strong>Collaboration and Management</strong>: Administrators, members, or contributors of the workspace can create, edit, and manage these environments. This flexibility empowers collaboration. When teams work on shared projects, persistent library specifications ensure to operate within the same library ecosystem. It simplifies collaboration and knowledge sharing.</li></ul><h3>Best Practice 3: Use Inline Installation Techniques</h3><p>Inline installation refers to the practice of installing libraries directly within an interactive notebook (such as a Jupyter notebook) for one-time use. Unlike persistent installations, inline installations are effective only for the current notebook session and don’t persist across different sessions.</p><p>Inline Libraries allows you to manage Python and R Libraries.</p><p><strong>Inline Installation for Python Libraries</strong></p><p>When you run an inline installation command, the Python interpreter restarts to apply the library change. Note that any variables defined before running the command cell are lost during this process. To maintain consistency, it’s recommended to place all library-related commands (additions, deletions, updates) at the beginning of your notebook.</p><p>By default, inline commands for managing Python libraries are disabled in notebook pipelines. However, if you want to enable <strong>%pip install</strong> for pipeline runs, you can add a parameter called <strong>_inlineInstallationEnabled</strong> with a value of <strong>True</strong> in the notebook activity parameters.</p><p>Suppose you want to use the powerful visualization library <strong>Altair</strong> for a one-time data exploration in your notebook. If Altair isn’t installed in your workspace, follow these steps:</p><p>Run the following commands in a notebook code cell:</p><pre>%conda install altair # Install the latest version through conda command %conda install vega_datasets # Install vega_datasets (contains a semantic model for visualization)</pre><p>The output indicates the result of the installation.</p><p>Import the package and semantic model in another notebook cell:</p><pre>import altair as alt from vega_datasets import data</pre><p>Now you can explore Altair visualizations within your session.</p><p><strong>Inline Installation for R Libraries</strong></p><p>The <strong>inline</strong> package allows you to define R functions using inlined C, C++, or Fortran code. It supports the <strong>.C</strong> and <strong>.Call</strong> calling conventions. To install the <strong>inline</strong> package, you can use the following command in an R notebook cell:</p><pre>install.packages(&quot;inline&quot;)</pre><p>Once installed, you can create custom R functions with inlined code.</p><p>After installing the <strong>caesar</strong> library, you can use it within your SparkR session. Here’s an example of defining a function called <strong>hello</strong> that applies the <strong>caesar</strong> function to a list of strings:</p><pre>library(SparkR) <br>sparkR.session() <br><br>hello &lt;- function(x) { <br>	library(caesar) <br>	caesar(x) <br>} <br><br>spark.lapply(c(&quot;hello world&quot;, &quot;good morning&quot;, &quot;good evening&quot;), hello)</pre><p>To include external JAR files in your SparkR session, you can configure the <strong>spark.jars</strong> property. In a Scala cell, use the following syntax (replace placeholders with actual values):</p><pre>%%configure -f <br>{ <br>	&quot;conf&quot;: { <br>		&quot;spark.jars&quot;: &quot;abfss://&lt;&lt;Lakehouse prefix&gt;&gt;.dfs.fabric.microsoft.com/&lt;&lt;path to JAR file&gt;&gt;/&lt;&lt;JAR file name&gt;&gt;.jar&quot; <br>	} <br>}</pre><p>Make sure to replace the placeholders with the correct ABFS path to your JAR file.</p><p><strong>Benefits of Inline Installation</strong></p><ol><li>Inline installation allows you to quickly add libraries when needed without affecting other notebooks or Spark sessions. It’s ideal for ad hoc tasks or exploratory data analysis where you require specific libraries temporarily.</li><li>Libraries installed inline are scoped to the current session. They won’t interfere with other notebooks or workspaces. You can experiment freely without worrying about global effects.</li><li>Since inline installations are session-specific, you avoid unnecessary overhead in environments where the library isn’t needed beyond the current task. This efficient resource usage benefits both development and runtime environments.</li></ol><h3>Conclusion</h3><p>Efficiently managing libraries is essential for maintaining an organized and productive development environment. Properly handling libraries ensures access to necessary tools, functions, and dependencies, minimizing code duplication and improving overall quality. Microsoft Fabric offers features like R inline installation, custom functions using the <strong>inline</strong> package, and support for external JAR files.</p><p>Explore these capabilities to enhance your development workflow! 😊🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e83a2cf12673" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Modular Blazor Apps: RCLs, Static SSR, and Interactive Strategies]]></title>
            <link>https://thetechplatform.medium.com/building-modular-blazor-apps-rcls-static-ssr-and-interactive-strategies-bc63301eb648?source=rss-f458f38f5c02------2</link>
            <guid isPermaLink="false">https://medium.com/p/bc63301eb648</guid>
            <category><![CDATA[razorpages]]></category>
            <category><![CDATA[blazor]]></category>
            <category><![CDATA[web-framework]]></category>
            <category><![CDATA[aspnet]]></category>
            <category><![CDATA[web-app-development]]></category>
            <dc:creator><![CDATA[The Tech Platform]]></dc:creator>
            <pubDate>Thu, 01 Aug 2024 08:19:43 GMT</pubDate>
            <atom:updated>2024-08-01T08:19:43.476Z</atom:updated>
            <content:encoded><![CDATA[<p>Blazor, a web framework by Microsoft, empowers developers to build interactive web applications using C# and .NET. With Blazor, you can create reusable UI components, manage state, and handle user interactions — all while targeting client-side (WebAssembly) and server-side (ASP.NET Core) scenarios.</p><figure><img alt="Building Modular Blazor Apps: RCLs, Static SSR, and Interactive Strategies" src="https://cdn-images-1.medium.com/max/836/0*BoU3YUAMtpgdVM4p.png" /></figure><p>In this article, we’ll explore three essential aspects of Blazor components:</p><ol><li><strong>Razor Class Libraries (RCLs)</strong>: Discover how RCLs simplify component sharing, promote code reuse, and enhance modularity within your Blazor projects.</li><li><strong>Static Server-Side Rendering (SSR)</strong>: Learn about the benefits of pre-rendering components on the server and how to optimize initial load times.</li><li><strong>Interactive Strategies</strong>: Understand how to handle links, forms, and other interactive elements across different rendering modes.</li></ol><h3>What are Razor Class Libraries (RCLs)?</h3><p>Razor Class Libraries (RCLs) are a powerful feature introduced in <a href="http://asp.net/">ASP.NET</a> Core. They simplify the management and distribution of reusable UI components, including Razor pages, views, and controllers. Image RCLs as a way to package and share UI-related code across multiple projects within a solution or even among different solutions.</p><p>Read: <a href="https://www.thetechplatform.com/post/razor-pages-a-beginner-s-guide-to-asp-net-core-web-development">Razor Pages: A Beginner’s Guide to ASP.NET Core Web Development</a></p><p><strong>Why RCLs Matter for Component Authors:</strong></p><ol><li><strong>Packaging UI Components</strong>: RCLs allow you to bundle Razor pages, views, layouts, partials, and other UI-related assets into a class library. These components can then be referenced and consumed by other projects.</li><li><strong>Modularity and Separation of Concerns</strong>: By isolating UI components in separate libraries, you achieve better modularity and separation of concerns. This makes your codebase cleaner and more maintainable.</li><li><strong>Code Reuse</strong>: RCLs promote code reuse. You can create a set of common UI components (e.g., navigation menus, widgets, authentication pages) and share them across different parts of your application or even across applications.</li></ol><p>Read: <a href="https://www.thetechplatform.com/post/prerendering-in-asp-net-core-razor-components">Prerendering in ASP.NET Core Razor Components</a></p><h4>Here are the steps to create RCL:</h4><p><strong>STEP 1: Define Components and Services</strong>:</p><p>In the RCL project, create folders to organize your components. Common folders include:</p><ul><li><strong>Pages</strong>: For Razor pages.</li><li><strong>Views</strong>: For <a href="https://www.thetechplatform.com/post/razor-view-engine-vs-aspx-view-engines-in-asp-net">Razor views</a>.</li><li><strong>Components</strong>: For <a href="https://www.thetechplatform.com/post/prerendering-in-asp-net-core-razor-components">Blazor components</a>.</li><li><strong>Services</strong>: For any services or utilities.</li></ul><p>Add your Razor pages, views, and components within these folders. For example: Create a Razor page named <strong>MyPage.cshtml</strong> in the <strong>Pages</strong> folder. Design your Blazor components (e.g., <strong>MyButton.razor</strong>, <strong>MyChart.razor</strong>) in the <strong>Components</strong> folder.</p><p><strong>STEP 2: Resource Files (Optional)</strong>:</p><p>If your components require CSS, JavaScript, or other static files, add them to the RCL project. Create a <strong>wwwroot</strong> folder and organize your resources there.</p><p><strong>STEP 3: Build and Package</strong>:</p><p>Build your RCL project to ensure there are no compilation errors. Once successfully built, the RCL generates a <strong>.dll</strong> file containing your components.</p><p><strong>STEP 4: Referencing the RCL</strong>:</p><p>In your main ASP.NET Core application (e.g., a Blazor app), add a reference to your RCL project.</p><p>In the main app’s <strong>.csproj</strong> file, include the following line:</p><pre>&lt;ItemGroup&gt; &lt;ProjectReference Include=&quot;path-to-MyComponentLibrary.csproj&quot; /&gt; &lt;/ItemGroup&gt;</pre><p>Now you can use the components from your RCL in your main app.</p><p><strong>STEP 5: Consuming Components</strong>:</p><p>In your main app, import the namespaces corresponding to your RCL components. Use the components in your Razor pages or Blazor components.</p><h3>Understanding Static Server-Side Rendering</h3><p>Static SSR is a rendering mode where components execute on the server when handling an incoming HTTP request. When a user requests a page (e.g., a Blazor page), the server processes the incoming HTTP request. The server-side component executes on the server, following the component’s logic and data flow. During execution, the component generates HTML output based on its rendering instructions.</p><p>After executing the component, the server produces an HTML representation of the component’s rendered content. This HTML is then included in the HTTP response sent back to the client (usually the user’s browser). The client receives the pre-rendered HTML and displays it immediately.</p><p>Unlike client-side rendering, where components run in the browser, static SSR doesn’t maintain ongoing connections or client-side state. The server discards the component and its state after rendering, which reduces memory usage and server resources. Subsequent interactions (e.g., user clicks) trigger new HTTP requests, repeating the process.</p><h4>Benefits of static SSR:</h4><ol><li>Static SSR reduces the load on the client, as the server performs the heavy lifting.</li><li>It is valuable in scenarios with high traffic or limited server capacity.</li><li>Unlike client-side Blazor, which establishes a WebSocket connection for real-time updates, static SSR doesn’t require an ongoing connection.</li></ol><h4>Limitations of Static SSR:</h4><p>Here are some of the limitations of Static — Side Rendering in Blazor:</p><p><strong>1. Event handler restrictions</strong></p><p>In static SSR, event handlers that rely on client-side .NET code (such as <strong>@onclick</strong>) won’t work during the initial rendering. These handlers require JavaScript interop, which isn’t available until the client-side Blazor runtime initializes.</p><pre>&lt;!-- MyComponent.razor --&gt;<br><br>&lt;button @onclick=&quot;HandleClick&quot;&gt;Click me!&lt;/button&gt;<br><br>@code {<br>    private void HandleClick()<br>    {<br>        // This logic won&#39;t execute during initial rendering.<br>        // It requires client-side Blazor runtime.<br>    }<br>}</pre><p><strong>2. Immediate discarding of State</strong></p><p>After rendering, the server discards the component and its renderer state. Unlike client-side Blazor, where components persist in memory, static SSR doesn’t maintain ongoing connections. Subsequent interactions (e.g., user clicks) trigger new requests, re-rendering the component.</p><p><strong>3. Special exception for @onsubmit</strong></p><p>The <strong>@onsubmit</strong> event handler for forms is an exception. Even in static SSR, form submissions are handled on the server, allowing validation and processing before the response is sent back to the client.</p><pre>&lt;!-- MyForm.razor --&gt;<br><br>&lt;form @onsubmit=&quot;HandleSubmit&quot;&gt;<br>    &lt;input type=&quot;text&quot; /&gt;<br>    &lt;button type=&quot;submit&quot;&gt;Submit&lt;/button&gt;<br>&lt;/form&gt;<br><br>@code {<br>    private void HandleSubmit()<br>    {<br>        // Handle form submission logic (runs on the server).<br>    }<br>}</pre><p>In case you missed: <a href="https://www.thetechplatform.com/post/how-to-mitigate-security-threats-in-interactive-server-side-blazor">How to Mitigate Security Threats in Interactive Server-Side Blazor?</a></p><h3>Strategies for Handling Static SSR</h3><h4>Read-Only Components</h4><p>Read-only components produce static content — content that doesn’t require client-side interactivity. These components are ideal for static SSR because they don’t rely on JavaScript or user interactions. Examples include displaying user profiles, static charts, or informational content.</p><pre>&lt;!-- ReadOnlyComponent.razor --&gt;<br><br>&lt;h3&gt;User Profile&lt;/h3&gt;<br>&lt;p&gt;Name: John Doe&lt;/p&gt;<br>&lt;p&gt;Email: john@example.com&lt;/p&gt;<br>&lt;!-- Other static content here --&gt;</pre><h4>Hybrid Approach</h4><p>The hybrid approach detects the render mode (static or interactive) using the <strong>@rendermode</strong> directive. Based on the context, you adjust the behavior of your components:</p><p><strong>Static SSR Mode</strong>:</p><ul><li>Provide read-only functionality.</li><li>Avoid event handlers that require client-side .NET code.</li><li>Optimize for initial load time.</li></ul><p><strong>Interactive SSR Mode</strong>:</p><ul><li>Allow full interactivity.</li><li>Use event handlers like <strong>@onclick</strong>.</li><li>Leverage client-side Blazor features.</li></ul><pre>&lt;!-- HybridComponent.razor --&gt;<br><br>@if (@rendermode == &quot;static&quot;)<br>{<br>    &lt;p&gt;This content is static.&lt;/p&gt;<br>}<br>else<br>{<br>    &lt;button @onclick=&quot;HandleClick&quot;&gt;Click me!&lt;/button&gt;<br>}<br><br>@code {<br>    [Parameter] public string RenderMode { get; set; }<br><br>    private void HandleClick()<br>    {<br>        // Handle button click logic (runs on the client).<br>    }<br>}</pre><h4>Client-Side Rendering (CSR) Fallback</h4><p>When static SSR limitations are too restrictive (e.g., for complex interactivity), consider providing a fallback mechanism for client-side rendering. You can load additional JavaScript and switch to client-side Blazor when needed.</p><pre>&lt;!-- CSRComponent.razor --&gt;<br><br>@if (@rendermode == &quot;static&quot;)<br>{<br>    &lt;p&gt;This content is static.&lt;/p&gt;<br>}<br>else<br>{<br>    &lt;p&gt;Loading interactive content...&lt;/p&gt;<br>    &lt;!-- Load client-side Blazor scripts here --&gt;<br>}<br><br>@code {<br>    [Parameter] public string RenderMode { get; set; }<br>}</pre><h3>Streaming Rendering and Incremental UI Updates:</h3><p>Streaming rendering allows the server to send parts of the rendered content to the client as they become available. It improves perceived performance by showing content sooner, especially for large pages or complex components. In Blazor, streaming rendering is particularly useful during static SSR.</p><p>Apply the <strong>[StreamRendering]</strong> attribute to a component to enable streaming rendering. It instructs Blazor to send the initial part of the component’s rendering to the client as soon as it’s available. Subsequent parts are sent incrementally, allowing the client to start rendering before the entire component is processed on the server.</p><pre>&lt;!-- StreamingComponent.razor --&gt;<br><br>@page &quot;/streaming&quot;<br><br>&lt;h3&gt;Streaming Rendering Example&lt;/h3&gt;<br>&lt;p&gt;This content is streamed to the client.&lt;/p&gt;<br><br>@code {<br>    [StreamRendering]<br>    private async Task OnInitializedAsync()<br>    {<br>        // Simulate async data loading (e.g., fetching from an API).<br>        await Task.Delay(1000);<br>    }<br>}</pre><h4>Consistency in Data-Loading Patterns</h4><p>Let’s compare Static Server-Side Rendering (SSR) with Interactive Rendering (client-side Blazor)</p><figure><img alt="Building Modular Blazor Apps: RCLs, Static SSR, and Interactive Strategies" src="https://cdn-images-1.medium.com/max/907/1*KHhefskq9NWrHeoZuyxjgw.png" /></figure><h3>Handling Links and Forms Across Render Modes:</h3><p>The importance of handling links and forms consistently across different render modes (static SSR and interactive rendering) in Blazor.</p><p><strong>User Experience Consistency</strong>:</p><ul><li>Users expect consistent behavior when interacting with links and forms, regardless of whether the page initially loads via static SSR or client-side rendering.</li><li>Inconsistent behavior can confuse users and negatively impact their experience.</li></ul><p><strong>Seamless Navigation</strong>:</p><ul><li>Links play a crucial role in navigation. Whether it’s a simple link (<strong>&lt;a&gt;</strong> tag) or an enhanced navigation component (<strong>NavLink</strong>), users rely on them to move between pages.</li><li>Ensuring equivalent behavior for links across render modes ensures seamless navigation transitions.</li></ul><p><strong>Form Handling and Validation</strong>:</p><ul><li>Forms are essential for user input (e.g., login forms, search forms, data submission).</li><li>Consistent form behavior includes validation, input handling, and submission logic.</li><li>Forms should work reliably whether rendered statically or interactively.</li></ul><h3>Handling Links</h3><p><strong>Use the @href Attribute</strong>: When creating links, use the <strong>@href</strong> attribute to specify the target URL. Whether it’s a static SSR link or a client-side navigation link, ensure they lead to the same destination.</p><p>Example of a simple link in Blazor:</p><pre>&lt;!-- MyLink.razor --&gt;<br>&lt;a href=&quot;/about&quot;&gt;About Us&lt;/a&gt;</pre><p>For client-side routing, consider using Blazor’s built-in <strong>NavLink</strong> component. <strong>NavLink</strong> provides additional features like active link styling and smooth transitions. It’s useful when building dynamic navigation menus or handling active routes.</p><p>Example of using <strong>NavLink</strong>:</p><pre>&lt;!-- MyNavigation.razor --&gt;<br>&lt;NavLink href=&quot;/products&quot; Match=&quot;NavLinkMatch.All&quot;&gt;<br>    Products<br>&lt;/NavLink&gt;</pre><h3>Handling Forms</h3><p>When building Blazor applications with static SSR, it’s essential to ensure consistent behavior for forms. Forms allow users to input data, submit requests, and interact with your application. Here’s how to handle forms effectively:</p><p><strong>Define Forms as Usual</strong>:</p><ul><li>Create your forms using standard HTML elements (e.g., <strong>&lt;form&gt;</strong>) or Blazor’s built-in <strong>&lt;EditForm&gt;</strong> component.</li><li>Include input fields (textboxes, checkboxes, etc.), labels, and any other form elements you need.</li></ul><p><strong>Validation and Input Handling</strong>:</p><ul><li>Implement form validation logic to ensure data integrity.</li><li>Use Blazor’s validation features (e.g., data annotations, custom validation logic) to validate user input.</li><li>Bind form fields to model properties using <strong>@bind-Value</strong> or other appropriate binding techniques.</li></ul><p><strong>Handle Form Submissions on the Server</strong>:</p><ul><li>In static SSR, form submissions are processed on the server.</li><li>Define an event handler for form submission (usually <strong>OnSubmitAsync</strong>).</li><li>Inside the event handler, handle the form data, perform any necessary server-side processing, and respond accordingly.</li></ul><p>Example of a simple form in static SSR:</p><pre>&lt;!-- MyForm.razor --&gt;<br>&lt;EditForm Model=&quot;@myModel&quot; OnSubmit=&quot;HandleSubmit&quot;&gt;<br>	&lt;label for=&quot;name&quot;&gt;Name:&lt;/label&gt;<br>    &lt;InputText @bind-Value=&quot;myModel.Name&quot; /&gt;<br><br>    &lt;button type=&quot;submit&quot;&gt;Submit&lt;/button&gt;<br>&lt;/EditForm&gt;<br><br>@code {<br>    private MyModel myModel = new MyModel();<br><br>    private async Task HandleSubmit()<br>    {<br>        // Handle form submission logic (runs on the server).<br>	   // For example, save data to a database or perform other server-side actions.<br>    }<br>}</pre><h3>Avoiding APIs Specific to Static SSR</h3><p>While static SSR provides benefits, it’s essential to use the right tools and avoid relying on context that might not be available during server-side rendering.</p><p><strong>Avoid HttpContext in Static SSR</strong></p><ol><li><strong>HttpContext Limitations</strong>: With static SSR, the <strong>HttpContext</strong> object is available only on the server. Components executing on the server can access it, but client-side components won’t have access.</li><li><strong>Avoid Direct Reliance</strong>: Discourage direct reliance on <strong>HttpContext</strong> within your components. Instead, use alternatives that work consistently across static SSR and interactive rendering.</li></ol><h4>Suggested Alternatives</h4><p><strong>1. NavigationManager for URL-Related Tasks</strong>:</p><p>Use NavigationManager to handle navigation and URL-related tasks. It provides methods like NavigateTo for programmatic navigation.</p><p>Example of using <strong>NavigationManager</strong>:</p><pre>@inject NavigationManager Navigation <br><br>&lt;button @onclick=&quot;NavigateToAbout&quot;&gt;Go to About&lt;/button&gt; <br>@code <br>{ <br>	private void NavigateToAbout() <br>	{ <br>		Navigation.NavigateTo(&quot;/about&quot;); <br>	} <br>}</pre><p><strong>2. AuthenticationStateProvider for Authentication State</strong>:</p><p>To manage the authentication state, use <strong>AuthenticationStateProvider. </strong>It provides information about the user’s authentication status.</p><p>Example of using <strong>AuthenticationStateProvider</strong>:</p><pre>@inject AuthenticationStateProvider AuthenticationState <br><br>&lt;p&gt;User is authenticated: @AuthenticationState.User.Identity.IsAuthenticated&lt;/p&gt;</pre><p>You ensure consistent behavior across rendering modes by avoiding direct reliance on <strong>HttpContext</strong> and using recommended alternatives.</p><h3>Conclusion</h3><p>In this article on building modular Blazor apps, we’ve delved into essential concepts that empower developers to create efficient and user-friendly web applications. As you continue your Blazor journey, keep these principles in mind. Whether you’re building enterprise applications, personal projects, or contributing to open-source libraries, Blazor empowers you to create delightful web experiences using familiar tools and languages.</p><p>Happy coding! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bc63301eb648" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Boosting Web Performance: Introducing MapStaticAsset in ASP.NET Core]]></title>
            <link>https://thetechplatform.medium.com/boosting-web-performance-introducing-mapstaticasset-in-asp-net-core-6ee1e1b20fe2?source=rss-f458f38f5c02------2</link>
            <guid isPermaLink="false">https://medium.com/p/6ee1e1b20fe2</guid>
            <category><![CDATA[aspnetcore]]></category>
            <category><![CDATA[aspnet]]></category>
            <category><![CDATA[web-app-development]]></category>
            <category><![CDATA[webdev]]></category>
            <category><![CDATA[web-applications]]></category>
            <dc:creator><![CDATA[The Tech Platform]]></dc:creator>
            <pubDate>Mon, 29 Jul 2024 11:48:14 GMT</pubDate>
            <atom:updated>2024-07-30T11:41:23.872Z</atom:updated>
            <content:encoded><![CDATA[<p>Every user expects websites to load quickly and search engines favor speedy pages in their rankings. The developers will optimize every aspect of our applications, from database queries to front-end rendering. The most important overlooked are the static assets-CSS files, JavaScript, and images the visual components of web pages. All these assets determine how fast the website loads and how responsive they are.</p><figure><img alt="Boosting Web Performance: Introducing MapStaticAsset in ASP.NET Core" src="https://cdn-images-1.medium.com/max/570/0*NU_dcgTDCpsT6UUO.png" /></figure><p>Static asset optimization improves the performance and efficiency of static resources on a website. These optimizations enhance user experience, reduce load times, and minimize bandwidth usage.</p><p>Optimizing the delivery of static assets is important for:</p><ol><li><strong>Page Load Speed: </strong>Faster-loading web pages enhance user experience. Optimized assets reduce initial load times, leading to improved performance and engagement.</li><li><strong>Bandwidth Efficiency: </strong>Efficient asset delivery minimizes data transfer. Smaller file sizes reduce bandwidth consumption, benefiting both users and server costs.</li><li><strong>SEO and Rankings: </strong>Search engines consider page speed as a ranking factor. Well-optimized assets contribute to better search engine visibility.</li><li><strong>User Retention: </strong>Slow-loading pages frustrate users and increase bounce rates. Optimized assets keep visitors engaged and encourage longer sessions.</li></ol><p>Here are some of the challenges you can face without proper optimization:</p><ol><li><strong>Additional Requests: </strong>Unoptimized assets result in multiple HTTP requests. Each request adds latency, impacting overall page load time.</li><li><strong>Inefficient Data Transfer: </strong>Large asset files consume more bandwidth. Overloaded networks lead to slower loading, especially on mobile devices.</li><li><strong>Serving Outdated Files: </strong>Browsers may serve cached, outdated assets. Users see stale content, affecting their experience without proper caching and version control.</li></ol><p>MapStaticAssets is a new middleware introduced in ASP.NET Core to enhance the delivery of static assets (such as CSS files, JavaScript scripts, and images) to web browsers. Its primary goal is asset serving, making web applications faster and more efficient.</p><p>The introduction of MapStaticAssets aims to address these limitations and provide a more robust solution for static asset delivery:</p><ol><li><strong>Build-Time Compression: </strong>MapStaticAssets compress assets during both development and publish time. During development, it uses gzip compression. During publish, it further compresses assets using both gzip and brotli. Smaller asset sizes reduce network transfer time and improve overall performance.</li><li><strong>Content-Based ETags:: </strong>MapStaticAssets calculates ETags based on the SHA-256 hash of asset content. When an asset’s content changes, its ETag changes accordingly. Efficient caching ensures that browsers redownload assets only when necessary, avoiding unnecessary network requests.</li></ol><p><strong>For a step-by-step guide to implementing MapStaticAssets in ASP.NET Core click the link — </strong><a href="https://www.thetechplatform.com/post/boosting-web-performance-introducing-mapstaticasset-in-asp-net-core">https://www.thetechplatform.com/post/boosting-web-performance-introducing-mapstaticasset-in-asp-net-core</a></p><p><em>Originally published at </em><a href="https://www.thetechplatform.com/post/boosting-web-performance-introducing-mapstaticasset-in-asp-net-core"><em>https://www.thetechplatform.com</em></a><em> on July 29, 2024.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6ee1e1b20fe2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[XSS vs CSRF Attack: Protecting your Web Applications]]></title>
            <link>https://thetechplatform.medium.com/xss-vs-csrf-attack-protecting-your-web-applications-f36aee91153d?source=rss-f458f38f5c02------2</link>
            <guid isPermaLink="false">https://medium.com/p/f36aee91153d</guid>
            <category><![CDATA[csrf-attack]]></category>
            <category><![CDATA[web-application-security]]></category>
            <category><![CDATA[web-security]]></category>
            <category><![CDATA[xss-attack]]></category>
            <category><![CDATA[web-application-developer]]></category>
            <dc:creator><![CDATA[The Tech Platform]]></dc:creator>
            <pubDate>Fri, 12 Jul 2024 10:49:45 GMT</pubDate>
            <atom:updated>2024-07-12T10:49:45.867Z</atom:updated>
            <content:encoded><![CDATA[<p>We entrust the web platforms with our sensitive data, financial information, and personal communication. However, this trust can easily be exploited by malicious actors through vulnerabilities like Cross-Site Scripting (XSS) and Cross-Site Request Forgery (CSRF) attacks. These attacks can compromise user security and steal valuable data, making web application security paramount.</p><p>In this article, we will learn about XSS and CSRF attacks, exploring their mechanisms, potential consequences, and most importantly, how to defend against them.</p><p>By understanding these threats, developers can build robust security measures that safeguard user data and maintain a trusted web environment.</p><figure><img alt="XSS vs CSRF Attack: Protecting your Web Applications" src="https://cdn-images-1.medium.com/max/626/0*XXu3rzfeORKTHp9L.jpg" /></figure><h3>What is XSS (Cross-Site Scripting) Attack?</h3><p><strong>XSS (Cross-Site Scripting)</strong> is a web security vulnerability that allows attackers to inject malicious scripts into otherwise trusted websites. These scripts are then executed within the victim’s browser when they visit the vulnerable website.</p><p>There are three main types of XSS attacks:</p><p><strong>1. Reflected XSS:</strong> This is the most common type of XSS. It occurs when an attacker injects malicious code into a web form or URL parameter. The vulnerable web application reflects this code in the user’s browser as part of the response. The malicious code is also executed when the user’s browser renders the response.</p><ul><li><strong>Example:</strong> Imagine a search function on a website that doesn’t properly validate user input. An attacker could enter a search query like &lt;script&gt;alert(&#39;XSS Attack!&#39;)&lt;/script&gt;. When the search results are displayed, the victim&#39;s browser executes this script, causing an alert box with the &quot;XSS Attack!&quot; message.</li></ul><p><strong>2. Stored XSS:</strong> This type of XSS occurs when an attacker injects malicious code that is stored on the web server. This code is then displayed to any user who visits the affected page.</p><ul><li><strong>Example:</strong> A forum application might allow users to post comments. An attacker could inject malicious code into a comment if the application doesn’t properly validate user input. This code would then be displayed to any user who reads the comment, potentially stealing their session cookie or performing other malicious actions.</li></ul><p><strong>3. DOM-based XSS:</strong> This type of XSS exploits vulnerabilities in the way that web browsers handle the Document Object Model (DOM). It doesn’t involve storing malicious code on the server. Instead, the attacker manipulates the DOM on the client side (victim’s browser) to inject and execute malicious scripts.</p><ul><li><strong>Example:</strong> An attacker might send a victim a link that the victim will click, and the attacker will modify the DOM of a legitimate website to inject a malicious script. This script could then steal the victim’s login credentials or perform other actions.</li></ul><p>In all these scenarios, the key is that the attacker tricks the victim’s browser into trusting and executing malicious code. This code can then steal sensitive information, hijack accounts, deface websites, or perform other harmful actions.</p><h3>What is CSRF (Cross-Site Request Forgery) Attack?</h3><p><strong>Cross-Site Request Forgery (CSRF)</strong> is a web security vulnerability that allows an attacker to trick a user’s authenticated browser into performing unwanted actions on a specific web application. In simpler terms, the attacker manipulates the victim’s browser to send requests to a trusted website, but with the intention the user will not approve.</p><p>The core idea behind CSRF is exploiting the trust a user’s browser has for a website they’re already logged into. When a user is logged in, their browser automatically sends their session credentials (often in cookies) with every request to that website. A CSRF attack leverages this behavior to trick the browser into sending these credentials with a malicious request, even though the user never intended to perform that action.</p><p>There are two main things an attacker needs to pull off a successful CSRF attack:</p><ol><li><strong>Valid User Session:</strong> The attacker needs the victim to be logged in to the vulnerable web application because the attack relies on the victim’s browser already having a valid session and the associated credentials.</li><li><strong>Tricking the Victim:</strong> The attacker convinces the victim to send the malicious request. This is typically done through social engineering techniques. For instance, the attacker might send the victim an email with a link that seems to be legitimate but triggers unwanted action on the vulnerable website.</li></ol><p><strong>Example Scenario:</strong></p><p>Imagine Alice is logged in to her online banking website. An attacker creates a malicious webpage that, when loaded, automatically submits a transfer request to Alice’s bank account. The attacker then sends Alice an email with a link to this malicious webpage disguised as a link to a funny cat video. If Alice clicks on the link, her browser will be tricked into sending the transfer request along with her session cookies, potentially allowing the attacker to steal money from her account.</p><h3>The Difference: XSS vs CSRF Attack</h3><figure><img alt="XSS vs CSRF Attack: Protecting your Web Applications" src="https://cdn-images-1.medium.com/max/850/1*O0GpqIzc7A1Hq2aML7WqGg.png" /></figure><figure><img alt="XSS vs CSRF Attack: Protecting your Web Applications" src="https://cdn-images-1.medium.com/max/841/1*jRex-V1sCD5HvuvvhWWU_g.png" /></figure><figure><img alt="XSS vs CSRF Attack: Protecting your Web Applications" src="https://cdn-images-1.medium.com/max/844/1*E0dl9sxe111azsN2Ysvwhw.png" /></figure><h3>Potential Impacts of XSS A<strong>ttacks:</strong></h3><ul><li><strong>Data Theft:</strong> Malicious scripts injected through XSS can steal sensitive information from a user’s session, such as cookies, login credentials, credit card details, or any other data stored by the web application. This stolen data can be used for further attacks or sold on the dark web.</li><li><strong>Account Takeover:</strong> By stealing session cookies or login credentials, attackers can hijack a user’s account and gain full access. This can allow them to impersonate the user, change account settings, send malicious messages, or perform unauthorized actions.</li><li><strong>Malware Distribution:</strong> XSS can be used to inject malicious code that downloads and installs malware onto a user’s device. This malware can steal data, spy on user activity, or damage the system.</li><li><strong>Website Defacement:</strong> Attackers can use XSS to deface a website by injecting code that alters its content. This can damage the website’s reputation and confuse users.</li><li><strong>Phishing Attacks:</strong> XSS can create phishing attacks that appear to come from a trusted source. These attacks can trick users into revealing sensitive information or clicking on malicious links.</li></ul><h3><strong>Potential Impact of CSRF Attacks:</strong></h3><ul><li><strong>Unauthorized Transactions:</strong> CSRF attacks can force a user’s browser to perform unauthorized actions on a vulnerable web application. This could involve transferring money, changing account settings, purchasing unwanted items, or performing any action that the user is authorized to do.</li><li><strong>Data Modification:</strong> Attackers can use CSRF to modify data on a web application. This could involve changing a user’s profile information, deleting data, or manipulating other sensitive information.</li><li><strong>Denial-of-Service (DoS) Attacks:</strong> In some cases, CSRF attacks can overwhelm a web application with huge requests, causing it to crash or become unavailable to legitimate users.</li></ul><h3>Mitigating XSS Attacks</h3><ul><li><strong>Input Validation:</strong> Validate all user input to ensure it meets expected formats and doesn’t contain malicious code. This can help prevent attackers from injecting scripts into the application.</li><li><strong>Output Encoding:</strong> Encode all user input before displaying it on the web page. This ensures that any malicious code is rendered harmless. Common encoding techniques include HTML entity encoding and URL encoding.</li><li><strong>Content Security Policy (CSP):</strong> A CSP defines what resources (scripts, stylesheets, images) can be loaded from a web page. This helps prevent attackers from injecting their scripts from untrusted sources.</li></ul><h3><strong>CSRF Mitigation Techniques</strong></h3><ul><li><strong>CSRF Tokens:</strong> Generate a unique token for each user session and embed it within forms or requests. The server validates the presence and validity of the token before processing the request. This ensures that only authorized requests with valid tokens are processed.</li><li><strong>Double-Submit Cookies:</strong> Use a combination of a cookie and a hidden form field to store a random value. The server validates that the values in both the cookie and the form field match before processing the request. This adds an extra layer of security compared to just using tokens.</li><li><strong>SameSite Attribute:</strong> This attribute for cookies specifies whether the cookie should be sent in cross-site requests. Setting the SameSite attribute to ‘Strict’ helps prevent CSRF attacks as the cookie won’t be sent when making requests from a different website.</li></ul><h3>Conclusion</h3><p>For developers, implementing proper security measures like input validation, output encoding, Content Security Policy (CSP) for XSS, CSRF tokens, double-submit cookies, and SameSite attribute can significantly improve the security posture of their web applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f36aee91153d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to use MLflow for Multi-Model Serving with External LLMs?]]></title>
            <link>https://thetechplatform.medium.com/how-to-use-mlflow-for-multi-model-serving-with-external-llms-117a895f73d5?source=rss-f458f38f5c02------2</link>
            <guid isPermaLink="false">https://medium.com/p/117a895f73d5</guid>
            <category><![CDATA[ai-model]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[The Tech Platform]]></dc:creator>
            <pubDate>Fri, 12 Jul 2024 06:58:19 GMT</pubDate>
            <atom:updated>2024-07-12T06:58:19.345Z</atom:updated>
            <content:encoded><![CDATA[<p>LLMs are <a href="https://www.thetechplatform.com/post/5-biggest-artificial-intelligence-ai-trends-2023">artificial intelligence</a> trained on massive amounts of text data, allowing them to understand and process language with remarkable sophistication. Their ability to handle complex tasks and generate human-like text makes them increasingly important in various fields.</p><figure><img alt="How to use MLflow for Multi-Model Serving with External LLMs?" src="https://cdn-images-1.medium.com/max/791/0*cDdDis-ZPFbJtpjE.png" /></figure><p>As <a href="https://www.thetechplatform.com/post/large-language-models-definition-capabilities-risks-and-best-practice">LLMs</a> and other <a href="https://www.thetechplatform.com/post/machine-learning-models-best-tools-and-techniques-to-deploy">machine learning models</a> become more powerful, deploying and managing them effectively becomes crucial. MLflow is an open-source platform that streamlines the entire machine learning lifecycle, from experimentation and training to deployment and monitoring. It provides tools:</p><ul><li>To track and compare different training runs of your models, making it easier to identify and configure.</li><li>Helps package trained models into a standard format, facilitating deployment across different environments.</li><li>Manage different versions of your models and track their performance.</li></ul><p>You can build even better programs by using MLflow to connect your applications with different powerful language models (like fancy AI programs that understand text). These new programs can be flexible and handle various situations because they can choose the best language model for the job.</p><p>Let’s explore how to use MLflow for Multi-Model Serving with External LLMs.</p><h3>What is Multi-Model Serving?</h3><p>Multi-model serving (MMS) is a technique in machine learning that allows you to deploy and manage <strong>multiple machine learning models</strong> behind a single serving endpoint. This means you can have an application or service to access and utilize the predictions or outputs from various models depending on the specific task or situation.</p><p>Here are some key characteristics of multi-model serving:</p><ul><li><strong>Flexibility:</strong> MMS lets you choose the most suitable model for a given task at runtime. This can be based on model specialization, accuracy requirements, or resource constraints.</li><li><strong>Scalability:</strong> By efficiently sharing resources across multiple models, MMS can improve overall serving efficiency and handle increased workloads.</li><li><strong>Fault Tolerance:</strong> If one model becomes unavailable or encounters issues, the serving endpoint can still function by routing requests to other available models.</li><li><strong>A/B Testing:</strong> MMS facilitates A/B testing where you can compare the performance of different models on the same data and choose the best-performing one.</li></ul><p>There are two main approaches to multi-model serving:</p><ol><li><strong>Model Selection:</strong> In this approach, the serving endpoint analyzes the incoming request and selects the most appropriate model based on pre-defined criteria. This could involve factors like the type of data, the desired task, or the specific needs.</li><li><strong>Traffic Splitting:</strong> The incoming traffic is distributed among different models than a pre-defined ratio. This can be helpful for scenarios where you want to explore the performance of multiple models simultaneously or leverage the strengths of various models for different use cases.</li></ol><p>In this, we will use traffic splitting multi-model serving for routing requests between the two external Large Language Models (LLMs).</p><h4>Multi-Model Serving vs. Single-Model Deployment for LLMs</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/912/1*ZvcwbDWBOsH3_JfH8y5fEQ.png" /></figure><p><strong>Additional:</strong></p><ul><li><strong>Cost:</strong> Multi-model serving can incur higher costs due to the potential use of multiple external services or increased resource consumption.</li><li><strong>Latency:</strong> Complex traffic routing logic in multi-model serving might introduce slight latency overhead compared to single-model deployment.</li></ul><p>Multi-model serving offers greater flexibility, scalability, and fault tolerance than single-model deployment for LLMs. It’s particularly beneficial when you need to:</p><ul><li>Utilize different LLM strengths for various tasks.</li><li>Build robust systems with redundancy.</li><li>Conduct A/B testing for model comparison.</li></ul><h3>How to use MLflow for Multi-Model Serving with External LLMs?</h3><p>The steps involved in creating a serving endpoint using MLflow on Azure Databricks to route traffic between multiple external Large Language Models (LLMs) are:</p><h4>STEP 1. Installation and Configuration of mlflow.deployments</h4><p>Since <a href="https://www.thetechplatform.com/post/filestore-easier-data-access-in-azure-databricks">Azure Databricks</a> offers a managed version of MLflow, you typically don’t need separate installation. However, to leverage the mlflow.deployments functionalities for creating serving endpoints, some configuration might be required. Here’s what you might encounter:</p><ul><li><a href="https://www.thetechplatform.com/post/3-reasons-to-choose-a-wide-cluster-over-multi-cluster-with-kubernetes"><strong>Cluster</strong></a><strong> Configuration:</strong> Depending on your cluster setup in Databricks, you might need to ensure libraries like mlflow and its dependencies are available on the cluster workers. This could involve installing required libraries using cluster configuration options within the Databricks workspace.</li><li><strong>Spark Version Compatibility:</strong> The mlflow.deployments library might have specific Spark version compatibility requirements. Verify the compatibility with your current Databricks environment to avoid potential issues.</li></ul><h4>STEP 2. Specifying the “served_entities” Section</h4><p>This section within the endpoint configuration defines the details of the external LLMs you want to integrate:</p><ul><li><strong>Unique Names:</strong> Each LLM must have a unique name within the endpoint. This allows the serving logic to differentiate between them when routing requests. The code snippet uses “served_model_name_1” and “served_model_name_2” for the two LLMs.</li><li><strong>Provider Details:</strong> Specify the provider of the LLM service. In the example, “openai” indicates OpenAI’s GPT-4, and “anthropic” refers to Anthropic’s claude-3-opus-20240229.</li><li><strong>Task Type:</strong> Define the type of task the LLM can handle. The “llm/v1/chat” suggests it’s a chat-related task, but this can vary depending on the specific LLM capabilities.</li><li><strong>External Model Configuration:</strong> This section provides details for accessing the external service. The code snippet demonstrates using Databricks Secrets to store API keys:</li><li><strong>openai_config:</strong> Likely contains the key “openai_api_key” referencing a secret holding the OpenAI API key.</li><li><strong>anthropic_config: </strong>Similar to openai_config, this likely holds the Anthropic API key for accessing claude-3-opus-20240229.</li></ul><p>Essentially, the “served_entities” section creates a mapping between the unique names and the external LLM service details.</p><h4>STEP 3. Setting Up Traffic Allocation with the “traffic_config” Section</h4><p>This section defines how incoming requests are distributed among the different LLMs:</p><ol><li><strong>Traffic Splitting:</strong> The code utilizes traffic splitting to route requests. This involves specifying the percentage of traffic directed to each LLM. In the example, a 50/50 split is used with:</li></ol><ul><li>“traffic_percentage”: 50 for “served_model_name_1” (gpt-4).</li><li>“traffic_percentage”: 50 for “served_model_name_2” (claude-3-opus-20240229).</li></ul><p><strong>2. Alternative Approaches:</strong> While the code shows a 50/50 split, you can adjust the percentages to favor specific models based on their strengths or resource requirements. Additionally, advanced configurations might allow for dynamic traffic allocation based on real-time factors like model performance or workload distribution.</p><p>The “traffic_config” section dictates the load-balancing strategy for routing requests to the available external LLMs.</p><h4>Code</h4><p>This code demonstrates a basic example with a 50/50 split. To create different traffic allocation strategies you can adjust the “traffic_percentage” values in the “routes” list.</p><pre>import mlflow.deployments<br><br># Assuming mlflow.deployments is already configured within your Databricks environment<br><br># Create a client to interact with the Databricks deployment service<br>client = mlflow.deployments.get_deploy_client(&quot;databricks&quot;)<br><br># Define the endpoint name<br>endpoint_name = &quot;mix-chat-endpoint&quot;<br><br># Define the configuration dictionary for the endpoint<br>config = {<br>    # List of served entities (external LLMs)<br>    &quot;served_entities&quot;: [<br>        {<br>            # Unique name for the first LLM<br>            &quot;name&quot;: &quot;served_model_name_1&quot;,<br>            # External model configuration for the first LLM<br>            &quot;external_model&quot;: {<br>                # Name of the LLM provider (e.g., OpenAI)<br>                &quot;name&quot;: &quot;gpt-4&quot;,<br>                # Task type this LLM can handle (e.g., chat)<br>                &quot;task&quot;: &quot;llm/v1/chat&quot;,<br>                # Configuration for accessing the external service (OpenAI in this case)<br>                &quot;openai_config&quot;: {<br>                    # Accessing OpenAI API key securely using Databricks Secrets<br>                    &quot;openai_api_key&quot;: &quot;{{secrets/my_openai_secret_scope/openai_api_key}}&quot;<br>                }<br>            }<br>        },<br>        {<br>            # Unique name for the second LLM<br>            &quot;name&quot;: &quot;served_model_name_2&quot;,<br>            # External model configuration for the second LLM<br>            &quot;external_model&quot;: {<br>                # Name of the LLM provider (e.g., Anthropic)<br>                &quot;name&quot;: &quot;claude-3-opus-20240229&quot;,<br>                # Task type this LLM can handle (e.g., chat)<br>                &quot;task&quot;: &quot;llm/v1/chat&quot;,<br>                # Configuration for accessing the external service (Anthropic in this case)<br>                &quot;anthropic_config&quot;: {<br>                    # Accessing Anthropic API key securely using Databricks Secrets<br>                    &quot;openai_api_key&quot;: &quot;{{secrets/my_anthropic_secret_scope/anthropic_api_key}}&quot;<br>                }<br>            }<br>        }<br>    ],<br>    # Traffic allocation configuration<br>    &quot;traffic_config&quot;: {<br>        # Routes for distributing traffic<br>        &quot;routes&quot;: [<br>            # 50% traffic to served_model_name_1 (gpt-4)<br>            {&quot;served_model_name&quot;: &quot;served_model_name_1&quot;, &quot;traffic_percentage&quot;: 50},<br>            # 50% traffic to served_model_name_2 (claude-3-opus-20240229)<br>            {&quot;served_model_name&quot;: &quot;served_model_name_2&quot;, &quot;traffic_percentage&quot;: 50}<br>        ]<br>    }<br>}<br><br># Create the serving endpoint using the client and configuration<br>client.create_endpoint(name=endpoint_name, config=config)<br><br>print(f&quot;Serving endpoint &#39;{endpoint_name}&#39; created successfully!&quot;)</pre><h3>Conclusion</h3><p>This article explored the powerful combination of MLflow and external Large Language Models (LLMs). This approach opens doors for innovative applications across various fields:</p><ul><li><strong>Natural Language Processing (NLP):</strong> Enhance the accuracy and efficiency of tasks like machine translation, text summarization, and sentiment analysis by leveraging the strengths of different LLMs.</li><li><strong>Creative Content Generation:</strong> Develop applications to generate unique and engaging content in various formats, from marketing copy to poems and scripts.</li><li><strong>Intelligent Chatbots:</strong> Build chatbots that can hold more natural and nuanced conversations by utilizing the capabilities of multiple LLMs.</li></ul><p>The future of multi-model serving with external LLMs is bright!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=117a895f73d5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Golang Enum: A Practical Guide]]></title>
            <link>https://thetechplatform.medium.com/golang-enum-a-practical-guide-816a509f248a?source=rss-f458f38f5c02------2</link>
            <guid isPermaLink="false">https://medium.com/p/816a509f248a</guid>
            <category><![CDATA[enum]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[golang-tutorial]]></category>
            <category><![CDATA[golang-development]]></category>
            <dc:creator><![CDATA[The Tech Platform]]></dc:creator>
            <pubDate>Wed, 10 Jul 2024 07:08:28 GMT</pubDate>
            <atom:updated>2024-07-10T07:08:28.121Z</atom:updated>
            <content:encoded><![CDATA[<p>Enums, short for enumerations, are a way to represent a fixed set of related constants with distinct values. They’re commonly used to define a specific range of options or states within a program, for example, days of the week, HTTP status codes, or different roles in an application.</p><p><a href="https://www.thetechplatform.com/post/golang-for-loop-a-comprehensive-guide">Golang </a>enum doesn’t have built-in enum types like other languages (e.g., C# or Java). However, Go provides alternative approaches to achieve similar functionality. Developers often use constants or custom types to emulate enums. Let’s explore those alternatives!</p><p>Read: <a href="https://www.thetechplatform.com/post/best-golang-ides-the-top-10-picks">Best Golang IDEs: The Top 10 Picks</a></p><figure><img alt="Golang Enum: A Practical Guide" src="https://cdn-images-1.medium.com/max/946/1*PGvfKpAcqY8RE1OoHUNa0Q.png" /></figure><p>This guide will give you the knowledge to emulate enum in <a href="https://www.thetechplatform.com/post/golang-programming-language">Golang</a> applications. We’ll explore two main approaches: using constants with iota and creating custom types. By the end, you’ll be well-versed in leveraging enums to boost the clarity and efficiency of your Go code.</p><p>Read: <a href="https://www.thetechplatform.com/post/how-to-validate-domain-names-in-go-golang-and-c-c">How to Validate Domain Names in Go(Golang)?</a></p><p>To proceed, it’s important to grasp the difference between Go’s approach to Golang enums and native enums:</p><h4>Differences between Golang enum and native enum</h4><p>Let’s compare Go’s approach to native enums:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/903/1*BFgN8oaVO0bkpEPBHfuDnw.png" /></figure><h3>Emulating Enums in Go</h3><p>In Go (Golang), enumerations (enums) are not directly built into the language. However, developers can achieve enum-like behavior using alternative approaches. Let’s explore these alternatives:</p><h3>Defining Golang Enum as Constants:</h3><p>Constraints in traditional enums often refer to restrictions placed on the allowed values or associated data types. In Golang’s emulated enums with constants, constraints are achieved through a combination of:</p><ul><li><strong>Golang Type Safety:</strong> Defining the Golang enum as a constant type (e.g., int or string) inherently restricts the variable’s type. It can only hold values defined within the enum itself.</li><li><strong>Limited Control with iota:</strong> Using iota for constant assignments offers a basic level of constraint by assigning sequential values. This helps prevent assigning unrelated numbers outside the defined range. However, it doesn’t enforce specific value names.</li></ul><p><strong>Defining Golang constants with iota:</strong></p><p>STEP 1: Declare the Enum Type:</p><pre>const ( // Your enum options here )</pre><p>STEP 2: Assign Initial Value (Optional):</p><pre>const ( <br>	Sunday = 0 // Initial value for the first option (optional) <br>	Monday = iota <br>	Tuesday // ... <br>)</pre><p>Assign the desired initial value (often 0) to the first constant if using integer values.</p><p>STEP 3: Define Enum Options with iota:</p><pre>const ( <br>	Sunday = 0 // Initial value for the first option (optional) <br>	Monday = iota <br>	Tuesday <br>	Wednesday // ... <br>)</pre><ul><li>Create constants with descriptive names representing your enum options.</li><li>iota automatically assigns sequential integer values (or string literals if using string type) to each subsequent constant.</li></ul><p><strong>Example:</strong></p><pre>const (<br>  Sunday = 0<br>  Monday = iota<br>  Tuesday<br>  Wednesday<br>  Thursday<br>  Friday<br>  Saturday<br>)<br><br>// This is valid because the variable is of type Day and can only hold values defined in the enum<br>var today Day = Monday<br><br>// This would result in a compile-time error because the value is not part of the enum<br>// var invalidDay Day = 10</pre><h3>Golang Custom Types:</h3><p>Golang allows you to create custom types to emulate enums, offering more flexibility and type safety compared to using constants with iota.</p><p><strong>STEP 1: Define the Golang Custom Types:</strong></p><ul><li>Declare a new type using the type keyword followed by a name (often PascalCase like DayOfWeek).</li><li>Set the underlying type within parentheses (usually int or string for enum values).</li></ul><p><strong>STEP 2: Define Enum in Golang with Options as Unexported Constants:</strong></p><ul><li>Create constants with descriptive names representing your enum options, inside the custom type definition.</li><li>Make these constants unexported (private) using lowercase names to prevent accidental usage outside the type.</li><li>Assign the desired integer or string values to these constants.</li></ul><p><strong>Example:</strong></p><pre>type DayOfWeek int<br><br>const (<br>  sunday DayOfWeek = iota // Unexported constant<br>  monday<br>  tuesday<br>  // ...<br>)</pre><ul><li>We define a custom type DayOfWeek with an underlying type int.</li><li>Inside the type definition, we create unexported constants like Sunday, Monday, etc., representing the days of the week.</li><li>Iota is still used here, but its values are assigned to the unexported constants for internal use.</li></ul><p><strong>Benefits:</strong></p><ul><li><strong>Golang Type Safety:</strong> The variable’s type enforces can only hold values defined within the enum.</li><li><strong>Encapsulation:</strong> Unexported constants within the type hide implementation details and prevent misuse.</li><li><strong>Flexibility:</strong> You can add methods to the custom type to define additional behavior specific to the enum.</li></ul><p><strong>Example Usage:</strong></p><pre>var today DayOfWeek = monday<br><br>fmt.Println(today) // Prints &quot;monday&quot;<br><br>// This would result in a compile-time error because &quot;Wednesday&quot; is not a public constant<br>// fmt.Println(Wednesday)</pre><p><strong>Choosing When to Use:</strong></p><p>This approach is ideal for complex enums where you might need:</p><ul><li>Additional methods associated with the enum values (e.g., converting to string).</li><li>Stricter-type safety to prevent accidental usage of invalid values.</li></ul><p>Read: <a href="https://www.thetechplatform.com/post/csharp">C# vs Golang: Difference and Similarities</a></p><h3>String Representation:</h3><p>By default, Custom type Go enum is their underlying integer value (e.g., 0 for Sunday). Implementing a String method allows you to convert these internal values to human-readable strings (“Sunday”). This improves code readability and makes it easier to work with enums.</p><p><strong>Example with String Method:</strong></p><pre>type DayOfWeek int<br><br>const (<br>  sunday DayOfWeek = iota // Unexported constant<br>  monday<br>  tuesday<br>  // ...<br>)<br><br>func (d DayOfWeek) String() string {<br>  days := [...]string{&quot;Sunday&quot;, &quot;Monday&quot;, &quot;Tuesday&quot;, /* ... */}<br>  if d &lt; 0 || d &gt;= len(days) {<br>    return &quot;Invalid DayOfWeek&quot;<br>  }<br>  return days[d]<br>}<br><br>day := monday<br><br>fmt.Println(day)       // Prints &quot;0&quot; (underlying integer value)<br>fmt.Println(day.String()) // Prints &quot;Monday&quot; (string representation)</pre><ol><li>We define a String method on the DayOfWeek type.</li><li>Inside the method:</li></ol><ul><li>We create slice days containing the string representations of each day.</li><li>We check if the DayOfWeek value is within the valid range of the slice index.</li><li>If valid, we return the corresponding string from the day’s slice using the value as the index.</li><li>If invalid, we return a message indicating an “Invalid DayOfWeek”.</li></ul><p><strong>Benefits:</strong></p><ul><li>Improves code readability by displaying human-readable strings.</li><li>It simplifies working with enums in functions that expect strings.</li></ul><h3>When to use enums in Golang?</h3><p>Knowing when to use enum in Golang is essential for writing clean, maintainable code. Here are some scenarios where enums are handy:</p><ol><li><strong>Status Codes and Flags</strong>: Use Golang enums to represent status codes (e.g., success, error, warning) or flags (on/off, enabled/disabled). Example: Define an enum for HTTP status codes (200, 404, 500) or user roles (admin, user, guest).</li><li><strong>Options and Configuration</strong>: When you have a finite set of options to handle enums in different cases. Example: Enum for sorting options (ascending, descending) or logging levels (debug, info, error).</li><li><strong>Domain-Specific Values</strong>: Enums help express domain-specific concepts clearly — for example, Days of the week (Monday to Sunday), and months (January to December).</li><li><strong>State Machines and Finite State Transitions</strong>: Represent states and transitions in state machines using enums. Example: A traffic light state machine (red, yellow, green).</li><li><strong>Type Safety and Readability</strong>: Custom enum types enhance type safety and make code more readable. Example: Define a <strong>Season</strong> enum (Spring, Summer, Autumn, Winter) instead of using raw integers.</li></ol><h3>Benefits of using enums in Golang</h3><ol><li>Golang enum make code more readable by replacing cryptic integer or string literals with clear and descriptive names.</li><li>Enums enforce type safety by restricting variables to a predefined set of values. This reduces the risk of runtime errors caused by typos or accidental assignment of invalid values.</li><li>By using enums for domain-specific concepts, you prevent errors caused by using incorrect values. For example, an OrderStatus enum ensures you only use valid states like “pending” or “shipped” instead of typos or unexpected strings.</li></ol><h3>Limitations of using enums in Golang</h3><ol><li>Offers less flexibility. You can’t easily add methods or behaviors directly to enums defined with constants and iota.</li><li>Using constants and iota might introduce unnecessary boilerplate code compared to using raw literals for simple enums with just a few options.</li><li>Adding new options later might require code changes in multiple places, impacting maintainability.</li></ol><h3>Golang Enum Best Practices</h3><ul><li><strong>Clear and Descriptive Names:</strong> Use meaningful names for the enum type (e.g., WeekDay, OrderStatus) and its options (e.g., Sunday, Monday, Pending, Shipped). This improves code readability and maintainability.</li><li><strong>Consistent Naming Conventions:</strong> Maintain consistency in naming conventions for enum types and options. Common approaches include PascalCase (e.g., OrderStatus) or snake_case (e.g., order_status).</li><li><strong>Avoid Magic Numbers:</strong> Eliminate raw integer or string literals scattered throughout your code. Enums centralize these values, making them easier to manage and update.</li><li><strong>Handle Edge Cases:</strong> Consider all potential scenarios when defining your enum. If new options become necessary, ensure the design allows for easy expansion.</li><li><strong>Document Your Enums:</strong> Provide clear comments explaining the purpose of the enum, its allowed values, and any relevant usage guidelines. Documentation helps other developers understand your code.</li><li><strong>Choose the Right Approach:</strong> Constants with iota are for simple cases with few options. Consider custom types enums of Golang for complex enums requiring additional behavior or type safety.</li><li><strong>Leverage Tools:</strong> Utilize tools like the stringer package to generate string conversion methods for your custom-type enums. This simplifies interacting with the enum values as strings.</li></ul><h3>Conclusion</h3><p>While Go doesn’t offer native enums, the techniques covered in this article — using constants with iota and creating custom types — provide effective workarounds. Remember, Golang enums (emulated enums) excel when representing a well-defined set of values within your program’s domain. By leveraging these techniques, you can significantly improve the readability, maintainability, and type safety of Golang code.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=816a509f248a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cookies-Based Authentication vs Token-Based Authentication]]></title>
            <link>https://thetechplatform.medium.com/cookies-based-authentication-vs-token-based-authentication-b385c1fc56aa?source=rss-f458f38f5c02------2</link>
            <guid isPermaLink="false">https://medium.com/p/b385c1fc56aa</guid>
            <category><![CDATA[aspnetcore]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[website-development]]></category>
            <category><![CDATA[security-token]]></category>
            <category><![CDATA[aspnet]]></category>
            <dc:creator><![CDATA[The Tech Platform]]></dc:creator>
            <pubDate>Thu, 04 Jul 2024 14:49:53 GMT</pubDate>
            <atom:updated>2024-07-04T14:49:53.280Z</atom:updated>
            <content:encoded><![CDATA[<p>Understanding the difference between cookie-based and token-based authentication is crucial because it helps developers make informed decisions when designing and securing their applications.</p><figure><img alt="Cookies-Based Authentication vs Token-Based Authentication" src="https://cdn-images-1.medium.com/max/970/0*MSGovhqS2SmSaZTw.jpg" /></figure><p>Let’s explore why this knowledge matters:</p><figure><img alt="Cookies-Based Authentication vs Token-Based Authentication" src="https://cdn-images-1.medium.com/max/757/1*2yzULZjjkmRF1jePIza97A.png" /></figure><p>Let’s consider a simple scenario where we have a web application that allows users to access a restricted resource (e.g., a dashboard) after logging in. We’ll explore how both cookie-based and token-based authentication work in this context.</p><h3>Cookie-Based Authentication</h3><p>Cookie-based authentication is a method where user authentication information is stored and managed using <a href="https://www.thetechplatform.com/post/explore-the-inner-working-of-cookies-in-asp-net"><strong>cookies</strong></a>. These cookies are sent between the client (usually a web browser) and the server.</p><p>Here we will see how this works:</p><p><strong>STEP 1: User Login</strong>:</p><ul><li>When a user logs in, the server validates their credentials (username and password).</li><li>If the credentials are correct, the server creates an authentication cookie.</li><li>This cookie contains a session ID or user-specific data (encrypted and signed).</li><li>The server sends the back cookie to the client (usually the browser).</li></ul><p><strong>STEP 2: Subsequent Requests</strong>:</p><ul><li>The browser includes the authentication cookie in the request headers when the user accesses a restricted resource (e.g., the dashboard).</li><li>The server decrypts and verifies the cookie to identify the user.</li><li>The server grants access to the requested resource if the cookie is valid.</li></ul><p><strong>STEP 3: Session Management</strong>:</p><ul><li>The server maintains the session state (e.g., session duration, expiration).</li><li>The server invalidates the cookie if the user logs out or the session expires.</li></ul><p><strong>Advantage</strong>: Simplicity, session management, domain-bound.</p><p><strong>Disadvantage</strong>: Vulnerable to <a href="https://www.thetechplatform.com/post/csrf-protection-in-asp-net-core-a-comprehensive-guide">CSRF attacks</a>, limited scalability.</p><h4>Example Code:</h4><p>In Startup.cs: We configure cookie-based authentication using services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).</p><pre>public void ConfigureServices(IServiceCollection services)<br>{<br>    // Other services configuration...<br><br>    services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)<br>        .AddCookie(options =&gt;<br>        {<br>            options.LoginPath = &quot;/Account/Login&quot;; // Customize login path<br>            options.AccessDeniedPath = &quot;/Account/AccessDenied&quot;; // Customize access denied path<br>        });<br><br>    // Other configurations...<br>}</pre><p>We customize the login path and access denied path.</p><p>In AccountController.cs: The Login action handles user login. If the user’s credentials are valid, we create an authentication cookie using HttpContext.SignInAsync. If not, we display an error message.</p><pre>public async Task&lt;IActionResult&gt; Login(LoginViewModel model)<br>{<br>    // Validate user credentials (e.g., against a database)<br>    if (IsValidUser(model.Username, model.Password))<br>    {<br>        var claims = new List&lt;Claim&gt;<br>        {<br>            new Claim(ClaimTypes.Name, model.Username),<br>            // Add other claims (e.g., roles)<br>        };<br><br>        var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);<br>        await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(identity));<br><br>        return RedirectToAction(&quot;Dashboard&quot;);<br>    }<br><br>    ModelState.AddModelError(&quot;&quot;, &quot;Invalid credentials&quot;);<br>    return View(model);<br>}</pre><p>In DashboardController.cs: The Dashboard action is marked with [Authorize], requiring authentication. If the user has a valid authentication cookie, they can access the dashboard.</p><pre>[Authorize] // Requires authentication<br>public IActionResult Dashboard()<br>{<br>    // Display dashboard content<br>    return View();<br>}</pre><h3>Token-Based Authentication</h3><p>Token-based authentication is a method where authentication is performed using tokens. Tokens verify the user’s identity instead of relying on session cookies (like cookie-based authentication).</p><p>Let’s see how this works:</p><p><strong>STEP 1: User Login</strong>:</p><ul><li>After successful login, the server generates a JWT <a href="https://www.thetechplatform.com/post/what-is-javascript-web-token-when-and-why-to-use-jwt-where-to-store-json-jwt">(JSON Web Token)</a>.</li><li>The <a href="https://www.thetechplatform.com/post/jwt-and-refresh-tokens-in-asp-net-core">JWT</a> contains claims (e.g., user ID, roles) and is signed with a secret key.</li><li>The server sends the JWT to the client (usually a Single-Page Application or mobile app).</li></ul><p><strong>STEP 2: Subsequent Requests</strong>:</p><ul><li>The client stores the JWT (e.g., in local storage).</li><li>For each subsequent request (e.g., fetching data from an API), the client includes the JWT in the Authorization header.</li><li>The server verifies the JWT’s signature using the secret key.</li><li>The server grants access if the signature is valid and the token hasn’t expired.</li></ul><p><strong>STEP 3: Statelessness</strong>:</p><ul><li>Unlike cookies, tokens are stateless. The server doesn’t maintain a session state.</li><li>This makes token-based authentication highly scalable and suitable for microservices and APIs.</li></ul><p><strong>Advantage</strong>: Stateless, immune to <a href="https://www.thetechplatform.com/post/csrf-protection-in-asp-net-core-a-comprehensive-guide">CSRF attacks</a>, scalable.</p><p><strong>Disadvantage</strong>: Requires additional setup (e.g., JWT handling).</p><p><strong>Read: </strong><a href="https://www.thetechplatform.com/post/secure-authentication-via-json-web-tokens-jwt"><strong>Secure Authentication via JSON Web Tokens (JWT)</strong></a></p><h4>Example Code:</h4><p>In Startup.cs: We configure token-based authentication using services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).</p><pre>public void ConfigureServices(IServiceCollection services)<br>{<br>    // Other services configuration...<br><br>    services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)<br>        .AddJwtBearer(options =&gt;<br>        {<br>            options.TokenValidationParameters = new TokenValidationParameters<br>            {<br>                ValidateIssuer = true,<br>                ValidateAudience = true,<br>                ValidateIssuerSigningKey = true,<br>                ValidIssuer = &quot;your-issuer&quot;,<br>                ValidAudience = &quot;your-audience&quot;,<br>                IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(&quot;your-secret-key&quot;))<br>            };<br>        });<br><br>    // Other configurations...<br>}</pre><p>We set up validation parameters for JWTs.</p><p>In AuthController.cs: The GenerateToken action generates a JWT after a successful login. We create claims (e.g., user ID) and sign the token using a secret key. The client (SPA) receives this token.</p><pre>public IActionResult GenerateToken(string username)<br>{<br>    var claims = new List&lt;Claim&gt;<br>    {<br>        new Claim(ClaimTypes.Name, username),<br>        // Add other claims (e.g., roles)<br>    };<br><br>    var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(&quot;your-secret-key&quot;));<br>    var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);<br><br>    var token = new JwtSecurityToken(<br>        issuer: &quot;your-issuer&quot;,<br>        audience: &quot;your-audience&quot;,<br>        claims: claims,<br>        expires: DateTime.UtcNow.AddHours(1), // Set token expiration<br>        signingCredentials: creds<br>    );<br><br>    return Ok(new { token = new JwtSecurityTokenHandler().WriteToken(token) });<br>}</pre><p>In DashboardController.cs: The Dashboard action is marked with [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)], requiring a valid JWT. They can access the dashboard if the client includes a valid JWT in the request.</p><pre>[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)] // Requires JWT<br>public IActionResult Dashboard()<br>{<br>    // Display dashboard content<br>    return View();<br>}</pre><h3>Conclusion</h3><p>Choose the approach based on your application’s needs, security requirements, and client type.</p><p><strong>Use Cookie-Based Authentication When:</strong></p><ol><li><strong>Traditional Web Apps with Server-Side Rendering</strong>: If you’re building a web application with server-side rendering (e.g., ASP.NET MVC) and need a straightforward authentication mechanism.</li><li><strong>Session Management Requirements</strong>: When you want to manage user sessions easily (e.g., controlling session duration, handling logouts).</li></ol><p><strong>Use Token-Based Authentication When:</strong></p><ol><li><strong>Single-Page Apps (SPAs)</strong>: If you’re developing SPAs using frameworks like React, Angular, or Blazor.</li><li><strong>APIs and Microservices</strong>: For securing APIs or microservices.</li></ol><p>Both methods play essential roles in modern web development, and understanding their differences empowers developers to make informed decisions.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b385c1fc56aa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[State Management Libraries to Handle Large Datasets in Blazor Apps]]></title>
            <link>https://thetechplatform.medium.com/state-management-libraries-to-handle-large-datasets-in-blazor-apps-5d85485091e7?source=rss-f458f38f5c02------2</link>
            <guid isPermaLink="false">https://medium.com/p/5d85485091e7</guid>
            <category><![CDATA[web-applications]]></category>
            <category><![CDATA[aspnetcore]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[blazor]]></category>
            <category><![CDATA[aspnet]]></category>
            <dc:creator><![CDATA[The Tech Platform]]></dc:creator>
            <pubDate>Fri, 28 Jun 2024 09:13:43 GMT</pubDate>
            <atom:updated>2024-06-28T09:13:43.428Z</atom:updated>
            <content:encoded><![CDATA[<p>Blazor is a powerful framework for building web applications using C# and .NET. As your app grows in complexity, managing the application state becomes critical. State includes user preferences, data fetched from APIs, UI component states, and more.</p><p>We will explore State Management approaches and libraries specifically tailored for Blazor applications dealing with substantial data.</p><figure><img alt="State Management Libraries to Handle Large Datasets in Blazor Apps" src="https://cdn-images-1.medium.com/max/705/1*tVyo2vZ6A3U3u6hZz0m69Q.png" /></figure><h4>Why Do We Need State Management Libraries?</h4><ol><li><strong>Data Persistence</strong>: Large datasets require efficient storage and retrieval mechanisms.</li><li><strong>Reactivity</strong>: When data changes, UI components must update accordingly.</li><li><strong>Scalability</strong>: Handling state across multiple components and pages can become unwieldy without proper management.</li><li><strong>SEO Considerations</strong>: Prerendering and SEO optimization benefit from well-organized state management.</li></ol><h4>Benefits of State Management Libraries:</h4><ol><li><strong>Predictable Flow</strong>: Libraries enforce unidirectional data flow, making debugging easier.</li><li><strong>Efficient Updates</strong>: Components re-render only when necessary, improving performance.</li><li><strong>Abstraction</strong>: Libraries abstract away low-level state handling, allowing developers to focus on app logic.</li><li><strong>Integration</strong>: Libraries seamlessly integrate with Blazor components, ensuring consistent state management.</li></ol><h3>State Management Libraries to Handle Large Datasets in Blazor Apps</h3><p>Here are the most popular state management libraries and approaches to handle large datasets in blazor apps:</p><ol><li>Fluxor</li><li>Blazored.LocalStorage</li><li>Cortex.NET</li><li>Prerendering</li></ol><h4>1. Fluxor</h4><p>Fluxor is an open-source library designed specifically for managing application state within <a href="https://www.thetechplatform.com/post/advanced-techniques-for-optimizing-blazor-webassembly-applications">Blazor applications</a>. It draws inspiration from the Flux pattern, which originally emerged in Facebook’s React ecosystem. The primary goal of Fluxor is to make state changes transparent, predictable, and easy to debug.</p><p><strong>Flux Pattern</strong> is an architectural design that addresses the front end&#39;s complex state management challenges. The main goal of Flux is to make state changes transparent and predictable, simplifying unit testing and debugging.</p><p><strong>Core Concepts in Fluxor:</strong></p><ol><li><strong>Stores:</strong> In Fluxor, a <strong>store</strong> represents a specific domain of your application state. Each store manages a particular aspect of your app, such as user authentication or a shopping cart. Stores act as the central hub for handling state-related operations.</li><li><strong>Actions:</strong> Actions are events triggered by user interactions or other system events. They describe what happened in your application (e.g., “Add item to cart”). When an action occurs, it is dispatched to the relevant store.</li><li><strong>Reducers: </strong>Reducers are responsible for processing actions and producing new states. They take the current state and an action as input and return an updated state. By enforcing immutability, reducers ensure that state modifications are predictable and consistent.</li><li><strong>Effects: </strong>Effects handle side effects, such as making API calls or interacting with external services. Unlike reducers, effects can perform non-pure operations. Separating effects from reducers keeps the latter pure and testable.</li></ol><p>Fluxor has a unidirectional data flow pattern, which means data flows from parent components to children, preventing direct modification of parent or child state.</p><p>Here is an example that demonstrates how Fluxor manages state, actions, and reducers in a Blazor app:</p><p><strong>STEP 1: Setting Up Fluxor: </strong>First, register the Fluxor services in your Program.cs file:</p><pre>builder.Services.AddFluxor(o =&gt; <br>{<br>    o.ScanAssemblies(typeof(Program).Assembly);<br>    o.UseRouting();<br>    #if DEBUG<br>    o.UseReduxDevTools();<br>    #endif<br>});</pre><p>This will set up Fluxor for your Blazor app.</p><p><strong>STEP 2: Creating a Counter Feature: </strong>Let’s create a counter feature that increments and decrements a value. Define an action to handle incrementing the counter:</p><pre>public class IncrementCounterAction<br>{<br>    // Any necessary data for the action (e.g., step value)<br>}</pre><p>Next, create a reducer to handle this action:</p><pre>public class CounterReducer<br>{<br>    [ReducerMethod]<br>    public CounterState ReduceIncrementCounterAction(CounterState state, IncrementCounterAction action)<br>    {<br>        // Create a new state object with an incremented counter value<br>        return new CounterState(state.Count + 1);<br>    }<br>}</pre><p>The CounterState a class represents the state of our counter.</p><p><strong>STEP 3: State and Store: </strong>Define the initial state for the counter:</p><pre>public class CounterState<br>{<br>    public int Count { get; }<br><br>    public CounterState(int count)<br>    {<br>        Count = count;<br>    }<br>}</pre><p>Create a store to manage the counter state:</p><pre>public class CounterStore : Store&lt;CounterState&gt;<br>{<br>    public CounterStore()<br>    {<br>        // Initialize the state (e.g., set initial count to 0)<br>        State = new CounterState(0);<br>    }<br>}</pre><p><strong>STEP 4: UI Integration:</strong> In your Blazor component, inject the IState&lt;CounterState&gt; service:</p><pre>@inject IState&lt;CounterState&gt; CounterState</pre><p>Use the state in your component:</p><pre>&lt;h1&gt;Counter Value: @CounterState.Value.Count&lt;/h1&gt; &lt;button @onclick=&quot;Increment&quot;&gt;Increment&lt;/button&gt;</pre><p>Implement the Increment method to dispatch the action:</p><pre>private void Increment()<br>{<br>    // Dispatch the action<br>    Dispatcher.Dispatch(new IncrementCounterAction());<br>}</pre><p><strong>STEP 5: Effects (Optional):</strong> If you need side effects (e.g., API calls), create an effect:</p><pre>public class CounterEffects<br>{<br>    [EffectMethod]<br>    public async Task HandleIncrementCounterAction(IncrementCounterAction action, IDispatcher dispatcher)<br>    {<br>        // Perform any necessary side effects here<br>        // For example, update the server with the new count<br>    }<br>}</pre><p>Effects keep reducers pure by handling non-pure operations.</p><p><strong>Benefits of Using Fluxor:</strong></p><ol><li><strong>Predictability: </strong>Fluxor’s strict data flow simplifies debugging. You can trace how actions lead to state changes. Predictable behavior makes it easier to maintain and troubleshoot your app.</li><li><strong>Zero Boilerplate: </strong>Fluxor minimizes repetitive code. You define actions, reducers, and initial state succinctly. This simplicity allows you to focus on your application logic.</li><li><strong>Performance: </strong>Immutability ensures that only necessary components re-render when a state changes. This optimization improves performance, especially in large applications.</li><li><strong>Testability: </strong>Actions and reducers are easy to test in isolation. You can verify that state changes occur as expected.</li></ol><p><strong>Limitations:</strong></p><ol><li>Understanding Fluxor’s concepts may take time, especially if you’re new to the Flux pattern. Invest time in learning the library to reap its benefits.</li><li>Consider Fluxor when dealing with more complex state requirements.</li></ol><p><em>Read: </em><a href="https://www.thetechplatform.com/post/tools-to-build-asp-net-blazor-apps"><em>Tools to build ASP.NET Blazor Apps</em></a></p><h4>2. Blazored.LocalStorage</h4><p>Blazored.LocalStorage is an open-source library specifically designed for Blazor applications. Its primary purpose is to simplify working with local storage, allowing you to store and manage data on the client side.</p><p>In version 4, Blazored.LocalStorage switched to using the default JsonSerializerOptions from System.Text.Json. If you were using custom options in v3, you’ll need to adjust your configuration.</p><p>For backward compatibility, configure Blazored.LocalStorage with the following settings:</p><pre>builder.Services.AddBlazoredLocalStorage(config =&gt;<br>{<br>    config.JsonSerializerOptions.DictionaryKeyPolicy = JsonNamingPolicy.CamelCase;<br>    // Other options...<br>});</pre><p>Here is an example of how to store and retrieve data from local storage using Blazored.LocalStorage:</p><p><strong>STEP 1: </strong>First, make sure you’ve added the Blazored.LocalStorage package to your project. You can do this via NuGet or the .NET CLI.</p><p>For example, using the .NET CLI:</p><pre>dotnet add package Blazored.LocalStorage</pre><p><strong>STEP 2: Setup in Startup.cs:</strong> In your Startup.cs file, register the local storage services with the service collection:</p><pre>public void ConfigureServices(IServiceCollection services) <br>{     <br>  // Other services...     <br>  services.AddBlazoredLocalStorage(); <br>}</pre><p><strong>STEP 3: Usage in a Blazor Component:</strong> Here is an example where you want to store a user’s name in local storage.</p><p>Inject the ILocalStorageService into your Blazor component:</p><pre>@inject Blazored.LocalStorage.ILocalStorageService localStorage</pre><p>In your component, you can set and retrieve the user’s name:</p><pre>@code {<br>    private string userName;<br><br>    protected override async Task OnInitializedAsync()<br>    {<br>        // Set the user&#39;s name<br>        await localStorage.SetItemAsync(&quot;name&quot;, &quot;John Smith&quot;);<br><br>        // Retrieve the user&#39;s name<br>        userName = await localStorage.GetItemAsync&lt;string&gt;(&quot;name&quot;);<br>    }<br>}<br><br>&lt;h1&gt;Hello, @userName!&lt;/h1&gt;</pre><p>In this example, we set the name “John Smith” in local storage and then retrieve it to display in the UI.</p><p><strong>Benefits:</strong></p><ol><li><strong>Simplified Local Storage Interaction: </strong>Blazored.LocalStorage streamlines working with local storage in Blazor. You can easily store and retrieve data without dealing with low-level APIs.</li><li><strong>Automatic Serialization and Deserialization: </strong>When saving or retrieving values, the library handles serialization and deserialization automatically. Complex objects (e.g., dictionaries, lists) are serialized for storage and deserialized when retrieved.</li><li><strong>Large Data Storage:</strong> Local storage can store substantial amounts of data (compared to session storage). Use it for user preferences, cached form data, or other persistent client-side data.</li><li><strong>Cross-Tab Persistence: </strong>Data stored in local storage persists across browser tabs. Users can close and reopen tabs without losing their stored settings.</li></ol><p><strong>Limitations:</strong></p><ol><li>Local storage is specific to a domain (origin). Data saved in one domain’s local storage won’t be accessible from another domain.</li><li>Local storage has a size limit (usually around 5–10 MB per domain). Be careful to store large datasets, as exceeding this limit can cause issues.</li><li>Data stored in local storage is accessible to JavaScript running on the same domain. Avoid storing sensitive information (e.g., tokens, passwords) unless properly encrypted.</li><li>Accessing local storage is synchronous, which means it can block JavaScript execution. Be cautious when dealing with large data sets to avoid performance bottlenecks.</li></ol><h4>3. Prerendering</h4><p>Prerendering, a technique where the initial HTML content of a web page is generated on the server before being sent to the client, offers several advantages when dealing with substantial data:</p><ol><li>SEO Optimization</li><li>Faster Indexing</li><li>Reduced Time-to-Content</li><li>Balancing Performance and SEO</li></ol><p>Prerendering ensures that your large dataset content is visible to search engines during the initial page load. Without prerendering, search engines might miss dynamically loaded content (e.g., data fetched via JavaScript), impacting your SEO efforts.</p><p><em>To know more about prerendering in detail click — </em><a href="https://www.thetechplatform.com/post/prerendering-in-asp-net-core-razor-components"><em>Prerendering in ASP.NET Core Blazor Components</em></a></p><h4>4. Cortex.Net</h4><p>Cortex.Net simplifies state management by transparently applying functional reactive programming (TFRP). It is a port of the popular MobX library in the JavaScript ecosystem. While MobX leverages prototype-based inheritance, Cortex.Net adapts to C#’s class-based inheritance model. This includes UI rendering, data serialization, server communication, and more.</p><p>Let’s see how to use Cortex.Net for state management in your Blazor applications:</p><p><strong>STEP 1: NuGet Installation: </strong>Start by installing the main Cortex.Net NuGet package:</p><pre>Install-Package Cortex.Net</pre><p>If you’re working with Blazor, consider adding the Cortex.Net.Blazor package:</p><pre>Install-Package Cortex.Net.Blazor</pre><p><strong>STEP 2: Weaving for Transparent Observables: </strong>Cortex.Net supports weaving, which creates a transparent observable state.</p><p>To enable weaving, create a FodyWeavers.xml file in your project (if it doesn’t exist).</p><p>Add the following line to the file:</p><pre>&lt;Weavers&gt;     &lt;Cortex.Net /&gt; &lt;/Weavers&gt;</pre><p>Weaving ensures that the derived state updates automatically whenever the application state changes.</p><p><strong>Example Usage: </strong>Suppose you have an observable state representing a list of users:</p><pre>using Cortex.Net;  public class UserStore {     public IObservableList&lt;User&gt; Users { get; } = new ObservableList&lt;User&gt;(); }</pre><p><strong>Updating State: </strong>You can add or modify users in your Blazor components:</p><pre>@page &quot;/users&quot;  @inject UserStore UserStore  &lt;h1&gt;Users&lt;/h1&gt; &lt;ul&gt;     @foreach (var user in UserStore.Users)     {         &lt;li&gt;@user.Name&lt;/li&gt;     } &lt;/ul&gt;  @code {     protected override void OnInitialized()     {         // Add some sample users         UserStore.Users.Add(new User { Name = &quot;Alice&quot; });         UserStore.Users.Add(new User { Name = &quot;Bob&quot; });     } }</pre><p><strong>Benefits:</strong></p><ol><li><strong>Reactive State Management: </strong>Cortex.Net ensures that anything dependent on the application state updates reactively. When dealing with large datasets, this approach keeps UI components synchronized with the data. Cortex.Net efficiently propagates updates to relevant parts of your Blazor app as your dataset changes.</li><li><strong>Integration with Blazor: </strong>Cortex.Net seamlessly integrates with Blazor components providing mechanisms to store and update the application state. Blazor renders the UI based on this state, ensuring efficient synchronization.</li></ol><p><strong>Limitations:</strong></p><ol><li>Cortex.Net introduces a learning curve, especially for developers new to reactive programming concepts and weaving.</li><li>While Cortex.Net provides powerful features, consider whether its complexity aligns with your project’s needs. For simpler apps, other state management solutions might suffice.</li></ol><h3>Conclusion</h3><p>As your app grows, consider the trade-offs between complexity and benefits, and choose the state management approach that aligns with your project’s needs. Whether you’re optimizing for performance, SEO, or user experience, thoughtful state management is a key ingredient in building successful Blazor apps.</p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5d85485091e7" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>