<?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 Ehsan on Medium]]></title>
        <description><![CDATA[Stories by Ehsan on Medium]]></description>
        <link>https://medium.com/@ehsan.aslani?source=rss-ed26f8dca0d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*urLUX9kBnXgQyqgaNr7Eog.jpeg</url>
            <title>Stories by Ehsan on Medium</title>
            <link>https://medium.com/@ehsan.aslani?source=rss-ed26f8dca0d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 16 Nov 2026 22:52:33 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ehsan.aslani/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Building Your Own Powerful Real-Time Chat Application from Scratch]]></title>
            <link>https://medium.com/@ehsan.aslani/building-your-own-powerful-real-time-chat-application-from-scratch-7079311d014b?source=rss-ed26f8dca0d------2</link>
            <guid isPermaLink="false">https://medium.com/p/7079311d014b</guid>
            <category><![CDATA[chat-application]]></category>
            <category><![CDATA[chat-app-development]]></category>
            <category><![CDATA[real-time-data]]></category>
            <category><![CDATA[key-value-store]]></category>
            <category><![CDATA[websocket]]></category>
            <dc:creator><![CDATA[Ehsan]]></dc:creator>
            <pubDate>Thu, 13 Mar 2025 18:32:22 GMT</pubDate>
            <atom:updated>2025-03-13T18:32:22.159Z</atom:updated>
            <content:encoded><![CDATA[<p>Have you ever wondered how chat apps like WhatsApp or Slack keep your conversations flowing in real-time? These tools have become essential to our daily lives, connecting us instantly across the globe. Building your own chat application might sound daunting — real-time data, scalability, and security are no small feats — but it’s an exciting challenge worth tackling. In this guide, I’ll take you step-by-step through creating your own real-time chat app, unpacking the tech behind the magic. Let’s dive in and bring your messaging dreams to life. Together we will develop an application with some great features:</p><ol><li><strong>Real-time updates</strong>: Changes to data are instantly pushed to all clients with amazing speed</li><li><strong>Simple Architecture/Code</strong>: No need for a complex message broker or dedicated WebSocket server</li><li><strong>Client-side focus</strong>: Most of the application logic can live in the browser. Backend only handles token generation</li><li><strong>Built-in persistence</strong>: No need to take any extra steps for persisting message history</li></ol><p><em>Source Code: The complete code base for this application is available on </em><a href="https://github.com/ehsanaslani/realtime-chat"><em>Github</em></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZPNzdjxf52NIuoFePxLLCg.png" /></figure><h3>Exploring Different Approaches to Build a Chat Application</h3><p>When developing a chat application, you’ve got several options, each with its own perks and pitfalls. Here’s a quick rundown of some of the options:</p><ul><li><strong>Traditional Polling</strong><br> The client repeatedly asks the server, “Any new messages?” It’s simple but inefficient — think of it like checking your mailbox every minute. It wastes resources and slows things down.</li><li><strong>WebSockets</strong><br> This modern gem opens a two-way channel between client and server, delivering messages instantly without constant checking. It’s fast, efficient, and powers many of today’s chat apps.</li><li><strong>Socket.IO</strong><br> A step above WebSockets, Socket.IO adds handy features like auto-reconnects and room-based messaging. It’s user-friendly and perfect if you want real-time power without the complexity.</li><li><strong>Other Options</strong><br> Server-Sent Events (SSE) push updates one-way from server to client — great for notifications, less so for chats. Message queues like RabbitMQ shine in massive systems but might be overkill here.</li></ul><p>For our application, We are going to use websockets, but in a relatively different appraoch which makes it much simpler to implement and maintain without the need to setup custom websocket servers, messages queues or any additional infrastructure. We are just going to use a key value database</p><h3>Our Unique Approach: Leveraging HPKV for Simplicity and Performance</h3><p>At the heart of this chat application lies <a href="https://hpkv.io/"><strong>HPKV (High Performance Key Value)</strong></a>, a key-value store service that makes development both simple and incredibly powerful. But first, what’s a <strong>key-value database</strong>? It’s a type of database that organizes data as unique keys paired with values — imagine a dictionary where each word (key) has a definition (value). This design makes key-value stores fast, scalable, and perfect for tasks like real-time chat, caching, or session management.</p><p>HPKV takes this concept further with exceptional performance — <a href="https://hpkv.io/blog/2025/02/redis-vs-hpkv-benchmark">outpacing Redis in benchmarks</a> — and a standout <a href="https://hpkv.io/blog/2025/03/real-time-pub-sub"><strong>real-time pub/sub feature</strong></a>. This allows clients to subscribe to specific keys and receive instant notifications when those keys change. What sets HPKV apart is its <strong>bi-directional WebSocket connection</strong>, which lets clients perform CRUD operations (create, read, update, delete) and get real-time updates through a single, secure channel. No separate WebSocket server or message broker is needed — HPKV handles everything.</p><p>Beyond that, HPKV offers <strong>persistence out of the box</strong>, ensuring data is safely stored and survives server restarts, all while maintaining top-tier performance with minimal delays. Security is seamless too: a token generation endpoint lets clients connect via WebSocket without exposing sensitive API keys. With just a free HPKV account, there’s no need for external databases or complex setups.</p><p>and last but not least: There is a <a href="https://hpkv.io/signup">free tier</a>!</p><p>The architecture powering our chat app is elegantly simple:</p><ul><li>Each chat room gets its own key in HPKV, storing the room’s messages.</li><li>Participants subscribe to the chat room key, write messages to its value, and instantly receive updates when new messages are added.</li></ul><p>This streamlined approach eliminates complexity while delivering a responsive, real-time chat experience.</p><p>This sequence diagram illustrates how our chat application works:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WmDcEJh3vHdNOxhO-yrS3A.png" /></figure><h3>Architecture</h3><p>The application consists of three main components:</p><ol><li><strong>Client-side application</strong>: React/Next.js frontend that handles UI and WebSocket communication.</li><li><strong>WebSocket token API</strong>: A minimal backend endpoint that generates authentication tokens.</li><li><strong>HPKV service</strong>: Handles WebSocket connections, message storage, and pub/sub notifications.</li></ol><p><strong>HPKV’s Role</strong>: HPKV simplifies WebSocket implementation, allowing you to focus on application logic rather than low-level connection management. It also let us not be concerned about persistence and enables us to establish a bi-directioanl websocket connections from client browser to the databse</p><h4>Key and Data Structures</h4><p>Our application uses two primary key structures:</p><ol><li><strong>Chatroom Registry</strong>: A single key (<em>chatrooms</em>) containing a list of all available chat rooms</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a785d510e69016c8246271c6e29eee6c/href">https://medium.com/media/a785d510e69016c8246271c6e29eee6c/href</a></iframe><p>2. <strong>Chat Messages</strong>: Each chat room has its own key (<em>chat:{roomId}</em>) containing the messages for that room</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/efd16cee5a011748baa0951385bc81d6/href">https://medium.com/media/efd16cee5a011748baa0951385bc81d6/href</a></iframe><p>This key structure allows to:</p><ul><li>Subscribe to the <em>chatrooms </em>key to get notified when new rooms are created</li><li>Subscribe to specific <em>chat:{roomId}</em> keys to receive messages only for rooms a user has joined</li><li>Keep each room’s messages separate for better data management</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/556/1*BL0yBFzLzANshj0HaM4J2w.jpeg" /><figcaption>Clients write messages to database and get notified when the values changed</figcaption></figure><h3>Implementation Details</h3><h4><strong>HPKV WebsocketClient</strong>:</h4><p>This class is the heart of our application. It provides methods for connection to HPKV through websocket, performing operations and receiving notifications when a key value is updated (A new message is written to the chat room).</p><p>Here is a snippet of how it does CRUD operations:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a77015eda660780222f8e1d45c8a4a68/href">https://medium.com/media/a77015eda660780222f8e1d45c8a4a68/href</a></iframe><p>It also listens for change notifications:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0f4579c97fa6a2b7c0656ec12444092e/href">https://medium.com/media/0f4579c97fa6a2b7c0656ec12444092e/href</a></iframe><h4>Chat-Specific Client Implementation</h4><p>Building on the WebSocket client, we create a ChatClient class that handles chat-specific operations. This class implements the chat-specific functionality:</p><ul><li>Creating and joining chat rooms</li><li>Sending and receiving messages</li><li>Managing the chatroom registry</li></ul><p>This snippet shows how it sends messages</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/59606c052678d5aead6fd9ae1ed5edcb/href">https://medium.com/media/59606c052678d5aead6fd9ae1ed5edcb/href</a></iframe><p>and here’s how it handles notifications for new messages:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a79f54183574c329a785d8718b766cb3/href">https://medium.com/media/a79f54183574c329a785d8718b766cb3/href</a></iframe><h4>React Components for the UI</h4><p>Now let’s look at the frontend React components that provide the user interface.</p><p><strong>ChatRoomsManager</strong></p><p>This component displays a list of chat rooms and allows user to join chat rooms or create a new chat room. It hooks into <em>onChatroomsUpdated </em>event of <em>ChatClient </em>to update the UI when a new chat room is created:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4645fd0312d5eb631de76374fa58ac94/href">https://medium.com/media/4645fd0312d5eb631de76374fa58ac94/href</a></iframe><p><strong>Chatroom</strong></p><p>This component provides a UI to send and receive messages in a chat room. it hooks into onMessageReceived event of ChatClient to receive the new messages and displays them in the UI:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/19a285b8d0104aaa8bab3e65189524f1/href">https://medium.com/media/19a285b8d0104aaa8bab3e65189524f1/href</a></iframe><h4>Backend Token API</h4><p>The only backend component we need is a simple API endpoint that generates WebSocket tokens. In Next.js, this would be an API route like /api/join-chatroom:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f6cb44b15742c397670751ee34138ba6/href">https://medium.com/media/f6cb44b15742c397670751ee34138ba6/href</a></iframe><p>We also need an initialization endpoint that only subscribes to the chatrooms list:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0f7d54a828692567412e9122f3042d31/href">https://medium.com/media/0f7d54a828692567412e9122f3042d31/href</a></iframe><h3>Security</h3><p>This application uses the HPKV’s access pattern filter to limit what clients can perform on database. HPKV’s token generation endpoint accepts an optional parameter (<em>accessPattern</em>) which allows to use regular expressions to specify what are the keys that the websocket client can perform operation on them using the generated token.</p><p>You can see the access patterns used in our token generation API endpoints (<em>initialize </em>and <em>join-chatroom</em>)</p><p><strong>initialize:</strong>This endpoint is called when user just opens the application in a browser. It subscribe to the chat room registry key (<em>chatrooms</em>) and generates a token by which user has only access to this key in the database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CIpXAx6oaP1B6c5yu3ClRg.png" /></figure><p><strong>join-chatroom:</strong> This endpoint is called when the user tries to join a chat room and limits the access to the chat room key (<em>chat:{roomId}</em>) and the chat room registry key (<em>chatrooms</em>)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gJZqiBnG8QzomfSZKQNnVA.png" /></figure><h3>Advantage of this approach</h3><p>Compared to the alternatives, thischat application implementation offers several advantages:</p><ol><li>Simplified Architecture</li></ol><ul><li>No need for a separate message broker</li><li>Built-in persistence eliminates the need for a separate database</li><li>Single connection handles both data access and real-time updates</li></ul><p>2. Client-Side Focus</p><ul><li>Most application logic lives in the browser</li><li>Minimal backend required (just token generation)</li><li>Easier to deploy and scale</li></ul><p>3. Key-Based Subscriptions</p><ul><li>Fine-grained control over what updates clients receive</li><li>Clients only receive notifications for rooms they’ve joined</li><li>Efficient message routing</li></ul><p>4. Built-in Security</p><ul><li>Token-based authentication</li><li>Operation-level permissions</li><li>Scoped key access</li></ul><p>5. Deployment Simplicity</p><ul><li>Minimal server-side infrastructure</li><li>Static site hosting for the frontend</li><li>Single API endpoint for token generation</li></ul><h3>Conclusion</h3><p>Building a real-time chat application with HPKV WebSockets offers a streamlined development experience with minimal backend requirements. By leveraging key-based subscriptions and the pub/sub pattern, we can create a responsive and scalable chat application that runs primarily on the client side.This approach is particularly well-suited for applications where:</p><ul><li>You want to minimize backend complexity</li><li>Real-time updates are essential</li><li>You need built-in data persistence</li><li>You prefer a client-focused architecture</li></ul><p>By following the patterns outlined in this guide, you can build a fully functional chat application with features like chat room creation, message exchange, and real-time updates, all while keeping your backend requirements minimal. <a href="https://github.com/ehsanaslani/realtime-chat">The complete source code</a> for this application serves as a foundation that you can extend with additional features like user authentication, message read receipts, typing indicators, or file sharing, depending on your specific requirements.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7079311d014b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unlocking the Power of Persistent Key-Value Stores with HPKV]]></title>
            <link>https://medium.com/@ehsan.aslani/unlocking-the-power-of-persistent-key-value-stores-with-hpkv-a0e892a379b1?source=rss-ed26f8dca0d------2</link>
            <guid isPermaLink="false">https://medium.com/p/a0e892a379b1</guid>
            <category><![CDATA[key-value-database]]></category>
            <category><![CDATA[high-performance-storage]]></category>
            <category><![CDATA[key-value-store]]></category>
            <category><![CDATA[high-performace-computing]]></category>
            <category><![CDATA[key-value-storage]]></category>
            <dc:creator><![CDATA[Ehsan]]></dc:creator>
            <pubDate>Wed, 26 Feb 2025 15:21:10 GMT</pubDate>
            <atom:updated>2025-02-26T15:21:10.985Z</atom:updated>
            <content:encoded><![CDATA[<p>In the realm of modern web development, achieving both high performance and data persistence in a key-value store is a significant challenge. <a href="https://hpkv.io/"><strong>HPKV</strong></a> emerges as a robust solution, engineered to deliver persistent storage without the performance trade-offs that plague many traditional systems. Unlike conventional key-value stores that prioritize in-memory speed and treat persistence as a secondary concern, HPKV integrates durability into its core design, making it a versatile tool for a wide array of technical use cases. This blog post delves into HPKV’s architecture, explores its diverse applications and provides a technical comparison with Redis to highlight its advantages.</p><h4>Technical Overview</h4><p>HPKV combines in-memory storage with efficient disk persistence, ensuring data durability without the usual trade-offs. While many key-value stores slow down when persistence is enabled, HPKV leverages advanced storage techniques and optimized data structures to keep access times blazing fast. This means your application gets the reliability of persistent data and the speed of in-memory performance — all in one package.</p><p>To get more technical details on how HPKV acheives a high performance persistent key values store, read the <a href="https://hpkv.io/blog/2025/01/introducing-hpkv">blog post</a> explaining the innovative architecture and design of HPKV</p><h3>Use Cases: Where HPKV Excels</h3><h4>1. Shopping Carts</h4><p>In e-commerce platforms, shopping carts must persist across user sessions to prevent data loss due to browser closures or server restarts. HPKV stores cart items as key-value pairs, with the key representing a user ID and the value containing serialized cart contents. Its high write throughput supports rapid updates — such as adding or removing items — while its persistence ensures that cart data remains intact during system failures. This reliability, paired with sub-millisecond read latencies, enhances the user experience by delivering seamless and responsive cart interactions.</p><h4>2. Logging and Monitoring</h4><p>Applications generating high volumes of logs or metrics require a storage system capable of handling intense write workloads and enabling real-time queries. HPKV serves as a persistent backend for logging systems, storing timestamped key-value pairs where keys encode event metadata (e.g., log:timestamp:service) and values hold the log entries. Its log-structured design excels in write-heavy scenarios, while the in-memory cache accelerates queries for monitoring dashboards. This makes HPKV ideal for real-time analytics in production environments.</p><h4>3. Message Queueing</h4><p>Message queues demand durability to prevent message loss during system crashes, alongside fast access for dequeuing operations. HPKV can act as a persistent queue store, with keys representing queue identifiers and values maintaining ordered message lists or pointers. Its atomic operations ensure reliable message insertion and removal, while persistence guarantees that unprocessed messages survive restarts. This capability suits HPKV for task queues, event-driven architectures, and other systems requiring guaranteed delivery.</p><h4>4. Real-Time Ad Servers</h4><p>Ad servers require rapid decision-making to select and serve advertisements based on user profiles and inventory data. HPKV can store user attributes (<em>e.g., user:123:profile</em>) and ad metadata (<em>e.g., ad:456:details</em>) as key-value pairs, leveraging its low-latency reads to meet tight real-time constraints. Persistence ensures that profile updates and billing records remain consistent across server restarts, critical for accurate targeting and revenue tracking in high-throughput advertising platforms.</p><h4>5. Distributed Rate Limiting</h4><p>In distributed systems, rate limiting prevents resource abuse by tracking usage across multiple nodes. HPKV provides a centralized, persistent store for rate limit counters (<em>e.g., rate:api:user123</em>), accessible cluster-wide. Its high-performance reads and atomic increment operations enable low-latency limit checks and updates, while persistence ensures that counters survive node failures, maintaining fairness and consistency in API gateways or microservices.</p><h4>6. Configuration Management</h4><p>Microservices and distributed applications rely on consistent configuration data across instances. HPKV stores configuration key-value pairs (<em>e.g., config:service:setting</em>), ensuring that all nodes access up-to-date settings with minimal latency. Persistence eliminates the need to reload configurations after restarts, simplifying deployment workflows and enhancing system reliability.</p><h4>7. Leaderboard Systems</h4><p>Gaming applications require real-time leaderboard updates with persistent storage to preserve rankings during downtime. HPKV can maintain sorted sets or key-value pairs (<em>e.g., leaderboard:game:player123</em>) with scores, leveraging its fast write capabilities for frequent updates and persistence for data integrity. This ensures players experience uninterrupted, accurate rankings even under heavy load.</p><h4><strong>8. Real-Time Data Processing for IoT Applications</strong></h4><p>In IoT applications, devices stream frequent updates that need quick storage and retrieval. HPKV handles this in real-time, with persistence ensuring no data is lost during system maintenance.</p><h3>Comparison with Redis</h3><p>Redis, a widely adopted in-memory key-value store, offers persistence through two mechanisms: <strong>RDB snapshots</strong> and <strong>Append-Only File (AOF)</strong> logging. However, these come with trade-offs that HPKV avoids:</p><ul><li><strong>RDB Snapshots</strong>: Redis periodically saves its in-memory data to disk, which can pause operations during the snapshot process, introducing latency spikes. Data written between snapshots may be lost in a crash, compromising durability.</li><li><strong>AOF Logging</strong>: Redis logs every write operation to an append-only file, ensuring higher durability but increasing I/O overhead and write latency. Replaying the AOF on restart can also delay recovery for large datasets.</li></ul><p>HPKV, by contrast, integrates persistence into its core design. Its log-structured storage eliminates the need for separate snapshot or logging modes, providing seamless durability without performance penalties. Benchmarks demonstrate that HPKV achieves <strong>higher throughput and lower latency</strong> than Redis in persistence-enabled configurations, particularly under mixed read-write workloads. Furthermore, HPKV’s architecture supports easier scaling and high availability, addressing some of Redis’s operational complexities in clustered setups.</p><p><a href="https://hpkv.io/blog/2025/02/redis-vs-hpkv-benchmark">Detailed benchmark comparison</a> between HPKV and Redis demonstrates the performance advantages of HPKV</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J6k-NmdSFGLNXTYw22_7hw.png" /></figure><h3>Conclusion</h3><p>HPKV redefines the capabilities of persistent key-value stores, offering a rare blend of durability and performance. Its optimized storage design, efficient caching, and advanced memory and concurrency management makes it a superior choice for applications demanding both speed and reliability. From powering e-commerce shopping carts to enabling real-time ad servers and distributed rate limiting, HPKV adapts to diverse technical challenges with ease. <a href="https://hpkv.io/blog/2025/02/redis-vs-hpkv-benchmark">Compared to Redis</a>, HPKV provides higher performance and stands out in scenarios where persistence is non-negotiable, delivering consistent performance without the operational overhead.</p><p>For developers seeking a robust, high-performance key-value store, HPKV is a compelling option. Explore its potential in your next project — visit our <a href="https://hpkv.io/">website </a>to learn more and <a href="https://hpkv.io/signup">get started with HPKV</a> today.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a0e892a379b1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Consciousness Emerging from Internal Language and Learning: A Theoretical Perspective]]></title>
            <link>https://medium.com/@ehsan.aslani/consciousness-emerging-from-internal-language-and-learning-a-theoretical-perspective-a4a5e70e0cfe?source=rss-ed26f8dca0d------2</link>
            <guid isPermaLink="false">https://medium.com/p/a4a5e70e0cfe</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[consciousness]]></category>
            <category><![CDATA[conscious-ai]]></category>
            <category><![CDATA[emergent-consciousness]]></category>
            <category><![CDATA[emergent-properties]]></category>
            <dc:creator><![CDATA[Ehsan]]></dc:creator>
            <pubDate>Sun, 04 Jun 2023 14:19:33 GMT</pubDate>
            <atom:updated>2023-06-04T14:19:33.054Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Consciousness has been a subject of fascination and inquiry for philosophers, psychologists, and neuroscientists for centuries. It is our intimate sense of self, the private theater that houses our sensations, thoughts, and experiences. Yet, despite its centrality to our existence, a comprehensive understanding of consciousness remains elusive. This article introduces a novel theoretical perspective: that consciousness might be an emergent property of any system which possesses an internal language and the capacity for learning.</p><h3>Key Concepts</h3><p>Before we delve into the theory, it’s crucial to understand some underlying concepts.</p><ol><li>Emergent Properties: These are characteristics or phenomena that arise from the interactions and relationships among smaller, simpler entities. They are not properties that can be predicted merely by understanding these individual components.</li><li>Internal Language: This concept refers to the symbolic representation of information within a system, akin to how the human mind might symbolize aspects of the world for internal processing.</li><li>Learning: Learning here implies a system’s ability to adapt and evolve its internal states in response to interactions with its environment. This concept draws from machine learning and cognitive science, wherein models or organisms adjust their behavior based on experience.</li></ol><h3>The Emergence of Consciousness: A New Theory</h3><p>This theory proposes that consciousness could emerge from systems capable of representing information symbolically (having an ‘internal language’) and dynamically adapting their behavior based on that information (learning). The inspiration for this theory springs from various sources: functionalism in philosophy of mind, symbolic AI, connectionism, and theories like the Global Workspace Theory (GWT) and Integrated Information Theory (IIT).</p><p>Functionalism suggests that mental states are defined by their functional roles, meaning any system performing the correct functions could be conscious. Symbolic AI and GWT offer insights into what an ‘internal language’ might be: a system of symbols used for representation and manipulation of information or a mechanism for global broadcasting of information, respectively. Connectionism and machine learning provide models of learning, where systems adjust their behavior or internal states based on experience.</p><p>The Integrated Information Theory (IIT) further supports the idea. It posits that consciousness arises from the integration of a vast array of information — a process central to learning. Additionally, IIT proposes a measure for consciousness, called Phi, which could potentially be used to evaluate the consciousness level of various systems, not just biological brains.</p><h3>Supporting Evidence</h3><p>While empirical evidence directly supporting this theory is limited — primarily due to the nascent stage of research in artificial consciousness — there are several suggestive findings. Various artificial neural networks, for example, demonstrate complex behaviors and learning capabilities that some argue hint at a form of machine consciousness.</p><p>Furthermore, research in symbolic AI and cognitive architectures have started to produce machines capable of higher-level reasoning and problem-solving skills. They display an ability to use internal symbol systems in ways that are reminiscent of human thinking.</p><p>Importantly, these systems demonstrate the critical properties our theory predicates for consciousness: the utilization of an internal language and the ability to learn. As such, they suggest the potential for an emergent form of consciousness.</p><h3>Conclusion</h3><p>The proposed theory, that consciousness might emerge from systems with an internal language and the capacity for learning, offers a fresh perspective on the nature of consciousness. While more empirical research is necessary to validate this theory, the initial findings in AI and cognitive science offer promising avenues for exploration. Understanding consciousness — whether in humans, animals, or machines — remains a significant scientific challenge, but theories like this one bring us closer to unraveling the mystery.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a4a5e70e0cfe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Digital Experience Platform (DXP) :Introduction]]></title>
            <link>https://medium.com/@ehsan.aslani/digital-experience-platform-dxp-introduction-54134a260f1f?source=rss-ed26f8dca0d------2</link>
            <guid isPermaLink="false">https://medium.com/p/54134a260f1f</guid>
            <category><![CDATA[technology-trends]]></category>
            <category><![CDATA[dxp-platform]]></category>
            <category><![CDATA[digitalexperienceplatform]]></category>
            <category><![CDATA[digital-marketing]]></category>
            <category><![CDATA[content-management-system]]></category>
            <dc:creator><![CDATA[Ehsan]]></dc:creator>
            <pubDate>Wed, 21 Dec 2022 00:51:48 GMT</pubDate>
            <atom:updated>2022-12-21T00:51:48.060Z</atom:updated>
            <content:encoded><![CDATA[<h3>Digital Experience Platform (DXP) :Introduction</h3><h3>What is it?</h3><p>Digital experience platforms (DXP) are software solutions that enable organizations to create and deliver personalized, seamless, and engaging digital experiences to their customers and employees across various channels and devices. These platforms provide a single, integrated platform for managing and delivering digital content, applications, and services, which can help to improve customer satisfaction, loyalty, and retention, as well as employee productivity and engagement.</p><h3>Monolithic DXPs</h3><p>A monolithic DXP is a comprehensive platform that includes all the tools and capabilities required to manage and deliver digital experiences in a single, integrated package. These platforms are designed to be easy to use and require minimal technical expertise to set up and maintain. However, they can be inflexible and may not be well-suited to organizations with complex or rapidly-changing digital needs.</p><h3>Headless DXPs</h3><p>A headless DXP is a platform that provides the back-end infrastructure and capabilities required to manage and deliver digital experiences, but does not include a user interface (UI). Instead, the UI is provided by separate front-end systems, which are connected to the DXP via APIs (application programming interfaces). This allows organizations to decouple the content management and delivery components of their digital experiences and create a more flexible and scalable system. However, headless DXPs can be more complex to set up and maintain than monolithic DXPs.</p><h3>Composable DXPs</h3><p>A composable DXP is a platform that provides a set of modular, reusable components that can be combined to create customized digital experiences. These platforms are designed to be highly flexible and allow organizations to easily create and manage a wide range of digital experiences without requiring extensive technical expertise. However, composable DXPs may require more upfront planning and configuration to ensure that the components are correctly assembled and integrated.</p><p>The choice of DXP will depend on the specific needs and goals of an organization. Monolithic DXPs may be well-suited to small organizations with simple digital needs, while headless or composable DXPs may be more appropriate for larger organizations with more complex or rapidly-changing digital requirements.</p><h3>Why Corporates Need It?</h3><ol><li><em>Personalized customer experiences</em>: A DXP can help organizations create personalized, seamless, and engaging digital experiences for their customers across all touchpoints. For example, a clothing retailer might use a DXP to create personalized product recommendations for customers based on their past purchases and browsing history, which can improve customer satisfaction and loyalty.</li><li><em>To streamline operations</em>: A DXP can provide a single, integrated platform for managing various aspects of digital operations, such as content management, personalization, e-commerce, and customer service. This can help organizations streamline their operations and reduce the complexity of managing multiple systems. For example, a financial services company might use a DXP to manage its online banking and customer service operations, which can improve efficiency and reduce the need for manual labor.</li><li><em>To improve efficiency</em>: A DXP can help organizations automate various processes and tasks, such as marketing campaigns and customer service, which can improve efficiency and reduce the need for manual labor. For example, an airline might use a DXP to automate its marketing campaigns and customer service inquiries, which can improve efficiency and reduce the workload of its customer service team.</li><li><em>To increase revenue</em>: By improving customer experiences and streamlining operations, a DXP can help organizations increase revenue through increased customer acquisition and retention, as well as increased efficiency and productivity. For example, a hotel chain might use a DXP to create personalized promotions and offers for customers based on their past bookings and preferences, which can increase revenue through increased bookings.</li><li><em>To stay competitive</em>: In today’s digital age, it’s important for organizations to have a strong online presence and be able to deliver engaging digital experiences to their customers. A DXP can help organizations stay competitive by enabling them to create and deliver high-quality digital experiences that meet the needs and expectations of their customers.</li></ol><p>DXPs can help organizations to improve customer and employee experiences, streamline digital operations, increase agility and flexibility, enhance security, and gain valuable insights and analytics. For CTOs, implementing a DXP can be an effective way to drive business growth and improve the efficiency and effectiveness of their organization’s digital operations.</p><h3>Choosing a Vendor</h3><p>As a decision maker, you are likely well aware of the importance of delivering high-quality digital experiences to your customers. A DXP can help you achieve this by providing a range of tools and capabilities, such as content management, personalization, e-commerce, marketing automation, and customer service. But with so many DXP vendors on the market, how do you choose the right one for your organization? Here are some key considerations to keep in mind:</p><ol><li><strong>Features</strong>: Look for a DXP that offers a range of features that meet your organization’s needs and goals. These might include content management, personalization, CRM, e-commerce, marketing automation, and customer service, among others.</li><li><strong>Integration</strong>: A DXP that integrates well with your existing systems and processes can help streamline your operations and reduce the complexity of managing multiple systems. Look for a DXP that offers robust integration capabilities and can seamlessly connect with your existing CRM, e-commerce, marketing automation, and other systems.</li><li><strong>Cost</strong>: DXP solutions can be costly to implement and maintain, so it’s important to carefully evaluate the total cost of ownership before making a decision. This should include the upfront costs of purchasing and implementing the DXP, as well as ongoing maintenance, support, and training costs. Make sure to carefully compare the costs of different DXP solutions to ensure that you are getting the best value for your money.</li><li><strong>Technical expertise</strong>: Some DXP solutions may require specialized technical expertise to set up and maintain, so consider whether you have the necessary resources in-house or whether you will need to bring in external help. This can have a significant impact on the total cost of ownership, as well as the time and effort required to implement and maintain the DXP.</li><li><strong>Scalability</strong>: As your organization grows, you will likely need to scale your DXP solution to meet increasing demands. Look for a DXP that can grow with you and support your long-term needs. This might include the ability to handle increasing amounts of traffic and data, support for new channels and devices, and the ability to add new features and capabilities as needed.</li></ol><p>There are several different types of DXPs, including monolithic, headless, and composable DXPs.</p><h3>Some Key Vendors</h3><ul><li><a href="https://www.sitecore.com/products/sitecore-experience-platform"><strong>Sitecore Experience Platform</strong></a>: Sitecore Experience Platform is a DXP that enables organizations to create personalized, contextually-relevant digital experiences across all touchpoints. Key features include content management, personalization, analytics, and marketing automation. Sitecore has a strong market presence and is considered a leader in the DXP space.</li><li><a href="https://experienceleague.adobe.com/docs/experience-platform/landing/home.html"><strong>Adobe Experience Platform</strong></a>: Adobe Experience Platform is a comprehensive DXP that provides a range of tools and capabilities for creating and delivering personalized, seamless, and engaging digital experiences. Key features include content management, personalization, CRM, e-commerce, marketing automation, and customer service. Adobe has a strong market presence and is considered a leader in the DXP space.</li><li><a href="https://www.acquia.com/resources/report/customer-experience-trends-report"><strong>Acquia CX</strong></a>: Acquia CX is a DXP that enables organizations to create and deliver personalized, seamless, and engaging digital experiences across all touchpoints. Key features include content management, personalization, CRM, and analytics. Acquia has a strong market presence and is considered a leader in the DXP space.</li><li><a href="https://docs.developers.optimizely.com/digital-experience-platform"><strong>Optimizely</strong></a>: Optimizely is a DXP that enables organizations to orchestrate the entire content lifecycle, monetize every digital experience and experiment across all customer touchpoints. Strengths include its strong A/B testing and personalization capabilities. (it is primarily focused on optimization and personalization).</li><li><a href="https://www.salesforce.com/eu/products/"><strong>Salesforce Customer 360</strong></a>: Salesforce Customer 360 is a DXP that provides a single, integrated platform for managing customer relationships and delivering personalized digital experiences. Key features include CRM, marketing automation, customer service, and e-commerce. Salesforce is a well-established player in the DXP market with a strong market presence.</li><li><a href="https://www.contentful.com/blog/whats-a-digital-experience-platform/"><strong>Contentful</strong></a>: Contentful is a headless DXP that enables organizations to create, manage, and deliver digital content across all channels and devices. Strengths include its API-based delivery and flexibility to support a wide range of use cases. Things to watch out for include the need for specialized technical expertise and the lack of built-in features (such as personalization and analytics) that may need to be added through integrations with other systems.</li><li><a href="https://www.kentico.com/discover/resources/shaping-the-future-of-digital-marketing?pi_campaign_id=1001&amp;utm_source=google&amp;utm_medium=cpc&amp;utm_campaign=2nd_top_en_sea_wps-and-ebooks&amp;utm_type=acquisition&amp;utm_audience=top6&amp;utm_term=dxp&amp;keyword=dxp&amp;gclid=Cj0KCQiA14WdBhD8ARIsANao07hCJEpSXFco6m0m9puw7DO-jEvFkZJM7p5Y1G_Bq1IN9Pe0SgGbP04aAhrmEALw_wcB"><strong>Kentico</strong></a>: KKontent.ai is the modular content platform that enables content and engineering teams to create, organize, and reuse valuable content, making every experience consistent and relevant. Strengths include its strong content management and e-commerce capabilities, as well as its integration with Microsoft technologies.</li><li><a href="https://www.liferay.com/products/dxp?utm_term=liferay%20dxp&amp;utm_campaign=7014u000001t9aoAAA%20-%20EMEA%20T1%20%7C%20SEM%20-%20Brand&amp;utm_source=adwords&amp;utm_medium=ppc&amp;gclid=Cj0KCQiA14WdBhD8ARIsANao07j-QqC65EEG0GvviuJrZQwqdHb2PTe6JBKX7zGGBWjIbHTLqD4tK7kaAlB1EALw_wcB"><strong>Liferay</strong></a>: Liferay is a DXP that enables organizations to create and deliver personalized, seamless, and engaging digital experiences across all touchpoints. Strengths include its strong content management and integration capabilities.</li><li><a href="https://www.progress.com/sitefinity-cms"><strong>Progress Sitefinity</strong></a> : Sitefinity provides a single, integrated platform for managing and delivering digital content, applications, and services, which can help to improve customer satisfaction, loyalty, and retention, as well as employee productivity and engagement. Some key features of Progress Sitefinity include content management, personalization, e-commerce, marketing automation, and customer service. Sitefinity is designed to be easy to use and requires minimal technical expertise to set up and maintain. However, it may not be well-suited to organizations with complex or rapidly-changing digital needs.</li><li><a href="https://www.bloomreach.com/en?kw=bloomreach&amp;cpn=17488368655&amp;utm_term=campaignid=17488368655:tid=kwd-300473983578:dev=c:adp=:gclid=Cj0KCQiA14WdBhD8ARIsANao07iXv-4fBqZ5v6JHCr-b4S-d5vDm4hDGHPj5FvUukhzfmsgdCgR_KFUaAo_PEALw_wcB&amp;utm_campaign=Bloomreach_Brand_All_New-Business_FR_EN_Search&amp;utm_source=adwords&amp;utm_medium=ppc&amp;utm_content=603906397811&amp;hsa_acc=6989952547&amp;hsa_cam=17488368655&amp;hsa_grp=138159188336&amp;hsa_ad=603906397811&amp;hsa_src=g&amp;hsa_tgt=kwd-300473983578&amp;hsa_kw=bloomreach&amp;hsa_mt=p&amp;hsa_net=adwords&amp;hsa_ver=3&amp;gclid=Cj0KCQiA14WdBhD8ARIsANao07iXv-4fBqZ5v6JHCr-b4S-d5vDm4hDGHPj5FvUukhzfmsgdCgR_KFUaAo_PEALw_wcB"><strong>Bloomreach Commerce Experience Cloud</strong></a>: Bloomreach Commerce Experience Cloud is a digital experience platform (DXP), a cloud-based platform that enables organizations to create and deliver personalized, seamless, and engaging digital experiences across various channels and devices. Some key features of Bloomreach Commerce Experience Cloud include content management, personalization, e-commerce, search engine optimization (SEO), and analytics. The platform is designed to help organizations increase online sales and customer loyalty through the use of artificial intelligence (AI) and machine learning (ML) technologies.</li></ul><p><strong>Useful Links:</strong></p><p><em>Gartner’s DXP Vendors Reviews and Ratings</em> : <a href="https://www.gartner.com/reviews/market/digital-experience-platforms">https://www.gartner.com/reviews/market/digital-experience-platforms</a></p><p><em>Sitecore Case Studies:</em></p><p><a href="https://www.sitecore.com/customers">https://www.sitecore.com/customers</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=54134a260f1f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sitecore Unit Testing Guide — Part 4 : Mocking ServiceLocator]]></title>
            <link>https://medium.com/@ehsan.aslani/sitecore-unit-testing-guide-part-4-mocking-servicelocator-5be28228d832?source=rss-ed26f8dca0d------2</link>
            <guid isPermaLink="false">https://medium.com/p/5be28228d832</guid>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[sitecore-development]]></category>
            <category><![CDATA[sitecore-unit-testing]]></category>
            <category><![CDATA[sitecore]]></category>
            <category><![CDATA[best-practices]]></category>
            <dc:creator><![CDATA[Ehsan]]></dc:creator>
            <pubDate>Sun, 12 Jun 2022 20:54:24 GMT</pubDate>
            <atom:updated>2022-06-12T20:59:43.125Z</atom:updated>
            <content:encoded><![CDATA[<h3>Sitecore Unit Testing Guide — Part 4 : Mocking ServiceLocator</h3><p><em>Find the source code here : </em><a href="https://github.com/ehsanaslani/SitecoreUnitTesting"><em>https://github.com/ehsanaslani/SitecoreUnitTesting</em></a></p><ul><li>Part 1 : <a href="https://medium.com/@ehsan.aslani/sitecore-unit-testing-guide-part-1-the-basics-265acb1b3b0">The Basics</a></li><li>Part 2 : <a href="https://medium.com/@ehsan.aslani/sitecore-unit-testing-guide-part-2-using-fixtures-a6729c56a3d">Fixtures</a></li><li>Part 3 : <a href="https://medium.com/@ehsan.aslani/sitecore-unit-testing-guide-part-3-mocking-sitecore-services-9dbb33615352">Mocking Sitecore Services</a></li></ul><p>In the previous parts we reviews mocking Items, Databases, Sitecore services such as LinkManager and how to write cleaner tests using Fixture.</p><p>In the previous article, it was advised to avoid using the Sitecore static classes such as Sitecore.Links.LinkManager and use the dependency injection to make your code testable. But it’s not always easy or possible to do that. For example:</p><ul><li>You have so many dependencies in your constructor and you don’t want to add more</li><li>You are creating a static class to add method extensions and therefore you can’t inject the dependencies through constructor</li></ul><p>We can still write unit tests even if those dependencies are not injected through constructor but we need to mock ServiceLocator which could be a bit tricky as we will see. However, in this article I want to introduce a better way for achieving this purpose.</p><p>Let’s imagine you have added an extension method for Item to get the url of that item</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/817/1*gq8HY5ADrQGUoYqZjyq1YA.png" /></figure><p>Here you can’t use the dependency injection to inject BaseLinkManager through constructor because it’s an static class. If you try to write unit test for this class, it will fail because the default LinkManager instance will be null when executing the test and it makes it difficult to test.</p><h3>Mocking ServiceLocator</h3><p>Let’s take a look at LinkManager class to see how we can test it. First you will see that Sitecore is using the ServiceLocator to create an instance of LinkManager used by static Sitecore.Links.LinkManager class</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QljOQwoaRSS-W31zCVvB_g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hYuPXDVaD2sTR-LoJj6MKw.png" /></figure><p>So to be able to write a test and inject the mocked LinkManager, we should manipulate ServiceLocator to return a mocked BaseLinkManager. We can write a test in this way to do that:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qQQUWF5ucSh41kyQCF7MXw.png" /></figure><p>This test tries to create a custom ServiceCollection instance which stores the registered dependencies. It uses DefaultSitecoreServicesConfigurator class to set the basic Sitecore dependencies and then it changes the registerd dependency for BaseLinkManager to our custom mocked linkManager.</p><h3>Concurrency Problem</h3><p>This test works fine as long as it runs in isolation but when running in parallel with other tests, you will see that some tests fail randomly. Why? because ServiceLocator is a static class. Once you set the ServiceProvider in one test, it will affect all other tests running in parallel and they might fail because the dependencies set in this test does not match with what they expect.</p><p>So what would be the solution? We need to find a way to set the ServiceProvider of ServiceLocator in the scope of one thread so it doesn’t affect other running parallel threads. But how to do that?</p><h3>Using Sitecore.Context.Items</h3><p>One way to achieve this goal is to utilize Sitecore.Context.Items. Sitecore.Context.Items is a ThreadStatic property which means it’s a static property which is not shared among threads. That’s how your Sitecore server handles multiple concurrent requests which they each have their own context item as they are serving different pages.</p><p>So we need to write a switcher that uses the Sitecore.Context.Items to store the ServiceCollection instance of each thread without affecting other threads.</p><p>So let’s create a Switcher class that can switch ServiceProvider just for the thread that uses it. (You can find the source code for this class in the repository)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qbVLwO1_RgtP-7ihhNXvWg.png" /></figure><p>Then we create a wrapper class for ServiceProvider that delegates the calls to its internal ServiceProvider instance. I the beginning of running tests we will set the ServiceLocator’s ServiceProvider to this wrapper and we will change it’s internal provider when a switching is requested:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4PMYwxALD2qwuk3Y7K_dYA.png" /></figure><p>So then all we need is to make sure that before our test runs begin, ServiceLocator uses this ServiceProviderWarpper class. To ensure this we create a base test class with a static constructor to make sure this is executed once and only once:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/862/1*7R0x4jvfAI69kqo1FEQGeA.png" /></figure><p>Then we derive our test class from this base class and use the ServiceProviderSwitcher that we created. So our test would be like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gQqbWeYedhDbEJ6sYDHBwQ.png" /></figure><p>So we make sure that there can be many tests manipulating ServiceLocator that can run in parallel.</p><h3>Last words</h3><p>This was the last part in these series of articles. I have tried to cover the most essential parts and yet there are more to talk about. Please provide me your feedbacks and let me know about your requests if you think there are more things to be discussed.</p><p>Enjoy testing!</p><p>Find me on :</p><ul><li><strong>Linkedin </strong>: <a href="https://www.linkedin.com/in/ehsan-aslani/">https://www.linkedin.com/in/ehsan-aslani/</a></li><li><strong>Twitter </strong>: <a href="https://twitter.com/ehsan_a">https://twitter.com/ehsan_a</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5be28228d832" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sitecore Unit Testing Guide — Part 3 : Mocking Sitecore Services]]></title>
            <link>https://medium.com/@ehsan.aslani/sitecore-unit-testing-guide-part-3-mocking-sitecore-services-9dbb33615352?source=rss-ed26f8dca0d------2</link>
            <guid isPermaLink="false">https://medium.com/p/9dbb33615352</guid>
            <category><![CDATA[best-practices]]></category>
            <category><![CDATA[sitecore-unit-testing]]></category>
            <category><![CDATA[sitecore-development]]></category>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[sitecore]]></category>
            <dc:creator><![CDATA[Ehsan]]></dc:creator>
            <pubDate>Sun, 12 Jun 2022 20:53:31 GMT</pubDate>
            <atom:updated>2022-06-12T20:59:15.399Z</atom:updated>
            <content:encoded><![CDATA[<h3>Sitecore Unit Testing Guide — Part 3 : Mocking Sitecore Services</h3><p><em>Find the source code here : </em><a href="https://github.com/ehsanaslani/SitecoreUnitTesting"><em>https://github.com/ehsanaslani/SitecoreUnitTesting</em></a></p><ul><li>Part 1 : <a href="https://medium.com/@ehsan.aslani/sitecore-unit-testing-guide-part-1-the-basics-265acb1b3b0">The Basics</a></li><li>Part 2 : <a href="https://medium.com/@ehsan.aslani/sitecore-unit-testing-guide-part-2-using-fixtures-a6729c56a3d">Fixtures</a></li><li>Part 4 : <a href="https://medium.com/@ehsan.aslani/sitecore-unit-testing-guide-part-4-mocking-servicelocator-5be28228d832">Mocking ServiceLocator</a></li></ul><p>In the previous parts we looked at mocking sitecore Items and Databases and writing more readable tests using Fixtures. In this part we will review unit testing other Sitecore services such as <em>LinkManager </em>and <em>ItemManager</em>.</p><p>Most of the Sitecore services are derived from abstract classes that can be utilized for mocking these services in our unit tests. For example <em>LinkManager </em>is derived from <em>BaseLinkManager </em>and <em>ItemManager </em>from <em>BaseItemManager</em>.</p><p>Before everything, we need to make sure that our code is testable. The dependencies such as <em>LinkManager </em>should be injected through the constructor to make our classes testable. So instead of this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mdEP6bNZlosfhyCpe0sE8Q.png" /></figure><p>We should write our class in this way so we can inject our mocked <em>LinkManager </em>to our class and unit test it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/918/1*43f6lC4aEWpmDVUijgSaTw.png" /></figure><p>However, you can still unit test the code written in the first sample which directly uses the static <em>Sitecore.Links.LinkManager</em>. We will look into that in the next part.</p><p>so let’s write a unit test for our method. First let’s add the <em>BaseLinkManager </em>to the fixture we created in the previous part:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yKqkOpFOAzqpyl6WuoWnnQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/935/1*KbR3LwqNq4vr8bILIwLA5g.png" /></figure><p>So our test will look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lQP1SOEmv8cUnzyf68Rc-g.png" /></figure><p>Now let’s look at another example. In this example our code is trying to read the settings in configuration to verify whether Foo setting is enabled:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pO7nE9aX_BpaPm4XVYA7vA.png" /></figure><p>First, as we did in the previous example, let’s make our code testable by using the <em>BaseSettings </em>class and injecting it through constructor:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z4K4g4BLQbW-nS7daP6sUw.png" /></figure><p>Next we can add it to our fixture:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0pmMyN7F76O-5C-tRtIp4g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/923/1*YcNKSQATi1uNxqVc2hisWg.png" /></figure><p>And then we can write our unit test:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Man1jFbPhJ9qVvrAr37meA.png" /></figure><p>You can do the same for any other Sitecore service that you use in your code such as <em>MediaManager</em>, <em>CorePipelineManager</em>, <em>AuthenticationManager</em>, <em>IndexResolver </em>and etc. All you need to do is to find the base abstract class that this services are derived from or the interface that they implement and then you can mock them and add them to your fixture so you can use it in all your tests.</p><p>In next part, we will look at mocking the <em>ServiceLocator </em>which can be useful when you are dealing with static classes or when you don’t want to inject the dependencies through constructor for any reason.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9dbb33615352" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sitecore Unit Testing Guide — Part 2 : Using Fixtures]]></title>
            <link>https://medium.com/@ehsan.aslani/sitecore-unit-testing-guide-part-2-using-fixtures-a6729c56a3d?source=rss-ed26f8dca0d------2</link>
            <guid isPermaLink="false">https://medium.com/p/a6729c56a3d</guid>
            <category><![CDATA[sitecore-unit-testing]]></category>
            <category><![CDATA[sitecore-development]]></category>
            <category><![CDATA[sitecore]]></category>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[best-practices]]></category>
            <dc:creator><![CDATA[Ehsan]]></dc:creator>
            <pubDate>Sun, 12 Jun 2022 20:51:01 GMT</pubDate>
            <atom:updated>2022-06-12T20:58:26.131Z</atom:updated>
            <content:encoded><![CDATA[<h3>Sitecore Unit Testing Guide — Part 2 : Using Fixtures</h3><p><em>Find the source code here : </em><a href="https://github.com/ehsanaslani/SitecoreUnitTesting"><em>https://github.com/ehsanaslani/SitecoreUnitTesting</em></a></p><ul><li>Part 1 : <a href="https://medium.com/@ehsan.aslani/sitecore-unit-testing-guide-part-1-the-basics-265acb1b3b0">The Basics</a></li><li>Part 3 : <a href="https://medium.com/@ehsan.aslani/sitecore-unit-testing-guide-part-3-mocking-sitecore-services-9dbb33615352">Mocking Sitecore Services</a></li><li>Part 4 : <a href="https://medium.com/@ehsan.aslani/sitecore-unit-testing-guide-part-4-mocking-servicelocator-5be28228d832">Mocking ServiceLocator</a></li></ul><p>In the previous part, we examined mocking Items, Fields and Database and how to write basic unit tests. In this part we will see how to make better tests using the fixtures and reuse the mocking code in our tests</p><h3>AutoData Attribute</h3><p>Test fixtures can be used to encapsulate and reuse the code for setting up the objects and data used by tests. We are going to use that for mocking items, templates, databases and other mocked object used in unit tests.</p><p><a href="https://www.nuget.org/packages/AutoFixture.Xunit2/">Xunit2.AutoFixture</a> library provides <em>AutoData </em>atrribute which we are going to uses it to simplify our tests. By using this attribute we can automate setup of mock objects that are passed to the tests through the method parameters. To uses this attribute, we will encapsulate our mocking logic into instances of <em>AutoFixture.ICustomization</em> interface. Let’s create three implementations of this interface for Item, Template and Database.</p><p>First let’s add an extension method to Database class to add a mock item</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JVdkVFVkaSwX0dmWawhCjA.png" /></figure><p>Now we will create Customization classes :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/830/1*18ZqfZ47rBgKehsuDicU_g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WHsJEJMwJByH-x7vPdg8CQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vA9mjLBkCS9sNeN7B9DLoQ.png" /></figure><p>Then we will create a custom AutoData attribute and configure it to use our customizations:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/793/1*wEBKZo4Ap9b8umoooNI2Hw.png" /></figure><p>So we are ready to use our fixture in our test. Let’s rewrite the tests in the first part using our SitecoreAutoData attribute:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qrEvteyAITSG8aEMmI9Cuw.png" /></figure><p>So now to get the mocked Item for personData and child, we just need to specify them as parameters for our test class. Let’s make this even better by adding an extension method for Item class to add a field and remove the AddField method from our test class. We can also add an extension method for adding child items to an item:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Cs3dx5gmpHR6LEHjvfbmkg.png" /></figure><p>So now our test class will look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lfHE81XhLF15b-OWVEzo-w.png" /></figure><p>This test is much more readable and easier to maintain. You can add more extensions to Item and Database classes as needed to shorten your tests.</p><p>In next part we will try to add more customizations to our test fixture for mocking other Sitecore services such as LinkManager</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a6729c56a3d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sitecore Unit Testing Guide — Part 1 : The Basics]]></title>
            <link>https://medium.com/@ehsan.aslani/sitecore-unit-testing-guide-part-1-the-basics-265acb1b3b0?source=rss-ed26f8dca0d------2</link>
            <guid isPermaLink="false">https://medium.com/p/265acb1b3b0</guid>
            <category><![CDATA[sitecore]]></category>
            <category><![CDATA[best-practices]]></category>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[sitecore-development]]></category>
            <category><![CDATA[sitecore-unit-testing]]></category>
            <dc:creator><![CDATA[Ehsan]]></dc:creator>
            <pubDate>Sun, 12 Jun 2022 20:48:52 GMT</pubDate>
            <atom:updated>2022-06-12T20:58:02.370Z</atom:updated>
            <content:encoded><![CDATA[<h3>Sitecore Unit Testing Guide — Part 1 : The Basics</h3><p><em>Find the source code here : </em><a href="https://github.com/ehsanaslani/SitecoreUnitTesting"><em>https://github.com/ehsanaslani/SitecoreUnitTesting</em></a></p><ul><li>Part 2 : <a href="https://medium.com/@ehsan.aslani/sitecore-unit-testing-guide-part-2-using-fixtures-a6729c56a3d">Fixtures</a></li><li>Part 3 : <a href="https://medium.com/@ehsan.aslani/sitecore-unit-testing-guide-part-3-mocking-sitecore-services-9dbb33615352">Mocking Sitecore Services</a></li><li>Part 4 : <a href="https://medium.com/@ehsan.aslani/sitecore-unit-testing-guide-part-4-mocking-servicelocator-5be28228d832">Mocking ServiceLocator</a></li></ul><p>Writing unit tests could be tricky sometimes and unit testing Sitecore solutions, introduces its own kind of challenges. In these series of articles I will try to explain about unit testing Sitecore solutions and address the challenges faced by developers in writing tests. I hope that this guide can help developers to make unit testing an enjoyable experience.</p><h3>Let’s start</h3><p>In the first part let’s start with the basics of writing Sitecore unit tests. It is assumed that the reader has basic knowledge about unit tests as it’s needed to understand the contents.</p><p>In the examples and the companion source code, I have used Xunit, Nsubstitute, FluentAssertions libraries but of course the principles can be used with any other frameworks of your preference</p><h3>How to write unit tests?</h3><p>To write useful and high quality unit tests, which can be maintained and understood by others, keep these standard best practices in mind:</p><ul><li><strong>Choose descriptive names for your tests</strong>: Your tests should be readable for other developers looking at your tests. Unit tests also serve as a documentation for your code. Use a naming convention which can describe the subject of test, the scenario and the expected result and follow the convention in all your tests. You can see some of the common naming conventions <a href="https://medium.com/@stefanovskyi/unit-test-naming-conventions-dd9208eadbea">here</a></li><li><strong>Your tests should only test the unit under test</strong>: When you are testing a class that has dependencies, your test should only test that class and not the dependencies. Use mocking frameworks to mock all the dependencies.</li><li><strong>Write independent tests</strong>: Don’t write tests that depend on each other. Each of your tests should not be aware of existence of other tests and should not depend on them</li><li><strong>Write stable tests</strong> : Your tests should only fail if there is a bug in the code. So make sure that they don’t fail because of the running conditions. For example keep in mind that your tests will be run in parallel with other tests and make sure tests will not fail when executed with others. This can happen if your tests modify static members that other tests use it.</li><li><strong>Write short and readable tests</strong>: Long unit tests with several lines could be difficult to read and are difficult to maintain as well. Keep them as short as possible.</li><li><strong>Do not use multiple assertions in a single test</strong>: Each test should only test one scenario and ideally one assertion. This makes it more readable and maintainable. Whenever you find yourself adding multiple assertions in a test consider breaking it into multiple separate tests.</li><li><strong>Follow the AAA pattern</strong> : Your tests should simply have three sections. Arrange, Act and Assert. Arrange the test data, Act the function that is going to be tested and Assert the expected results.</li><li><strong>Do not use conditions and loops in your tests</strong>: Your test should not include conditions (if &amp; switch statements), loops (while, for, foreach). If your test includes these statements, it’s probably a sign that it can be broken into few smaller tests.</li></ul><h3>Mocking Items, Templates and Databases</h3><p>Your code for Sitecore solutions will normally use Items, Templates and Databases a lot. As we don’t want to retrieve actual items from databases, you need to mock them. Mocking is a way to fake the dependencies of the systems under test and testing it in isolation. There are several mocking frameworks such as <a href="https://nsubstitute.github.io/"><em>NSubstitute </em></a>and <a href="http://nmock.sourceforge.net/"><em>NMock</em></a><em> </em>that you can use to create fake objects. When you mock a dependency like an Item or Template, you can define its behavior to simulate your test scenario.</p><p>You can’t mock concrete classes. You can only mock interfaces, abstract classes or partially mock concrete classes that have abstract or virtual members. The good news is that Sitecore uses those abstractions and therefore it’s mostly mockable:</p><ul><li><strong>Database </strong>class is an abstract class</li><li>Public members of <strong>Item </strong>&amp; <strong>Field </strong>classes are virtual</li><li>Public members of <strong>TemplateItem </strong>class are virtual</li></ul><p>This means that you can easily create mock objects for these classes and define how they should behave during test. Let’s see an example:</p><p>Let’s try to unit test this simplified piece of code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/935/1*voHSZgvC2SU1RdLl4rmZxw.png" /></figure><p>We want to make sure that the method does not throw exception if the <strong>Age </strong>field does not have a valid integer value (as you can guess, this test should fail). So we need to provide a mock item for the <em>personData </em>that has a child item with an invalid integer value in it’s age field.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PCuTvWhtvrMd0M0IPxRkqQ.png" /></figure><p><em>GetMockItem </em>method creates a mock item object using the <em>Substitute.For&lt;&gt;</em>. Item class constructor expects three parameters : <em>Item ID</em>, an <em>ItemData</em> instance and a <em>Database </em>instance which are passed to it through the <em>For&lt;&gt;</em> method parameters. Item fields are also mocked by setting a mock <em>FiledCollection </em>object.</p><p><em>AddField </em>method, first creates a mock Field object and then sets the behavior so it return the specified value when <em>Field.Value</em> is called. then the <em>Field[ID]</em> and <em>Item[String]</em> indexers are mocked. Remember that we fed a mocked <em>FieldCollection </em>when mocking the item, so we can use the <em>Returns </em>method in <em>Item.Fields</em> to define its behavior.</p><p>Now let’s take a look at another simplistic example. This method tries to get the value of “Page Category” field of the current page and if it’s not set, it will return the default value which is set in another item in the database:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jDlgG8xP_hsha1_y4p6SxA.png" /></figure><p>so let’s write a unit test to make sure that this method will return the default value if the category is not set:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8FwTPXUioKH29C1PMq2brw.png" /></figure><p>In this test, we create the mock items for the context page and the default data item, then the database <em>GetItem </em>is wired to return the default data item and finally the Context item and database is set.</p><h3>Next Steps</h3><p>Although these tests work well, there is still room for improvement. In <a href="https://medium.com/@ehsan.aslani/sitecore-unit-testing-guide-part-2-using-fixtures-a6729c56a3d">next part</a> we will look into the ways to make the tests shorter and more readable and ways to reuse the mocking code in our tests to avoid repeating them across our test classes.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=265acb1b3b0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Speed up Retrieving Item’s Descendants by Microsoft TPL Dataflow Library]]></title>
            <link>https://medium.com/@ehsan.aslani/speed-up-retrieving-items-descendants-by-microsoft-tpl-dataflow-library-b655db02379?source=rss-ed26f8dca0d------2</link>
            <guid isPermaLink="false">https://medium.com/p/b655db02379</guid>
            <category><![CDATA[sitecoe-axes-api]]></category>
            <category><![CDATA[concurrent-programming]]></category>
            <category><![CDATA[tpl-data-flow]]></category>
            <category><![CDATA[sitecore]]></category>
            <category><![CDATA[sitecore-development]]></category>
            <dc:creator><![CDATA[Ehsan]]></dc:creator>
            <pubDate>Mon, 14 Mar 2022 01:41:14 GMT</pubDate>
            <atom:updated>2022-03-14T01:41:14.106Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Sitecore.Data.Items</strong> namespace includes <strong>ItemAxes</strong> class that provides a <em>GetDescendants()</em> method for retrieving the descendants of an item</p><pre>Item.Axes.GetDescendants()</pre><p>This method recursively calls <strong>Item.Children</strong> to retrieve all the descendants and therefore it’s an expensive methods which can take long time to complete when there are so many items. This article suggests an approach for speeding up the retrieval of an item’s descendants using concurrency features provided by <a href="https://docs.microsoft.com/en-us/dotnet/standard/parallel-programming/dataflow-task-parallel-library">Microsoft TPL Dataflow</a></p><h3>Concurrent Programing Using Microsoft Dataflow Library</h3><p>Dataflow library provides some foundation for building pipelines made of processing blocks that can pass messages to each other and makes parallel processing of messages so easy.</p><p>This library provides few types of blocks (<a href="https://docs.microsoft.com/en-us/dotnet/api/system.threading.tasks.dataflow.bufferblock-1?view=net-6.0">BufferBlock</a>, <a href="https://docs.microsoft.com/en-us/dotnet/api/system.threading.tasks.dataflow.transformblock-2?view=net-6.0">TransformBlock</a>, <a href="https://docs.microsoft.com/en-us/dotnet/api/system.threading.tasks.dataflow.broadcastblock-1?view=net-6.0">BroadcastBlock </a>and <a href="https://docs.microsoft.com/en-us/dotnet/api/system.threading.tasks.dataflow.actionblock-1?view=net-6.0">ActionBlock</a>) that can be linked to each other to build a pipeline for processing messages.</p><p>A <strong>TransformBlock </strong>takes an input, processes the input and generates an output sent to next link block. TPL library provides parallel processing as it can execute multiple processing at the same time which take an input posted to the block and send it to next linked block after processing.</p><p>A <strong>BufferBlock </strong>takes messages as input and sends it to the next linked block.</p><p>Once all the input objects posted to a block are consumed, the block state changes to <em>completed. </em>A completed block does not perform any more processing. It is possible to propagate the completion to next blocks.</p><p>To use Dataflow library add <strong>Microsoft.Tpl.Dataflow</strong> nuget package to your project.</p><h3><strong>A GetDescendants Method using Dataflow Library</strong></h3><p>to speed up the retrieval of descendant items, it’s possible to call multiple Item.Children at the same time running in parallel. Here we are going to build a recursive pipeline that can process input items to retrieve the children and send it to an output BufferBlock</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eo63O4i7xr3KPiWl7I4qWw.png" /><figcaption>Get Item’s Descendants Pipeline</figcaption></figure><p>The root item is posted to the Input BufferBlock, input block passes the item to a Transform Block which calls Item.Children and passes the parent to the output BufferBlock, while the children are passed to the input block to enter the pipeline again so all the descendants are retrieved by the processing block and sent to Output BufferBlock.</p><p>You can control the degree of parallelization in the processing block which calls Item.Children to achieve the optimal performance.</p><pre>public class SpeedyFindDescendants</pre><pre>{</pre><pre>  public IList&lt;Item&gt; GetDescendants(Item root)</pre><pre> {</pre><pre>  //Input block</pre><pre>  var sourceBlock = new BufferBlock&lt;Item&gt;();</pre><pre>//Output block</pre><pre>var outputBlock = new BufferBlock&lt;Item&gt;();</pre><pre>//The processing block which sends the input item to next linked block (output),</pre><pre>//but the children are sent back to input block to enter the pipeline again</pre><pre>var getChildrenBlock = new TransformBlock&lt;Item, Item&gt;(item =&gt;</pre><pre>{</pre><pre>//get input item’s children and post them back to source block</pre><pre>foreach (Item child in item.Children)</pre><pre>{</pre><pre>sourceBlock.Post(child);</pre><pre>}</pre><pre>//return the input item so it can be sent to output block</pre><pre>return item;</pre><pre>} ,</pre><pre>//Maximum five concurrent instances of getChildrenBlock can run in parallel</pre><pre>new ExecutionDataflowBlockOptions{MaxDegreeOfParallelism = 5});</pre><pre>//Link the sourceblock to getChildrenBlock and propagate completion</pre><pre>sourceBlock.LinkTo(getChildrenBlock, new DataflowLinkOptions {PropagateCompletion = true});</pre><pre>//Link the getChildrenBlock to output block that buffers the descendant items</pre><pre>getChildrenBlock.LinkTo(outputBlock, new DataflowLinkOptions {PropagateCompletion = true});</pre><pre>//Post the root item to source block so pipeline starts processing</pre><pre>sourceBlock.Post(root);</pre><pre>//Wait until all child items are processed and the descendants are retrieved.</pre><pre>//When source block is completed (there are no items with children) it propagates completion to</pre><pre>//getChildren block which in turn propagates completion to output block.</pre><pre>outputBlock.Completion.Wait();</pre><pre>//retrieve all descendant items from output buffer block</pre><pre>outputBlock.TryReceiveAll(out var descendants);</pre><pre>return descendants;</pre><pre>}</pre><pre>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b655db02379" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>