<?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 tong eric on Medium]]></title>
        <description><![CDATA[Stories by tong eric on Medium]]></description>
        <link>https://medium.com/@ericjonson490?source=rss-f0e2a107b11------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*zwHYPrJb-1muIWOuZSgPdQ.jpeg</url>
            <title>Stories by tong eric on Medium</title>
            <link>https://medium.com/@ericjonson490?source=rss-f0e2a107b11------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 17:21:37 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ericjonson490/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[A Comprehensive Guide to Implementing xUnit Tests in C# .NET]]></title>
            <link>https://medium.com/bina-nusantara-it-division/a-comprehensive-guide-to-implementing-xunit-tests-in-c-net-b2eea43b48b?source=rss-f0e2a107b11------2</link>
            <guid isPermaLink="false">https://medium.com/p/b2eea43b48b</guid>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[unit-test-tools]]></category>
            <category><![CDATA[unit-test-framework]]></category>
            <category><![CDATA[xunit]]></category>
            <category><![CDATA[unit-testing]]></category>
            <dc:creator><![CDATA[tong eric]]></dc:creator>
            <pubDate>Fri, 29 Sep 2023 10:57:34 GMT</pubDate>
            <atom:updated>2023-09-29T10:57:34.450Z</atom:updated>
            <content:encoded><![CDATA[<h3>A Comprehensive Guide to Implementing xUnit Tests in C# .NET</h3><p>Mastering Test-Driven Development with xUnit: A Definitive Guide for C# .NET Developers</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*V7povbW6bg08lMet" /><figcaption>Photo by <a href="https://unsplash.com/@moonshadowpress?utm_source=medium&amp;utm_medium=referral">Joyce Hankins</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong>In software </strong>development, think of testing as your trusty sidekick — a vigilant partner in ensuring your software works as expected. Imagine it as a safety net, catching bugs and glitches before they cause chaos. Now, meet xUnit — an essential tool for C# .NET developers that makes testing your code a breeze. In this article, we’ll take you on a journey into the fascinating realm of testing and show you why xUnit is your new best friend. It’s not just about finding bugs; it’s about crafting code that’s strong and reliable from the start. Join us as we explore how xUnit makes testing in C# .NET both practical and powerful, helping you build better software. Welcome to the world of testing made easy and effective with xUnit.</p><h3>Understanding xUnit</h3><h4>What is xUnit, and Where Did It Come From?</h4><p>Before we dive into the nitty-gritty details of xUnit, let’s get to know what it is and where it comes from. xUnit is not just a testing framework; it’s a lineage of testing frameworks. The “x” in xUnit signifies the variable nature of the framework, adaptable to various programming languages. In the realm of C# .NET, we have xUnit.net, which is the star of our show.</p><p>xUnit.net was inspired by the earlier frameworks like JUnit (for Java) and NUnit (for .NET). Its origins can be traced back to the early 2000s when it was first developed by James Newkirk and Brad Wilson. They aimed to create a testing framework that overcame some limitations of its predecessors and was designed with extensibility and simplicity in mind.</p><h4>Key Features and Advantages of xUnit</h4><p>So, what makes xUnit stand out in the crowded field of testing frameworks, and why should you consider using it for your C# .NET projects? Let’s explore some of its key features and advantages:</p><ol><li><strong>Simplicity</strong>: One of the hallmarks of xUnit is its simplicity. Writing tests with xUnit is straightforward, and the framework does away with unnecessary abstractions, making it easy for developers to get started.</li><li><strong>Extensibility</strong>: xUnit is highly extensible, allowing you to customize it to your specific testing needs. You can create custom test runners, reporters, and even your own test attributes.</li><li><strong>Conventions over Configuration</strong>: xUnit follows the principle of “conventions over configuration.” This means that it encourages sensible defaults and eliminates the need for excessive configuration, saving you time and reducing complexity.</li><li><strong>Parallel Test Execution</strong>: With xUnit, you can run tests in parallel, harnessing the power of multi-core processors for faster test execution. This is especially useful when you have a large test suite.</li><li><strong>Data-Driven Tests</strong>: xUnit makes it easy to write data-driven tests, allowing you to run the same test with different input data, which can be incredibly useful for testing various scenarios.</li><li><strong>Rich Assertions</strong>: The framework provides a wide array of assertion methods, making it easy to check the expected behavior of your code. You can verify conditions, exceptions, and more with ease.</li><li><strong>Test Output Capture</strong>: xUnit captures and logs test output, making it easier to diagnose issues when a test fails. This can be especially helpful for debugging.</li><li><strong>Community and Support</strong>: xUnit has a vibrant and active community, with ongoing development and support. You can find ample documentation, tutorials, and help from fellow developers.</li></ol><p>Now that we’ve scratched the surface, it’s time to roll up our sleeves and learn how to put xUnit to work in your C# .NET projects. In the next sections, we’ll guide you through setting up xUnit and writing your first tests. Get ready to see how xUnit can make testing in C# .NET a breeze!</p><h3>Writing Your First xUnit Test</h3><p>Now that we’ve familiarized ourselves with xUnit, it’s time to roll up our sleeves and get hands-on with some actual testing. In this section, we’ll guide you through the process of creating a simple C# .NET project to demonstrate xUnit and then walk you through the steps of writing your very first xUnit test.</p><h4>Creating a Simple C# .NET Project</h4><p>Before we can start testing, we need a project to work with. Let’s create a basic C# .NET project in Visual Studio (or your preferred IDE) to get started:</p><ol><li><strong>Open Visual Studio</strong>: Launch your Visual Studio IDE or any C# .NET development environment you prefer.</li><li><strong>Create a New Project</strong>: Go to the “File” menu, select “New,” and then choose “Project.”</li><li><strong>Select Project Type</strong>: Choose a project template that suits your needs. For this example, we’ll create a “Console App (.NET Core)” project, but xUnit works equally well with other project types like ASP.NET Core applications and class libraries.</li><li><strong>Name Your Project</strong>: Give your project a meaningful name, and choose a location to save it.</li><li><strong>Click Create</strong>: After configuring the project, click the “Create” button to generate your project files.</li></ol><p>Now that we have our project ready, let’s dive into writing our first xUnit test.</p><h4>Writing Your First xUnit Test</h4><p>In this example, we’ll create a simple test to check if a basic math operation works as expected. Follow these steps:</p><ol><li><strong>Add xUnit NuGet Package</strong>: To use xUnit, we need to add the xUnit NuGet package to our project. Right-click on the project in the Solution Explorer, select “Manage NuGet Packages,” search for “xUnit,” and install the “xunit” package.</li><li><strong>Create a Test Class</strong>: In your project, add a new class for your tests. Name it something like “MathTests.cs.”</li><li><strong>Using xUnit</strong>: At the top of your test class file, add the necessary using directives for xUnit:</li></ol><pre>using Xunit;</pre><p>4. <strong>Write a Test Method</strong>: Create a test method within your test class. A test method is a regular C# method decorated with xUnit attributes. Here’s an example:</p><pre>public class MathTests<br>{<br>    [Fact] // This attribute marks this method as a test.<br>    public void ShouldAddTwoNumbers()<br>    {<br>        // Arrange<br>        int a = 3;<br>        int b = 5;<br><br>        // Act<br>        int result = a + b;<br><br>        // Assert<br>        Assert.Equal(8, result); // Check if the result is as expected.<br>    }<br>}</pre><p>5. Understanding the Anatomy:</p><ul><li>[Fact] attribute: This attribute denotes that the method is a test. It tells xUnit to execute this method as a test case.</li><li>Arrange: In this section, you set up the prerequisites for your test, such as initializing variables and objects.</li><li>Act: Here, you perform the action or operation that you want to test.</li><li>Assert: This is where you verify that the result of your test matches your expectations. In this example, we use Assert.Equal to check if the sum of a and b equals 8.</li></ul><p>6. Run Your Tests: To run your xUnit tests, you can use your IDE’s test runner or use the command line with dotnet test. The results will show you if your test passed or failed.</p><p>That’s it! You’ve written and executed your first xUnit test. As you can see, xUnit follows a simple and intuitive structure that makes it easy to write and understand tests. In the next sections, we’ll explore more advanced xUnit features and best practices for writing effective tests.</p><h3>Test Fixtures and Data-driven Tests</h3><p>In our journey through the world of xUnit testing, it’s essential to understand two crucial concepts: test fixtures and data-driven tests. These concepts play a pivotal role in enhancing the organization and scope of your tests. Let’s explore how they work and how xUnit makes them easy to implement.</p><h4>What are Test Fixtures and Why Are They Important?</h4><p>In the context of testing, a test fixture represents the environment or context in which a collection of tests operates. Think of it as a setup or a shared state that multiple tests can rely on. Test fixtures are essential because they allow you to establish a consistent starting point for your tests, reducing redundancy and ensuring that your tests are isolated from one another.</p><h4>Creating Test Fixtures in xUnit</h4><p>xUnit provides an elegant way to create test fixtures using the [Collection] attribute and a dedicated class to hold your fixture setup code. Here&#39;s how you can do it:</p><ul><li><strong>Create a Fixture Class</strong>: Start by creating a class that will serve as your test fixture. This class should contain the setup and teardown logic shared by multiple tests.</li></ul><pre>public class DatabaseFixture : IDisposable<br>{<br>    // Constructor: Set up your fixture.<br>    public DatabaseFixture()<br>    {<br>        // Initialize your test database or any other resources.<br>    }<br><br>    // IDisposable implementation: Clean up your fixture.<br>    public void Dispose()<br>    {<br>        // Dispose of or release any resources used by your fixture.<br>    }<br>}</pre><ul><li><strong>Use the </strong><strong>[Collection] Attribute</strong>: In your test class, use the [<strong>Collection</strong>] attribute to specify which fixture it belongs to. This ensures that tests within the same collection share the same fixture instance.</li></ul><pre>[Collection(&quot;DatabaseCollection&quot;)]<br>public class DatabaseTests<br>{<br>    private readonly DatabaseFixture _fixture;<br><br>    public DatabaseTests(DatabaseFixture fixture)<br>    {<br>        _fixture = fixture;<br>    }<br><br>    // Your tests go here, utilizing the shared fixture.<br>}</pre><h4>Introducing Data-Driven Tests</h4><p>What Are Data-Driven Tests and Why Are They Useful? Data-driven tests allow you to run the same test logic with multiple sets of input data. This is incredibly valuable when you want to verify that your code behaves correctly under different conditions. Instead of writing separate tests for each data set, data-driven tests reuse the same test code with varying inputs.</p><h4>Creating Data-Driven Tests with xUnit</h4><p>xUnit makes it easy to create data-driven tests using the <strong>[Theory]</strong> attribute. Here&#39;s a step-by-step guide:</p><ul><li><strong>Define a Data Source</strong>: Create a public method that returns an IEnumerable&lt;object[]&gt;. Each object array represents a set of input data for your test.</li></ul><pre>public static IEnumerable&lt;object[]&gt; TestData()<br>{<br>    yield return new object[] { 3, 5, 8 }; // Input values and expected result<br>    yield return new object[] { 0, 0, 0 };<br>    yield return new object[] { -3, 3, 0 };<br>}</pre><ul><li><strong>Use the </strong><strong>[Theory] Attribute</strong>: Create a test method and decorate it with the <strong>[Theory]</strong> attribute. This method should accept parameters that match the data source&#39;s structure.</li></ul><pre>[Theory]<br>[MemberData(nameof(TestData))] // Link to your data source<br>public void Add_ShouldCalculateCorrectly(int a, int b, int expected)<br>{<br>    // Act<br>    int result = a + b;<br><br>    // Assert<br>    Assert.Equal(expected, result);<br>}</pre><p>In this example, the [Theory] attribute instructs xUnit to run the Add_ShouldCalculateCorrectly method for each set of data provided by the TestData method. The parameters a, b, and expected are automatically mapped to the values in each object array.</p><p>With test fixtures and data-driven tests, xUnit empowers you to structure and expand your test suite systematically. You can maintain a clean separation between different types of tests and explore a wide range of input scenarios without duplicating your testing code. In the following sections, we’ll delve deeper into more advanced xUnit features and best practices, helping you become a testing virtuoso in C# .NET development.</p><h3>Assertions and Test Output</h3><p>In our exploration of xUnit testing, it’s time to dive into two critical aspects of the testing process: assertions and test output. Understanding how to make assertions and interpret test output is fundamental to ensuring that your tests provide meaningful results and uncover issues in your code effectively.</p><h4>The Importance of Assertions in Testing</h4><p>Assertions are the heart and soul of testing. They are the means by which you express your expectations about the behavior of your code. When you write a test, you are essentially saying, “I expect this specific condition to be true.” Assertions validate whether your expectations align with the actual behavior of your code. Here’s why assertions are crucial:</p><ol><li><strong>Bug Detection</strong>: Assertions help you catch bugs and defects early in the development cycle. By specifying expected outcomes, you can quickly spot deviations from the intended behavior.</li><li><strong>Documentation</strong>: Tests serve as living documentation for your code. Assertions describe what your code should do, making it easier for you and your team to understand and maintain the codebase.</li><li><strong>Safety Net</strong>: As your codebase evolves, assertions act as a safety net. They guard against regressions, ensuring that existing functionality remains intact when you make changes.</li><li><strong>Refactoring Confidence</strong>: When you refactor or modify code, assertions give you confidence that you haven’t introduced new issues. If your tests pass, you can trust that your changes haven’t broken anything.</li></ol><h4>Common Assertion Methods in xUnit</h4><p>xUnit provides a comprehensive set of assertion methods to validate conditions in your tests. Here are some commonly used assertion methods:</p><ol><li>Assert.Equal(expected, actual): Checks if expected and actual values are equal.</li><li>Assert.NotEqual(expected, actual): Verifies that expected and actual values are not equal.</li><li>Assert.True(condition): Asserts that the condition is true.</li><li>Assert.False(condition): Asserts that the condition is false.</li><li>Assert.Null(object): Ensures that the object is null.</li><li>Assert.NotNull(object): Validates that the object is not null.</li><li>Assert.Contains(expected, collection): Checks if expected is present in the collection.</li><li>Assert.Throws&lt;ExceptionType&gt;(action): Verifies that action throws an exception of type ExceptionType.</li><li>Assert.IsType&lt;ExpectedType&gt;(object): Asserts that object is of type ExpectedType.</li><li>Assert.IsAssignableFrom&lt;ExpectedType&gt;(object): Validates that object is assignable to ExpectedType.</li></ol><h4>Interpreting and Analyzing Test Output</h4><p>When you run your xUnit tests, you’ll receive output that informs you about the status of your tests. Understanding this output is vital for diagnosing issues and maintaining code quality:</p><ul><li><strong>Passing Tests</strong>: If all tests pass, you’ll see a green indicator, signaling that your code behaves as expected.</li><li><strong>Failing Tests</strong>: When a test fails, you’ll receive detailed information about the failure, including which assertion failed and the expected vs. actual values. This output helps you pinpoint the problem.</li><li><strong>Test Execution Time</strong>: xUnit also reports how long each test took to execute. This can be useful for identifying slow or resource-intensive tests.</li><li><strong>Coverage Reports</strong>: If you’ve set up code coverage analysis, xUnit can provide insights into which parts of your code are covered by tests. This can help you identify areas that need additional testing.</li></ul><p>By carefully reviewing the test output, you can quickly identify and address issues in your code. Remember that the goal of testing is not just to write tests that pass but to write tests that reveal problems. The more you understand your test output, the better equipped you are to achieve this goal and ensure the reliability of your software.</p><h3>Conclusion</h3><p>In summary, this article has covered the following key points:</p><ol><li>The importance of testing in software development.</li><li>The versatility and significance of xUnit as a testing framework for C# .NET.</li><li>The fundamental principles of writing effective tests using the Arrange-Act-Assert pattern.</li><li>The role of test fixtures in organizing and reusing test contexts.</li><li>The power of data-driven testing for broader test coverage.</li><li>The importance of assertions in validating code behavior.</li><li>The skill of interpreting and analyzing test output to identify issues effectively.</li></ol><p>With these insights, you are now well-equipped to excel in xUnit testing for C# .NET development.</p><p>In the next article, we will delve into essential best practices for xUnit testing, explore the concept of code coverage, and show you how to integrate external tools to visualize your test results. Stay tuned as we uncover these valuable insights to elevate your testing game.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b2eea43b48b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/bina-nusantara-it-division/a-comprehensive-guide-to-implementing-xunit-tests-in-c-net-b2eea43b48b">A Comprehensive Guide to Implementing xUnit Tests in C# .NET</a> was originally published in <a href="https://medium.com/bina-nusantara-it-division">Bina Nusantara IT Division</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Next.js: The Complete Overview and Why It’s Gaining Popularity]]></title>
            <link>https://medium.com/bina-nusantara-it-division/next-js-the-complete-overview-and-why-its-gaining-popularity-77db5c47dc6d?source=rss-f0e2a107b11------2</link>
            <guid isPermaLink="false">https://medium.com/p/77db5c47dc6d</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[next]]></category>
            <category><![CDATA[website]]></category>
            <dc:creator><![CDATA[tong eric]]></dc:creator>
            <pubDate>Fri, 30 Jun 2023 07:01:27 GMT</pubDate>
            <atom:updated>2023-06-30T07:01:27.962Z</atom:updated>
            <content:encoded><![CDATA[<p>Unleashing the Power of Next.js: A Comprehensive Exploration of its Features, Benefits, and Rising Popularity</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*eJblWSMF2t56JOZo" /><figcaption>Photo by <a href="https://unsplash.com/@grakozy?utm_source=medium&amp;utm_medium=referral">Greg Rakozy</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>Next.js has taken the web development world by storm, captivating developers with its transformative capabilities. By seamlessly blending server-side rendering (SSR) and static site generation (SSG), Next.js empowers developers to create lightning-fast websites and applications. With automatic code splitting, hot module replacement, and optimized asset loading, Next.js streamlines the development process, maximizing efficiency and productivity.</p><p>In this article, we explore Next.js in-depth, uncovering its features, benefits, and practical use cases. From routing and navigation to seamless API integration, we provide insights to help you leverage Next.js to its fullest potential. We also touch on deployment options and the thriving Next.js ecosystem, ensuring you stay at the forefront of modern web development.</p><h3>Features and Benefits of Next.js</h3><p>Next.js is not just a buzzword in the web development community; it offers a rich set of features and benefits that make it a go-to choice for developers seeking optimal performance, scalability, and developer experience. Let’s delve into some of the remarkable features and benefits that Next.js brings to the table.</p><ol><li><strong>Server-side Rendering (SSR) and Static Site Generation (SSG)</strong>: Next.js combines the best of both worlds, allowing you to generate pages on the server or at build time. This ensures fast initial loading and improved search engine optimization.</li><li><strong>Automatic Code Splitting:</strong> Next.js intelligently splits your code into smaller bundles, loading only what’s necessary for each page. This optimizes performance and ensures a smooth user experience.</li><li><strong>Hot Module Replacement:</strong> Making code changes in real-time becomes a breeze with Next.js. You can see the updates instantly without losing the application’s state, resulting in a highly efficient development workflow.</li><li><strong>Optimized Asset Loading:</strong> Next.js optimizes assets like images and provides lazy loading, reducing load times and improving overall performance. Your users will experience faster page loads and optimized bandwidth usage.</li><li><strong>Seamless Routing and Navigation:</strong> Next.js simplifies routing, allowing you to create dynamic and nested routes effortlessly. Client-side navigation ensures smooth transitions between pages, enhancing the user experience.</li><li><strong>Data Fetching Made Easy:</strong> Next.js provides built-in methods for fetching data on both the server and client sides. You can effortlessly fetch data during server-side rendering, pre-fetch data before rendering a page, or retrieve data on the client side.</li><li><strong>Scalability and Deployment Options:</strong> Next.js scales effortlessly to handle increased traffic and offers various deployment options. Whether you prefer serverless deployments, traditional hosting, or static site hosting, Next.js has you covered.</li></ol><p>By leveraging these features and benefits, you can empower your web development projects with Next.js, delivering exceptional performance, scalability, and an outstanding user experience. Next.js continues to evolve and gain momentum, solidifying its position as a leading framework for modern web development.</p><h3>Server-side Rendering (SSR) vs. Static Site Generation (SSG) in Next.js</h3><p>Next.js offers two powerful approaches for generating web pages: s<strong>erver-side rendering (SSR)</strong> and <strong>static site generation (SSG)</strong>. Understanding the differences between SSR and SSG, and knowing when to use each approach, is key to optimizing your Next.js project based on specific requirements.</p><p><strong>Server-side Rendering (SSR)</strong> in Next.js: Server-side rendering involves generating the HTML for a page on the server and sending it to the client. With SSR in Next.js, the server dynamically renders the page with the latest data upon each request. This enables search engines to crawl and index the content effectively, resulting in better search engine optimization (SEO). SSR is useful for pages that require frequently updated data or personalized content.</p><p><strong>Static Site Generation (SSG)</strong> in Next.js: Static site generation, on the other hand, generates the HTML for all pages at build time rather than on each request. With SSG in Next.js, you pre-render your pages during the build process, resulting in a collection of static HTML files. This approach offers incredible performance benefits, as the pre-rendered pages can be served instantly without any server-side processing. SSG is well-suited for content-heavy websites or applications with relatively static content that doesn’t require frequent updates.</p><p>Choosing between SSR and SSG: The choice between SSR and SSG depends on the specific requirements of your project:</p><ol><li>SSR is ideal when you need real-time data fetching, dynamic content, or personalized experiences. It ensures that the most up-to-date data is displayed to the user upon each request, making it suitable for applications that rely heavily on user-specific or frequently updated content.</li><li>SSG excels in scenarios where content doesn’t change frequently and can be pre-rendered during the build process. This approach guarantees fast loading times and reduces the server load, making it perfect for content-focused websites, blogs, or landing pages.</li></ol><p>Data Fetching and Caching in Next.js: Next.js provides various methods for data fetching, both during server-side rendering and on the client side. You can fetch data using built-in functions like getServerSideProps for SSR or getStaticProps for SSG. These functions allow you to fetch data from external APIs, databases, or any data source and pass it as props to your components.</p><p>Next.js also offers efficient data caching mechanisms to optimize page rendering. By leveraging features like revalidate and incremental static regeneration, you can control how frequently the data is refreshed. This ensures a balance between providing fresh data and minimizing the load on servers.</p><p>By understanding how Next.js handles data fetching and caching, you can design your application to fetch data efficiently and strike the right balance between real-time updates and performance optimization.</p><h3>Routing and Navigation in Next.js: Simplifying User Experience</h3><p>Next.js simplifies routing and navigation with its built-in system, eliminating the need for additional libraries. You define routes by creating files in the pages directory, making project architecture clear and organized.</p><p>Advantages of Next.js Routing:</p><ol><li>Simplicity: Next.js reduces complex routing setup, allowing you to focus on building functionality.</li><li>Server-side Rendering (SSR): Next.js enables faster initial page loads and better SEO through server-side rendering.</li><li>Code Splitting: Next.js automatically loads only necessary code, optimizing performance.</li></ol><p>Dynamic Routing and Parameter Handling: Next.js supports dynamic routing, handling routes with dynamic segments or parameters. Use square brackets ([]) in file names to define dynamic routes. For example, [id].js matches /users/1 or /products/42 and extracts the id parameter for use.</p><p>Dynamic routes can fetch data with getServerSideProps or getStaticProps functions, pre-rendering data for page loads. This enables personalized and dynamic experiences based on parameter values.</p><p>Next.js’ dynamic routing and parameter handling empower you to create flexible and interactive applications tailored to user needs.</p><p>In summary, Next.js simplifies routing and navigation, with advantages like simplicity, server-side rendering, and code splitting. Dynamic routing handles parameters, and data fetching enhances dynamic experiences. Next.js is an excellent choice for building user-friendly web applications.</p><h3>API Routes and Serverless Functions in Next.js: Simplifying Backend Development and Integration</h3><p>Next.js introduces a powerful feature called API routes, revolutionizing the way backend logic is handled. With API routes, developers can create serverless functions that act as endpoints to process HTTP requests, enabling seamless integration with front-end applications and external services. Let’s delve deeper into the world of API routes and discover how they simplify backend development while enhancing flexibility and scalability.</p><p>Creating RESTful APIs Made Simple: Next.js API routes offer a streamlined approach to building RESTful APIs. By defining different HTTP methods (such as GET, POST, PUT, and DELETE) within an API route file, developers can easily handle specific types of requests. For example, you can have a dedicated users.js API route file that handles CRUD operations for user data. Next.js abstracts away the complexities, allowing developers to focus on writing clean and efficient code for their APIs.</p><h4><strong>Seamless Integration with External Services</strong></h4><p>API routes in Next.js open up endless possibilities for integrating with external services. Leveraging serverless functions within these routes, developers can effortlessly interact with third-party APIs or trigger actions in other systems. This means you can fetch data from external sources, process it, and seamlessly incorporate it into your application. Whether it’s retrieving real-time weather information, fetching user data from a social media platform, or interacting with payment gateways, Next.js API routes provide a secure and efficient way to integrate with external services.</p><h4>Scalability, Flexibility, and Maintenance</h4><p>The serverless nature of API routes in Next.js brings scalability and flexibility to your backend architecture. Since the functions are executed on-demand, you can easily handle fluctuating traffic loads without the need for complex server setups. Additionally, the modular structure of API routes enables easy maintenance and extensibility. You can create separate route files for different endpoints, keeping your code organized and allowing for easy updates or additions to your API.</p><h4>Security and Authentication</h4><p>Next.js offers robust security measures for API routes. You can implement authentication mechanisms, such as JSON Web Tokens (JWT) or OAuth, to protect your routes and ensure that only authorized requests are processed. By leveraging Next.js’ environment variables, you can securely store sensitive information, such as API keys or access tokens, preventing unauthorized access to external services.</p><h3>Deployment and Scaling Next.js Applications</h3><p>When it comes to deploying and scaling Next.js applications, you have several options to consider. In this section, we’ll explore different deployment strategies and provide tips for scaling your Next.js applications to handle increased traffic and load.</p><p>Deployment Options:</p><ol><li><strong>Serverless Platforms:</strong> Leveraging serverless platforms like AWS Lambda, Google Cloud Functions, or Azure Functions allows you to deploy Next.js applications without worrying about infrastructure management. Serverless platforms scale automatically based on demand and offer cost efficiency, as you only pay for the actual usage of resources.</li><li><strong>Traditional Hosting:</strong> Deploying Next.js applications on traditional hosting providers, such as virtual private servers (VPS) or dedicated servers, offers more control over the infrastructure. This option is suitable for applications with specific configuration requirements or the need for custom server setups. However, it requires manual scaling and maintenance.</li><li><strong>Static Site Hosting:</strong> Next.js also provides an option to generate a static version of your application, which can be hosted on platforms like Netlify, Vercel, or GitHub Pages. This approach is ideal for applications with static content or where dynamic content can be pre-rendered. Static site hosting simplifies deployment and offers excellent performance and scalability.</li></ol><p>Scaling Next.js Applications: To ensure your Next.js application can handle increased traffic and load, consider the following tips for scaling:</p><ol><li><strong>Caching:</strong> Implement caching mechanisms at different levels, such as CDN caching for static assets, server-side caching for dynamic content, or client-side caching for API responses. Caching reduces the load on your server and improves response times.</li><li><strong>Load Balancing:</strong> Distribute incoming requests across multiple servers using load balancers. Load balancing ensures that the traffic is evenly distributed, improving overall application performance and preventing single points of failure.</li><li><strong>Horizontal Scaling:</strong> Scale your Next.js application horizontally by adding more instances or servers to handle increased traffic. Load balancers can distribute incoming requests among these instances, allowing your application to scale seamlessly.</li><li><strong>Database Optimization:</strong> Optimize database queries, index usage, and caching strategies to minimize database load. Consider implementing database scaling techniques, such as sharding or replication, to handle larger datasets and high read/write operations.</li><li><strong>Monitoring and Auto-scaling:</strong> Set up monitoring tools to track the performance of your Next.js application. Configure auto-scaling based on predefined metrics, such as CPU usage or request rate, to automatically adjust the number of instances based on demand.</li><li><strong>Content Delivery Network (CDN):</strong> Utilize a CDN to distribute static assets globally, reducing the latency for users accessing your application from different geographical locations. CDNs cache and deliver content from edge locations, providing faster and more reliable content delivery.</li></ol><p>By deploying your Next.js application using an appropriate strategy and implementing effective scaling techniques, you can ensure availability, performance, and a smooth user experience even under high-traffic conditions. Evaluate your application’s requirements and choose the deployment option that aligns with your needs while considering the potential for scaling in the future.</p><h3>Conclusion</h3><p>In conclusion, Next.js stands as a valuable tool in the web development arena. Its combination of server-side rendering, static site generation, intuitive routing, and support for API routes positions it as a compelling choice for creating exceptional web experiences. By embracing Next.js and adhering to best practices, developers can unlock the true potential of their web applications, leaving a lasting impact on users. Let Next.js be your trusted companion on the journey to crafting remarkable web experiences that inspire and delight.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=77db5c47dc6d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/bina-nusantara-it-division/next-js-the-complete-overview-and-why-its-gaining-popularity-77db5c47dc6d">Next.js: The Complete Overview and Why It’s Gaining Popularity</a> was originally published in <a href="https://medium.com/bina-nusantara-it-division">Bina Nusantara IT Division</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[useState vs useSignal: A Comprehensive Comparison for React Developers]]></title>
            <link>https://medium.com/bina-nusantara-it-division/usestate-vs-usesignal-a-comprehensive-comparison-for-react-developers-cdcd047da708?source=rss-f0e2a107b11------2</link>
            <guid isPermaLink="false">https://medium.com/p/cdcd047da708</guid>
            <category><![CDATA[hooks]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[state-management]]></category>
            <category><![CDATA[reactjs]]></category>
            <dc:creator><![CDATA[tong eric]]></dc:creator>
            <pubDate>Fri, 31 Mar 2023 07:14:27 GMT</pubDate>
            <atom:updated>2023-03-31T07:14:27.615Z</atom:updated>
            <content:encoded><![CDATA[<p>Comparing useState and useSignal for Optimal React State Management</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xfrqjUzlte-IdTpb" /><figcaption>Photo by <a href="https://unsplash.com/@lautaroandreani?utm_source=medium&amp;utm_medium=referral">Lautaro Andreani</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>If you’re a React developer, you know that state management is a critical part of building modern applications. And when it comes to managing state in React, you have two main options: useState and useSignal. Both of these options can be effective, but some critical differences between them make one a better choice than the other. In this article, we’ll look at both useState and useSignal and argue that useSignal is the better option for managing state in React. Whether you’re new to React or a seasoned pro, it’s important to understand these state management options to build efficient, scalable, and easy-to-maintain applications. So, let’s explore the differences between useState and useSignal, and find out why we think useSignal is the way to go.</p><h4>What is useState?</h4><p>useState is a built-in hook in React that allows developers to add stateful logic to their functional components. It works by providing a way to define a state variable and a function to update that variable. Whenever the state variable changes, React will automatically re-render the component to reflect the updated state.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/0*PXKi_3NvRYlGcYhh.png" /></figure><p>The benefits of using useState for state management include its simplicity and ease of use. It requires minimal setup and can be easily integrated into any functional component. Additionally, because it’s built-in to React, there’s no need to install any additional libraries or dependencies.</p><p>While useState is a great option for managing state in React, it does have some limitations that can make it challenging to work within certain situations. Below is some limitations for useState :</p><ul><li>Performance issues when dealing with large datasets or frequent state updates (e.g., a real-time chat application).</li><li>Challenging to share state between components, especially in larger and more complex component trees (e.g., a shopping cart with multiple pages and components).</li><li>Difficult to manage complex state that involves multiple variables or objects (e.g., a form with multiple input fields).</li></ul><h4>What is useSignal?</h4><p>UseSignal is an alternative state management solution for React that addresses some of the limitations of useState. It’s a small and efficient library that provides a way to manage state using signals, which are lightweight objects that represent a single value or a set of related values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/705/0*BICaFzsioYS8b9WW" /><figcaption>useSignal Example BY <a href="https://twitter.com/mhevery">MIŠKO HEVERY</a></figcaption></figure><p>One of the benefits of using UseSignal is that it makes it easier to manage complex state by allowing you to group related values together in a signal object. This makes it easier to organize and manage state, especially when dealing with large and complex applications. For example :</p><pre>import { createSignal } from &#39;usesignal&#39;;<br><br>function App() {<br>  const [userData, setUserData] = createSignal({<br>    name: &#39;&#39;,<br>    email: &#39;&#39;,<br>    phone: &#39;&#39;,<br>    address: {<br>      street: &#39;&#39;,<br>      city: &#39;&#39;,<br>      state: &#39;&#39;,<br>      zip: &#39;&#39;,<br>    },<br>  });<br><br>  function handleInputChange(event) {<br>    const { name, value } = event.target;<br>    setUserData(prevState =&gt; ({<br>      ...prevState,<br>      [name]: value,<br>    }));<br>  }<br><br>  return (<br>    &lt;div&gt;<br>      &lt;input<br>        type=&quot;text&quot;<br>        name=&quot;name&quot;<br>        value={userData.name}<br>        onChange={handleInputChange}<br>      /&gt;<br>      &lt;input<br>        type=&quot;text&quot;<br>        name=&quot;email&quot;<br>        value={userData.email}<br>        onChange={handleInputChange}<br>      /&gt;<br>      &lt;input<br>        type=&quot;text&quot;<br>        name=&quot;phone&quot;<br>        value={userData.phone}<br>        onChange={handleInputChange}<br>      /&gt;<br>      &lt;input<br>        type=&quot;text&quot;<br>        name=&quot;street&quot;<br>        value={userData.address.street}<br>        onChange={handleInputChange}<br>      /&gt;<br>      &lt;input<br>        type=&quot;text&quot;<br>        name=&quot;city&quot;<br>        value={userData.address.city}<br>        onChange={handleInputChange}<br>      /&gt;<br>      &lt;input<br>        type=&quot;text&quot;<br>        name=&quot;state&quot;<br>        value={userData.address.state}<br>        onChange={handleInputChange}<br>      /&gt;<br>      &lt;input<br>        type=&quot;text&quot;<br>        name=&quot;zip&quot;<br>        value={userData.address.zip}<br>        onChange={handleInputChange}<br>      /&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>In this example, we’re using UseSignal to manage the complex state of a user profile form. We define a signal called userData that contains several related values, including the user&#39;s name, email, phone, and address.</p><p>We then define a function called handleInputChange that updates the userData signal whenever one of the input fields is changed. This function uses the setUserData function provided by UseSignal to update the state object in an immutable way.</p><p>Using UseSignal in this way allows us to easily group related values together in a single object, making it easier to manage and update complex state in our React components.</p><p>Another advantage of useSignal is that it can improve the performance of your application by minimizing unnecessary re-renders. UseSignal uses a concept called “signal propagation” to notify components when the state has changed. This means that only the affected components will be re-rendered, rather than the entire component tree. For example :</p><pre>import { createSignal, createEffect } from &#39;usesignal&#39;;<br><br>function App() {<br>  const [count, setCount] = createSignal(0);<br><br>  createEffect(() =&gt; {<br>    console.log(`Count changed to ${count()}`);<br>  });<br><br>  return (<br>    &lt;div&gt;<br>      &lt;p&gt;Count: {count()}&lt;/p&gt;<br>      &lt;button onClick={() =&gt; setCount(count() + 1)}&gt;Increment&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>In this example, we define a signal called count that represents the current count value. We also define an effect that logs a message to the console whenever the count value changes.</p><p>When we click the “Increment” button, the count value changes and triggers a signal propagation. UseSignal then notifies the effect that depends on the count value that it needs to re-run.</p><p>However, because the count value only affects the p element that displays the count value, only that element will be re-rendered. The rest of the component tree will be unaffected.</p><p>This approach to state management and rendering optimization can greatly improve the performance of React applications, especially those that deal with large amounts of data or frequent state updates.</p><p>Lastly, UseSignal makes it easier to share state between components. With UseSignal, you can define signals at the top level of your application and pass them down to child components as needed. This makes it easier to manage and share state across your entire application. Here’s some example how to attempt it :</p><pre>import { createSignal } from &#39;usesignal&#39;;<br><br>function Parent() {<br>  const [count, setCount] = createSignal(0);<br><br>  return (<br>    &lt;div&gt;<br>      &lt;Child count={count} setCount={setCount} /&gt;<br>      &lt;Child count={count} setCount={setCount} /&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>function Child({ count, setCount }) {<br>  function handleClick() {<br>    setCount(count() + 1);<br>  }<br><br>  return (<br>    &lt;div&gt;<br>      &lt;p&gt;Count: {count()}&lt;/p&gt;<br>      &lt;button onClick={handleClick}&gt;Increment&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>In this example, we define a Parent component that holds the count signal and passes it down to two Child components as props. The Child components can then read and update the count value using the setCount function.</p><p>Because both Child components receive the same count signal, they share the same state. This means that when one Child component updates the count value, the other Child component (and any other components that depend on the count signal) will also be updated.</p><p>This approach to state management makes it easy to share state between components and ensure that they stay in sync with each other. It also helps to reduce the amount of duplicated code and state management logic that you need to write in your components.</p><h3>Conclusion</h3><p>In conclusion, while both UseSignal and useState are powerful tools for managing state in React applications, UseSignal offers several advantages over the traditional useState approach. With UseSignal, you can easily manage complex state by grouping related values, share state across components, and optimize rendering performance by only updating the components that depend on the changed value. UseSignal’s signal propagation mechanism ensures that your application stays fast and responsive, even as your state grows in complexity. Additionally, UseSignal is designed to be intuitive and easy to use, making it accessible to developers of all levels of experience. Overall, UseSignal is a compelling alternative to useState that can help you build better React applications with less code and better performance.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cdcd047da708" width="1" height="1" alt=""><hr><p><a href="https://medium.com/bina-nusantara-it-division/usestate-vs-usesignal-a-comprehensive-comparison-for-react-developers-cdcd047da708">useState vs useSignal: A Comprehensive Comparison for React Developers</a> was originally published in <a href="https://medium.com/bina-nusantara-it-division">Bina Nusantara IT Division</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Docker for Windows Beginner Guide]]></title>
            <link>https://medium.com/bina-nusantara-it-division/docker-for-windows-beginner-guide-9e03d8d46de?source=rss-f0e2a107b11------2</link>
            <guid isPermaLink="false">https://medium.com/p/9e03d8d46de</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[windows]]></category>
            <category><![CDATA[requirements]]></category>
            <category><![CDATA[dockerfiles]]></category>
            <dc:creator><![CDATA[tong eric]]></dc:creator>
            <pubDate>Fri, 30 Dec 2022 14:34:21 GMT</pubDate>
            <atom:updated>2022-12-30T14:34:59.817Z</atom:updated>
            <content:encoded><![CDATA[<p>A simple guide for those starting to learn about Docker</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gIFK-_c-uODAECAV" /><figcaption>Photo by <a href="https://unsplash.com/@rubaitulazad?utm_source=medium&amp;utm_medium=referral">Rubaitul Azad</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Docker is an open platform for developing, shipping, and running applications. Docker enables you to separate your applications from your infrastructure to deliver software quickly. With Docker, you can manage your infrastructure in the same ways you organize your applications. By taking advantage of Docker’s methodologies for shipping, testing, and deploying code quickly, you can significantly reduce the delay between writing code and running it in production.</p><p>This tutorial will teach you how to implement Docker on a Windows server.</p><h4>System Requirement</h4><p>The following are system requirements for the Docker Windows server which uses WSL :</p><ul><li>Windows 10 64-bit: Home or Pro 2004 (build 19041) or higher, or Enterprise or Education 1909 (build 18363) or higher.</li><li>Enable the WSL 2 feature on Windows. For detailed instructions, refer to the <a href="https://docs.microsoft.com/en-us/windows/wsl/install-win10">Microsoft documentation</a>.</li></ul><p>The following hardware prerequisites are required to successfully run WSL 2 on Windows 10:</p><ul><li>64-bit processor with <a href="https://en.wikipedia.org/wiki/Second_Level_Address_Translation">Second Level Address Translation (SLAT)</a></li><li>4GB system RAM</li><li>BIOS-level hardware virtualization support must be enabled in the BIOS settings. For more information, see <a href="https://docs.docker.com/docker-for-windows/troubleshoot/#virtualization-must-be-enabled">Virtualization</a>.</li><li>Download and install the <a href="https://docs.microsoft.com/windows/wsl/wsl2-kernel">Linux kernel update package</a>.</li></ul><h4>Installation of Docker Windows</h4><p>Let&#39;s start with installation, First, download the installer for Docker Desktops with <a href="https://desktop.docker.com/win/stable/amd64/Docker%20Desktop%20Installer.exe">this</a> link or you can find the latest version of the installer by visiting this website <a href="https://hub.docker.com/editions/community/docker-ce-desktop-windows/">Link Here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*I6f6bwe3d7grwzu7" /></figure><p>Click the Get Docker button to start downloading the Docker Desktop installer.</p><p>The Docker Desktop installation includes <a href="https://docs.docker.com/engine/">Docker Engine</a>, Docker CLI client, <a href="https://docs.docker.com/compose/">Docker Compose</a>, <a href="https://docs.docker.com/docker-for-windows/engine/security/trust.md">Docker Content Trust</a>, <a href="https://github.com/kubernetes/kubernetes/">Kubernetes</a>, and <a href="https://github.com/docker/docker-credential-helpers/">Credential Helper</a>.</p><p>Containers and images created with Docker Desktop are shared between all user accounts on the machines where it is installed. This is because all Windows accounts use the same VM to build and run containers. Note that it is not possible to share containers and images between user accounts when using the Docker Desktop WSL 2 backend.</p><p>After that, double-click on <strong>Docker Desktop Installer.exe</strong> to run the installer.</p><p>When prompted, ensure the <strong>Enable Hyper-V Windows Features</strong> or the <strong>Install required Windows components for WSL 2</strong> option is selected on the Configuration page.</p><p>Follow the instructions on the installation wizard to authorize the installer and proceed with the installation.</p><p>When the installation is successful, click <strong>Close</strong> to complete the installation process.</p><p>If your admin account is different from your user account, you must add the user to the <strong>docker-users</strong> group. Run <strong>Computer Management</strong> as an administrator and navigate to <strong>Local Users and Groups</strong> &gt; <strong>Groups</strong> &gt; <strong>docker-users</strong>. Right-click to add the user to the group. Log out and log back in for the changes to take effect.</p><p>When the installation finishes, Docker starts automatically. The whale in the notification area indicates that Docker is running, and accessible from a terminal.</p><p>You can check for the installation is complete or not from the command above :</p><ol><li>Run the docker version to check the version.</li><li>Run docker run hello-world to verify that your Docker installation was successful.</li></ol><p>For Docker Windows, you will need an account from Docker Hub to pull images.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YNtXKD0wVZslK8sR" /></figure><p>Go to <a href="https://hub.docker.com/">Docker Hub</a> and then register your account by clicking the Signup button on this page. Remember your Docker ID cause you will need it to log in to your account.</p><p>You can log in to your account by opening the Docker Desktop application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4kBt4_PaNv2RhW8Z" /></figure><p>Click on the Sign in button on top of the application and then input your Docker ID and passwords.</p><h4>Tutorial for Docker Windows</h4><p>Here I will give an example of how to host static websites using official Nginx images from the docker hub.</p><p>First, pull the Nginx images to local, you can do it via command prompt with the command below</p><pre>Docker pull nginx</pre><p>After that, check on your Docker Desktop. It should have a new image name Nginx in your local repository.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vTuRCEE7p2lhltHx" /></figure><p>After that, create a folder that will be your workspace. Open it up using your favorite code editor (for example, Visual studio code).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Lbqg7S2R5Oi9oWGB" /></figure><p>Let’s start by creating an index.html for our static website. Create a new file in this folder and name it index.html.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GfcmX4XsMmt8c2I1" /></figure><p>Copy the HTML below to be contained inside it</p><pre>&lt;!doctype html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>&lt;head&gt;<br>  &lt;meta charset=&quot;utf-8&quot;&gt;<br>  &lt;title&gt;Docker Nginx&lt;/title&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>  &lt;h2&gt;Hello from Nginx container&lt;/h2&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>You can make your own modification as long as it is still a static web.</p><p>Then we create a file named DockerFile to this folder.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*baXKdnzD2NdOG7pa" /></figure><p>A Dockerfile is a text document that contains all the commands a user could call on the command line to assemble an image. Docker can build images automatically by reading the instructions from a DockerFile.</p><p>Copy the command below as our Dockerfile command.</p><pre>FROM nginx:latest<br>COPY ./index.html /usr/share/nginx/html/index.html</pre><p>This command simply copies and index.html from the Docker container. You start building our custom image by using a base image. On line 1, you can see we do this using the FROM command. This will pull the nginx:latest image to our local machine and then build our custom image on top of it.</p><p>Next, we COPY our index.html file into the /usr/share/nginx/html directory inside the container overwriting the default index.html file provided by nginx:latest image.</p><p>After you finish all preparation, you can run this command to build our image</p><pre>docker build -t &lt;image name&gt; .</pre><p>Note: Remember to run this command when your command prompt directory is the same as your DockerFile location.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DhHWHntFtOxH4o01" /></figure><p>After that, you can check your build image from Docker Desktop. To run this image as a container, you can use the command below in the command prompt :</p><pre>docker run -it --rm -p 8080:80 --name &lt;container name&gt; &lt;image name&gt;</pre><p>Docker run for running image, -it is for interactive mode, — rm for stopping removing any container with the same name as it. -p 8080:80 is used to redirect our local machine port 8080 to docker container port 80 and last — name &lt;container name&gt; &lt;image name&gt; to specify which image we want to run.</p><p>After that, go to your browser and navigate to <a href="http://localhost:8080/">http://localhost:8080</a> to make sure our Html page is being served correctly.</p><h4>Summary</h4><p>From this tutorial, we learn about</p><ol><li>Installation requirement and process for Docker windows</li><li>Basic use of Docker command</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9e03d8d46de" width="1" height="1" alt=""><hr><p><a href="https://medium.com/bina-nusantara-it-division/docker-for-windows-beginner-guide-9e03d8d46de">Docker for Windows Beginner Guide</a> was originally published in <a href="https://medium.com/bina-nusantara-it-division">Bina Nusantara IT Division</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Set up a Redis Server]]></title>
            <link>https://medium.com/bina-nusantara-it-division/how-to-set-up-a-redis-server-4fc246965196?source=rss-f0e2a107b11------2</link>
            <guid isPermaLink="false">https://medium.com/p/4fc246965196</guid>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[redis-server]]></category>
            <category><![CDATA[vpn]]></category>
            <category><![CDATA[centos]]></category>
            <category><![CDATA[networking]]></category>
            <dc:creator><![CDATA[tong eric]]></dc:creator>
            <pubDate>Fri, 30 Sep 2022 15:31:57 GMT</pubDate>
            <atom:updated>2022-09-30T15:31:57.672Z</atom:updated>
            <content:encoded><![CDATA[<p>Simple tutorial for setting up your own Redis server and use it within connection</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GGPiYDxdLc9zba8r" /><figcaption>Photo by <a href="https://unsplash.com/@tap5a?utm_source=medium&amp;utm_medium=referral">Tapio Haaja</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>Prerequisites</h4><p>To complete this tutorial, you will need a server running CentOS 8. This server should have a non-root user with administrative privileges and a firewall configured with <strong>firewalld</strong>.</p><p>In today’s tutorial, we will prepare for 3 servers where 1 of them will be the master node and the others will be its replica.</p><h3>Step 1 — Installing and Starting Redis</h3><p>You can install Redis with the DNF package manager. The following command will install Redis, and its dependencies.</p><pre><em>sudo dnf install redis</em></pre><p>Press Y for the confirmation of installation. Find <strong>redis.conf</strong> and open it with your preferred text editor. File <strong>redis.conf</strong> usually will be stored on <strong>/etc/redis/</strong>. Here we’ll use nano as example:</p><pre><em>sudo nano /etc/redis.conf</em></pre><p>Inside the file, find the supervised directive. This directive allows you to declare an init system to manage Redis as a service, providing you with more control over its operation. The supervised directive is set to no by default. Since you are running CentOS, which uses the <a href="https://en.wikipedia.org/wiki/Systemd">systemd</a> init system, change this to systemd:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/0*d-cD6spfJGg_X0m2" /></figure><p>After that, bind your Redis host IP to your private IP in the network. The default host of the redis server is <strong>127.0.0.1</strong>. Find and uncomment the following line and replace it with your private IP.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/553/0*tlYDHsFMjrm0I97Q" /></figure><p>Disable a protected mode for allowed connective from another server:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/528/0*4DEKYOmPjyQvpaQQ" /></figure><p>You can also configure a port number that you want to use for hosting the redis server. Find and uncomment the following line and replace it with the port number that you want.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/528/0*xyi7XwySNOMuldd_" /></figure><p>That’s the only change you need to make to the Redis configuration file at this point, so save and close it when you are finished. If you used nano to edit the file, do so by pressing CTRL+X, Y then Enter.</p><p>After editing the file, start the Redis service with the following command:</p><pre><em>sudo systemctl start redis</em></pre><p>You can check Redis’s status by running the following:</p><pre><em>sudo systemctl status redis</em></pre><p>Once you’ve confirmed that Redis is indeed running, you can test its functionality with this command:</p><pre><em>redis-cli -h XXX.XXX.XXX.XXX -p YYYY<br>ping</em></pre><p>This should print Pong as the response:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/0*ZzrN75aJbPd54zqp" /></figure><p><strong><em>Note: if you receive an NOAUTH Authentication result. Then your redis server is already being configured and locked by password. Find and password in your redis.conf and try with the following command:</em></strong></p><pre><em>redis-cli -h XXX.XXX.XXX.XXX -p YYYY<br>auth password<br>ping</em></pre><h3>Step 2 — Configuring Redis and Securing it with a Firewall</h3><p>An effective way to safeguard Redis is to secure the server it’s running on. You can do this by ensuring that Redis is bound only to either localhost or to a private IP address and also that the server has a firewall up and running.</p><p>To begin, add a dedicated redis zone to your <strong>firewalld </strong>policy:</p><pre><em>sudo  firewall-cmd –-permanent –-new-zone=redis</em></pre><p>Then specify which port you’d like to have open. Redis uses port 6379 by default:</p><pre><em>sudo firewall-cmd — permanent — zone=redis — add-port=6379/tcp</em></pre><p>Next, specify any private IP addresses which should be allowed to pass through the firewall and access Redis, this step is optional.</p><pre><em>sudo firewall-cmd — permanent — zone=redis — add source=client_server_private_IP</em></pre><p>After running those commands, reload the firewall to implement the new rules:</p><pre><em>sudo firewall-cmd –reload</em></pre><p>You can check the active zone of <strong>firewalld </strong>by the following command:</p><pre><em>sudo firewall-cmd –get-active-zones</em></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/476/0*ut0Ws2SN6_hRFkwO" /></figure><p>Under this configuration, when the firewall encounters a packet from your client’s IP address, it will apply the rules in the dedicated the redis zone to that connection. All other connections will be processed by the default public zone. The services in the default zone apply to every connection, not just those that don’t match explicitly, so you don’t need to add other services (e.g. SSH) to the redis zone because those rules will be applied to that connection automatically.</p><h3>Step 3 — Configuring a Redis Password</h3><p>Configuring a Redis password enables one of its built-in security features — the auth command — which requires clients to authenticate before being allowed access to the database. Like the binding setting, the password is configured directly in Redis’s configuration file, <strong>/etc/redis.conf</strong>. Reopen that file:</p><pre><em>sudo nano /etc/redis.conf</em></pre><p>Scroll to the SECURITY section and look for a commented directive that reads:</p><p>Uncomment it by removing the #, and change “foobared” to a very strong password of your choosing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/743/0*yvK309incr40761e" /></figure><p>Reset a redis.service with the following command :</p><pre><em>sudo systemctl reload redis</em></pre><p>So the configuration of redis is completed. Now let’s try to access the server that we have configured. In this case, I will try to connect to a remote server redis from my local computer that connects to a VPN with the help of WSL (Windows Subsystem Linux). This WSL has already installed the redis server. Here is the result of the testing:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nJ3DhmgIIJxVYurJ" /></figure><h3>Conclusion</h3><p>in this tutorial, we learn about how to set up a Redis on your server and make it available to another server in a secure way. Hope this articel can help you in learning about Redis.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4fc246965196" width="1" height="1" alt=""><hr><p><a href="https://medium.com/bina-nusantara-it-division/how-to-set-up-a-redis-server-4fc246965196">How to Set up a Redis Server</a> was originally published in <a href="https://medium.com/bina-nusantara-it-division">Bina Nusantara IT Division</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tutorial on Microsoft Azure Account and Cosmos DB]]></title>
            <link>https://medium.com/bina-nusantara-it-division/tutorial-on-microsoft-azure-account-and-cosmos-db-f8b2c5b969?source=rss-f0e2a107b11------2</link>
            <guid isPermaLink="false">https://medium.com/p/f8b2c5b969</guid>
            <category><![CDATA[cosmosdb]]></category>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[microsoft]]></category>
            <category><![CDATA[azure-services]]></category>
            <category><![CDATA[azure-subscription]]></category>
            <dc:creator><![CDATA[tong eric]]></dc:creator>
            <pubDate>Thu, 30 Jun 2022 07:30:09 GMT</pubDate>
            <atom:updated>2022-06-30T07:30:09.743Z</atom:updated>
            <content:encoded><![CDATA[<h4>Beginner guide for exploring Microsoft Azure service in a free trial</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vIXbj6FLAifYxiXA" /><figcaption>Photo by <a href="https://unsplash.com/@realfish?utm_source=medium&amp;utm_medium=referral">realfish</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Microsoft Azure, formerly known as Windows Azure, is Microsoft’s public cloud computing platform. It provides a range of cloud services, including computing, analytics, storage, and networking. Users can pick and choose from these services to develop and scale new applications, or run existing applications in the public cloud.</p><p>Microsoft charges for Azure on a pay-as-you-go basis, meaning subscribers receive a bill each month that only charges them for the specific resources they have used. For those payment calculations and charges, you will need the resource name Azure Subscription. In this tutorial, we will be discussing how to use a Microsoft Azure account subscription and create an underlying Cosmos DB as an example for using the Azure service.</p><h3>What is Cosmos DB</h3><p>Before we start our Tutorial we should know What is Cosmos DB. Azure Cosmos DB is Microsoft’s globally distributed, multi-model database service. Cosmos DB enables you to elastically and independently scale throughput and storage across any number of Azure regions worldwide. You can elastically scale throughput and storage, and take advantage of fast, single-digit-millisecond data access using your favorite API including SQL, MongoDB, Cassandra, Tables, or Gremlin. Cosmos DB provides comprehensive service level agreements (SLAs) for throughput, latency, availability, and consistency guarantees, something no other database service offers.</p><p>Simply Azure Cosmos DB is one of the Microsoft database services that is classified as NoSQL. Internally, Cosmos DB stores “items” in “containers”, with these two concepts being surfaced differently depending on the API used (these would be “documents” in “collections” when using the MongoDB-compatible API, for example). Containers are grouped in “databases”, which are analogous to the namespaces above containers. Containers are schema-agnostic, which means that no schema is enforced when adding items.</p><h3>How to Create Azure Cosmos DB</h3><p>In order to create and use Azure Cosmos DB, You have to own a Microsoft Account first. In this case, you can use a Microsoft account yourself. FYI Cosmos DB is NOT a free service, you will have to pay per month for the quantity of Cosmos DB you use. The Payment of Cosmos DB has to be done with a <strong>Subscription</strong></p><h4>Subscription in Azure</h4><p>There are a lot of types of subscriptions that you can do in Microsoft Azure. Here we will explain 2 of them, a Free trial subscription and an Azure for Students Starter Subscription.</p><h4>Azure for Students Starter Subscription</h4><p>Azure for Students Starter Subscription gets you started with the Azure products you need to develop in the cloud at no cost to you. For using this subscription you have to use an account that is provided by BINUS.</p><p>First, go to the <a href="https://portal.azure.com/">portal.azure.com</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*p34tdnk9ldk2jkgE0VRLNA.png" /></figure><p>Log in with your Microsoft account as usual</p><p>After login you will find the homepage of Azure Portal, Azure portal is a portal to view and manage every service of your Microsoft Account. Here click Subscription button that we mark or you can search for Subscription if it didn’t appear.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*qAeP7kL96ouIABFp" /></figure><p>On this page you can view all your Subscriptions, you can have multiple subscriptions in one account. Click add Subscription in the left Corner.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B0g4DVfl_C0f1LG2O4Wj7w.png" /></figure><p>Select Azure for Students Starter, and then fill out the form for the First name, Last name, Email, and Phone. And then accept the Agreement for Policy. Here are the first Azure subscriptions you have made. In Azure for Students, you will get about 100 USD credit for 12 months.</p><h4>Free Trial Subscription</h4><p>The step for getting Free Trial Subscription is the same as Azure for Student subscription, You just need to select for free trial option in the last step. This option is for people who want to try but are not a student anymore. For a free trial, you will get a 200 USD Credit for 12 months.</p><h3>Create Cosmos DB</h3><p>After we create a subscription we can use it to access other services in Microsoft Azure. let&#39;s try it on creating your first Cosmos DB.First search for Cosmos DB in Azure portal Homepage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hm_7FX9rtd5f94Sr_cMmIA.png" /></figure><p>Click Add for Cosmos Database in Left Corner.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EyNrYTOWK1jDy5spFbsvFw.png" /></figure><p>Fill the form with the below information</p><p><em>Subscription: Subscription that you want to use for this Cosmos DB. Pick your subscription (Free trial or Azure for Students).</em></p><p><em>Resource Group: Logical collections of virtual machines, storage accounts, virtual networks, web apps, databases, and/or database servers. Click “Create new” to create a new Resource group</em></p><p><em>Account Name: Username for This Cosmos DB</em></p><p><em>Location: Pick the nearest location for good performance</em></p><p>After that click next for Networking</p><p>Here is the setting for your cosmos DB Firewall, you can set it for allowed all networks or set it to Only specific IPs that can connect to your Cosmos DB.</p><p>After that click Create and Congratulation, You have Created your first Cosmos DB</p><p>You can check your Cosmos DB connection string, endpoint, Primary key, etc on the Overview page, you can also view and add your data from the data explorer</p><h3>Summary</h3><p>To summarize, in this tutorial, we learn about</p><ul><li>What is Azure Subscription and how to create a free trial subscription for learning purposes</li><li>How to use subscription to create other services in Microsoft Azure</li></ul><p>Thanks for reading and hope this article help on your purpose.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f8b2c5b969" width="1" height="1" alt=""><hr><p><a href="https://medium.com/bina-nusantara-it-division/tutorial-on-microsoft-azure-account-and-cosmos-db-f8b2c5b969">Tutorial on Microsoft Azure Account and Cosmos DB</a> was originally published in <a href="https://medium.com/bina-nusantara-it-division">Bina Nusantara IT Division</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build and Deploy Flutter Application using CI/CD Azure Pipelines DevOps]]></title>
            <link>https://medium.com/bina-nusantara-it-division/build-and-deploy-flutter-application-using-ci-cd-azure-pipelines-devops-d5f7fc8d47be?source=rss-f0e2a107b11------2</link>
            <guid isPermaLink="false">https://medium.com/p/d5f7fc8d47be</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[nginx]]></category>
            <category><![CDATA[web]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[azure-pipelines]]></category>
            <dc:creator><![CDATA[tong eric]]></dc:creator>
            <pubDate>Thu, 31 Mar 2022 16:12:54 GMT</pubDate>
            <atom:updated>2022-03-31T16:12:54.720Z</atom:updated>
            <content:encoded><![CDATA[<p>Automated CI flow to build and publish your flutter application</p><h3>Introduction</h3><p>Flutter is an open-source framework that allowed us to build multi-platform applications with only a single codebase needed. To develop with Flutter, you will use a programming language called Dart. The language was created by Google in October 2011, but it has improved a lot over these past years.</p><p>Meanwhile, Azure Pipelines is a cloud service that you can use to automatically build and test your code project and make it available to other users. It works with just about any language or project type. Azure Pipelines combines continuous integration (CI) and continuous delivery (CD) to test and build your code and ship it to any target constantly and consistently. Today we gonna use Azure Pipelines to help us achieve full automated deployment flow for our Flutter applications. So without further ado let’s dive into the tutorial</p><h3>Prerequisites</h3><p>Our target in this tutorial is to build and deploy your flutter application in your local server. For starter, you will need :</p><ol><li>Azure DevOps account</li><li>Repositories that contain your Flutter apps</li><li>Linux Server (Nginx configured)</li></ol><h3>Configure Deployment Group</h3><p>Before we start to build our Azure Pipeline, we must let our account know where the targeted machine for deployment is. A deployment group is a logical set of deployment target machines that have agents installed on each one. To let our account know where to target, we simply installed an agent on our machine and it will be recognized by the deployment group</p><p>First, log in to your DevOps account and open the deployment group menu on <strong>Organization Name -&gt; Project Name -&gt; Pipeline -&gt; Deployment Group</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*pw9y6wUGMfKdfxJyUcT_Yg.png" /></figure><p>Click on the + New button to create a new Deployment Group</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*bImsvTk4ILTXd-hxGWRn6A.png" /></figure><p>Creating a deployment group only needs a name for it and some brief description (optional). After you create your deployment group, it will show you a script like below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sziFQ7I5g0nrUbm6nhutGA.png" /></figure><p>Copy those scripts and run them on your Linux server. After you got a result like the example below, you can set up a tag to make it easier to mark off this server. Follow the instruction that the script makes to you.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/1*x7EEX43RSOJ8Jk4ejqupdw.png" /></figure><p>When it’s all done, you can check for the machine that is already being registered on your deployment group. Now the pre-step for making the Azure pipeline is done, let&#39;s go to the next step on “Building CI Pipeline”</p><h3>Building CI Pipeline</h3><p>To build a CI pipeline for Flutter, you will need to install the extension below</p><p><a href="https://marketplace.visualstudio.com/items?itemName=Hey24sheep.flutter&amp;ssr=false#overview">Flutter — Visual Studio Marketplace</a></p><p>You can check this to learn how to install the extension for your Azure DevOps organization</p><p><a href="https://docs.microsoft.com/en-us/azure/devops/marketplace/install-extension?view=azure-devops&amp;tabs=browser">How to Install extensions on Azure DevOps</a></p><p>First, Access the Pipeline menu from the sidebar and then click <em>New Pipeline</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*_K5N1o8kSLftbC3TmY8sUw.png" /></figure><p>Use the classic editor to configure the pipeline</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/611/1*e-VDReSZo1wcp7e1YMIXnA.png" /></figure><p>Select the source of the project with Azure Repos Git, then configure to a project branch that you want to deploy</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*YKLaiK4OKVypP47vL3bNFQ.png" /></figure><p>Configure your pipeline with an empty job option, then you will get an empty Azure Pipeline for you to configure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ICtPEs_lDI1c7qaFEXW5LQ.png" /></figure><p>Add Task to your pipeline by clicking the + button on the right side of your job name, for flutter building you will need 2 tasks, flutter install and flutter build.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AczVkSO8vfryifltzpjHug.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DWyyvvD2t47Lion2s-5ZnQ.png" /></figure><p>For the install task, you have to make sure that Release Url Mode on this task is set to auto, the channel for downloading flutter SDK is using stable and the version is set to be the latest.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/695/1*PLbZ0ucjHlGVrOZMT-FquQ.png" /></figure><p>Then for the building task, you can choose what target platform you want to build your app for. In this tutorial, I will choose to build and deploy this app as a website so I will choose Web as a build platform option.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/688/1*2yv4Ld63jz0N-gDmbCH4xw.png" /></figure><p>Now your CI pipeline is ready to build your flutter app. The next step for us is to copy our build to the artifact stagging directory and then publish it with the publish artifact task.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xodUdpT00H_r-LoVEbEMsw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q6VekTQQIMeRaI4Nqaa_bg.png" /></figure><p>After that press for Save &amp; Queue button and wait for the first time running the result of this CI pipeline.</p><h3>Building a CD pipeline</h3><p>Now after we configure a CI pipeline, we are ready to build a deployment pipeline for our project</p><p>First find a Releases menu on <strong>Organization Name -&gt; Project Name -&gt; Pipeline -&gt; Releases</strong>, pick + new button and choose for new release pipeline.</p><p>Choose an empty job to get an empty deploy pipeline.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dxaWzO43EUWNHxzRAyU-uA.png" /></figure><p>Give a proper name for your CD pipeline and then click the add artifact option.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ChnDm-g9EilD8dVB4qT6GA.png" /></figure><p>Select the CI pipeline that you made before for this artifact and then click the thunder button on the upper right. Enabled Continuous deployment trigger on it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*2FYihiSEDT7d7LcUosLuDA.png" /></figure><p>Go to Stage 1 to configure your deployment task, first remove the unused agent job in this pipeline, after that replace it with the deployment group job by clicking the button on the right side.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8W_Cipx3mdW4BHaxLmNqEw.png" /></figure><p>After that set the deployment group that you make earlier as the deployment target for this job.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OTNaMA3tVkm83LzH2ZMzOQ.png" /></figure><p>Add Command Line Script task to run cmd command and then write command below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UFdaMWFUMdL-SMiA6tOT9g.png" /></figure><pre>sudo cp -r _$(Build.DefinitionName) /var/www/html</pre><p>After that you can save your pipeline and congrats, your Azure pipeline has been set up and ready to launch.</p><h3>Set Up Nginx</h3><p>The last step you must do to test your website is to set up your Nginx config. You can follow the guide from this article <a href="https://agustinustheo.github.io/tech/2020/11/09/how-to-host-flutter-using-nginx.html">How To Host Flutter Web In Linux Using Nginx</a>.</p><h3>Conclusion</h3><p>from today&#39;s tutorial, we learn how to build an automated pipeline for deploying your application to your local server. Hope this tutorial can help for someone that start to learn about CI/CD or want to try automated deployment for flutter. Thanks for your attention.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d5f7fc8d47be" width="1" height="1" alt=""><hr><p><a href="https://medium.com/bina-nusantara-it-division/build-and-deploy-flutter-application-using-ci-cd-azure-pipelines-devops-d5f7fc8d47be">Build and Deploy Flutter Application using CI/CD Azure Pipelines DevOps</a> was originally published in <a href="https://medium.com/bina-nusantara-it-division">Bina Nusantara IT Division</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Beginners Guideline to RabbitMq and MassTransit(Part 1): RabbitMq and How To Install it]]></title>
            <link>https://medium.com/bina-nusantara-it-division/a-beginners-guideline-to-rabbitmq-and-masstransit-part-1-rabbitmq-and-how-to-install-it-ab91e1dc65ad?source=rss-f0e2a107b11------2</link>
            <guid isPermaLink="false">https://medium.com/p/ab91e1dc65ad</guid>
            <category><![CDATA[rabbitmq]]></category>
            <category><![CDATA[message-broker]]></category>
            <category><![CDATA[mass-transit]]></category>
            <dc:creator><![CDATA[tong eric]]></dc:creator>
            <pubDate>Wed, 29 Dec 2021 13:18:01 GMT</pubDate>
            <atom:updated>2021-12-29T13:21:10.395Z</atom:updated>
            <content:encoded><![CDATA[<p>A Complete Guideline from Installation to Implementation for RabbitMq as Message Broker</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BGwG5AJ4P88K2bNO_upjOQ.jpeg" /><figcaption>Picture by <a href="https://unsplash.com/@lucabravo">Luca Bravo</a> on <a href="https://unsplash.com/">Unsplash</a></figcaption></figure><blockquote><em>This article is a three-part series about complete implementation of RabbitMq as message broker . You can navigate to other part by link below :</em></blockquote><blockquote><a href="https://medium.com/bina-nusantara-it-division/a-beginners-guideline-to-rabbitmq-and-masstransit-part-2-implement-rabbitmq-in-code-with-af0503db2613">Part 2 : Implement RabbitMQ in Code with MassTransit</a></blockquote><blockquote><a href="https://medium.com/@ericjonson490/a-beginners-guideline-to-rabbitmq-and-masstransit-part-2-user-access-management-and-good-practice-e5dbab49699c"><em>Part 3 : User Access Management and Good Practice for Using RabbitMq</em></a></blockquote><p>In distributed systems, communication between various applications plays an important role. Effectively passing messages between applications was always crucial in system design. One of the solutions to pass messages around your distributed system is a message broker. They bring in decoupling between the applications and provide an effective way to communicate between services. With message brokers, the services need no prior knowledge of their recipients to communicate.</p><p>In this tutorial, we will learn about message brokers, more specifically RabbitMQ, and learn about how to implement RabbitMQ as a message broker for our applications starting from setting up the broker itself to implementation in-code. So, stay tuned till the end.</p><p>First, let’s start with an explanation of what a message broker is.</p><h3>Message Broker</h3><p>In general, a broker is a person who facilitates trades between a buyer and a seller. An example could be a real estate agent or a stockbroker.</p><p>Similarly, if we want to trade messages between two distributed software components, we need a mediator. This mediator is known as the message broker. It receives incoming messages from a sender and sends them to a recipient. This way the sender and receiver can be totally isolated.</p><p>Another analogy for a message broker can be a Post Office . Let’s take a scenario where you are going to send a letter to your cousin living in another city. Then as per this analogy, you are a producer, your cousin is a consumer, and the post office is a message broker.</p><h3>RabbitMQ as Message Broker</h3><p>Now we know that the purpose of a message broker is to route messages from a producer to a consumer. Let’s examine one such message broker — RabbitMQ. It’s one of the most extensively used message brokers these days.</p><p>RabbitMQ is an open-source message-broker software that originally implemented the Advanced Message Queuing Protocol (AMQP) and has since been extended with a plug-in architecture to support Streaming Text Oriented Messaging Protocol (STOMP), MQ Telemetry Transport (MQTT), and other protocols.The way RabbitMQ routes messages depends on the messaging protocol it implements. RabbitMQ supports multiple messaging protocols like we mentioned above. But the one that we will use for this tutorial is AMQP.</p><p>AMQP or Advanced Message Queuing Protocol depends on 3 important entities: queue, binding and exchange. When a publisher pushes a message to RabbitMQ, it first arrives at an exchange. The exchange then distributes copies of these messages to variously connected queues. Finally, consumers receive these messages.</p><p>AMQP is a programmable protocol; programmers have the choice to use libraries to configure entities (exchange, binding, and queue) as per their own needs. A RabbitMQ admin has no role in setting up these entities. There are plenty of libraries available to work with RabbitMQ, you can choose from Nodejs, Python, .Net, Java, and many more. In this tutorial, we will use a library called MassTransit.</p><h3>Installation of RabbitMQ</h3><p>So, after we know what RabbitMQ is, we can start to implement it in our solution. Let’s start with the installation and setting up the RabbitMQ server.</p><h4>Add the required dependencies</h4><p>Add the RabbitMq repository in the repo configurations file. Open the config file:</p><pre><em>sudo vi /etc/yum.repos.d/rabbitmq-server.repo</em></pre><p>Add this to the lines below:</p><pre><em>[rabbitmq-server]</em></pre><pre><em>name=rabbitmq-server</em></pre><pre><em>baseurl=https://packagecloud.io/rabbitmq/rabbitmq-server/el/7/$basearch</em></pre><pre><em>repo_gpgcheck=1</em></pre><pre><em>gpgcheck=0</em></pre><pre><em>enabled=1</em></pre><pre><em>gpgkey=https://packagecloud.io/rabbitmq/rabbitmq-server/gpgkey</em></pre><pre><em>sslverify=1</em></pre><pre><em>sslcacert=/etc/pki/tls/certs/ca-bundle.crt</em></pre><pre><em>metadata_expire=300</em></pre><p>Add Hostname to the <em>hosts</em> file</p><p>RabbitMq is built on top of Erlang. So it would make sense for us to install it beforehand. <strong>This part is very crucial as if you do not add the hostname to </strong><em>/etc/hosts</em><strong> then </strong><em>rabbitmqctl status</em><strong> will not work.</strong></p><pre><em>echo “127.0.0.1 $(hostname -s)” | sudo tee -a /etc/hosts</em></pre><h4>Setting Up RabbitMq Server</h4><ol><li>Install RabbitMq Server</li></ol><p>After completing the previous configuration setup steps, install RabbitMq by using this command:</p><pre><em>sudo dnf install -y rabbitmq-server</em></pre><p>After installation is completed, check if the installation is correct by running:</p><pre><em>rpm -qi rabbitmq-server</em></pre><ol><li>Open Ports</li></ol><p>Centos has a pre-installed firewall called <em>firewalld</em>. It blocks all ports from connecting unless asked to. So we must whitelist the TCP ports that are going to be used by RabbitMq.</p><pre><em>sudo firewall-cmd — zone=public — permanent — add-port={5672,15672}/tcp</em></pre><pre><em>sudo firewall-cmd — reload</em></pre><p>2. Start the RabbitMq service</p><p>The RabbitMq service doesn’t start on its own when you install it. You have to start it manually, then enable it to run on server startup. To start the RabbitMq service (the service might take a minute or two to start):</p><pre><em>sudo systemctl start rabbitmq-server.service</em></pre><p>To enable the service run:</p><pre><em>sudo systemctl enable rabbitmq-server.service</em></pre><p>To check if the service is still running:</p><pre><em>sudo rabbitmqctl status</em></pre><p>3. Enable RabbitMq Management</p><p>If you want to enable the RabbitMq admin dashboard, run:</p><pre><em>sudo rabbitmq-plugins enable rabbitmq_management</em></pre><p>Then try to open the dashboard from the browser:</p><pre><a href="http://*your-server-ip*:15672/"><em>sudo rabbitmq-plugins enable rabbitmq_management</em></a></pre><h3>Conclusion</h3><p>To summarize, RabbitMq is an open-source message broker that can be implemented in your business process and only need simple setting and maintenance on it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ab91e1dc65ad" width="1" height="1" alt=""><hr><p><a href="https://medium.com/bina-nusantara-it-division/a-beginners-guideline-to-rabbitmq-and-masstransit-part-1-rabbitmq-and-how-to-install-it-ab91e1dc65ad">A Beginners Guideline to RabbitMq and MassTransit(Part 1): RabbitMq and How To Install it</a> was originally published in <a href="https://medium.com/bina-nusantara-it-division">Bina Nusantara IT Division</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Beginners Guideline to RabbitMq and MassTransit(Part 2): Implement RabbitMQ in Code with…]]></title>
            <link>https://medium.com/bina-nusantara-it-division/a-beginners-guideline-to-rabbitmq-and-masstransit-part-2-implement-rabbitmq-in-code-with-af0503db2613?source=rss-f0e2a107b11------2</link>
            <guid isPermaLink="false">https://medium.com/p/af0503db2613</guid>
            <category><![CDATA[message-broker]]></category>
            <category><![CDATA[rabbitmq]]></category>
            <category><![CDATA[mass-transit]]></category>
            <dc:creator><![CDATA[tong eric]]></dc:creator>
            <pubDate>Wed, 29 Dec 2021 13:17:51 GMT</pubDate>
            <atom:updated>2021-12-29T13:20:12.600Z</atom:updated>
            <content:encoded><![CDATA[<h3>A Beginners Guideline to RabbitMq and MassTransit(Part 2): Implement RabbitMQ in Code with MassTransit</h3><p>Implementation and Explanation About Using RabbitMq With MassTransit</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_GZO1oEtSkFY405QQK02VA.jpeg" /><figcaption>Picture by<a href="https://unsplash.com/@marvelous"> Marvin Meyer</a> on <a href="https://unsplash.com/">Unsplash</a></figcaption></figure><blockquote><em>This article is a three-part series about complete implementation of RabbitMq as message broker . You can navigate to other part by link below :</em></blockquote><blockquote><a href="https://medium.com/@ericjonson490/ab91e1dc65ad">Part 1 : RabbitMq and How To Install it</a></blockquote><blockquote><a href="https://medium.com/@ericjonson490/a-beginners-guideline-to-rabbitmq-and-masstransit-part-2-user-access-management-and-good-practice-e5dbab49699c">Part 3 : User Access Management and Good Practice for Using RabbitMq</a></blockquote><p>RabbitMQ implements AMQP and it’s programmable. It supports a lot of languages like Nodejs, Python, C#, Java, and many more. You can choose those libraries based on your application needs. Today we will try to use one of those libraries, MassTransit.</p><h3>What is MassTransit</h3><p>MassTransit is a free, open-source distributed application framework for .NET. MassTransit makes it easy to create applications and services that leverage message-based, loosely-coupled asynchronous communication for higher availability, reliability, and scalability. It aims to be a .NET-friendly abstraction over the messaging technologies MSMQ (Microsoft Message Queuing) and RabbitMQ. As such it brings a lot of the application-specific logic closer to the programmer in an easy-to-configure manner.</p><p>Below I listed the benefits that we can get from using MassTransit :</p><h4>1. Exception Management</h4><p>MassTransit provides an ability to automatically reconnect and handle failures when something happens to your connection to the queue server.</p><h4>2. Retries Queue</h4><p>Upon failure, MassTransit will move your message to a separate error queue. It allows you to inspect failure messages and you can even shovel them back to the main queue.</p><p>If exceptions are thrown from your consumers. It will not immediately move it to the error queue. MassTransit will try to re-queue the message by several tries before moving it to the error queue.</p><h4>3. Serialization</h4><p>MassTransit provides a number of serializers, including BSON, JSON, XML, and Binary. You can handle those types of data with ease with those serializers.</p><h4>4. Diagnostic, Tracing, and Monitoring</h4><p>MassTransit provides a full developer kit and function to simplify diagnostic progress. A tracing functionality simplified developer for tracing detailed timings of message consumed, message rate for receive and consume, and what exceptions are thrown if any exceptions occurred. You can check for your queue health state using the performance counter from this library and <em>System.Diagnostics</em> namespace.</p><h4>5. Unit-Testable</h4><p>MassTransit provides an in-memory transport bus that allows you to modify and use for your integration tests. Furthermore, the <em>TestFactory</em> allows you to easily set up both in-memory transport and real transport-based unit tests for your consumers.</p><h3>Getting Started with MassTransit</h3><p>Getting started with MassTransit is fast and easy, for prerequisite you will need a .NET 5 SDK to be installed.</p><p>There are 2 kinds of applications that use MassTransit to connect to brokers, a consumer and publisher. Let’s start by making a consumer project first. Consumer projects will listen and consume a queue from your service bus (RabbitMQ or In-Memory or Azure Service Bus). you can configure your consumer in any kind of project that is based on .NET. For this tutorial, however, let’s try to make a consumer use background worker service.</p><h3>Consumer Example</h3><p>Create a new directory for this example project, direct to that folder, and then open up the command prompt from that directory.</p><pre>dotnet new worker -n Example.WorkerService</pre><p>Use this command to create a basic template for worker service. Try to run that project and you will get some results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*J-CHq_kbjGB9iUvV" /></figure><p>Now let’s start by configuring a consumer queue with an in-memory service bus.</p><p>Add MassTransit.AspNetCore packages by command below.</p><p>dotnet add package MassTransit.AspNetCore</p><p>You can add this package via NuGet manager if you are using Microsoft Visual Studio. Navigate to dependencies of your project, right-click on packages then click to manage NuGet packages. Find this package by typing MassTransit.AspNetCore in the search bar and then install it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CurMD-Q4vqpF5z1w" /></figure><p>Edit your Program.cs like below for the configuration.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a70bec5ada816b135d8b316a402f134e/href">https://medium.com/media/a70bec5ada816b135d8b316a402f134e/href</a></iframe><p>Don’t forget to add using MassTransit on top of code as references for using this library.</p><p>MassTransit can be used by using the function AddMassTransit in your services. UsingInMemory function is to define a service bus that we will use for this case, then we configure the endpoint by default context of this application. After that, we add the hosted service of MassTransit by using the AddMassTransitHostedService function.</p><p>Next, let’s create a consumer class that will handle a queue from this bus.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d6c04c21d87f8e0082db39e3d5981be7/href">https://medium.com/media/d6c04c21d87f8e0082db39e3d5981be7/href</a></iframe><p>Here is a simple consumer to handle messages from MassTransit. Basically, the consumer for MassTransit is created by extending the <em>IConsumer&lt;T&gt;</em> interface.</p><p>T is to inform the class model of the message that will be consumed and make sure you create a message model by using the same namespace from consumer and publisher because MassTransit divides exchange by their model namespace.</p><p>Task Consumer will be triggered when there is a message in your queue.</p><p>After that add your consumer to configuration by adding the code below in your Program.cs before UsingInMemory.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/025184aa788902a82e7aab676bf89377/href">https://medium.com/media/025184aa788902a82e7aab676bf89377/href</a></iframe><p>Then you can run the project again and The output should have changed to show the message consumer generating the output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Q0-UeHCJBapScebH" /></figure><p>To configure your consumer to listen to the queue from RabbitMq, just simply replace the UsingInMemory function with the code below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dfad78cd1f5248443581a48dc3a5ea68/href">https://medium.com/media/dfad78cd1f5248443581a48dc3a5ea68/href</a></iframe><p>Replace <em>&lt;connection_string&gt;</em> with your RabbitMQ connection string and <em>&lt;queue name&gt;</em> with the queue name you want to listen to. MassTransit will create a new queue based on the name in there if that queue does not exist so be careful with it.</p><p>And don’t forget to add a library for RabbitMQ with the command below</p><pre>dotnet add package MassTransit.RabbitMQ</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4xJXebYfUbIO8I3q" /></figure><p>At this point, the service can connect to RabbitMQ and is publishing messages which are received by the consumer.</p><h3>Publisher Example</h3><p>The publisher can be implemented to any application that is based on the .NET. In this tutorial, we will try to create a publisher for RabbitMQ in console apps. Create a new directory for this example project, direct to that folder, and then open up the command prompt from that directory.</p><pre>dotnet new console -n Example.Publisher -f 5.0</pre><p>Use this command to generate a base project for your console application.</p><p>After that add the package needed from the list below with console commands or with NuGet package manager, for example:</p><ul><li>MassTransit</li></ul><pre>dotnet add package MassTransit</pre><ul><li>MassTransit.RabbitMQ</li></ul><pre>dotnet add package MassTransit.RabbitMQ</pre><p>In the generated project, create a class name RabbitMqSingleton.cs</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9fdf57504158f028cbd5c022c41b89ba/href">https://medium.com/media/9fdf57504158f028cbd5c022c41b89ba/href</a></iframe><p>This is a singleton class that is used to send your message to the queue. Every time you call GetInstance it will return the same instance for you. The instance is created using the BusFactory of MassTransit that uses the CreateUsingRabbitMq function.</p><p>After that create a Message class using the same namespace with the receiver.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9fb7ca1dc45593ed7eae9ff426b27787/href">https://medium.com/media/9fb7ca1dc45593ed7eae9ff426b27787/href</a></iframe><p>Now the preparation for sending messages is all done. To send a message edit your <em>Program.cs</em> like the example below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/48ec24e08c9a6233e9ef1898140d36f8/href">https://medium.com/media/48ec24e08c9a6233e9ef1898140d36f8/href</a></iframe><p>Replace <em>connection_string</em> and <em>queue_name</em> with the correct value.Then run your project, you will</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_qnNT5ypV9QYTp4V" /></figure><p>see results like the following image below.</p><p>Check your dashboard to confirm that the message is already in the queue.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*U1Stk0R_11QsrEih" /></figure><h3>Best Practice For Code</h3><p>There are a couple of things that you can try when implementing RabbitMQ using MassTransit.</p><h4>Single Out Message Model</h4><p>Exchanges play an important role while using RabbitMQ. Consumers identify which message they should consume by using exchanges. With MassTransit, your exchanges are automatically set by this library to be divided by namespace. To make sure that your model can have the same namespace between publisher and consumer code, we can single out the message model to a different project then it can be shared between the publisher solution file and consumer solution file. Note that if those solutions are divided into different repositories, make sure to commit and push a change in both of them if there are any updates on that model.</p><h4>Singleton concept</h4><p>RabbitMQ creates a connection every time you initialize a bus instance by using <em>BusFactory</em>, so to decrease a connection that is created, use the singleton concept while creating a bus from it. Singleton means that only one object of its kind exists and provides a single point of access to it for any other code. The example on top is already shown how to create a RabbitMqSingleton class that will initialize only one time when a project is running.</p><h4>Private Out Configuration File</h4><p>To access RabbitMQ, you need a connection string and the proper queue name that your application wants to consume/publish. Putting those values in the configuration file will give you plenty of benefits like you can easily change between production and development servers, change queue names based on the application environment, and secure out your production server access to your system admin (no to the developer).</p><h3>Conclusion</h3><p>To summarize, MassTransit is a library that we can implement for using RabbitMq more efficiently. For proper message broker architecture we will have 2 main components :</p><ul><li>Message Publisher</li><li>Message Consumer</li></ul><p>And here is some best concept for us to follow while designing broker application :</p><p>Single Out Message Model</p><ul><li>Single Out Message Model</li><li>Singleton concept</li><li>Private Out Configuration File</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=af0503db2613" width="1" height="1" alt=""><hr><p><a href="https://medium.com/bina-nusantara-it-division/a-beginners-guideline-to-rabbitmq-and-masstransit-part-2-implement-rabbitmq-in-code-with-af0503db2613">A Beginners Guideline to RabbitMq and MassTransit(Part 2): Implement RabbitMQ in Code with…</a> was originally published in <a href="https://medium.com/bina-nusantara-it-division">Bina Nusantara IT Division</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Beginners Guideline to RabbitMq and MassTransit(Part 3): User Access Management and Good Practice…]]></title>
            <link>https://medium.com/bina-nusantara-it-division/a-beginners-guideline-to-rabbitmq-and-masstransit-part-2-user-access-management-and-good-practice-e5dbab49699c?source=rss-f0e2a107b11------2</link>
            <guid isPermaLink="false">https://medium.com/p/e5dbab49699c</guid>
            <category><![CDATA[message-broker]]></category>
            <category><![CDATA[rabbitmq]]></category>
            <category><![CDATA[mass-transit]]></category>
            <dc:creator><![CDATA[tong eric]]></dc:creator>
            <pubDate>Wed, 29 Dec 2021 13:16:56 GMT</pubDate>
            <atom:updated>2021-12-29T13:22:38.033Z</atom:updated>
            <content:encoded><![CDATA[<h3>A Beginners Guideline to RabbitMq and MassTransit(Part 3): User Access Management and Good Practice for Using RabbitMq</h3><p>Basic of Authorization and Authentication User in RabbitMq</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Dl0F36mQqB_LNtA_dKd3ug.jpeg" /><figcaption>Picture by<a href="https://unsplash.com/@marvelous"> </a><a href="https://unsplash.com/@markusspiske">Markus Spiske</a> on <a href="https://unsplash.com/">Unsplash</a></figcaption></figure><blockquote><em>This article is a three-part series about complete implementation of RabbitMq as message broker . You can navigate to other part by link below :</em></blockquote><blockquote><a href="https://medium.com/@ericjonson490/ab91e1dc65ad"><em>Part 1 : RabbitMq and How To Install it</em></a></blockquote><blockquote><a href="https://medium.com/bina-nusantara-it-division/a-beginners-guideline-to-rabbitmq-and-masstransit-part-2-implement-rabbitmq-in-code-with-af0503db2613">Part 2 : Implement RabbitMQ in Code with MassTransit</a></blockquote><p>RabbitMQ provides features for authorization and authentication for each access to it. Different users can be granted access only to specific virtual hosts. Their permissions in each virtual host also can be limited. For the sake of simplicity, we’ll define authentication as “identifying who the user is” and authorization as “determining what the user is and isn’t allowed to do.”.</p><h3>The Basics</h3><p>Clients use RabbitMQ features to connect to it. Every connection has an associated user which is authenticated. It also targets a virtual host for which the user must have a certain set of permissions. User credentials, target virtual host, and (optionally) client certificate are specified at connection initiation time.</p><p>There is a default pair of credentials called the default user. This user can only be used for host-local connections by default. Remote connections that use it will be refused.</p><p>When the server first starts running and detects that its database is uninitialized or has been deleted, it initializes a fresh database with the following resources:</p><ul><li>a virtual host named / (a slash)</li><li>a user named guest with a default password of guest, granted full access to the / virtual host</li></ul><p>It is advisable to pre-configure a new user with a generated username and password or delete the guest user or at least change its password to a reasonably secure generated value that won’t be known to the public.</p><h3>Authentication</h3><p>After an application connects to RabbitMQ and before it can perform operations, it must authenticate, that is, present and prove its identity. With that identity, RabbitMQ nodes can look up their permissions and authorize access to resources such as virtual hosts, queues, exchanges, and so on.</p><p>Two primary ways of authenticating a client are username/password pairs and X.509 certificates. Username/password pairs can be used with a variety of authentication backends that verify the credentials. Connections that fail to authenticate will be closed with an error message in the server log.</p><p>To authenticate client connections using X.509 certificate a built-in plugin, rabbitmq-auth-mechanism-ssl must be enabled and clients must be configured to use the EXTERNAL mechanism. With this mechanism, any client-provided password will be ignored.</p><h3>Authorization</h3><p>By default, the guest user is prohibited from connecting from remote hosts; it can only connect over a loopback interface (i.e. localhost). This applies to connections regardless of the protocol. Any other users will not (by default) be restricted in this way.</p><p>The recommended way to address this in production systems is to create a new user or set of users with the permissions to access the necessary virtual hosts. This can be done using CLI tools, HTTP API, or definitions import. This is configured via the loopback_users item in the configuration file.</p><p>It is possible to allow the guest user to connect from a remote host by setting the loopback_users configuration to none like the example below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qz1oAujkDrmFnmcW" /></figure><h3>Managing Users and Permissions</h3><p>RabbitMQ provides CLI tools to manage your users and permissions, <em>rabbitmqctl.</em>with this command you can do several actions like add a new user, grant permissions to a user, etc.</p><p>Before We Start: Shell Escaping and Generated Passwords. It is a common security practice to generate complex passwords, often involving non-alphanumeric characters. This practice is perfectly applicable to RabbitMQ users. Shells (<em>bash, zsh</em>, and so on) interpret certain characters (!, ?, &amp;, ^, “, ‘, *, ~, and others) as control characters.</p><p>When a password is specified on the command line for rabbitmqctl add_user, rabbitmqctl change_password, and other commands that accept a password, such control characters must be escaped appropriately for the shell used. With inappropriate escaping the command will fail or RabbitMQ CLI tools will receive a different value from the shell.</p><p>When generating passwords that will be passed on the command line, long (say, 40 to 100 characters) alphanumeric value with a very limited set of symbols (e.g. :, =) is the safest option.</p><ul><li>Adding a User</li></ul><p>To add a user, use rabbitmqctl add_user. It has multiple ways of specifying a password:</p><pre><em>rabbitmqctl add_user “</em><strong><em>username</em></strong><em>”</em></pre><p>This is a basic way to add users. With this command it will prompt for a password, only use this option interactively</p><pre><em>echo ‘</em><strong><em>password</em></strong><em>’ | rabbitmqctl add_user ‘</em><strong><em>username</em></strong><em>’</em></pre><p>In an advanced way, you can provide your password via standard output, Note that certain characters such as $, &amp;, &amp;, #, and so on must be escaped to avoid special interpretation by the shell.</p><pre><em>rabbitmqctl add_user ‘</em><strong><em>username</em></strong><em>’ ‘</em><strong><em>password</em></strong><em>’</em></pre><p>And the last way is directly interpreted by a shell command, you must escape for a special character too before putting the password in your command.</p><ul><li>Listing Users</li></ul><p>To list users in a cluster, use rabbitmqctl list_users:</p><pre><em>rabbitmqctl list_users</em></pre><p>The output can be changed to be JSON by adding option<em> — formatter=json</em></p><pre><em>rabbitmqctl list_users — formatter=json</em></pre><ul><li>Deleting a User</li></ul><p>To delete a user, use rabbitmqctl delete_user:</p><pre><em>rabbitmqctl delete_user ‘</em><strong><em>username</em></strong><em>’</em></pre><ul><li>Granting Permissions to a User</li></ul><p>Granting permissions to user can be done by command below:</p><pre><em>rabbitmqctl set_permissions -p “</em><strong><em>custom-vhost</em></strong><em>” “</em><strong><em>username</em></strong><em>” “.*” “.*” “.*”</em></pre><p>First “.*” is used to configure permission on every entity, Second “.*” for write permission on every entity, and Third “.*” for reading permission on every entity. If you don’t want to grant it for specific access just type an empty quotation mark “”.</p><p>RabbitMQ accepts wildcards or regular expressions for granting access to specific entities. For example, you can grant read permissions of any exchanges that start with My.Example with the command below</p><pre><em>rabbitmqctl set_permissions -p “</em><strong><em>custom-vhost</em></strong><em>” “</em><strong><em>username</em></strong><em>” “” “” “^[My.Example].*”</em></pre><ul><li>Revoke permissions</li></ul><p>To revoke permissions from a user in a virtual host, use rabbitmqctl clear_permissions:</p><pre><em>rabbitmqctl clear_permissions -p “</em><strong><em>custom-vhost</em></strong><em>” “</em><strong><em>username</em></strong><em>”</em></pre><h3>Good Practice for User Management in RabbitMQ</h3><p>With command on top, we can create various users and grant it for different access to achieve a full management architecture. You can separate users by each division, application, or even can be divided into users that can only configure and users that can read and write in the same application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gi_8qvlr9dw6sbpJ" /></figure><p>This is a simple example of user management that you can do in RabbitMQ. Start with an administrator user that has all access to entities in this vhost. Then create a user divide by the application that connects to it. Users for specific applications can access only entities with specific prefixes of this application. Each app has 2 users, 1 for the operator which can view the dashboard and configure entity on it, and the other one is used by the application to do write and read actions. User_app users can be kept by only sysadmin in the production server so developer and QA can only have access to read and configure dashboard entities.</p><h3>Common mistakes on RabbitMQ and how to avoid it</h3><p>Below is common mistakes on RabbitMQ implementation and how to avoid them:</p><h4>1. Don’t open and close connections or channels repeatedly.</h4><p>Have long-lived connections if possible, and use channels for each task. Don’t open a channel each time you are publishing. If you can’t have long-lived connections, then make sure to gracefully close the connection. The best practice is to reuse connections and multiplex a connection between threads with channels.</p><h4>2. Don’t use too many connections or channels.</h4><p>Try to keep the connection/channel count low. Use separate connections to publish and consume. Ideally, you should have one connection per process, and then use one channel per thread in your application.</p><ul><li>Reuse connections</li><li>1 connection for publishing</li><li>1 connection for consuming</li></ul><h4>3. Don’t share channels between threads.</h4><p>Don’t share channels between threads, as most clients don’t make channels thread-safe for performance reasons.</p><h4>4. Don’t have queues that are too large or too long.</h4><p>Having many messages in a queue places a heavy load on RAM usage. When this happens, RabbitMQ will start flushing (page out) messages to the disk to free up RAM, and when that happens queueing speeds will deteriorate. Separate your queue into smaller ones and increase consumer on each queue to handle it</p><h4>5. Don’t use old RabbitMQ/Erlang versions or RabbitMQ clients/libraries.</h4><p>Stay up-to-date with the latest stable versions of RabbitMQ and Erlang. Make sure you are using the latest recommended version of client libraries.</p><h4>6. Don’t have an unlimited prefetch value.</h4><p>The channel prefetch value defines the max number of unacknowledged deliveries that are permitted on a channel. A typical mistake is to have an unlimited prefetch, where one client receives all messages. This can lead to the client running out of memory and crashing, and then all messages are re-delivered.</p><h4>7. Don’t ignore lazy queues</h4><p>Use lazy queues to achieve predictable performance or if you have large queues. With lazy queues, the messages go straight to disk, thereby minimizing the RAM usage, though throughput will be lower. Lazy queues create a more stable cluster, with more predictable performance. Your messages will not, without a warning, get flushed to disk.</p><h4>8. Limit queue size with TTL or max-length, if possible</h4><p>Applications that get hit by spikes of messages, and where throughput is a priority, set a max-length on the queue. This keeps the queue short by discarding messages from the head of the queues so that it’s never larger than the max-length setting.</p><h4>9. Use multiple queues and consumers.</h4><p>Achieve better throughput on a multi-core system with multiple queues and consumers. You will achieve optimal throughput if you have as many queues as cores on the underlying node(s).</p><h4>10. Persistent messages and durable queues for a message to survive a server restart</h4><p>If you cannot afford to lose any messages, make sure that your queue is declared as “durable” and your messages are sent with delivery mode “persistent” (delivery_mode=2). For high throughput send transient messages to non-lazy queues.</p><h4>11. Split your queues over different cores.</h4><p>Queue performance is limited to one CPU core. You will, therefore, get better performance if you split your queues into different cores, and also into different nodes if you have a RabbitMQ cluster.</p><h4>12. Consume (push), don’t poll (pull) for messages.</h4><p>Make sure that your consumer consumes messages from the queue instead of using basic get actions.</p><h4>13. Missing a High Availability policy while creating a new vhost on a cluster.</h4><p>When you create a new vhost on a cluster, don’t forget to enable an HA-policy for that vhost (even if you don’t have an HA setup, you will need it for plan changes when using classic mirrored queue). Messages will not be synced between nodes without an HA policy.</p><h3>Conclusion</h3><p>RabbitMq has its personal user management for authentication and authorization. it can be done with management UI or with console command tools called rabbitmqctl. It&#39;s better for us to understand those commands to implement RabbitMq with better security control. Also, there is some situation we must avoid when designing our architecture so make sure to review it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e5dbab49699c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/bina-nusantara-it-division/a-beginners-guideline-to-rabbitmq-and-masstransit-part-2-user-access-management-and-good-practice-e5dbab49699c">A Beginners Guideline to RabbitMq and MassTransit(Part 3): User Access Management and Good Practice…</a> was originally published in <a href="https://medium.com/bina-nusantara-it-division">Bina Nusantara IT Division</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>