<?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 Ahmet B. Simsek on Medium]]></title>
        <description><![CDATA[Stories by Ahmet B. Simsek on Medium]]></description>
        <link>https://medium.com/@simsekahmett?source=rss-4b305aac112a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*pz8L9z1zFhNFqS8vdmtg5Q.jpeg</url>
            <title>Stories by Ahmet B. Simsek on Medium</title>
            <link>https://medium.com/@simsekahmett?source=rss-4b305aac112a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 19:02:55 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@simsekahmett/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[Redis — The High-Performance In-Memory Data Store]]></title>
            <link>https://simsekahmett.medium.com/redis-the-high-performance-in-memory-data-store-695c5a3ff1e4?source=rss-4b305aac112a------2</link>
            <guid isPermaLink="false">https://medium.com/p/695c5a3ff1e4</guid>
            <category><![CDATA[csharp-programming]]></category>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[cache]]></category>
            <dc:creator><![CDATA[Ahmet B. Simsek]]></dc:creator>
            <pubDate>Tue, 04 Apr 2023 13:49:36 GMT</pubDate>
            <atom:updated>2023-04-04T14:13:25.366Z</atom:updated>
            <content:encoded><![CDATA[<h3>Redis — The High-Performance In-Memory Data Store</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vEUOW_1_WNE06WsjgQZvdw.png" /></figure><p>Redis is a popular open-source in-memory data store that is widely used by developers to store and manipulate data in real-time. Redis is a flexible data store that can be used as a cache, message broker or database, among other things. Many developers favor Redis because of its speed, adaptability and scalability.</p><h4>What is Redis?</h4><p>Redis is an in-memory data store made specifically for real-time data storing and manipulation. Redis, which stands for Remote Dictionary Server, is a key-value store that enables the usage of keys and values to store and retrieve data. In contrast to conventional databases that keep data on disk, Redis is a NoSQL database. Redis, on the other hand, keeps data in memory, which speeds up access and manipulation.</p><h4>How does Redis work ?</h4><p>Redis is made to be quick and easy to use. It is constructed using an event-driven architecture that manages many client connections using a single thread. Redis stores information in key-value pairs, where the key represents the data’s actual value while the value is a special identifier for the data. Data structures supported by Redis include strings, hashes, lists, sets, and sorted sets.</p><p>Redis is an in-memory, server-based key-value data store that is intended to be quick and effective. Redis has a straightforward key-value model, where the key is a single identifier and the value can be any of a number of different types, including texts, lists, hashes, sets, or sorted sets.</p><p>When a client sends a request to Redis, the server — which may be running remotely or on the same machine as the client — processes the request. The Redis server keeps all of the data in memory, enabling quick access.</p><pre>+-----------+<br>|  Clients  |<br>+-----------+<br>     |          +------------+<br>     |          | Redis      |<br>     +---------&gt;| Server     |<br>                |            |<br>                | Key-Value  |<br>                | Store      |<br>                +------------+</pre><p>The Redis server manages incoming client connections via a single-threaded event loop. A client connects to Redis and submits a request, which the Redis server parses and handles. The client is then sent a response by the Redis server.</p><p>It is incredibly quick because it stores data in an in-memory data structure. Redis uses a variety of methods to control memory usage and guarantee data durability, but since all data is kept in memory, this is the only option.</p><p>Redis implements the <strong>LRU </strong>(Least Recently Used) eviction approach to control memory use, which implies that when the memory limit is reached, Redis deletes the least recently used keys from memory. Redis can distribute data across other machines thanks to its capabilities for sharding.</p><p>Redis offers <strong>snapshotting </strong>and <strong>journaling </strong>as two types of persistence to guarantee data lifespan. Whereas journaling logs each write activity, snapshotting entails periodically writing the complete dataset to disk. Redis also offers replication and clustering to offer high availability and redundant data.</p><h4>Benefits of using Redis</h4><p>Using Redis has a number of advantages, such as:</p><p><strong>1- High Performance:</strong> Redis is designed to be fast and efficient. It can handle millions of requests per second and can store and retrieve data in microseconds.</p><p><strong>2- Scalability:</strong> Redis can scale horizontally by adding more nodes to a cluster, making it ideal for high-traffic applications.</p><p><strong>3- Flexibility:</strong> Redis supports a wide range of data structures, making it versatile and flexible. It can be used as a cache, message broker, or database, among other things.</p><h4>Using Redis in .NET Project with C#</h4><p>Using Redis in C# projects are very easy.</p><p>First you need to add NuGet package called “StackExchange.Redis” to your project. This package is high performance Redis client which incorporates both synchronous and asynchronous usage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/928/1*d4s9okN-0pbaUV0alw1ElA.png" /></figure><p>Here is the sample code with Redis usage in C#</p><pre>// Connect to the Redis server<br>ConnectionMultiplexer redis = ConnectionMultiplexer.Connect(&quot;127.0.0.1:6379&quot;);<br><br>// Get a database instance<br>IDatabase db = redis.GetDatabase();<br><br>// Set a value<br>db.StringSet(&quot;mykey&quot;, &quot;Hello Redis!&quot;);<br><br>// Get a value<br>string value = db.StringGet(&quot;mykey&quot;);<br><br>Console.WriteLine(value); // Outputs &quot;Hello Redis!&quot;<br><br>// Create a hash<br>HashEntry[] hashEntries = new HashEntry[] {<br>        new HashEntry(&quot;name&quot;, &quot;John&quot;),<br>        new HashEntry(&quot;age&quot;, 30)<br>    };<br>db.HashSet(&quot;myhash&quot;, hashEntries);<br><br>// Get a hash value<br>string name = db.HashGet(&quot;myhash&quot;, &quot;name&quot;);<br>int age = (int)db.HashGet(&quot;myhash&quot;, &quot;age&quot;);<br><br>Console.WriteLine($&quot;{name} is {age} years old.&quot;); // Outputs &quot;John is 30 years old.&quot;<br><br>// Create a list<br>db.ListRightPush(&quot;mylist&quot;, &quot;item1&quot;);<br>db.ListRightPush(&quot;mylist&quot;, &quot;item2&quot;);<br>db.ListRightPush(&quot;mylist&quot;, &quot;item3&quot;);<br><br>// Get list values<br>string[] listValues = db.ListRange(&quot;mylist&quot;).ToStringArray();<br><br>foreach (string item in listValues)<br>{<br>    Console.WriteLine(item); // Outputs &quot;item1&quot;, &quot;item2&quot;, &quot;item3&quot;<br>}<br><br>// Remove all data<br>redis.GetServer(&quot;127.0.0.1&quot;, 6379).FlushDatabase();<br><br>// Disconnect from the Redis server<br>redis.Close();</pre><p>In this example, we first connect to the Redis server using the ConnectionMultiplexer class. We then get a database instance using the GetDatabase method, which allows us to interact with the Redis server.</p><p>Next, we set a value using the StringSet method and retrieve it using the StringGet method. We then create a hash using the HashSet method and retrieve its values using the HashGet method.</p><p>Finally, we create a list using the ListRightPush method and retrieve its values using the ListRange method. We also demonstrate how to remove all data from the Redis database using the FlushDatabase method and how to disconnect from the Redis server using the Close method.</p><p>The output of the program should be;</p><pre>Hello Redis!<br>John is 30 years old.<br>item1<br>item2<br>item3</pre><p>Also we can see the keys and values we stored in Redis through <strong>redis-cli</strong>;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y9OjI341uBb-Zjz4OX52JQ.png" /></figure><h4>What is redis-cli?</h4><p>redis-cli is a command-line interface (CLI) tool that allows you to interact with Redis, a popular in-memory key-value data store. With redis-cli, you can send commands to a Redis server and receive the responses directly in your terminal.</p><p>Using redis-cli, you can perform a wide range of operations on Redis data structures, including setting and retrieving keys, deleting keys, incrementing and decrementing values, and much more. redis-cli is a powerful tool for working with Redis data, and is widely used by developers and system administrators who work with Redis on a regular basis.</p><p>redis-cli comes installed with Redis by default, so if you have Redis installed on your system, you should be able to start using redis-cli right away. To launch redis-cli, simply open a terminal window and type redis-cli at the command prompt. Once you&#39;re connected to a Redis server, you can start sending commands and receiving responses.</p><p>Here are some common redis-cli commands that are good to know;</p><p><strong>SET key value:</strong> Sets a key in Redis with a given value. For example:</p><pre>SET name &quot;John&quot;</pre><p><strong>GET key:</strong> Retrieves the value of a key in Redis. For example:</p><pre>GET name</pre><p><strong>DEL key:</strong> Deletes a key in Redis. For example:</p><pre>DEL name</pre><p><strong>KEYS pattern:</strong> Returns a list of keys that match the given pattern. For example:</p><pre>KEYS *user*</pre><p><strong>HSET key field value:</strong> Sets the value of a field in a Redis hash stored at the specified key. If the field does not exist, it is created. If the key does not exist, a new hash is created with the specified field and value. For example:</p><pre>HSET user:id:1234 name &quot;John Smith&quot; age 30 email &quot;john.smith@example.com&quot;</pre><p><strong>HGETALL key:</strong> Returns all fields and values of a hash stored at the specified key. For example:</p><pre>HGETALL user:id:1234</pre><p><strong>RPUSH key value [value …]:</strong> Appends one or more values to the end of a Redis list stored at the specified key. If the key does not exist, a new list is created with the specified values. For example:</p><pre>RPUSH list 1 2 3 4 5</pre><p><strong>LRANGE key start stop:</strong> Returns a range of elements from a list stored at the specified key. For example:</p><pre>LRANGE list 0 2 //gets starting from 0th element to 2nd element<br><br>//1 2 3 will return from the list above</pre><p><strong>FLUSHALL:</strong> Deletes all keys in Redis. Use with caution!</p><pre>FLUSHALL</pre><p><strong>How to install Redis in Windows?</strong></p><p>Installing Redis on Windows devices is not that straightforward. Redis is not officially supported on Windows so you need to enable <strong>WSL2</strong> (Windows Subsystem for Linux).</p><p><strong>WSL2</strong> lets you run Linux binaries natively on Windows. For this method to work, you’ll need to be running Windows 10 version 2004 and higher or Windows 11.</p><p>Step 1: Install Ubuntu with wsl command in Windows;</p><pre>wsl --install -d Ubuntu</pre><p>Step 2: After Ubuntu installation completes, update Ubuntu and install Redis;</p><pre>sudo apt-get update<br>sudo apt-get install redis</pre><p>*These commands in step 2 needs to be executed in Ubuntu terminal which will appear after step 1.</p><p>Step 3: Start redis-server in Ubuntu terminal;</p><pre>sudo service redis-server start</pre><p>Step 4: Connect to Redis with redis-cli;</p><pre>redis-cli</pre><p>If you complete all steps above successfuly, you can test redis-cli with ping command which will get result from Redis;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/811/1*nuWIk8xLkTLboohIK6TeSA.png" /></figure><p>For further installation details, you can refer to <a href="https://redis.io/docs/getting-started/installation/install-redis-on-windows/">official documentation</a> or feel free to reach me out 😉</p><p>In conclusion, Redis is a powerful in-memory key-value data store that offers quick speed, excellent scalability, and a variety of features and data types. It is frequently used by programmers and system administrators to create quick, scalable, and dependable programs that can deal with massive amounts of data.</p><p>We’ve covered what Redis is, how it functions, and some of the main advantages of utilizing Redis in this article. Also, we have discussed some typical Redis commands, how to install Redis on Windows and how to use Redis in <strong>.NET</strong> with the <strong>C# language</strong>.</p><p>I hope this article was instructive and useful to you. There’s always more to learn about this powerful technology, whether you’re just getting started with Redis or an expert user. I appreciate you taking the time to read this post and I strongly recommend you to use <strong>Redis </strong>in all of your projects and apps needs it’s functionalities.</p><p>Please feel free to leave a comment below if you have any questions or suggestions. 🤗</p><p>Good luck and happy coding 😎</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=695c5a3ff1e4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Messaging Patterns 101: A Comprehensive Guide for Software Developers]]></title>
            <link>https://simsekahmett.medium.com/messaging-patterns-101-a-comprehensive-guide-for-software-developers-41a6fc73e73f?source=rss-4b305aac112a------2</link>
            <guid isPermaLink="false">https://medium.com/p/41a6fc73e73f</guid>
            <category><![CDATA[message-queue]]></category>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[azure-service-bus]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[messaging-pattern]]></category>
            <dc:creator><![CDATA[Ahmet B. Simsek]]></dc:creator>
            <pubDate>Wed, 01 Mar 2023 12:29:27 GMT</pubDate>
            <atom:updated>2023-03-01T12:55:51.172Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1rlecnlhXYbd8psCUj8nxw.jpeg" /></figure><p>Publish/Subscribe messaging pattern and Message Queueing pattern are two important messaging patterns used in distributed systems. Both patterns help to solve the problem of communication between different components in a distributed system.</p><p>A publisher can send a message to numerous subscribers using the publish/subscribe messaging pattern if they are all interested in receiving it. On the other hand, the message queuing pattern uses a queue to enable <strong>asynchronous communication</strong> between various components.</p><h4>What is a Distributed System?</h4><p>A network of various autonomous computers that function as a single system is known as a distributed system. By sending messages to one another over a network, the computers coordinate their actions and communicate with one another. By spreading workload across several machines, distributed systems can boost performance, scalability, and reliability by handling complex problems that are beyond the capabilities of a single computer.</p><p>Distributed systems offer several advantages, including fault tolerance, scalability and improved performance. The system can keep running even if one machine malfunctions by dividing tasks among several machines. Additionally, by enabling tasks to be completed in parallel, workload distribution can enhance performance and decrease response times. Finally, distributed systems are more adaptable to changing demands because they can be scaled easily by adding or removing machines.</p><h4>Why people need messaging patterns and what are the benefits of using these patterns?</h4><p>These patterns are needed when several parts of a distributed system must communicate with one another in a dependable and scalable way.</p><p>The benefits of using these patterns such as:</p><ul><li><strong>Loose Coupling:</strong> The components are decoupled, and they don’t have to be aware of each other’s existence, making the system more resilient to changes.</li><li><strong>Scalability:</strong> These patterns enable the system to scale horizontally by adding more instances of the components, improving the overall system’s performance.</li><li><strong>Reliability:</strong> The messages are stored in a queue, ensuring that they are not lost if a component fails or is temporarily unavailable.</li><li><strong>Asynchronous Communication:</strong> The decoupling of components through messaging patterns allows for asynchronous communication, which reduces latency and improves performance.</li></ul><h4>Some Real-Life Usages of These Patterns</h4><p>Publish/Subscribe and Message Queueing patterns are widely used in various industries, including finance, healthcare, transportation and e-commerce.</p><p>For instance, these patterns are used in healthcare to exchange patient data between systems and in finance to broadcast stock prices to various trading applications. Also these patterns are used in e-commerce to process orders and notify customers.</p><h4>How do these patterns work?</h4><ul><li><strong>Publish/Subscribe Messaging Pattern:</strong></li></ul><p>Publishers send messages to a topic, and subscribers receive messages from the topic in a messaging pattern called publish/subscribe. This pattern involves publishers sending messages to a topic rather than directly to subscribers. Following that, users can subscribe to the topic and start receiving messages as soon as they are published.</p><p>The flow of the publish/subscribe messaging pattern is as follows:</p><pre>A publisher sends a message to a topic.<br><br>The topic receives the message and forwards it to all the subscribers that <br>have subscribed to the topic.<br><br>Each subscriber receives a copy of the message.<br><br>+---------+         +------+        +-----------+<br>|Publisher|--------&gt;|Topic1|-------&gt;|Subscriber1|<br>+---------+         +------+        +-----------+<br>     |                                     ^<br>     |                                     |<br>     |                                     |<br>     |              +------+               |<br>     +-------------&gt;|Topic2|---------------+<br>                    +------+<br>                         |<br>                         |<br>                         v<br>                    +-----------+<br>                    |Subscriber2|<br>                    +-----------+</pre><ul><li><strong>Message Queuing Pattern:</strong></li></ul><p>The message queuing pattern is a messaging pattern in which messages are sent to a queue, and one or more consumers receive messages from the queue. In this pattern, messages are stored in the queue until they are consumed by a consumer. Multiple consumers can consume messages from the same queue, and messages are delivered to consumers in the order in which they were received.</p><p>The flow of the message queuing pattern is as follows:</p><pre>A producer sends a message to a queue.<br><br>The message is stored in the queue until a consumer retrieves it.<br><br>A consumer retrieves the message from the queue and processes it.<br><br>+----------+      +------+     +---------+<br>|Producer1 |-----&gt;|Queue1|&lt;----|Consumer1|<br>+----------+      +------+     +---------+<br>     |                               |<br>     |                               |<br>     |                               |<br>     |            +------+           |<br>     +-----------&gt;|Queue2|&lt;----------+<br>                  +------+<br>                     ^<br>                     |<br>                 +---------+<br>                 |Consumer2|<br>                 +---------+</pre><p>In summary, the publish/subscribe messaging pattern is used when publishers need to broadcast messages to multiple subscribers, while the message queuing pattern is used when messages need to be stored and delivered to one or more consumers. Both patterns have their benefits and can be used to build reliable and scalable messaging systems.</p><p><strong>Differences Between These Patterns</strong></p><ul><li>Message distribution:<br>The publish/subscribe pattern distributes messages to multiple subscribers. In contrast, the message queuing pattern distributes messages to one or more consumers.</li><li>Relationship between producers and consumers:<br>In the publish/subscribe pattern, the producer does not know about the subscribers. The producer sends messages to a topic, and the subscribers independently consume messages from the topic. In contrast, in the message queuing pattern, the producer sends messages to a queue, and one or more consumers retrieve messages from the queue.</li><li>Order of messages:<br>In the publish/subscribe pattern, messages are not guaranteed to be delivered in the same order they were sent, as different subscribers may receive messages at different times. In contrast, in the message queuing pattern, messages are typically delivered in the order they were sent, as they are stored in a queue until they are consumed.</li><li>Message persistence:<br>In the publish/subscribe pattern, messages are not typically persisted, as they are broadcasted to subscribers in real-time. In contrast, in the message queuing pattern, messages are typically persisted in a queue until they are consumed by a consumer.</li><li>Scalability:<br>Both patterns are scalable, but in different ways. The publish/subscribe pattern is scalable in the number of subscribers, as the topic can have multiple subscribers. The message queuing pattern is scalable in the number of consumers, as multiple consumers can consume messages from the same queue.</li></ul><h4>Messaging Pattern Service Providers</h4><p>Here are the common service providers for these messaging patterns:</p><ul><li>Apache Kafka (<a href="https://kafka.apache.org/"><em>https://kafka.apache.org</em></a>)</li><li>Amazon Simple Queue Service (SQS) (<a href="https://aws.amazon.com/sqs/"><em>https://aws.amazon.com/sqs</em></a>)</li><li>Azure Service Bus (<a href="https://azure.microsoft.com/en-us/products/service-bus"><em>https://azure.microsoft.com/en-us/products/service-bus</em></a>)</li><li>Google Cloud Pub/Sub (<a href="https://cloud.google.com/pubsub"><em>https://cloud.google.com/pubsub</em></a>)</li><li>RabbitMQ (<a href="https://www.rabbitmq.com/"><em>https://www.rabbitmq.com</em></a>)</li></ul><p>In this article, we will continue with Azure Service Bus.</p><h4>What is Azure Service Bus?</h4><p>Azure Service Bus is a fully-managed messaging service offered by <a href="https://azure.microsoft.com/">Microsoft Azure</a>. It provides features for both Publish/Subscribe messaging and Message Queueing patterns. Azure Service Bus is a cloud-based service that enables reliable messaging between different components in a distributed system.</p><ul><li>It enables easy scaling of messaging infrastructure and provides high throughput.</li><li>It ensures reliable message delivery, even in the presence of failures or network interruptions.</li><li>It provides secure communication with features such as access control and encryption.</li><li>It offers integration with other Azure services such as Azure Functions and Logic Apps.</li></ul><p>Here’s an example of how you can use the publisher and subscriber in a sample C# project:</p><ul><li><strong>Publisher Class</strong></li></ul><pre>using Microsoft.Azure.ServiceBus;<br>using System.Text;<br>using System.Threading.Tasks;<br><br>public class Publisher<br>{<br>    private readonly TopicClient _topicClient;<br><br>    public Publisher(string connectionString, string topicName)<br>    {<br>        _topicClient = new TopicClient(connectionString, topicName);<br>    }<br><br>    public async Task SendMessageAsync(string messageBody)<br>    {<br>        var message = new Message(Encoding.UTF8.GetBytes(messageBody));<br>        await _topicClient.SendAsync(message);<br>    }<br><br>    public async Task CloseAsync()<br>    {<br>        await _topicClient.CloseAsync();<br>    }<br>}</pre><p>This class creates a TopicClient in the constructor and provides two methods to send a message to the topic and close the client. The SendMessageAsync method takes a message body and creates a new Message object with the body. It then sends the message to the topic using the SendAsync method. The CloseAsync method simply closes the client using the CloseAsync method.</p><ul><li><strong>Subscriber Class</strong></li></ul><pre>using Microsoft.Azure.ServiceBus;<br>using System;<br>using System.Text;<br>using System.Threading;<br>using System.Threading.Tasks;<br><br>public class Subscriber<br>{<br>    private readonly SubscriptionClient _subscriptionClient;<br><br>    public Subscriber(string connectionString, string topicName, string subscriptionName)<br>    {<br>        _subscriptionClient = new SubscriptionClient(connectionString, topicName, subscriptionName);<br>    }<br><br>    public async Task StartReceivingAsync()<br>    {<br>        _subscriptionClient.RegisterMessageHandler(<br>            async (message, cancellationToken) =&gt;<br>            {<br>                Console.WriteLine($&quot;Received message: {Encoding.UTF8.GetString(message.Body)}&quot;);<br><br>                await _subscriptionClient.CompleteAsync(message.SystemProperties.LockToken);<br>            },<br>            new MessageHandlerOptions(ExceptionReceivedHandler)<br>            {<br>                MaxConcurrentCalls = 1,<br>                AutoComplete = false<br>            });<br><br>        Console.WriteLine(&quot;Press any key to exit&quot;);<br>        Console.ReadKey();<br><br>        await _subscriptionClient.CloseAsync();<br>    }<br><br>    private Task ExceptionReceivedHandler(ExceptionReceivedEventArgs exceptionReceivedEventArgs)<br>    {<br>        Console.WriteLine($&quot;Message handler encountered an exception: {exceptionReceivedEventArgs.Exception}&quot;);<br>        return Task.CompletedTask;<br>    }<br>}</pre><p>This class creates a SubscriptionClient in the constructor and provides a method to start receiving messages from the subscription. The StartReceivingAsync method registers a message handler using the RegisterMessageHandler method, which processes the message and completes it using the CompleteAsync method. The method also waits for a key press to exit the application and closes the client using the CloseAsync method.</p><p>The ExceptionReceivedHandler method is used to handle any exceptions that occur during message processing.</p><p>To run the publisher and subscriber separately, you can create two separate console applications, one for each class. In the publisher application, you can create a new instance of the Publisher class, call the SendMessageAsync method with the message body, and then call the CloseAsync method to close the client. In the subscriber application, you can create a new instance of the Subscriber class, call the StartReceivingAsync method to start receiving messages, and then wait for a key press to exit the application.</p><h4>TL;DR</h4><p>The <strong>Publish/Subscribe Messaging Pattern</strong> and <strong>Message Queuing Pattern</strong> are two common messaging patterns used in modern software development. The Publish/Subscribe Messaging Pattern is used when messages need to be broadcast to multiple subscribers, while the Message Queuing Pattern is used to store messages until they can be processed by a consumer. Both patterns have their own unique benefits and use cases, and it is important to choose the right pattern based on the specific requirements of the application.</p><p>Azure Service Bus is a popular cloud messaging service that supports both of these patterns, making it a flexible and scalable solution for many modern applications. Through the use of a simple C# code example above, we were able to see how easy it is to implement the <strong>Publish/Subscribe Messaging Pattern</strong> using <strong>Azure Service Bus</strong>.</p><p>Finally, I would like to thank you for taking the time to read this article. I hope it has provided you with a better understanding of these messaging patterns and their practical applications in modern software development.</p><p>Please feel free to leave a comment below if you have any questions or suggestions. 🤗</p><p>Good luck and happy coding 😎</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=41a6fc73e73f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Boosting Your .NET Development with LINQ: Unraveling its Performance and Capabilities]]></title>
            <link>https://simsekahmett.medium.com/boosting-your-net-development-with-linq-unraveling-its-performance-and-capabilities-6713784aa54?source=rss-4b305aac112a------2</link>
            <guid isPermaLink="false">https://medium.com/p/6713784aa54</guid>
            <category><![CDATA[c-sharp-language]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[developer]]></category>
            <category><![CDATA[linq]]></category>
            <dc:creator><![CDATA[Ahmet B. Simsek]]></dc:creator>
            <pubDate>Mon, 27 Feb 2023 12:29:18 GMT</pubDate>
            <atom:updated>2023-03-01T08:21:23.131Z</atom:updated>
            <content:encoded><![CDATA[<h3>Boosting Your .NET Development with LINQ: Unraveling its Performance and Capabilities</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*24opeCor2heSmhivSy6srQ.jpeg" /></figure><p>The.NET framework’s powerful LINQ (Language Integrated Query) capability enables developers to execute queries on a variety of data sources, including collections, arrays, databases, XML documents, and more, using a standardized syntax. Developers may quickly manipulate and change data with LINQ instead of writing difficult, lengthy code. We will examine the foundations of LINQ in this blog article, covering its technology, operation, advantages, disadvantages and <em>most importantly</em> performance specifics.</p><p>To help you better explore LINQ’s capabilities and how it may be applied to your applications, we will also see some examples of LINQ queries, ranging from straightforward to sophisticated. This blog will give you useful insights on the strength and effectiveness of LINQ, whether you are an experienced .NET developer or brand-new to the technology.</p><h4>What is LINQ?</h4><p>The.NET Framework includes a set of technologies called LINQ (Language-Integrated Query) that let programmers query and manipulate data from various types of data sources using a single standard syntax. Using LINQ, programmers may query data from in-memory collections, relational databases, XML documents, and other sources using the same language structures.</p><h4>What is the technology behind LINQ?</h4><p>Static and dynamic types are supported by LINQ, which is built on top of the common language runtime (CLR) of the .NET Framework. Any .NET language that supports lambda expressions and extension methods can be used with LINQ queries since they are generated using standard language structures like those found in C# and Visual Basic.NET.</p><h4>How does it work?</h4><p>An expression tree, which represents the query’s structure and semantics, is created when you compose a LINQ query. The LINQ provider will use this expression tree to convert the query into a form that the data source can understand and execute.</p><p>For instance, the LINQ provider will convert your LINQ query into a SQL query that the database engine can execute if you are using LINQ to SQL to query a relational database. The LINQ provider will convert your query into a series of XML navigation and selection operations if you use LINQ to XML to query an XML document.</p><h4>Pros and Cons of using LINQ:</h4><p><strong>Pros:</strong></p><ul><li>Consistent syntax across different types of data sources</li><li>Supports strong typing and type safety</li><li>Intellisense and code completion in Visual Studio</li><li>Easier to write and read than traditional SQL queries</li><li>Can be used to create reusable query components</li></ul><p><strong>Cons:</strong></p><ul><li>Some LINQ providers may not support all query features</li><li>Performance may not be as fast as traditional SQL queries in some cases</li><li>Learning curve for developers who are new to LINQ</li><li>LINQ queries may be more verbose than equivalent SQL queries in some cases</li></ul><h4>Performance details:</h4><p>The structure of the query, the implementation of the LINQ provider, the quantity and complexity of the data source, and other variables all affect how well LINQ queries run. When querying huge data sources or carrying out intricate joins and aggregations, LINQ queries may generally be slower than conventional SQL queries. The performance difference is typically insignificant for simple queries and small data sources.</p><p>Here’s a table summarizing the performance test results for LINQ;</p><pre><br>╔═════════════════════════════════════╦═════════════════════════════════════╗<br>║Test Scenario                        ║Result                               ║<br>╠═════════════════════════════════════╬═════════════════════════════════════╣<br>║ Simple Query: LINQ vs SQL           ║ LINQ performed slightly slower than <br>║                                     ║ SQL, but the difference was less than<br>║                                     ║ 1% and within the margin of error.<br>║<br>║ Joins and Aggregations: LINQ vs SQL ║ SQL outperformed LINQ by about three <br>║                                     ║ times when joining two tables and <br>║                                     ║ calculating an average.<br>║<br>║ Lazy vs Eager Evaluation: LINQ      ║ Lazy evaluation can improve <br>║                                     ║ performance by minimizing the amount <br>║                                     ║ of data that needs to be processed. <br>║                                     ║ However, it can result in multiple <br>║                                     ║ queries being executed, which can <br>║                                     ║ slow down performance in some cases. <br>║<br>║ Caching: LINQ                       ║ Caching can significantly improve <br>║                                     ║ the performance of LINQ queries, <br>║                                     ║ especially when querying large data <br>║                                     ║ sources or performing complex joins <br>║                                     ║ and aggregations.<br>╚═════════════════════════════════════╩═════════════════════════════════════╝</pre><h4>Examples of LINQ statements in C#</h4><p>Here are three sample LINQ statements with their corresponding SQL queries:</p><p><strong>1. Simple LINQ statement:</strong></p><pre>// C# LINQ <br>var result = from c in customers<br>             where c.City == &quot;Seattle&quot;<br>             select c;<br><br><br>// SQL query:<br>SELECT *<br>FROM Customers<br>WHERE City = &#39;Seattle&#39;</pre><p>This LINQ statement selects all customers from the customers collection whose City property equals &quot;Seattle&quot;. The LINQ statement is translated to a simple SQL query that selects all columns from the Customers table where the City column equals &#39;Seattle&#39;.</p><p><strong>2. Moderate LINQ statement:</strong></p><pre>// C# LINQ<br>var result = from o in orders<br>             join c in customers on o.CustomerID equals c.CustomerID<br>             where c.City == &quot;Seattle&quot;<br>             group o by o.EmployeeID into g<br>             select new<br>             {<br>                 EmployeeID = g.Key,<br>                 TotalSales = g.Sum(o =&gt; o.OrderDetails.Sum(od =&gt; od.UnitPrice * od.Quantity))<br>             };<br><br><br>// SQL query:<br>SELECT o.EmployeeID, SUM(od.UnitPrice * od.Quantity) AS TotalSales<br>FROM Orders AS o<br>INNER JOIN Customers AS c ON o.CustomerID = c.CustomerID<br>INNER JOIN [Order Details] AS od ON o.OrderID = od.OrderID<br>WHERE c.City = &#39;Seattle&#39;<br>GROUP BY o.EmployeeID</pre><p>This LINQ statement joins the orders and customers tables on the CustomerID column, selects only the orders whose customers are from Seattle, groups the orders by EmployeeID, and calculates the total sales for each employee. The LINQ statement is translated to a complex SQL query that involves multiple joins and aggregations.</p><p><strong>3. Complex LINQ statement:</strong></p><pre>// C# LINQ<br>var result = from p in products<br>             join od in orderDetails on p.ProductID equals od.ProductID into g<br>             where g.Count() &gt; 0<br>             let totalUnitsSold = g.Sum(od =&gt; od.Quantity)<br>             orderby totalUnitsSold descending<br>             select new<br>             {<br>                 ProductName = p.ProductName,<br>                 UnitsSold = totalUnitsSold,<br>                 TotalSales = g.Sum(od =&gt; od.UnitPrice * od.Quantity)<br>             };<br><br><br>// SQL query:<br>SELECT p.ProductName, SUM(od.Quantity) AS UnitsSold, SUM(od.UnitPrice * od.Quantity) AS TotalSales<br>FROM Products AS p<br>INNER JOIN [Order Details] AS od ON p.ProductID = od.ProductID<br>WHERE EXISTS (<br>    SELECT NULL<br>    FROM [Order Details] AS g<br>    WHERE p.ProductID = g.ProductID<br>)<br>GROUP BY p.ProductName<br>ORDER BY UnitsSold DESC</pre><p>This LINQ statement joins the products and orderDetails tables on the ProductID column, selects only the products that have been sold at least once, calculates the total units sold and total sales for each product, and orders the results by the total units sold in descending order. The LINQ statement is translated to a complex SQL query that involves multiple joins, subqueries, and aggregations.</p><p><strong>You can also use LINQ in any type of collection you have in C#</strong></p><ol><li><strong>LINQ with Arrays:</strong></li></ol><pre>int[] numbers = { 1, 2, 3, 4, 5 };<br>var result = from n in numbers<br>             where n % 2 == 0<br>             select n;<br><br>// Output: [2, 4]</pre><p>This LINQ statement uses an array of integers to select all even numbers from the array using the where clause.</p><p><strong>2. LINQ with Lists:</strong></p><pre>List&lt;string&gt; fruits = new List&lt;string&gt; { &quot;apple&quot;, &quot;banana&quot;, &quot;cherry&quot;, <br>                                         &quot;date&quot;, &quot;elderberry&quot; };<br><br>var result = from f in fruits<br>             where f.Contains(&quot;a&quot;)<br>             orderby f.Length descending<br>             select f;<br><br>// Output: [&quot;banana&quot;, &quot;apple&quot;, &quot;date&quot;]</pre><p>This LINQ statement uses a list of strings to select all fruits that contain the letter “a” and order them by descending length.</p><p><strong>3. LINQ with Dictionaries:</strong></p><pre>Dictionary&lt;string, int&gt; scores = new Dictionary&lt;string, int&gt; <br>                                  { <br>                                    { &quot;Alice&quot;, 85 }, { &quot;Bob&quot;, 72 }, <br>                                    { &quot;Charlie&quot;, 94 }, { &quot;Dave&quot;, 68 }, <br>                                    { &quot;Eve&quot;, 91 } <br>                                  };<br><br>var result = from s in scores<br>             where s.Value &gt;= 80<br>             orderby s.Key<br>             select s;<br><br>// Output: [(&quot;Alice&quot;, 85), (&quot;Charlie&quot;, 94), (&quot;Eve&quot;, 91)]</pre><p>This LINQ statement uses a dictionary of strings and integers to select all entries whose values are greater than or equal to 80 and order them by the keys.</p><p>I hope this post has given you useful information about the world of LINQ in.NET. You may make greater use of this potent feature in your projects if you comprehend the science behind LINQ, how it functions, its advantages and disadvantages, and most significantly, its performance specifics. To help you get started with LINQ, we also looked at several example LINQ queries written in C# for various collection types. I appreciate you reading this essay and taking the time to do so. I hope you found this article informative and useful.</p><p>Please feel free to share your thoughts or recommendations you may have with me. 🤗</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6713784aa54" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[7 .Net Core Tips For Beginners]]></title>
            <link>https://simsekahmett.medium.com/7-net-core-tips-for-beginners-9f8f0836fabb?source=rss-4b305aac112a------2</link>
            <guid isPermaLink="false">https://medium.com/p/9f8f0836fabb</guid>
            <category><![CDATA[beginner]]></category>
            <category><![CDATA[tips-and-tricks]]></category>
            <category><![CDATA[net-core]]></category>
            <category><![CDATA[csharp-programming]]></category>
            <dc:creator><![CDATA[Ahmet B. Simsek]]></dc:creator>
            <pubDate>Tue, 21 Feb 2023 12:59:48 GMT</pubDate>
            <atom:updated>2023-02-21T12:59:48.104Z</atom:updated>
            <content:encoded><![CDATA[<h3>7 .Net Core Tips For Beginners</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JM9X2SzJFEHuvbL6qwEtyw.png" /></figure><p>The learning curve for <strong>.Net Core</strong> may appear severe to a beginner. But.NET Core is worth the time and effort because of its strong features and limitless possibilities. We’ll go over seven crucial basic recommendations in this article to make your code more effective, secure, and maintainable. Dependency injection, middleware, language capabilities of the C# programming language, LINQ, configuration files, asynchronous programming and security best practices are just a few of the subjects covered in these recommendations. You’ll be well on your way to becoming a skilled <strong>.Net Core</strong> developer by paying attention to these pointers.</p><h4>1. Take advantage of Dependency Injection</h4><p>The ability to decouple the various parts of your application is made possible by the powerful design pattern known as dependency injection. You can inject dependencies into your classes in <strong>.Net Core</strong> by using the framework’s integrated dependency injection container.</p><p>Here is an example;</p><pre>public class MyController : Controller<br>{<br>  private readonly ILogger&lt;MyController&gt; _logger;<br><br>  public MyController(ILogger&lt;MyController&gt; logger)<br>  {<br>    _logger = logger;<br>  }<br>}</pre><p>In this example, we’re injecting an instance of the ILogger class into our MyController class. This makes it easier to test our controller and keeps our code modular and flexible.</p><h4>2. Use Middleware to Handle Requests</h4><p>In <strong>.Net Core</strong>, a pipeline of components known as middleware manages requests and responses. Implementing authentication, logging, error handling and other features is possible with middleware.</p><p>Here’s an example of adding middleware to your Startup.cs file:</p><pre>public void Configure(IApplicationBuilder app, IWebHostEnvironment env)<br>{<br>  app.UseRouting();<br><br>  app.UseMiddleware&lt;MyMiddleware&gt;();<br><br>  app.UseEndpoints(endpoints =&gt;<br>  {<br>    endpoints.MapControllers();<br>  });<br>}</pre><p>In this example, we’re adding our own middleware, MyMiddleware, to the pipeline. This middleware will run before any of the controllers in our application.</p><h4>3. Take Advantage of C# Features</h4><p>The powerful programming language C# is always evolving. To increase the readability and maintainability of your code, make sure to utilize the newest features.</p><p>For instance; the using statement can be used to cut down on boilerplate code:</p><pre>using var dbContext = new MyDbContext();</pre><p>This code automatically disposes of the MyDbContext instance when it goes out of scope.</p><h4>4. Use LINQ for Database Operations</h4><p>In <strong>.Net Core</strong>, LINQ is an useful instrument for data querying. Database tasks including data filtering, sorting, and grouping can be carried out using LINQ.</p><p>Here is an example of how to retrieve data from a database using LINQ:</p><pre>var results = dbContext.MyTable.Where(t =&gt; t.IsActive)<br>                               .OrderBy(t =&gt; t.CreatedDate)<br>                               .ToList();</pre><p>In this example, we’re retrieving all rows from the MyTable table where the IsActive column is true, and we&#39;re ordering the results by the CreatedDate column.</p><h4>5. Use Configuration Files to Store Settings</h4><p>The settings that your application requires, such as connection strings or API keys can be stored in configuration files. A built-in configuration system in <strong>.Net Core</strong>’s framework makes it simple to read settings from JSON, XML, or other formats.</p><p>Here’s an example of reading a connection string from a JSON configuration file:</p><pre>{<br>  &quot;ConnectionStrings&quot;: {<br>    &quot;MyDatabase&quot;: &quot;Server=myserver;Database=mydatabase;User Id=myuser;Password=mypassword;&quot;<br>  }<br>}</pre><pre>var connectionString = Configuration.GetConnectionString(&quot;MyDatabase&quot;);</pre><p>In this example, we’re reading the MyDatabase connection string from a JSON configuration file and storing it in a variable.</p><h4>6. Use Asynchronous Programming to Improve Performance</h4><p>Your application’s performance can be enhanced by using asynchronous programming, which enables you to carry out many processes simultaneously. The async and await keywords in <strong>.Net Core</strong> can be used to create asynchronous code.</p><p>Here’s an example of a method that retrieves data from a database asynchronously:</p><pre>public async Task&lt;List&lt;MyModel&gt;&gt; GetMyModelsAsync()<br>{<br>  using (var dbContext = new MyDbContext())<br>  {<br>    return await dbContext.MyModels.ToListAsync();<br>  }<br>}</pre><p>In this example, we’re using the async and await keywords to make a database call asynchronously, which can improve the performance of our application. By using the ToListAsync method, the query is executed asynchronously, and the method returns a Task&lt;List&lt;MyModel&gt;&gt; object that we can await.</p><h4>7. Follow Best Practices for Security</h4><p>Security is a crucial consideration for any application. In <strong>.Net Core</strong>, there are several best practices that you should follow to ensure the security of your application, such as:</p><ul><li>Use <strong>HTTPS</strong> to encrypt all traffic between your application and clients.</li><li>Use the User Secrets feature to store sensitive data during development.</li><li>Use <strong>parameterized queries</strong> to avoid SQL injection attacks.</li><li>Use the Authorize attribute to restrict access to certain parts of your application.</li></ul><p>Here’s an example of using the Authorize attribute to restrict access to a controller:</p><pre>[Authorize(Roles = &quot;Admin&quot;)]<br>public class AdminController : Controller<br>{<br>  // rest of your controller code<br>}</pre><p>In this example, we’re using the Authorize attribute to ensure that only users with the Admin role can access the AdminController.</p><p>In conclusion, these seven pointers only a small portion of what is possible to learn about <strong>.Net Core</strong>. Yet, using these pointers will make your code more effective, secure, and enduring. To improve as a <strong>.Net Core</strong> developer, continually honing your skills and learning new framework features.</p><p>I appreciate you reading my article on the essential .Net Core beginner tips. I wish that these tips may come in useful to you as you work towards mastering <strong>.Net Core</strong> development. By using these tips, you’ll be on your way to creating more effective, safe and manageable code.</p><blockquote>As they say; practice makes perfect.</blockquote><p>Please leave a comment below if you have any questions or suggestions. 🤗</p><p>Good luck and happy coding 😎</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9f8f0836fabb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Multithreading vs. Asynchronous Programming in .Net Core]]></title>
            <link>https://simsekahmett.medium.com/multithreading-vs-asynchronous-programming-in-net-core-1f1380c4946f?source=rss-4b305aac112a------2</link>
            <guid isPermaLink="false">https://medium.com/p/1f1380c4946f</guid>
            <category><![CDATA[multithreading]]></category>
            <category><![CDATA[developer]]></category>
            <category><![CDATA[net-core]]></category>
            <category><![CDATA[asynchronous-programming]]></category>
            <dc:creator><![CDATA[Ahmet B. Simsek]]></dc:creator>
            <pubDate>Sun, 19 Feb 2023 17:53:45 GMT</pubDate>
            <atom:updated>2023-02-19T17:54:52.144Z</atom:updated>
            <content:encoded><![CDATA[<h3>Multithreading vs. Asynchronous Programming in .Net Core</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LWr0e_KObdaf4grHN9Fw3w.png" /></figure><p>In recent years, asynchronous programming has grown in popularity, particularly in.NET Core development. We will examine the distinctions between multithreading and asynchronous programming, as well as their advantages and disadvantages, in this blog post.</p><p>By executing many threads concurrently, multithreading enables concurrency in a software. The operating system schedules these threads, which all operate concurrently with one another. For managing tasks that are computationally demanding or I/O-bound, multithreading is an effective tool.</p><p>On the other side, asynchronous programming is a method for carrying out non-blocking I/O activities. The foundation of asynchronous programming is the callback idea, in which a function that handles I/O doesn’t block the thread that called it. Instead, the method releases the calling thread and executes a callback on a different thread after the task is finished.</p><p>Asynchronous programming is about concurrency, whereas multithreading is really about parallelism. Asynchronous programming does I/O operations without blocking, whereas multithreading runs several threads at once.</p><h4>Multithreading and Asynchronous Programming Pros and Cons</h4><p>There are various advantages to multithreading, including:</p><ul><li><strong>Improved performance:</strong><br>Multithreading can help speed up the execution of computationally intensive tasks.</li><li><strong>Improved responsiveness:</strong><br>Multithreading can help make the user interface more responsive, as long-running tasks are executed in the background.</li></ul><p>However, there are a number of disadvantages to multithreading, including:</p><ul><li><strong>Complexity: </strong><br>Multithreading adds complexity to a program, as threads need to be synchronized and coordinated to avoid race conditions and deadlocks.</li><li><strong>Resource usage: </strong><br>Multithreading can consume a significant amount of system resources, such as memory and CPU time.</li></ul><p>Also there are various advantages to asynchronous programming, including:</p><ul><li><strong>Improved scalability: </strong><br>Asynchronous programming allows a single thread to handle multiple I/O-bound operations, which can improve the scalability of a program.</li><li><strong>Improved responsiveness: </strong><br>Asynchronous programming can make the user interface more responsive, as the calling thread is not blocked by I/O-bound operations.</li></ul><p>However, there are a number of disadvantages to asynchronous programming, including:</p><ul><li><strong>Complexity: </strong><br>Asynchronous programming can add complexity to a program, as it requires the use of callbacks and other asynchronous programming techniques.</li><li><strong>Debugging: </strong><br>Asynchronous programming can be more difficult to debug, as the execution of code is split across multiple threads.</li></ul><h4>When to Use Multithreading vs. Asynchronous Programming</h4><p>The best uses for multithreading are computationally demanding, <strong>parallelizable</strong> tasks. Multithreading is advantageous in processes like image processing and numerical simulations, for instance.</p><p>Making web requests, interacting with other services, and other I/O-bound operations like reading from and writing to files or databases are ideally suited for asynchronous programming. When I/O-bound actions are carried out in the background while the user interface remains responsive, asynchronous programming can increase a program’s responsiveness.</p><h4>Examples of Multithreading and Asynchronous Programming in .NET Core</h4><p>Let’s take a look at some examples of multithreading and asynchronous programming in .NET Core.</p><h4>Multithreading Example</h4><pre>using System;<br>using System.Threading;<br><br>class Program<br>{<br>    static void Main(string[] args)<br>    {<br>        Thread thread = new Thread(() =&gt; {<br>            // Perform a long-running task<br>            Thread.Sleep(1000);<br>            Console.WriteLine(&quot;Task complete&quot;);<br>        });<br>        thread.Start();<br>        Console.WriteLine(&quot;Thread started&quot;);<br>    }<br>}</pre><p>In this example, we create a new thread and start it. The thread performs a long-running task (in this case; sleeping for one second) and then outputs a message.</p><h4>Asynchronous Programming Example</h4><pre>using System;<br>using System.Net.Http;<br>using System.Threading.Tasks;<br><br>class Program<br>{<br>    static async Task Main(string[] args)<br>    {<br>        HttpClient client = new HttpClient();<br>        HttpResponseMessage response = await client.GetAsync(&quot;https://www.example.com&quot;);<br>        string content = await response.Content.ReadAsStringAsync();<br>        Console.WriteLine(content);<br>    }<br>}</pre><p>In this example, we create an instance of the HttpClient class and use it to make a web request to <em>https://www.example.com</em>. The <strong>GetAsync</strong> method returns a <strong>Task&lt;HttpResponseMessage&gt;</strong> that represents the asynchronous operation of making the request. We use the await keyword to wait for the operation to complete and get the <strong>HttpResponseMessage</strong> object.</p><p>Next, we use the ReadAsStringAsync method to read the content of the response as a string. Again, this method returns a Task&lt;string&gt; that represents the asynchronous operation of reading the response content. We use the await keyword to wait for the operation to complete and get the content as a string.</p><p>Finally, we output the content of the response to the console.</p><p>By using asynchronous programming, we can make a web request without blocking the calling thread. The await keyword allows the calling thread to continue executing other tasks, such as updating the user interface or handling user input.</p><h4>Conclusion</h4><p>Asynchronous programming and multithreading are effective methods for attaining concurrency in.NET Core development. <strong>Asynchronous programming</strong> is better suited for I/O-bound jobs than <strong>multithreading</strong> is for computationally heavy tasks. The best technique for the job must be chosen because both offer advantages and disadvantages. I hope this article has clarified the distinctions between <strong>asynchronous programming</strong> and <strong>multithreading</strong> as well as when to use each.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1f1380c4946f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SOLID Principles: The Secret to Crafting Robust and Future-Proof Software]]></title>
            <link>https://simsekahmett.medium.com/solid-principles-the-secret-to-crafting-robust-and-future-proof-software-cbae40609223?source=rss-4b305aac112a------2</link>
            <guid isPermaLink="false">https://medium.com/p/cbae40609223</guid>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[solid]]></category>
            <category><![CDATA[beginner]]></category>
            <dc:creator><![CDATA[Ahmet B. Simsek]]></dc:creator>
            <pubDate>Mon, 13 Feb 2023 13:12:56 GMT</pubDate>
            <atom:updated>2023-02-13T15:01:52.331Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X0D1rChby_Wu7OxvAeFhPg.png" /><figcaption>SOLID principles in Software Development field</figcaption></figure><p>I am pretty sure whoever reads this article heard “<strong>SOLID</strong>” at least one time in their life. It is an acrostic of 5 set of rules which should known to have a robust and future-proof software.</p><p>Let’s dive into SOLID Principles a little bit more 👇</p><p><strong>SOLID </strong>is a collection of five design guidelines that aid programmers in producing software that is simple to update and maintain over time. These guidelines help teams build and add new features to existing software systems without having to worry about unintended consequences or breaking existing functionality. Software developers all over the world have largely adopted the <strong>SOLID </strong>principles, which offer recommendations for writing clear, maintainable, and scalable code.</p><p>To put it simply; <strong>SOLID</strong> principles work to make sure that software systems are well-organized, simple to comprehend and less prone to errors and bugs.</p><p>As i said in my introduction, SOLID is an acrostic term;</p><p>Single Responsibility Principle (SRP):<br>A class should have just one job, which means it should have just one reason to change.</p><p>Open/Closed Principle (OCP):<br>Classes, modules, functions, and other software entities should be open to extension but closed to modification.</p><p>Liskov Substitution Principle (LSP):<br>A superclass’s objects should be interchangeable with a subclass’s objects without affecting the program’s correctness.</p><p>Interface Segregation Principle (ISP):<br>The dependence of clients on interfaces that they do not use should not be enforced.</p><p>Dependency Inversion Principle (DIP):<br>Low-level modules shouldn’t be a dependency of high-level modules. Both need to be based on abstractions.</p><h4>Single Responsibility Principle (SRP)</h4><p>Consider having a teacher who is in charge of several subjects. You must substitute teachers if the teacher’s position changes, such as if they begin teaching a new subject. However, if the teacher only covered a single subject, you would only need to have them replaced if that particular subject changed. Similar to how a computer program should only perform one task, any additional tasks should be written as separate programs.</p><p>C# Example;</p><pre>public class User<br>{<br>    public int UserId { get; set; }<br>    public string FirstName { get; set; }<br>    public string LastName { get; set; }<br>    public string Email { get; set; }<br><br>    public void UpdateUser(string firstName, string lastName, string email)<br>    {<br>        this.FirstName = firstName;<br>        this.LastName = lastName;<br>        this.Email = email;<br>    }<br>}<br><br>public class UserValidator<br>{<br>    public bool ValidateUser(User user)<br>    {<br>        // Validation logic<br>        return true;<br>    }<br>}</pre><p>In this example, the User class has only one responsibility, which is to store information about a user. The UserValidator class has the responsibility of validating a user. This separation of responsibilities makes it easier to maintain and test the code.</p><h4>Open/Closed Principle (OCP)</h4><p>Imagine a Lego block. A lego block cannot be altered after it has been created; however, you can add blocks to it to make it larger. Similar to how a computer program should be created, it should allow for future additions without requiring changes to the original code.</p><p>C# Example;</p><pre>public class Rectangle<br>{<br>    public virtual int Width { get; set; }<br>    public virtual int Height { get; set; }<br><br>    public int Area()<br>    {<br>        return Width * Height;<br>    }<br>}<br><br>public class Square : Rectangle<br>{<br>    private int _side;<br><br>    public override int Width<br>    {<br>        get { return _side; }<br>        set { _side = value; }<br>    }<br><br>    public override int Height<br>    {<br>        get { return _side; }<br>        set { _side = value; }<br>    }<br>}<br><br>public class AreaCalculator<br>{<br>    public int CalculateArea(Rectangle[] shapes)<br>    {<br>        int area = 0;<br>        foreach (var shape in shapes)<br>        {<br>            area += shape.Area();<br>        }<br>        return area;<br>    }<br>}</pre><p>In this example, the Rectangle class can be extended to create new shapes, such as Square, without changing the original code. The AreaCalculator class can be used to calculate the area of an array of shapes, regardless of the specific type of shape.</p><h4>Liskov Substitution Principle (LSP)</h4><p>Think of a light bulb that you can insert into a lamp. If you purchase a different light bulb, it ought to function just as well as the original light bulb as long as it fits into the lamp. A computer program should be created in a similar manner, allowing you to swap out any component as long as the new component continues to function in the same manner as the original.</p><p>C# Example;</p><pre>public interface IShape<br>{<br>    int Area();<br>}<br><br>public class Rectangle : IShape<br>{<br>    public int Width { get; set; }<br>    public int Height { get; set; }<br><br>    public int Area()<br>    {<br>        return Width * Height;<br>    }<br>}<br><br>public class Square : IShape<br>{<br>    public int SideLength { get; set; }<br><br>    public int Area()<br>    {<br>        return SideLength * SideLength;<br>    }<br>}<br><br>public class AreaCalculator<br>{<br>    public int CalculateArea(IShape[] shapes)<br>    {<br>        int area = 0;<br>        foreach (var shape in shapes)<br>        {<br>            area += shape.Area();<br>        }<br>        return area;<br>    }<br>}</pre><p>In this example, the Rectangle and Square classes both implement the IShape interface, and the AreaCalculator class can calculate the area of an array of shapes, regardless of the specific type of shape. This allows us to substitute a derived class for a base class without affecting the correctness of the program, as long as the derived class follows the same contracts as the base class.</p><h4>Interface Segregation Principle (ISP)</h4><p>Think of a toolbox as having a wide variety of tools inside. Some tools you never use, while others you use frequently. It would be better if you could just keep your actual tools in a toolbox. Similar to how a computer program should be created so that you only use the features that you actually require.</p><p>C# Example;</p><pre>public interface IWorker<br>{<br>    void Work();<br>    void Eat();<br>}<br><br>public interface IWorkable<br>{<br>    void Work();<br>}<br><br>public interface IFeedable<br>{<br>    void Eat();<br>}<br><br>public class Worker : IWorkable, IFeedable<br>{<br>    public void Work()<br>    {<br>        // Work logic<br>    }<br><br>    public void Eat()<br>    {<br>        // Eat logic<br>    }<br>}<br><br>public class Robot : IWorkable<br>{<br>    public void Work()<br>    {<br>        // Work logic<br>    }<br>}</pre><p>In this example, the IWorker interface has methods for both working and eating. However, this can lead to classes implementing methods that they don&#39;t need. To solve this, the IWorker interface is separated into two smaller interfaces, IWorkable and IFeedable. Classes that only need to work, like the Robot class, can implement only the IWorkable interface.</p><h4>Dependency Inversion Principle (DIP)</h4><p>Consider you are constructing a home. Everything else is constructed on top of the foundation, which is the most crucial component of the house. The rest of the house will be strong if the foundation is sturdy. Similar to this, the most crucial sections of a computer program ought to be written first, and everything else ought to be built on top of them. In this manner, everything will continue to function even if you need to change just the essential components.</p><p>C# Example;</p><pre>public interface IRepository&lt;T&gt;<br>{<br>    T GetById(int id);<br>    void Save(T entity);<br>}<br><br>public class SqlRepository&lt;T&gt; : IRepository&lt;T&gt;<br>{<br>    public T GetById(int id)<br>    {<br>        // Get from database logic<br>        return default(T);<br>    }<br><br>    public void Save(T entity)<br>    {<br>        // Save to database logic<br>    }<br>}<br><br>public class Service&lt;T&gt;<br>{<br>    private readonly IRepository&lt;T&gt; _repository;<br><br>    public Service(IRepository&lt;T&gt; repository)<br>    {<br>        _repository = repository;<br>    }<br><br>    public T GetById(int id)<br>    {<br>        return _repository.GetById(id);<br>    }<br><br>    public void Save(T entity)<br>    {<br>        _repository.Save(entity);<br>    }<br>}</pre><p>In this example, the Service class depends on an abstraction, the IRepository interface, rather than a concrete implementation, such as the SqlRepository. This makes it easier to switch out the underlying repository implementation if needed, without affecting the Service class. The Service class also uses constructor injection to receive the repository implementation, making the dependency explicit and easier to manage.</p><p>In conclusion; the <strong>SOLID</strong> principles are an important part of software development, assisting programmers in building systems that are extensible, maintainable, and simple to change. By adhering to these guidelines, software systems can be created to avoid common pitfalls like rigid structures and tightly coupled code. I hope the examples in C# have been useful in helping you gain a better understanding of the <strong>SOLID </strong>principles by showing how they can be used in practical situations.</p><p>I hope that this article has been informative and helpful, and I encourage you to continue exploring and learning more about the wonderful world of software development. 🤗</p><p><em>With the power of SOLID principles, the sky truly is the limit for what we can create. 🌌</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cbae40609223" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unlock the Power of Unit Testing: A Beginner’s Guide to Quality Software Development]]></title>
            <link>https://simsekahmett.medium.com/unlock-the-power-of-unit-testing-a-beginners-guide-to-quality-software-development-78b8a766fcca?source=rss-4b305aac112a------2</link>
            <guid isPermaLink="false">https://medium.com/p/78b8a766fcca</guid>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[learning-and-development]]></category>
            <category><![CDATA[unit-test-framework]]></category>
            <category><![CDATA[nunit]]></category>
            <dc:creator><![CDATA[Ahmet B. Simsek]]></dc:creator>
            <pubDate>Mon, 30 Jan 2023 18:13:43 GMT</pubDate>
            <atom:updated>2023-01-30T18:28:28.316Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ln5ivvzEaIHyRiYz6zgazA.png" /></figure><p>👋Greetings and welcome to in-depth manual on unit testing in software development 🎉 We’ll be diving deep into the world of unit testing in this article, learning what it is, why it’s crucial, and how it can help ensure the quality and dependability of your software.</p><p>Unit testing is a technique for checking that individual software parts function as intended. Before software is made available to the general public, it can be tested for dependability and quality.</p><p>Consider unit testing as a form of factory quality control. A product must pass thorough testing before it is released into the market. Any issues can be resolved before the product is delivered to the customer. Software development utilizes the same idea.</p><p>Unit testing makes it simpler and more affordable to make changes by assisting developers in identifying and fixing bugs early in the development process. It also acts as a backup plan for future modifications, giving programmers the assurance they need to add new features without affecting those already in place.</p><h4>Unit Testing In Details</h4><p>The smallest testable component of an application, such as a function or method, is referred to as a unit in software development. The process of unit testing includes creating and running tests for these independent units. The tests examine the behavior of the unit being tested and confirm that it complies with the given requirements.</p><p>Every time the code is modified, unit tests are typically automated and run to make sure no new bugs or functional issues are introduced. The tests should run quickly, produce consistent, repeatable results, and be simple and quick to run.</p><p>Unit tests are a critical element of an <strong>Agile software development process</strong> because they can find issues early in the cycle, when fixing them is less expensive. By requiring developers to think critically about how their code should behave and how it will be used, writing and maintaining unit tests can also help improve the design and quality of the code.</p><h4>Why Do Developers Need Unit Tests?</h4><ul><li><strong>Early bug detection: </strong>Unit tests assist in the early detection of bugs, which makes their correction simpler and less expensive.</li><li><strong>Faster and easier code refactoring: </strong>When making changes to code, unit tests act as a safety channel, making refactoring or other changes simpler and less risky.</li><li><strong>Improved code quality: </strong>Writing unit tests helps developers to write cleaner, more maintainable code, which helps them think critically about the behavior of their code and can enhance code quality.</li><li><strong>Better documentation: </strong>Unit tests can act as a kind of code documentation, making it simpler for other developers to comprehend how the code operates and what it does.</li><li><strong>Increased confidence in code: </strong>Unit tests give programmers a high level of assurance that their code is functioning as intended, lowering the risk of bugs and other issues in production environments.</li></ul><h4>Unit Testing Tips &amp; Tricks</h4><ul><li><strong>Write tests first: </strong>Before writing any code, write some tests to help you think through the behavior of the code and make sure it can be tested.</li><li><strong>Test both positive and negative scenarios:</strong> Test both scenarios, including edge cases and error conditions, for a unit.</li><li><strong>Keep tests simple and focused: </strong>Tests should be straightforward and concentrated on a single functional component. Complex tests can be more challenging to maintain and less successful at finding bugs.</li><li><strong>Avoid testing implementation details: </strong>Tests should examine how the code behaves, not how it was implemented. Tests ought to pass even if the implementation is altered.</li><li><strong>Automate tests: </strong>Automate tests as much as you can to make it simpler to run tests frequently and make sure they are reliable and consistent.</li><li><strong>Make tests run quickly: </strong>Tests should run quickly so that developers can run them frequently and receive quick feedback on their code.</li><li><strong>Isolate tests: </strong>Test isolation is important to ensure that changes to one test do not have an impact on the outcomes of other tests.</li><li><strong>Maintain tests: </strong>As the code changes, keep the tests current. Also, make sure to delete tests that are no longer required.</li><li><strong>Use appropriate testing frameworks</strong>: Use testing frameworks that are well-suited for unit testing, such as <strong>JUnit </strong>for Java or <strong>pytest </strong>for Python, <strong>NUnit </strong>for .Net.</li></ul><h4>Most Known Unit Test Frameworks</h4><p>Here are some of the most popular unit testing frameworks:</p><pre>JUnit: A popular testing framework for Java applications.<br><br>NUnit: A testing framework for .NET applications, including C#.<br><br>xUnit: A testing framework for .NET applications, including C#.<br><br>pytest: A testing framework for Python applications.<br><br>RSpec: A testing framework for Ruby applications.<br><br>PHPUnit: A testing framework for PHP applications.<br><br>Mocha: A testing framework for JavaScript applications.</pre><p>These are some of the best-known and most frequently used frameworks for unit testing. The programming language and application you are using will let you chose the testing framework you need.</p><p>Since we’ll use C# .Net Core as sample project in this article, let’s have a look at pros &amp; cons of <strong>NUnit </strong>and <strong>xUnit </strong>testing frameworks 👇</p><h4>💠NUnit</h4><pre>Pros:<br><br>Open source: NUnit is open source, so it is free to use and can be <br>easily modified and customized to meet the needs of your project.<br><br>Large community: NUnit has a large community of users, so there is a lot <br>of help and support available, including forums, tutorials, and plugins.<br><br>Extensive functionality: NUnit has extensive functionality, including <br>advanced features for testing, such as data-driven testing and code <br>generation.<br><br><br>Cons:<br><br>Steep learning curve: NUnit has a steep learning curve for new users, as <br>it has a lot of features and options.<br><br>Integration with Visual Studio: Integration with Visual Studio can be <br>difficult, as NUnit is not built into Visual Studio and requires <br>additional setup.</pre><h4>💠xUnit</h4><pre>Pros:<br><br>Open source: xUnit is open source, so it is free to use and can be easily <br>modified and customized to meet the needs of your project.<br><br>Clean and simple: xUnit has a clean and simple design, making it easy to <br>use and understand for new users.<br><br>Extensive functionality: xUnit has a wide range of capabilities, including <br>sophisticated testing tools like data-driven testing and code generation.<br><br><br>Cons:<br><br>Steep learning curve: xUnit has a steep learning curve for new users, as <br>it has a lot of features and options.<br><br>Integration with Visual Studio: Integration with Visual Studio can be <br>difficult, as xUnit is not built into Visual Studio and requires <br>additional setup.</pre><p>As you can see; their pros &amp; cons are nearly same, so it is up to you which one to go with when it comes to making a decision about NUnit and xUnit.</p><p>In this article, we’ll use NUnit in our sample project.</p><h4>Let’s create a sample Web API unit test with using <strong>NUnit </strong>from scratch for a .Net Core API Project</h4><ol><li>Open Visual Studio and create a new <strong>ASP.NET Core Web API </strong>project.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZMZ8h3FBbjYl-bRPl5lI7Q.png" /><figcaption>Screenshot from Visual Studio new project creation window</figcaption></figure><p>2. In the Solution Explorer, right-click on the project and select “<strong>Manage NuGet Packages</strong>”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/735/1*rc2vHSVJbeUKGpV_rU7d2A.png" /><figcaption>Screenshot from Visual Studio project context menu in Solution Explorer window</figcaption></figure><p>3. From the NuGet Package Manager, install following packages;</p><ul><li><a href="https://www.nuget.org/packages/Microsoft.NET.Test.SDK"><strong>Microsoft.NET.Test.Sdk</strong></a></li><li><a href="https://www.nuget.org/packages/NUnit"><strong>NUnit</strong></a></li><li><a href="https://www.nuget.org/packages/NUnit3TestAdapter"><strong>NUnit3TestAdapter</strong></a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p5ZDbiADj84qTX25C0CYww.png" /><figcaption>Screenshot from Visual Studio Nuget Package Manager window’s installed tab</figcaption></figure><p>4. In your project, add a new controller and name it “<strong>MediumSampleAPIController</strong>”. With simple <em>Get()</em> method, we’ll just return a string from our controller.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FCYDbujNwecXEkVL1ia5Pw.png" /><figcaption>Screenshot from Visual Studio showing our new API controller “MediumSampleAPI” with it’s Get method codes</figcaption></figure><p>5. Add a new class and name it as “<strong>MediumSampleAPITests</strong>” which will include our sample API controller’s tests.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/477/1*j9os27EAOF62KIJeyLVszA.png" /><figcaption>Screenshot from Visual Studio Solution Explorer showing new created class called “MediumSampleAPITests”</figcaption></figure><p>6. Let’s add our test method into “MediumSampleAPITests” class</p><pre>[TestFixture]<br>public class MediumSampleAPITests<br>{<br>    [Test]<br>    public async Task TestGetMethod()<br>    {<br>        // Arrange<br>        var controller = new MediumSampleAPIController();<br><br>        // Act<br>        var result = controller.Get();<br><br>        // Expected result string<br>        string expected = &quot;Hello World, this is Medium article Sample API project.&quot;;<br><br>        // Assert<br>        Assert.IsNotNull(result);<br>        Assert.AreEqual(expected, result.Value);<br>    }</pre><p>7. Now if you right click to “MediumSampleAPITests” class and click on “Run Tests” you’ll see Visual Studio’s “Test Explorer” window appears and your test will be executed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MtqhNZJBz8amA0Qwqz_hrQ.png" /><figcaption>Screenshot from Visual Studio Test Explorer</figcaption></figure><p>❗ Also you can use Visual Studio’s debugger to debug your tests by just clicking “Debug Tests” button as well;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8pZwUZ1EpoWk9dF03vocsA.gif" /><figcaption>Screen recording from debugging tests</figcaption></figure><p>👉And also if the “<strong>expected</strong>” does not meet with “<strong>actual</strong>”, your test will be failed ❌</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FcnU2jtBEYcWSDyhKtlg2A.png" /><figcaption>Screenshot from failed test</figcaption></figure><p>This is a basic example of how to create an NUnit unit test for a simple API in a controller with C#. You can find more information and resources on the <a href="https://nunit.org/">NUnit websit</a>e and in the <a href="https://docs.nunit.org/">NUnit documentation</a>.</p><h4>Let’s dive into our test code 👇</h4><pre>[Test]<br>public async Task TestGetMethod()<br>{<br>    // Arrange<br>    var controller = new MediumSampleAPIController();<br><br>    // Act<br>    var result = controller.Get();<br><br>    // Expected result string<br>    string expected = &quot;This is expected&quot;;<br><br>    // Assert<br>    Assert.IsNotNull(result);<br>    Assert.AreEqual(expected, result.Value);<br>}</pre><pre>[Test]<br>The [Test] attribute is a marker for NUnit indicating that the <br>following method is a unit test.<br><br>public async Task TestGetMethod()<br>This line defines the method TestGetMethod as a public asynchronous task. <br>Asynchronous tasks are used in C# to perform work that may take a long <br>time to complete, without blocking the execution of the rest of the <br>program.<br><br>// Arrange<br>var controller = new MediumSampleAPIController();<br>The Arrange section is used to prepare the objects and variables that <br>will be used in the test. Here, a new instance of the <br>MediumSampleAPIController class is created and assigned to the <br>controller variable.<br><br>// Act<br>var result = controller.Get();<br>The Act section is where the actual work of the test is performed. <br>In this case, the Get method of the controller object is called and <br>the result is stored in the result variable.<br><br>// Expected result string<br>string expected = &quot;This is expected&quot;;<br>Here, a string variable named expected is declared and initialized with <br>the value &quot;This is expected&quot;. This variable will be used to compare the <br>actual result of the test to what is expected.<br><br>// Assert<br>Assert.IsNotNull(result);<br>Assert.AreEqual(expected, result.Value);<br>The Assert section is where the test&#39;s results are verified. The first <br>line Assert.IsNotNull(result), checks that the result variable is not <br>null, indicating that the Get method returned a value. The second line, <br>Assert.AreEqual(expected, result.Value), compares the expected string to <br>the Value property of the result object, making sure that they are equal. <br>If they are equal, the test will pass. If not, the test will fail and an <br>error message will be generated indicating why the test failed.</pre><h4>Common Assertion Methods in NUnit</h4><pre>Assert.IsTrue(condition) - Verifies that the condition is true.<br><br>Assert.IsFalse(condition) - Verifies that the condition is false.<br><br>Assert.AreEqual(expected, actual) - Verifies that two values are equal.<br><br>Assert.AreNotEqual(expected, actual) - Verifies that two values are not equal.<br><br>Assert.IsNull(value) - Verifies that a value is null.<br><br>Assert.IsNotNull(value) - Verifies that a value is not null.<br><br>Assert.IsInstanceOf(expectedType, value) - Verifies that a value is of the <br>expected type.<br><br>Assert.Throws(expectedExceptionType, delegate) - Verifies that a delegate <br>throws an exception of the specified type.<br><br>Assert.That(expression, constraint) - Verifies that an expression matches <br>a specified constraint.<br><br>CollectionAssert.AreEqual(expected, actual) - Verifies that two collections <br>contain the same elements in the same order.</pre><p>Here are some examples of NUnit assertions 👇</p><p><strong>Example 1:</strong> Asserting that a condition is true:</p><pre>int a = 5;<br>int b = 3;<br>Assert.IsTrue(a &gt; b);</pre><p><strong>Example 2: </strong>Asserting that two values are equal:</p><pre>string expected = &quot;Hello World&quot;;<br>string actual = &quot;Hello World&quot;;<br>Assert.AreEqual(expected, actual);</pre><p><strong>Example 3:</strong> Asserting that a value is not null:</p><pre>object value = new object();<br>Assert.IsNotNull(value);</pre><p><strong>Example 4:</strong> Asserting that a value is of the expected type:</p><pre>object value = &quot;Hello World&quot;;<br>Assert.IsInstanceOf(typeof(string), value);</pre><p><strong>Example 5:</strong> Asserting that a delegate throws an exception:</p><pre>int a = 0;<br>int b = 0;<br>Assert.Throws(typeof(DivideByZeroException), delegate { int c = a / b; });</pre><p><strong>Example 6:</strong> Asserting that an expression matches a constraint:</p><pre>int[] values = { 1, 2, 3, 4, 5 };<br>Assert.That(values, Has.Length.EqualTo(5));</pre><p>These are just a few types of assertions that NUnit supports. The<a href="https://docs.nunit.org/"> NUnit documentation</a> contains more details and examples.</p><p>Thank you for taking the time to read the article about Unit Testing. 🤗 I hope this article has helped you to understand Unit Test, it’s benefits, well-known unit test frameworks and NUnit with .NET Core Web API in real life scanario.</p><p>Please feel free to ask any more questions if you have any 👏</p><h4>Fun Fact 😄</h4><p><em>Why do software engineers love writing unit tests?<br></em><strong>Because it gives them a chance to catch their own mistakes before their boss does! 😂</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=78b8a766fcca" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dockerizing Your Applications: The Ultimate Solution for Cross-Platform Deployment]]></title>
            <link>https://simsekahmett.medium.com/dockerizing-your-applications-the-ultimate-solution-for-cross-platform-deployment-be5734260407?source=rss-4b305aac112a------2</link>
            <guid isPermaLink="false">https://medium.com/p/be5734260407</guid>
            <category><![CDATA[dockerfiles]]></category>
            <category><![CDATA[dockerizing]]></category>
            <category><![CDATA[dockerized-web-api]]></category>
            <category><![CDATA[learndocker]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Ahmet B. Simsek]]></dc:creator>
            <pubDate>Fri, 27 Jan 2023 16:05:57 GMT</pubDate>
            <atom:updated>2023-01-27T16:05:57.935Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z_b23RiXCzVNrhFQqGx0Pg.png" /><figcaption>Software codes inside of the various containers</figcaption></figure><p><strong>Docker </strong>is a tool that allows you to run applications in a consistent way, like a box, where all the necessary parts, settings and dependencies are included, so that you can run the same application in different places with the same outcome, for example, imagine you want to make a cake, but you want to make it in different places, instead of sharing the recipe and making sure that all ingredients and ovens are the same, you put all the ingredients and oven settings in a “Docker container” and now you can make the same cake with the same recipe and ingredients in any kitchen with the same result.</p><p>With little bit more technical words;<br>For developing, delivering and operating distributed applications, <strong>Docker </strong>is a powerful platform. It enables programmers to bundle an application together with all of its dependencies into a solitary, portable container that may work on any Linux or Windows based computer. This makes it simple to test and deploy apps across various contexts and removes the “it works on my computer ¯\_(ツ)_/¯ ” difficulties while working on code with coworkers. Additionally, by offering lightweight and isolated environments, Docker makes it simple to expand and manage applications and promotes resource efficiency.<br>In this article, we’ll talk about Docker’s fundamentals, the reasons we need it, possible substitutes, how to use it with a sample.NET Core project, the advantages of utilizing it with.NET Core and some performance statistics.</p><p>Let’s dive into <strong>Docker </strong>more 👇</p><ul><li><strong>What is Docker?</strong><br>Docker is a platform that makes it simple for developers to build, distribute and operate programs inside containers. Applications may operate reliably across several contexts, including on-premises, cloud, and hybrid environments, thanks to containers; which are small, portable and self-sufficient environments.</li><li><strong>Why do we need Docker?</strong><br>Docker is needed because it enables predictable, consistent settings for developing, testing and deploying applications. Additionally, it facilitates sharing and distribution of programs and the optimal use of resources by packaging applications and their dependencies.</li><li><strong>Does it affect performance in positive way?</strong><br>Docker makes it possible to use resources more effectively and helps speed up application starting. It can also cut down on the number of servers required for deployment, which can save money. Depending on the particular use case, it could add some overhead and impact an application’s overall performance.</li><li><strong>Is there any negative points for Dockerizing the software?<br></strong>A built-in monitoring and logging solution is not offered by Docker. To monitor and resolve problems in the containers, you will need to use third-party tools or develop your own solution. Additional security considerations are needed when operating containers in a production environment, including making sure the containers are configured correctly, the images are safe, and there are no known vulnerabilities.</li></ul><h4>Docker Basics and Commons</h4><ul><li><strong>Containers: </strong>A container is a compact, mobile, and independent environment that enables a program to function reliably in many settings. Because containers offer separation for the program and its dependencies, moving and running the application on various computers is simple.</li><li><strong>Images: </strong>An image serves as a container’s template. It has every file, setting, and dependency required for a program to function. A Dockerfile, a script containing instructions for creating the image, is used to generate an image.</li><li><strong>Docker Daemon:</strong> The Docker daemon is the background service that manages containers and images. The Docker CLI is used to interact with the Docker daemon.</li><li><strong>Docker Hub: </strong>For the purpose of storing and exchanging Docker images, the Docker hub serves as the primary repository. It may be used as both a private register for businesses and a public registry that is open to everyone. (<a href="https://hub.docker.com/">https://hub.docker.com</a>)</li><li><strong>Volumes: </strong>Data is preserved in containers using volumes. They make it possible to keep information outside of the container’s filesystem so that it can endure deletion of the container.</li><li><strong>Networks: </strong>With the help of Docker, virtual networks can be built and utilized to link containers to the host computer and one another. This enables host exposure of container ports and communication amongst containers.</li><li><strong>Compose: </strong>A tool for creating and operating multi-container applications is called Docker Compose. By specifying the services, networks and volumes in a single yaml file; it enables the development of complicated applications.</li><li><strong>Swarm: </strong>A tool for orchestrating the deployment and administration of containers is called Docker Swarm. It enables the development of a swarm, which is a collection of machines that collaborate to manage a number of services.</li><li><strong>Kubernetes: </strong>Kubernetes is an open-source container orchestration system. It is used to automatically deploy, scale, and manage containerized applications. To manage the containers operating on a cluster of machines, it may be used in combination with Docker.</li></ul><p>These are some of the fundamental ideas and details of Docker, which may be effectively and consistently utilized for developing, deploying, and maintaining containerized applications.</p><h4>Docker Images and Containers In Details</h4><p>A <strong>Docker image</strong> is a container’s key component. It has every file, setting, and dependency required for a program to function. A Dockerfile, a script containing instructions for creating the image, is used to generate an image. Once an image has been created, it may be saved, distributed, and used to build additional containers.</p><p>An image is made up of a series of layers. Every command in a Dockerfile adds a fresh layer to the image. Each layer serves as the foundation for the subsequent layer when a container is built from an image. This enables effective layer sharing between photos, which minimizes the size of the image and accelerates the creation of new containers.</p><p>A running instance of an image is what a <strong>Docker container</strong> is. A container is given its own own filesystem, process tree, and network interfaces when it is formed. As a result, the container may be separated from the host computer and from other containers, giving it a unique perspective on the system and preventing it from accessing host resources unless specifically permitted.</p><p>Each container has a distinct ID that is used to manage and identify it. Since containers are lightweight and portable, they may be launched, halted, and removed without having an impact on the host computer or other containers. They can also be transported across environments without requiring any modifications. This makes it simple to test and deploy apps in various settings.</p><p>Developing, testing, and deploying applications can be done consistently and effectively using Docker’s key ideas of containers and images.</p><h4>Docker CLI</h4><p>Using the command line, you may communicate with and control Docker using the Docker CLI (Command Line Interface). It enables a number of functions, including the creation and management of containers, pictures, networks and volumes.</p><p>Here are some common operations that can be performed using the Docker CLI;</p><pre>Pulling images from a registry: docker pull &lt;image&gt;<br>Running a container: docker run &lt;image&gt;<br>Listing running containers: docker ps<br>Stopping a container: docker stop &lt;container-id&gt;<br>Removing a container: docker rm &lt;container-id&gt;<br>Building an image: docker build -t &lt;image-name&gt; .<br>Pushing an image to a registry: docker push &lt;image&gt;<br>Inspecting a container&#39;s configuration: docker inspect &lt;container-id&gt;</pre><p>Docker CLI also provides a set of commands for managing networks and volumes like creating, listing and removing them;</p><pre>Create a new network: docker network create &lt;network-name&gt;<br>List all networks: docker network ls<br>Inspect a network: docker network inspect &lt;network-name&gt;<br>Remove a network: docker network rm &lt;network-name&gt;<br>Connect container to a network: docker network connect &lt;network-name&gt; &lt;container-id&gt;<br>Disconnect container from a network: docker network disconnect &lt;network-name&gt; &lt;container-id&gt;<br>Create a new volume: docker volume create &lt;volume-name&gt;<br>List all volumes: docker volume ls<br>Inspect a volume: docker volume inspect &lt;volume-name&gt;<br>Remove a volume: docker volume rm &lt;volume-name&gt;<br>Mount a volume to a container: docker run -v &lt;volume-name&gt;:/&lt;container-path&gt; &lt;image&gt;<br>Unmount a volume from a container: docker volume rm $(docker volume ls -qf dangling=true)</pre><p>In order to manage containers and images, some individuals also choose to utilize a GUI tool. Docker Desktop is an official desktop application for Docker, and it may make some jobs simpler.</p><p>Docker Desktop can be downloaded from Docker’s official web page;<br><a href="https://www.docker.com/products/docker-desktop/">https://www.docker.com/products/docker-desktop</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KdbGIdvJeNEAe-_lJjpe_w.png" /><figcaption>Screenshot for Docker Desktop application</figcaption></figure><p>Here is a sample of a simple Docker-based Net Core Web API project 👇</p><p>First, lets start with creating the Net Core Web API project;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y_nUbTlgc0eeniMty-CyaA.png" /><figcaption>Screenshot from Visual Studio’s new project creation screen</figcaption></figure><p>Then, lets define the project name and solution path (<em>i named project as “DockerizedSampleApp” for this example</em>);</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zvSzWEbRZLUgqwcJxijMTQ.png" /><figcaption>Screenshot from Visual Studio’s new project name and path configuration screen</figcaption></figure><p>Now this is the important part which will create “Dockerfile” for our sample project when you check “Enable Docker” checkbox;<em> (i used Linux as Docker OS which will be the base OS to run my application on)</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O7VfMq6hA2pSSZWWi7AHFA.png" /><figcaption>Screenshot from Visual Studio’s new project’s additional information configuration screen</figcaption></figure><p>When we achieve all of these steps successfuly, our sample project should be generated by Visual Studio with following files including “Dockerfile”;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/290/1*hW0D9BeDXgWanS2wo001Tw.png" /><figcaption>Screenshot from Visual Studio’s solution explorer window</figcaption></figure><p>Well done 👏 We’ve just created a sample Net Core Web API project with Docker support including our Dockerfile;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*THAO2WUDF_cvRKL2ONSGrQ.png" /><figcaption>Screenshot from dockerfile</figcaption></figure><p>Let’s have a look to that “Dockerfile” in details section by section👇</p><ul><li>Section 1:</li></ul><pre>FROM mcr.microsoft.com/dotnet/aspnet:7.0 AS base<br>WORKDIR /app<br>EXPOSE 80<br>EXPOSE 443<br><br><br><br>The first section, &quot;FROM mcr.microsoft.com/dotnet/aspnet:7.0 AS base&quot;, <br>specifies the base image that will be used for the Docker image. <br>This image is based on .NET Core 7.0 and is designed for ASP.NET web <br>applications. The &quot;AS base&quot; at the end of the line specifies that this <br>image will be referred to as &quot;base&quot; in the later sections of the Dockerfile<br><br>The next line, &quot;WORKDIR /app&quot;, sets the working directory for the <br>container to be &quot;/app&quot; folder.<br><br>The next two lines, &quot;EXPOSE 80&quot; and &quot;EXPOSE 443&quot;, tell Docker that the <br>container will listen on the specified network ports at runtime.</pre><ul><li>Section 2:</li></ul><pre>FROM mcr.microsoft.com/dotnet/sdk:7.0 AS build<br>WORKDIR /src<br>COPY [&quot;DockerizedSampleApp/DockerizedSampleApp.csproj&quot;, &quot;DockerizedSampleApp/&quot;]<br>RUN dotnet restore &quot;DockerizedSampleApp/DockerizedSampleApp.csproj&quot;<br>COPY . .<br>WORKDIR &quot;/src/DockerizedSampleApp&quot;<br>RUN dotnet build &quot;DockerizedSampleApp.csproj&quot; -c Release -o /app/build<br><br><br><br>&quot;FROM mcr.microsoft.com/dotnet/sdk:7.0 AS build&quot;, specifies a new image to <br>use as the build environment, using the SDK image for .NET Core 7.0. <br>It then copies the project file and runs the dotnet restore command to <br>restore the dependencies of the application.<br><br>&quot;WORKDIR /src&quot;, <br>&quot;COPY [&quot;DockerizedSampleApp/DockerizedSampleApp.csproj&quot;, &quot;DockerizedSampleApp/&quot;]&quot;, <br>&quot;RUN dotnet restore &quot;DockerizedSampleApp/DockerizedSampleApp.csproj&quot;&quot; <br>sets the working directory to /src, copies the project file and runs a <br>command to restore the dependencies of the project.<br><br>&quot;COPY . .&quot; copies all the files from build context to the /src directory <br>of the container,<br><br>&quot;WORKDIR &quot;/src/DockerizedSampleApp&quot;&quot;<br>&quot;RUN dotnet build &quot;DockerizedSampleApp.csproj&quot; -c Release -o /app/build&quot; <br>sets the working directory to /src/DockerizedSampleApp and runs a <br>command to build the application in release mode and output it to <br>the /app/build directory.</pre><ul><li>Section 3</li></ul><pre>FROM build AS publish<br>RUN dotnet publish &quot;DockerizedSampleApp.csproj&quot; -c Release -o /app/publish /p:UseAppHost=false<br><br><br><br>&quot;FROM build AS publish&quot; uses the build image as the starting point and runs <br>the dotnet publish command to publish the application.<br><br>&quot;RUN dotnet publish &quot;DockerizedSampleApp.csproj&quot; -c Release -o /app/publish /p:UseAppHost=false&quot; <br>runs a command to publish the application in release mode and output it to <br>the /app/publish directory and set useapphost configuration to false.</pre><ul><li>Section 4</li></ul><pre>FROM base AS final<br>WORKDIR /app<br>COPY --from=publish /app/publish .<br>ENTRYPOINT [&quot;dotnet&quot;, &quot;DockerizedSampleApp.dll&quot;]<br><br><br><br>The final block, &quot;FROM base AS final&quot;, uses the base image as the <br>starting point and copies the published application from the previous <br>step and sets the entry point for the container to be the application&#39;s <br>DLL.<br><br>&quot;WORKDIR /app&quot; sets the working directory of the container to /app<br><br>&quot;COPY --from=publish /app/publish .&quot; copies the published files from <br>publish stage to the final image<br><br>The final line &quot;ENTRYPOINT [&quot;dotnet&quot;, &quot;DockerizedSampleApp.dll&quot;]&quot; sets the<br>entry point for the container to run the command <br>&quot;dotnet DockerizedSampleApp.dll&quot; when the container starts.</pre><h4>TL;DR</h4><p>As pseudo code form of all of the codes in the given “Dockerfile” is</p><pre>It starts by using the &quot;mcr.microsoft.com/dotnet/aspnet:7.0&quot; image as the <br>base image and sets the working directory to &quot;/app&quot;. It also exposes <br>ports 80 and 443.<br><br>Next, it uses the &quot;mcr.microsoft.com/dotnet/sdk:7.0&quot; image as the build <br>image, sets the working directory to &quot;/src&quot; and copies the project files.<br><br>Then it runs the command &quot;dotnet restore&quot; on the project file to restore <br>its dependencies<br><br>Next, it copies all the files and set the working directory to the project <br>folder<br><br>Then it runs the command &quot;dotnet build&quot; on the project file to build it <br>in release mode and output the result to the &quot;/app/build&quot; directory.<br><br>Next, it uses the &quot;build&quot; image as the publish image and runs the command <br>&quot;dotnet publish&quot; on the project file to publish it in release mode and <br>output the result to the &quot;/app/publish&quot; directory.<br><br>Finally, it uses the &quot;base&quot; image as the final image, sets the working <br>directory to &quot;/app&quot; and copies the published files from the previous stage <br>to the final image. It also sets the entrypoint command to run the <br>application using &quot;dotnet&quot; and providing the &quot;DockerizedSampleApp.dll&quot; <br>file as the command argument.</pre><p>Let’s run our application in Docker container and see the output;</p><p>In Visual Studio, it’s very simple such as just one click will execute your dockerfile and run it inside of the configured container;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/376/1*XOAxnKx7MdyrszbYcBNHlg.png" /><figcaption>Screenshot to run our application using Docker</figcaption></figure><p>And here is the magic;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NH8BgVXBq-_BJ9Cff7gOxA.png" /><figcaption>Screenshot from our application’s Swagger page which indicates it is running</figcaption></figure><p>Our application is running inside of our Docker container and can be reached from 32772 port.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y72k3WUmczdUIK00t887qA.png" /><figcaption>Screenshot from docker desktop showing our sample project’s container</figcaption></figure><p>Also from Docker Desktop application, you can see there is a container created with the name of our project and the status of that container which is “Running” in the screenshot. Also you can see the ports which makes you reach to your application inside the container.</p><h4>Real-world use cases for Docker;</h4><p><strong>1- Web Applications:</strong> Since Docker enables uniform and portable environments, it is frequently used to deploy web apps. This makes it simple to grow the application as necessary and to test and deploy apps in various contexts.</p><p><strong>2- Microservices: </strong>Docker can create tiny, narrowly focused containers that are simple to deploy and scale, making it a good fit for microservices design. This makes it simple to create and maintain complicated applications made up of several separate services.</p><p><strong>3- CI/CD:</strong> Docker may be used as a component of a pipeline for continuous integration and continuous deployment since it enables the construction of consistent build and test environments. This makes it simple to develop, test and deploy apps in an automated and repeatable manner.</p><p><strong>4- Cloud-Native Applications:</strong> Docker is frequently used to deploy cloud-native apps because it enables the production of portable, lightweight containers that are simple to set up in cloud settings.</p><p><strong>5- Database and Data Processing:</strong> In a containerized environment, Docker may be used to run databases and data processing programs. This makes it possible for resource segregation and simple application scaling.</p><p><strong>6- IoT:</strong> Docker may be used to deploy apps in IoT (internet of things) gadgets like the Raspberry Pi, enabling the usage of the same program on several gadgets and the simple updating of the application.</p><p><strong>7- Machine learning and Artificial Intelligence (AI):</strong> Since Docker enables the establishment of isolated environments in which the programs may function and guarantees that all requirements are satisfied, it can be used to deploy machine learning and AI applications.</p><h4>Docker explanation in simplest way;</h4><p>Docker is a tool that allows you to run applications in a consistent way, like a box, where all the necessary parts, settings and dependencies are included, so that you can run the same application in different places with the same outcome.</p><p>Imagine you want to make a cake, but you want to make it in different places, instead of sharing the recipe and making sure that all ingredients and ovens are the same, you put all the ingredients and oven settings in a “Docker container” and now you can make the same cake with the same recipe and ingredients in any kitchen with the same result.</p><p>I appreciate your interest in<strong> </strong>my article about<strong> Docker. </strong>Now that we’ve learned how to use Docker and its basic concepts including commands with a sample application example.</p><p>I hope you can put this knowledge to use in your projects. 🙏</p><p>Please feel free to ask any additional questions you may have. Good luck and;</p><p>Happy Dockerizings 🤗</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=be5734260407" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding and Using the ‘Unchecked’ Keyword in C#]]></title>
            <link>https://simsekahmett.medium.com/understanding-and-using-the-unchecked-keyword-in-c-e6489d6b73aa?source=rss-4b305aac112a------2</link>
            <guid isPermaLink="false">https://medium.com/p/e6489d6b73aa</guid>
            <category><![CDATA[unchecked-in-csharp]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[csharp-programming]]></category>
            <category><![CDATA[advanced-csharp]]></category>
            <category><![CDATA[c-sharp-language]]></category>
            <dc:creator><![CDATA[Ahmet B. Simsek]]></dc:creator>
            <pubDate>Fri, 20 Jan 2023 18:12:46 GMT</pubDate>
            <atom:updated>2023-01-20T18:12:46.842Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LCaEObXiH7U9kNzIX7uAPQ.png" /></figure><p>The “<strong>unchecked</strong>” keyword in C# is used to turn off overflow checking for integer operations within a block of code. This indicates that the program will not raise an exception and will instead carry on with the resulting value if an operation might cause an overflow or underflow.</p><p>Performance concerns and dealing with existing code that utilizes integer arithmetic when you know that overflow or underflow won’t happen are the main reasons to use the “<strong>unchecked</strong>” keyword. But if overflow or underflow does happen, it can result in unexpected behavior and issues, therefore it should be used with caution.</p><p>If an operation would produce an overflow or underflow (i.e: a value that is too large or small to be represented by the data type being used), the program would not raise an exception and would instead continue to run with the resulting value. This is the default behavior for integer operations in C#. This value is the outcome of truncation or wrap-around.</p><p>For instance, if we have the code below;</p><pre>int x = int.MaxValue; <br>x = x + 1;</pre><p>Here the value of <strong>x</strong> will be <strong>-2147483648</strong> instead of raising an exception.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/550/1*bkIF5zyMi-Hyjn9CDGCwhg.png" /><figcaption>Screenshot for the values in runtime for the code written above</figcaption></figure><p>To overcome this, C# provides the “<strong>checked</strong>” keyword, which can be used to specify that an operation or block of code should raise an exception if an overflow or underflow occurs.</p><pre>int x = int.MaxValue; <br>checked <br>{ <br>  x = x + 1; <br>}</pre><p>This will raise an exception of type <strong>System.OverflowException</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*hZqxdBXY6zrRizL-xWUbVg.png" /><figcaption>Screenshot for the System.OverflowException which has been raised for the code above</figcaption></figure><p>It’s important to note that you may explicitly turn off overflow checking within a block of code by using the “<strong>unchecked</strong>” keyword.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/411/1*S_sGolmvjsUv6odbHP_Fug.png" /><figcaption>Screehshot for the unchecked version of the code written above</figcaption></figure><p>In general, unless you have a special reason to anticipate and handle these circumstances, it’s advised to utilize “checked” blocks of code to prevent unexpected behavior and defects caused by integer overflow or underflow.</p><p>Let’s check it with another example;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TIYUYu41X-D9GydjjGDlnA.png" /><figcaption>Screenshot for another example for the “Unchecked” keyword usecase</figcaption></figure><pre>Console.WriteLine(unchecked(long.MaxValue + long.MaxValue));<br>Console.WriteLine(unchecked((ulong)(long.MaxValue + long.MaxValue)));<br>Console.WriteLine(ulong.MaxValue);</pre><p>The provided code is a C# program that publishes the results to the console after performing some arithmetic operations on the long and ulong data types’ maximum values using the “<strong>unchecked</strong>” keyword.</p><p>To explain the code written above;</p><pre>In the first line; <br>long.MaxValue + long.MaxValue <br>exceeds the maximum value that a long variable can represent, but <br>because of the unchecked keyword, the program won&#39;t throw an exception <br>if the result of the addition exceeds the maximum value that a long <br>variable can represent. Instead, a wrap-around will provide the outcome, <br>which in this case is -2.<br><br>In the second line;<br>long.MaxValue + long.MaxValue is exceeding the maximum value that can <br>be represented by a ulong variable, and then converting it to a ulong <br>variable. But because of the unchecked keyword, the program will not <br>raise an exception if the result of the addition exceeds the maximum <br>value that can be represented by a ulong variable. Instead, the result <br>will be the result of a wrap-around, which is 18446744073709551614 in <br>this case.<br><br>In the third line;<br>it just prints the maximum value that a ulong variable can store, <br>which is 18446744073709551615.</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dpyvTk9A0i0ygyuz0Oz_vg.png" /></figure><h4>TL;DR</h4><p>When using integer operations within a block of code in C#, overflow checking is turned off with the “unchecked” keyword.</p><h4>What is overflow in C# ?</h4><p>When an arithmetic operation returns a number that is either too large or too little to be represented by the data type being used, the condition is referred to as an overflow.</p><p>For instance;<br>if a variable is of type int and its maximum value is <strong>2,147,483,647</strong> and you add 1 to it, <br>it will cause an overflow because the result will be <strong>2,147,483,648</strong> which is too large to be represented by an int variable.</p><p>There is also underflow in C#.</p><h4>What is underflow in C# ?</h4><p>Similar to overflow, underflow happens when the operation’s result is too little to be represented by the data type.</p><p>When you remove 1 from an int variable whose minimum value is -2,147,483,648 <br>the result will be -2,147,483,649 <br>which is too tiny to be represented by an int variable and will result in an underflow.</p><h4>How C# handles overflow and underflow in runtime ?</h4><p>The C# language has a technique called as “<strong>wrap-around</strong>” to manage overflow and underflow in both situations. This implies that the program will carry on with the output value in the event of an overflow or underflow. It is advised to use the “checked” keyword to make sure that overflow and underflow are handled correctly and to prevent unexpected behavior because doing otherwise can result in problems and unexpected behavior.</p><p>I appreciate you taking the time to read the answers above and learn more about the “<strong>unchecked</strong>” and “<strong>checked</strong>” keyword in C#. <br>Programming in C# involves understanding how this keyword functions and when and why to use it, which may lead to more effective and reliable code. <br>Please don’t hesitate to reach me out if you have any further questions or if something is not obvious.</p><p>I want to thank you once again for reading and I hope you found the material to be useful 🤗</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e6489d6b73aa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Learning web development and JavaScript programming language]]></title>
            <link>https://simsekahmett.medium.com/learning-web-development-and-javascript-programming-language-526db7c03f8d?source=rss-4b305aac112a------2</link>
            <guid isPermaLink="false">https://medium.com/p/526db7c03f8d</guid>
            <category><![CDATA[learning-javascript]]></category>
            <category><![CDATA[how-to-learn-programming]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[learning-to-code]]></category>
            <category><![CDATA[javascript-development]]></category>
            <dc:creator><![CDATA[Ahmet B. Simsek]]></dc:creator>
            <pubDate>Sat, 14 Jan 2023 09:36:09 GMT</pubDate>
            <atom:updated>2023-01-14T09:50:19.457Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HQk734R2z7PS0guGIpSybg.png" /></figure><p>JavaScript is one of the most widely-used programming languages in the world, and is essential for creating dynamic and interactive web pages. Learning JavaScript is a useful ability that can lead to a variety of chances in the web development industry, whether you are a novice or an experienced developer. The fundamentals of JavaScript, the advantages of learning it, and some tools and advice to help you get started with studying this potent language are all covered in this article. We’ll also look at some of the popular frameworks and tools for JavaScript development and discuss how they might improve the effectiveness and efficiency of your development process. This post is for you whether you’re trying to create your first website or if you’re an experienced developer looking to learn JavaScript.</p><p>First let’s start from web development concept.</p><h4>What is web development ?</h4><p>The process of building and maintaining websites and web applications is known as web development. It includes a broad range of activities and technology, such as:</p><ul><li><strong>Front-end development:</strong> The process of developing a website’s or web application’s user interface and user experience. For the site to be dynamic and responsive, the visual layout and design must be created using languages like HTML, CSS, and JavaScript.</li><li><strong>Back-end development:</strong> The process of developing a website or online application’s server-side logic and functionality is known as back-end development. Working with programming languages like C#, Python, Ruby, and PHP is part of this.</li><li><strong>Database management: </strong>Creating, maintaining, and querying databases to store and retrieve data for a website or web application is known as database management. Working with solutions like MsSQL, MySQL, MongoDB, and SQLite is part of this.</li><li><strong>Web hosting: </strong>Making a website or web application accessible to internet users is known as web hosting. Server setup and web hosting services are included in this.</li><li><strong>Optimization:</strong> A website’s or web application’s performance can be improved through optimization. Using a Content Delivery Network (CDN), minifying code, and compressing pictures are some examples of how to do this.</li></ul><p>Web development is a constantly evolving field, and new technologies and best practices are always emerging. When working as a web developer, you might collaborate with other programmers to build complex web applications or work alone to make straightforward websites.</p><h4>What is Javascript ?</h4><p>Programming language JavaScript is primarily used to develop dynamic user interfaces and interactive front-end web applications. It is a scripting language that enables web designers to include dynamic elements like form validation, image sliders, and interactive maps on websites.</p><p>Because JavaScript is an event-driven language, it can react to user interactions as well as other events like page loads and clicks. Event listeners, functions that are called in response to particular events, are used to accomplish this.</p><p>JavaScript is also a single-threaded programming language, which means that it can only process one task at a time. But it makes use of a concurrency model called a “event loop” that enables non-blocking I/O operations. This implies that multiple tasks, such as user input and network requests, can be handled by JavaScript concurrently without the user interface becoming unresponsive.</p><p>Since JavaScript is a loosely typed language, variables do not always need to be declared with a particular data type and can store a variety of data at once. This has the potential to be both a benefit and a drawback because it increases coding flexibility while also making debugging more challenging.</p><p>JavaScript can also be used on the server-side using technologies like Node.js, which allows for full-stack JavaScript development. This means that the same language can be used for both the front-end and back-end of a web application, making it a popular choice for web developers.</p><p>JavaScript is a popular choice for creating web applications because it can be directly incorporated into HTML and CSS and run in the client’s web browser. Additionally, it is frequently combined with other web development tools like HTML, CSS and web frameworks like Angular or React.</p><p>In general, JavaScript is a strong and adaptable programming language that is frequently used to create dynamic, interactive web applications. It has a sizable and vibrant community as well as a broad selection of libraries and frameworks that make it simple to create sophisticated web applications.</p><h4>What are the benefits of learning JavaScript ?</h4><p>There are several benefits to learning JavaScript, such as:</p><ul><li><strong>High Demand</strong>: One of the most popular programming languages in use today, JavaScript is highly desired by employers. All of the main web browsers support this flexible language, which can be used for both front-end and back-end development.</li><li><strong>Flexibility:</strong> A wide variety of web applications, from straightforward static websites to intricate interactive ones, can be made using JavaScript. Additionally, it can be used to make desktop, mobile and browser extensions.</li><li><strong>Popularity:</strong> There are many resources available for learning JavaScript, troubleshooting issues and keeping up with new developments because there is a sizable and active community of developers.</li><li><strong>Job Opportunities:</strong> As a JavaScript developer, you can work in various fields such as web development, mobile app development and even machine learning or artificial intelligence.</li><li><strong>Better understanding of the web:</strong> Knowing JavaScript makes it easier to comprehend how the web, browsers and ways to interact with the web more effectively.</li></ul><p>JavaScript is a flexible, in-demand language with a variety of applications, so learning it can be a great investment for anyone looking to work in web development or any related field.</p><h4>How popular is JavaScript in development field ?</h4><p>JavaScript is one of the most widely-used programming languages in the world. According to the 2022 Stack Overflow Developer Survey, JavaScript is the most popular programming language, with more than 65% of developers reporting that they use it. <em>(Ref: </em><a href="https://survey.stackoverflow.co/2022/"><em>https://survey.stackoverflow.co/2022/</em></a><em>)</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IQvJ8omCxcYgdbSMp4yqsA.png" /><figcaption>Top 10 programming languages rated in the StackOverflow Developer Survey 2022</figcaption></figure><p>JavaScript is mainly used for front-end web development, but thanks to tools like Node.js, it can also be used for back-end web development. JavaScript has grown in popularity in web development thanks to the emergence of frameworks and libraries like React, Angular and Vue.js that allow programmers to create intricate and responsive web applications.</p><p>JavaScript consistently ranks in the top 10 of most popular programming languages, according to the TIOBE Index, which measures the popularity of programming languages based on the volume of search engine results.</p><p>The top 10 most popular programming languages in early 2023 are:<br> 1- Python (.py)<br> 2- C (.c)<br> 3- C++ (.cpp)<br> 4- Java (.java)<br> 5- C# (.cs)<br> 6- Visual Basic (.vb)<br> 7- <strong>JavaScript </strong>(.js)<br> 8- SQL (.sql)<br> 9- Assembly Language (.asm)<br> 10- PHP (.php)</p><p><em>*Note that the order of each language might vary based on the metrics used for measuring popularity. (Ref: </em><a href="https://www.tiobe.com/tiobe-index/"><em>https://www.tiobe.com/tiobe-index/</em></a><em>)</em></p><p>JavaScript is a flexible language for developing web applications that can be accessed by a variety of users because it is supported by all major web browsers.</p><p>In conclusion, JavaScript is one of the most well-liked and in-demand programming languages in the world. It has numerous uses in the creation of websites, mobile applications and more.</p><h4>Under which circumstances JavaScript is needed?</h4><p>JavaScript is primarily used for creating interactive front-end web applications and dynamic user interfaces. Some common use cases for JavaScript include:</p><ul><li><strong>Creating interactive forms</strong>: JavaScript can be used to create interactive forms, validate user input, run calculations, and give users immediate feedback.</li><li><strong>Creating dynamic user interfaces</strong>: A website can be made more interesting and interactive by adding animations, image sliders, and other dynamic effects using JavaScript.</li><li><strong>Creating single-page web applications:</strong> Web applications that dynamically update and change content without requiring a page refresh can be made using JavaScript.</li><li><strong>Accessing and manipulating the Document Object Model (DOM):</strong> JavaScript can be used to access and manipulate the elements of a web page, making it possible to create dynamic and interactive web pages.</li><li><strong>Making HTTP requests: </strong>A web page can retrieve or send data without refreshing by using JavaScript to make HTTP requests to a server.</li><li><strong>Creating browser extensions:</strong> JavaScript can be used to create browser extensions that can add new features and functionality to a web browser.</li><li><strong>Creating mobile apps: </strong>Mobile app development using JavaScript is possible by the frameworks like React Native, which enables developers to create mobile apps with using JavaScript.</li><li><strong>Creating desktop apps:</strong> JavaScript can be used to create desktop apps using technologies like Electron, which allows developers to build cross-platform desktop apps using web technologies.</li><li><strong>Machine learning: </strong>By using libraries like TensorFlow.js and Brain.js, JavaScript can be used to create machine learning models that can be run directly in the browser.</li></ul><h4>What are the resources to learn JavaScript ?</h4><p>There are many resources available for learning JavaScript, including online tutorials, video courses and books. Some popular options are:</p><ul><li><strong>Codecademy’s JavaScript course: </strong>An interactive, web-based course that covers the basics of JavaScript as well as more advanced topics. (<a href="https://www.codecademy.com/learn/paths/web-development">https://www.codecademy.com/learn/paths/web-development</a>)</li><li><strong>FreeCodeCamp’s JavaScript curriculum:</strong> A comprehensive, self-paced curriculum that covers JavaScript as well as other web development technologies. (<a href="https://www.freecodecamp.org/news/learn-JavaScript-full-course/">https://www.freecodecamp.org/news/learn-JavaScript-full-course/</a>)</li><li><strong>Eloquent JavaScript: </strong>A book by Marijn Haverbeke that covers the basics of JavaScript and can be read for free online. (<a href="https://eloquentjavascript.net/">https://eloquentJavaScript.net/</a>)</li><li><strong>JavaScript.info: </strong>A comprehensive resource that covers JavaScript from beginner to advanced level. (<a href="https://javascript.info/">https://JavaScript.info/</a>)</li><li><strong>MDN JavaScript Guide: </strong>Mozilla Developer Network (MDN) JavaScript Guide covers all aspects of JavaScript including the basics, working with the DOM and more advanced topics like functional and object-oriented programming. (<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript">https://developer.mozilla.org/en-US/docs/Web/JavaScript</a>)</li></ul><p>It’s also a good idea to practice writing JavaScript code by building small projects or working on exercises.</p><p>Additionally, you can find a mentor who can offer advice and respond to any questions you may have along the way, or you can join online communities.</p><h4>What is needed to know while learning JavaScript ?</h4><p>In order to become proficient in JavaScript, you will need to learn the basics of web development.</p><ul><li><strong>HTML (Hypertext Markup Language) and CSS (Cascading Style Sheets):</strong> A web page’s structure and design are created using these languages. While CSS is used to style the elements and produce an aesthetically pleasing layout, HTML defines the elements and their content, providing the page’s structure.</li><li><strong>The Document Object Model (DOM):</strong> The DOM, which is used by JavaScript to access and modify web page elements, is a representation of a web page in the form of a tree-like structure. For web pages to be dynamic and interactive, it is imperative to understand the DOM.</li><li><strong>Web developer tools:</strong> The majority of online browsers include built-in developer tools for inspecting and troubleshooting web pages. These tools can be quite beneficial for diagnosing issues and understanding how a web page is produced.</li><li><strong>Browser compatibility:</strong> JavaScript code may be displayed differently by different web browsers. It’s crucial to be aware of these variations and have the skills necessary to build code that is compatible with a variety of browsers.</li><li><strong>Libraries and frameworks:</strong> There are a lot of libraries and frameworks out there that can make development easier and offer more features and functionality. React, Angular, and Vue.js are some popular frameworks, whereas jQuery, Lodash, and Moment.js are some of the well-known libraries.</li><li><strong>Asynchronous programming:</strong> Despite being a single-threaded language, JavaScript uses a “event loop” to handle numerous processes at once. It’s important to understand how promises, async-await and callback functions work in JavaScript when dealing with asynchronous programming.</li><li><strong>Security:</strong> JavaScript is client-side programming, so it’s critical to know potential security issues and understand how to design secure code.</li></ul><p>Remember that learning JavaScript and web development is a continuous process, and new technologies and best practices are constantly being developed. As you develop your knowledge and skills, it’s critical to keep studying and exercising.</p><p>Let’s starts with the basics of web development then;</p><h4>What is HTML (Hypertext Markup Language) ?</h4><p>The standard language for building a web page’s structure and content is called HTML (Hypertext Markup Language). The headings, paragraphs, images, and links on a web page are all defined using tags and attributes in HTML. It provides the structure of the page by defining the elements and their content.</p><p>Here’s an example of a simple HTML document:</p><pre>&lt;!DOCTYPE html&gt;<br> &lt;html&gt;<br>   &lt;head&gt;<br>  &lt;title&gt;My Web Page&lt;/title&gt;<br>   &lt;/head&gt;<br>   &lt;body&gt;<br>  &lt;h1&gt;Welcome to my web page&lt;/h1&gt;<br>  &lt;p&gt;This is a simple web page created with HTML.&lt;/p&gt;<br>  &lt;img src=&quot;https://picsum.photos/100/100&quot; alt=&quot;Random Image&quot;&gt;<br>  &lt;a href=&quot;https://www.example.com&quot;&gt;Go to Example.com&lt;/a&gt;<br>   &lt;/body&gt;<br> &lt;/html&gt;</pre><p>This is a simple example of an HTML document that creates a web page with a heading, a paragraph, an image and a link. You can test the code with saving into a file with .html format (i.e: mypage.html) with using a text editor (i.e: notepad).</p><p>If you need to know much more details about the code above, here is the detailed description 👇</p><pre>The first line, &lt;!DOCTYPE html&gt;, is the document type declaration, which <br>tells the web browser that this is an HTML5 document.<br><br>The &lt;html&gt; tag indicates the start of an HTML document. All the content of <br>the HTML document should be placed between this tag and its closing <br>tag &lt;/html&gt;.<br><br>The &lt;head&gt; tag contains information about the document that is not <br>displayed on the web page, such as the title of the page, meta data and <br>links to stylesheets and scripts. Inside the head tag, there is the <br>&lt;title&gt; tag which contains the text that will be displayed on <br>the browser tab.<br><br>The &lt;body&gt; tag contains the content of the web page that will be displayed <br>in the browser window. Inside the body tag, there are several tags that <br>are used to create the structure and content of the web page:<br><br>The &lt;h1&gt; tag creates a heading, the text inside the tag will be displayed <br>as a heading on the web page.<br><br>The &lt;p&gt; tag creates a paragraph, the text inside the tag will be displayed <br>as a paragraph on the web page.<br><br>The &lt;img&gt; tag is used to embed an image in the web page, the src attribute <br>is used to specify the URL of the image file, the alt attribute is used <br>to provide alternative text for the image in case the image cannot be <br>displayed.<br><br>The &lt;a&gt; tag creates a hyperlink, the href attribute is used to specify <br>the URL of the link, the text inside the tag will be displayed as a <br>link on the web page.</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*13I7gQEWJMck23Bvw5vsxQ.png" /><figcaption>Output of the HTML code given as example</figcaption></figure><h4>What is CSS (Cascading Style Sheets) ?</h4><p>A web page’s design and layout can be added using the language known as CSS (Cascading Style Sheets). It enables you to manage how a web page’s visual elements such as color, typeface and spacing are displayed. A web page’s layout and design can be made aesthetically appealing using CSS.</p><p>Here’s an example of a simple CSS stylesheet 👇</p><pre>body {<br> background-color: #f0f0f0;<br> font-family: Arial, sans-serif;<br> }<br><br> h1 {<br>   color: blue;<br>   text-align: center;<br> }<br><br> p {<br>   font-size: 18px;<br>   line-height: 1.5;<br> }</pre><p>This CSS stylesheet will change the visual presentation of the elements on the web page, the background color of the page will be light gray, the text inside the h1 elements will be blue and centered, and the text inside the p elements will be 18px with 1.5 line height.</p><pre>The body selector targets the &lt;body&gt; element in the HTML document, and the <br>styles inside the curly braces {} are applied to it.<br><br>background-color: #f0f0f0; sets the background color of the body element <br>to a light gray color, it uses the hexadecimal color code to define <br>the color.<br><br>font-family: Arial, sans-serif; sets the font-family for the text inside <br>the body element to Arial, if Arial is not available it will use the <br>default sans-serif font.<br><br>The h1 selector targets all &lt;h1&gt; elements in the HTML document, and <br>the styles inside the curly braces {} are applied to them.<br><br>color: blue; sets the color of the text inside the h1 element to blue.<br><br>text-align: center; aligns the text inside the h1 element to the center.<br><br>The p selector targets all &lt;p&gt; elements in the HTML document, and the <br>styles inside the curly braces {} are applied to them.<br><br>font-size: 18px; sets the font size of the text inside the p element to <br>18 pixels.<br><br>line-height: 1.5; sets the line height of the text inside the p element <br>to 1.5 times the font size.</pre><p>Keep in mind that this is just a simple example, there are many other properties and selectors available in CSS that can be used to control the layout and design of a web page.</p><p>To apply the CSS styles to a HTML document by saving the CSS styles code into another file such as “style.css”,then you can link the CSS file (style.css) to the HTML file using a link tag in the head section of the HTML file.</p><pre>&lt;link rel=&quot;stylesheet&quot; type=&quot;text/css&quot; href=&quot;styles.css&quot;&gt;</pre><p>Or you can include the CSS styles directly inside the HTML file using &lt;style&gt; tag in the &lt;head&gt; section of the HTML file.</p><pre>&lt;!DOCTYPE html&gt;<br> &lt;html&gt;<br>   &lt;head&gt;<br>  &lt;title&gt;My Web Page&lt;/title&gt;<br>  &lt;style&gt;<br>    body {<br>   background-color: #f0f0f0;<br>   font-family: Arial, sans-serif;<br>    }<br>    h1 {<br>   color: blue;<br>   text-align: center;<br>    }<br>    p {<br>   font-size: 18px;<br>   line-height: 1.5;<br>    }<br>  &lt;/style&gt;<br>   &lt;/head&gt;<br>   &lt;body&gt;<br>  &lt;h1&gt;Welcome to my web page&lt;/h1&gt;<br>  &lt;p&gt;This is a simple web page created with HTML.&lt;/p&gt;<br>  &lt;img src=&quot;https://picsum.photos/100/100&quot; alt=&quot;Random Image&quot;&gt;<br>  &lt;a href=&quot;https://www.example.com&quot;&gt;Go to Example.com&lt;/a&gt;<br>   &lt;/body&gt;<br> &lt;/html&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zv_aTCESSHB31QBZRLqN4w.png" /><figcaption>Output of the HTML and CSS code given as example</figcaption></figure><p>Alright, i believe you have some idea about HTML and CSS which are the basics of web development. So now let’s start to talk much technical about JavaScript.</p><h4>What are the basics and commons of JavaScript ?</h4><p>It’s necessary to know the main basics and core JavaScript ideas when learning the language by followings:</p><ul><li><strong>Variables</strong>: Variables are used to store data in JavaScript. Variables are declared using the keyword “var”, “let” or “const” and can be assigned a value using the assignment operator =. The variable can be used to store any type of data, like strings, numbers, booleans, arrays and objects.</li><li><strong>Data types:</strong> JavaScript has several data types, such as strings, numbers, booleans and objects. Understanding these data types and how to work with them is important when writing JavaScript code.</li><li><strong>Operators:</strong> Operators are used to perform operations on variables and values. JavaScript has several types of operators including mathematical, comparison, logical and assignment operators.</li><li><strong>Conditional statements:</strong> Conditional statements are used to make decisions in JavaScript. The most common conditional statement is the if-else statement, which allows you to execute different code based on whether a certain condition is true or false.</li><li><strong>Loops: </strong>Loops are used to repeat a block of code a certain number of times. JavaScript has two types of loops: for and while loops.</li><li><strong>Functions:</strong> Functions are reusable blocks of code that can be executed multiple times. Functions are defined using the keyword “function” and can accept parameters and return a value.</li><li><strong>Arrays: </strong>Arrays are used to store lists of data. JavaScript arrays are a type of object and can hold multiple values of any data type.</li><li><strong>Objects: </strong>Objects are used to store collections of data. JavaScript objects are a type of data structure that can store multiple properties, which are similar to variables, and methods, which are similar to functions.</li><li><strong>Events:</strong> Events are actions that can be detected by JavaScript, such as a button click, a page load, or a form submission. Event listeners can be added to elements to execute a function when a specific event occurs.</li><li><strong>DOM: </strong>The Document Object Model (DOM) is a representation of a web page in the form of a tree-like structure, and it is used by JavaScript to access and manipulate the elements of a web page. Understanding the DOM is essential for creating dynamic and interactive web pages.</li></ul><p>Here’s an example of JavaScript code that demonstrates some of the common and basic concepts I mentioned above 👆:</p><pre>// Declare a variable and assign a string value<br> let message = &quot;Hello World!&quot;;<br><br> // Declare a variable and assign a number value<br> let num1 = 10;<br> let num2 = 20;<br><br> // Use mathematical operators to perform calculations<br> let result = num1 + num2;<br> console.log(result); // Output: 30<br><br> // Use comparison operators to compare values<br> if (num1 &gt; num2) {<br>    console.log(num1 + &quot; is greater than &quot; + num2);<br> } else {<br>    console.log(num2 + &quot; is greater than &quot; + num1);<br> }<br> // Output: 20 is greater than 10<br><br> // Use a loop to iterate through an array<br> let numbers = [1, 2, 3, 4, 5];<br> for (let i = 0; i &lt; numbers.length; i++) {<br>  console.log(numbers[i]);<br> }<br> // Output: 1 2 3 4 5<br><br> // Define a function and call it<br> function greet() {<br>  console.log(message);<br> }<br> greet(); // Output: &quot;Hello World!&quot;<br><br> // Create an object<br> let person = {<br>  name: &quot;John Doe&quot;,<br>  age: 30,<br>  speak: function() {<br>   console.log(&quot;My name is &quot; + this.name + &quot; and I am &quot; + this.age <br>               + &quot; years old.&quot;);<br>  }<br> };<br> console.log(person.name); // Output: &quot;John&quot;<br> console.log(person.age); // Output: 30<br> person.speak(); // Output: &quot;My name is John and I am 30 years old.&quot;</pre><p>In this code; we first defined some variables, then we did some calculation and comparison using mathematical and comparison operators, then we iterated through an array using a for loop, defined a function and called it, then we created an object called person with properties and methods, then we accessed the properties and called the method using the dot notation ‘.’</p><p>The majority of the fundamental and widely used JavaScript concepts are covered, including variables, data types, operators, conditional statements, loops, functions, arrays, objects, properties, and methods, events, and DOM manipulation. This code also has comments that describe what each section of the code does, making it simple for someone who is not familiar with JavaScript to understand.</p><p>❗ <em>Remember that JavaScript offers a lot more to study and explore; this is merely a basic example.</em></p><h4>A brief explanation for Document Object Model (DOM)</h4><p>The Document Object Model (DOM) is a programming interface for HTML and XML documents. It represents the structure of a document in a tree-like format, with each element, attribute, and piece of text in the document being represented as an object. The DOM allows you to programmatically access and manipulate the contents of a document, such as adding, modifying, or deleting elements, changing the styles of elements or responding to user events.</p><p>The DOM is used by JavaScript to access and manipulate the elements of a web page, allowing you to create dynamic and interactive web pages. For example, you can use the DOM to change the text inside an element, change the styles of an element, or add a new element to the page.</p><p>When a web page is loaded by a browser, the browser creates a DOM of the page, and you can use JavaScript to access and manipulate the elements of the DOM. The DOM is a standard that is supported by all major web browsers and allows for consistent access to the elements of a web page, regardless of the browser being used.</p><p>In a nutshell; the DOM is a programming interface that allows you to access and manipulate the contents of an HTML or XML document and it’s the foundation for creating dynamic and interactive web pages using JavaScript.</p><h4>What are the web developer tools and how to use them ?</h4><p>Developers can inspect, troubleshoot, and test web pages using browser-based web developer tools. They can be used to see and edit the HTML, CSS, and JavaScript of a web page as well as to test the functionality and compatibility of a web page. They are built into modern web browsers like Chrome, Firefox, and Safari.</p><p>Here is a brief explanation of some of the common features of web developer tools:</p><ul><li><strong>Inspect Element:</strong> Allows you to view and edit the HTML and CSS of a web page by selecting an element on the page. It also allows you to see the layout, styles, and computed styles of the selected element.</li><li><strong>Console:</strong> Allows you to interact with JavaScript on a web page by writing and executing code, displaying output and errors, and testing code snippets. It is a powerful debugging tool, you can use it to check the value of variables, output messages, and run JavaScript code on the fly.</li><li><strong>Network: </strong>Allows you to monitor and analyze network requests made by the browser, including the headers, status codes, and timings of each request. This can be useful for debugging performance issues and identifying slow-loading resources.</li><li><strong>Performance:</strong> Allows you to analyze the performance of a web page, including the load times, rendering times, and JavaScript execution times. It can help you identify and fix performance bottlenecks in your code.</li><li><strong>Application:</strong> Allows you to inspect and interact with the data stored in browser storage, such as cookies, local storage, and indexedDB. This can be useful for debugging and testing web applications that use client-side storage.</li></ul><p>The developer tools can be opened by pressing the <strong>F12</strong> key (in most browsers) or by choosing “Developer Tools” from the browser’s menu, or you can simply right-click anywhere on the web page and choose “Inspect Element.” For each feature, such as “Elements,” “Console,” “Network,” “Performance,” and “Application,” the developer tools will open as a panel at the bottom or side of the browser window. You may access the various capabilities and utilize them to investigate, debug, and test your web page by navigating between the tabs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hwy7ppSQ7GbgcZ1wZ3E72w.png" /><figcaption>Screenshot of the developer tools in Google Chrome</figcaption></figure><h4>What do i need to do JavaScript programming ?</h4><p>As environmental setup needs, JavaScript does not need too much installations or preparation. It is very lightweight to start programming.</p><p>To begin programming with JavaScript, you will need the followings:</p><ul><li>A Text Editor: You will need a text editor to write and save your JavaScript code. Some popular text editors for JavaScript development include Sublime Text, Atom, Visual Studio Code, and Notepad++.</li><li>A Web Browser: JavaScript code runs in the browser, so you will need a web browser to test your code. Popular web browsers include Google Chrome, Mozilla Firefox, Microsoft Edge, and Safari.</li><li>A Connection to the Internet: Some JavaScript development tools and libraries are available online, so you will need an internet connection to access them.</li></ul><p>Once you have these three things, you can start writing and testing your JavaScript code. You do not need any specific operating system or hardware to run JavaScript, as long as your computer can run a web browser and a text editor, you should be able to run JavaScript.</p><h4>Finally, let’s append to add some interactivity to the HTML and CSS code we wrote above with using JavaScript ✅</h4><pre>&lt;!DOCTYPE html&gt;<br> &lt;html&gt;<br>   &lt;head&gt;<br>  &lt;title&gt;My Web Page&lt;/title&gt;<br>  &lt;style&gt;<br>    body {<br>   background-color: #f0f0f0;<br>   font-family: Arial, sans-serif;<br>    }<br>    h1 {<br>   color: blue;<br>   text-align: center;<br>    }<br>    p {<br>   font-size: 18px;<br>   line-height: 1.5;<br>    }<br>  &lt;/style&gt;<br>   &lt;/head&gt;<br>   &lt;body&gt;<br>  &lt;h1&gt;Welcome to my web page&lt;/h1&gt;<br>  &lt;p&gt;This is a simple web page created with HTML.&lt;/p&gt;<br>  &lt;img src=&quot;https://picsum.photos/100/100&quot; alt=&quot;Random Image&quot;&gt;<br>  &lt;a href=&quot;https://www.example.com&quot;&gt;Go To Example.com&lt;/a&gt;<br>  &lt;script&gt;<br>    // Get the heading element<br>    var heading = document.querySelector(&quot;h1&quot;);<br><br>    // Add an event listener to the heading that changes the text color on mouseover<br>    heading.addEventListener(&quot;mouseover&quot;, function() {<br>   heading.style.color = &quot;red&quot;;<br>    });<br><br>    // Add an event listener to the heading that changes the text color back on mouseout<br>    heading.addEventListener(&quot;mouseout&quot;, function() {<br>   heading.style.color = &quot;blue&quot;;<br>    });<br>  &lt;/script&gt;<br>   &lt;/body&gt;<br> &lt;/html&gt;</pre><p>Our JavaScript code is added between <strong>&lt;script&gt; &lt;/script&gt;</strong> tags.</p><p>This JavaScript code changes the color of the <strong>h1 </strong>heading to red when the user’s mouse pointer is over the <strong>h1</strong> heading and change it back to blue when the user’s mouse pointer leave the <strong>h1</strong> heading.</p><pre>The code first selects the h1 heading element using the querySelector <br>method. querySelector is a method of the document object that allows you <br>to select the first element that matches a given CSS selector.<br><br>Next, it adds two event listeners to the heading element, one for mouseover <br>event and another for mouseout events.<br><br>The first event listener is triggered when the mouse pointer is moved over <br>the heading element and it changes the text color of the heading element <br>to red by setting the color property of the style object of the heading <br>element to &quot;red&quot;.<br><br>The second event listener is triggered when the mouse pointer is moved out <br>of the heading element and it changes the text color of the heading element <br>back to blue by setting the color property of the style object of the <br>heading element to &quot;blue&quot;.</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1-pcuf8t4ZFOpi_Z98ekzQ.gif" /><figcaption>Screen recording for the HTML, CSS and JavaScript code above.</figcaption></figure><p>We have covered the fundamentals of JavaScript, a programming language that enables the development of dynamic and interactive web pages. We’ve also talked about the advantages of learning JavaScript, how to get started, and how common it is among developers. Basic HTML and CSS concepts and their use in web development were also taught. A programming interface for HTML and XML documents called the Document Object Model (DOM) and how JavaScript may be used to access and modify web page elements were also covered. We discussed the web developer tools, how to utilize them, and the prerequisite environments for beginning JavaScript development.</p><p>Finally we wrote some HTML and CSS code including JavaScript code as examples. All of these concepts are important for understanding how JavaScript works and how to use it to create interactive web pages and web applications.</p><p>I hope you learned something useful and interesting about <strong>JavaScript</strong>, <strong>HTML</strong>, <strong>CSS</strong> and <strong>web development</strong>. I wish you the best in your future adventures as a web developer and hope you now have a better understanding of how these technologies combine to produce dynamic and interactive web pages. Thank you for reading, and I look forward to assisting you if you have any JavaScript-related questions.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=526db7c03f8d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>