<?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"><channel><title><![CDATA[Daniel's blog]]></title><description><![CDATA[Daniel's blog]]></description><link>https://danial.au</link><generator>RSS for Node</generator><lastBuildDate>Mon, 13 Apr 2026 22:26:40 GMT</lastBuildDate><atom:link href="https://danial.au/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Chrome vs Firefox vs Edge vs Opera vs Brave vs Safari on Mac]]></title><description><![CDATA[I just did a quick comparison for my personal use between these browsers and the only few things I considered were:

Performance: How smoothly the window resizes and the browser updates the layout.
Memory consumption.
CPU power

The latest version of...]]></description><link>https://danial.au/chrome-vs-firefox-vs-edge-vs-opera-vs-brave-vs-safari-on-mac</link><guid isPermaLink="true">https://danial.au/chrome-vs-firefox-vs-edge-vs-opera-vs-brave-vs-safari-on-mac</guid><category><![CDATA[default]]></category><dc:creator><![CDATA[Daniel]]></dc:creator><pubDate>Wed, 03 Feb 2021 07:44:16 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1715929152634/63fa7694-cbb9-4d49-9062-6a92208d3827.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>I just did a quick comparison for my personal use between these browsers and the only few things I considered were:</p>
<ol>
<li>Performance: How smoothly the window resizes and the browser updates the layout.</li>
<li>Memory consumption.</li>
<li><p>CPU power</p>
</li>
<li><p>The latest version of all 6 browsers have been used</p>
</li>
<li>All of them have 3 tabs on the same websites open (AppStore, Microsoft, YouTube)</li>
<li>The comparison has been on MacBook Pro (15-inch, 2017)</li>
<li>It’s not a through test just enough for me to see which one suits me</li>
</ol>
<p>Here is the results.</p>
<ul>
<li>In terms of performance Safari, Opera and Firefox are the best. The other 3 are laggy when resizing</li>
</ul>
<h2 id="heading-memory">Memory:</h2>
<p>It’a hard to tell which one is more efficient immediately as they all have side processes running but seems like Opera consumes least memory and Firefox uses the most.</p>
<p><a target="_blank" href="https://baharestani.com/wp-content/uploads/2021/02/image.png"><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1715929151398/dca6478e-238a-4656-b967-f0d9f395a6ba.png" alt /></a></p>
<p>Tracking CPU is even harder than memory but Firefox is always on top consuming the most CPU time and Safari is the most efficient one. Edge, Chrome and Brave are pretty much the same.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>The Winner on Mac is <strong>Safari</strong> but it’s not a cross platform browser. The next Winner in terms of performance is Opera and then Firefox. Chrome, Brave, and Edge failed the first test so they are not even considered as options.</p>
<p><strong>Update 1:</strong></p>
<p>I used Opera for a week and it has these cons:</p>
<ul>
<li>It has issue with location and google map couldn’t show my location OK.</li>
<li>It doesn’t have a good support and not listed as the supported browser for some websites.</li>
<li>Due to the limited support for import and export, it’s hard to switch from other browsers to Opera or switching back to them.</li>
<li>It doesn’t allow sending feedback.</li>
<li>The settings page is not well organized and it’s not easy to find the settings you need.</li>
</ul>
<p>So switching to Firefox now.</p>
<p><strong>Update 2:</strong></p>
<p>Firefox has some rendering issues with the android app. Have to tradeoff between Chrome’s performance issue on Mac while resizing and Firefox rendering issue on the phone.<br />The other issue Firefox has is, it sometimes doesn’t update the saved passwords (e.g. on Okta) but Chrome does.</p>
<p>So switching back to Chrome.</p>
]]></content:encoded></item><item><title><![CDATA[Linux Background Jobs]]></title><description><![CDATA[Suspend a job and send it to the background:
$ Ctrl+Z
Resumes jobs that have been suspended, and keeps them running in the background:
$ bg
Bring most recently suspended background job to foreground:
$ fg
Display status of jobs in the current session...]]></description><link>https://danial.au/linux-background-jobs</link><guid isPermaLink="true">https://danial.au/linux-background-jobs</guid><category><![CDATA[default]]></category><category><![CDATA[Linux]]></category><dc:creator><![CDATA[Daniel]]></dc:creator><pubDate>Tue, 07 Apr 2020 05:41:09 GMT</pubDate><content:encoded><![CDATA[<p>Suspend a job and send it to the background:</p>
<p>$ Ctrl+Z</p>
<p>Resumes jobs that have been suspended, and keeps them running in the background:</p>
<p>$ bg</p>
<p>Bring most recently suspended background job to foreground:</p>
<p>$ fg</p>
<p>Display status of jobs in the current session:</p>
<p>$ jobs</p>
]]></content:encoded></item><item><title><![CDATA[Java Runnable, Callable, Supplier, etc.]]></title><description><![CDATA[Java doesn’t have the concept of delegate; instead, if you need a pointer to a function, you can create inline anonymous classes (or lambda expressions as of Java 8 ) which are implementations of certain interfaces designed for this propose (a.k.a fu...]]></description><link>https://danial.au/java-runnable-callable-supplier-etc</link><guid isPermaLink="true">https://danial.au/java-runnable-callable-supplier-etc</guid><category><![CDATA[default]]></category><dc:creator><![CDATA[Daniel]]></dc:creator><pubDate>Wed, 02 May 2018 03:46:58 GMT</pubDate><content:encoded><![CDATA[<p>Java doesn’t have the concept of delegate; instead, if you need a pointer to a function, you can create inline anonymous classes (or lambda expressions as of Java 8 ) which are implementations of certain interfaces designed for this propose (a.k.a functional interfaces as of Java 8). However as Java evolves, more of such interfaces are being added. While they may seem very similar and confusing, each of them has a unique characteristic which sets it apart from the others. You can map many of them to identical types in .NET. The following table lists some of the famous interfaces but there are many more. For example to support functions with two arguments, Java has another interface called <a target="_blank" href="https://docs.oracle.com/javase/8/docs/api/java/util/function/BiFunction.html">BiFunction</a> and if you need more arguments, you have to create your own interfaces. Remember that Java (up to version 10) doesn’t support identical class names if the only difference is number of type arguments. (In .NET there are various Func and Action types with up to 16 type arguments.)</p>
<p>Java</p>
<p>Supports Exceptions</p>
<p>Argument</p>
<p>Returns</p>
<p>.NET Equivalent</p>
<p>Callable</p>
<p> Yes</p>
<p> No</p>
<p> Yes</p>
<p> Func</p>
<p>Supplier</p>
<p> No</p>
<p> No</p>
<p> Yes</p>
<p> Func</p>
<p>Function</p>
<p> No</p>
<p> Yes</p>
<p> Yes</p>
<p> Func</p>
<p>Consumer</p>
<p> No</p>
<p> Yes</p>
<p> No</p>
<p> Action</p>
<p>Runnable</p>
<p> No</p>
<p> No</p>
<p> No</p>
<p> Action</p>
]]></content:encoded></item><item><title><![CDATA[API Security Checklist]]></title><description><![CDATA[Use HTTPS to protect sensitive data (authentication credentials, API Keys, etc.) in transit.
Authentication/Authorisation: Make sure the endpoints are protected with proper access levels.
GET methods are an easy target for attackers. So never perform...]]></description><link>https://danial.au/api-security-checklist</link><guid isPermaLink="true">https://danial.au/api-security-checklist</guid><category><![CDATA[default]]></category><dc:creator><![CDATA[Daniel]]></dc:creator><pubDate>Thu, 08 Mar 2018 04:43:33 GMT</pubDate><content:encoded><![CDATA[<ul>
<li>Use HTTPS to protect sensitive data (authentication credentials, API Keys, etc.) in transit.</li>
<li>Authentication/Authorisation: Make sure the endpoints are protected with proper access levels.</li>
<li>GET methods are an easy target for attackers. So never perform an operation that changes the state of your application in a GET method.</li>
<li>Protect your API agains <a target="_blank" href="https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)">CSRF</a> (Cross-Site Request Forgery) attacks.</li>
<li>Make sure your API is not vulnerable to <a target="_blank" href="https://www.owasp.org/index.php/Cross-site_Scripting_(XSS)">XSS</a> (Cross-Site Scripting) attacks.</li>
<li>Sign <a target="_blank" href="https://jwt.io">JWT</a> (JSON Web Tokens) securely preferably using secrets.</li>
<li>Use API Keys for every request.</li>
<li>Treat Management Endpoints differently than normal ones, by enforcing stronger security policies (e.g. multi-factor authentication.</li>
<li>Handle exceptions decently so that technical error details are not exposed to clients.</li>
<li>Use <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy">SOP</a> (Same-Origin Policy) and disable <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS">CORS</a> if it’s not needed. When enabling CORS, be as specific as possible.</li>
<li>Do not put any sensitive information in the URL params as they can be logged by servers. Put them in the request header or body.</li>
<li>When setting cookies, use <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies#Secure_and_HttpOnly_cookies">Secure and HttpOnly.</a> Also restrict the <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies#Scope_of_cookies">scope of cookies</a>.</li>
<li>Any input or data being imported may eventually end up in users’s browsers as part of an HTML page and you don’t want to send a malicious script to the them. Validating input and imported data is one of the ways to prevent <a target="_blank" href="https://www.owasp.org/index.php/Clickjacking">clickjacking</a>, XSS or stored CSRF flaws.</li>
<li>Any input or data being imported may also end up being inserted into your database, so make sure your application is protected against <a target="_blank" href="https://www.owasp.org/index.php/SQL_Injection">SQL Injection</a> attacks.</li>
<li>Set response <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type">Content-Type</a> header properly to mach the response MIME type and <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Content-Type-Options">disable MIME type sniffing</a> (nosniff).</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Azure Service Bus Messaging]]></title><description><![CDATA[Microsoft Azure Service Bus supports two distinct messaging patterns: Azure Relay and Service Bus Brokered Messaging. This article is an introduction to Brokered Messaging.Brokered Messaging can decouple the communication between applications by intr...]]></description><link>https://danial.au/azure-service-bus-messaging</link><guid isPermaLink="true">https://danial.au/azure-service-bus-messaging</guid><category><![CDATA[architecture]]></category><category><![CDATA[Azure]]></category><category><![CDATA[General Programming]]></category><dc:creator><![CDATA[Daniel]]></dc:creator><pubDate>Fri, 07 Apr 2017 07:10:03 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1715929168402/ecd3c02f-9d3e-46d3-8de1-320077b337a3.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Microsoft Azure Service Bus supports two distinct messaging patterns: <em>Azure Relay</em> and <em>Service Bus Brokered Messaging</em>. This article is an introduction to Brokered Messaging.<br />Brokered Messaging can decouple the communication between applications by introducing an asynchronous messaging system. The sender applications put the requests on a queue and the receivers will pick them up and process them whenever they are available. This way if the receiver application is temporarily busy or unavailable the sender application doesn’t fail or get blocked.</p>
<h1 id="heading-queues">Queues</h1>
<p>A queue is an entity with a head and a tail. Senders put the messages on the head and receivers pick them up from the tail.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1715929159434/c88dd6b3-9068-4ace-892f-2656f116f20f.png" alt="sb-queues-08" /></p>
<p>Once a message is processed by a receiver it will no longer be available on the queue for other receivers. When there are multiple message receivers, the message load is distributed between them in a <strong>load balancing</strong> manner.</p>
<h1 id="heading-topics-and-subscriptions">Topics and Subscriptions</h1>
<p>Topics and Subscriptions can be thought as queues with one head but multiple tails. The head is called a Topic and each tail is called a Subscription. When a sender sends a message to a Topic, Service Bus creates multiple copies of it for each subscription. If there are several receivers interested in receiving the message, they can each listen on a different subscription and get a distinct copy of the message. However, if they listen on the same subscription, only one of them will be able to receive the message.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1715929160772/c7ac37c8-3af3-4589-a07f-8b91ec25229a.png" alt="sb-topics-01" /></p>
<p>The Subscriptions can specify <strong>filters</strong>. This way each subscription only exposes the messages that match its filter.</p>
<h1 id="heading-service-bus-namespace">Service Bus Namespace</h1>
<p>A namespace is the way to categorize the queues and topics. You cannot create any service bus entities unless you have created a namespace first. A company may want to have different namespaces for different projects or teams. Creating a namespace is easy, you just need to go to <a target="_blank" href="https://portal.azure.com">Azure portal</a> and follow the instructions. After the namespace is created it can be referred to, using its connection strings.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1715929161944/68305819-59be-40e8-acd8-a9f21b927b3f.png" alt="servicebus_overview" /></p>
<p>Creating Service Bus entities (Queues, Topics and Subscriptions) is also as easy as creating a Namespace. Just follow the instructions on Azure portal.</p>
<p>You can also manage Service Bus entities programmatically using the <code>NamespaceManager</code> class.</p>
<h1 id="heading-client-api">Client API</h1>
<p>In your project install <code>WindowsAzure.ServiceBus</code> Nuget package to get the Service Bus client library. Here are a few code snippets to get the basic things done:</p>
<h2 id="heading-basic-queues-operations">Basic Queues operations</h2>
<p>// Creating a Queue client
var client = QueueClient.CreateFromConnectionString(connectionString, queueName);</p>
<p>// Creating a message
var message = new BrokeredMessage("Hello");</p>
<p>// Sending a message
client.Send(message)</p>
<p>// Receiving a message
client.OnMessage(message =&gt;
{
    // Processing the message here...
});</p>
<h2 id="heading-basic-topics-operations">Basic Topics operations</h2>
<p>// Creating a Topic client
var topicClient = TopicClient.CreateFromConnectionString(connectionString, topicName);</p>
<p>// Sending a message
topicClient.Send(message)</p>
<p>// Create a Subscription client
var subscriptionClient = SubscriptionClient.CreateFromConnectionString(connectionString, topicName, subscriptionName);</p>
<p>// Receiving a message
subscriptionClient.OnMessage(message =&gt;
{
    // Processing the message here...
});</p>
<h2 id="heading-messaging-factory">Messaging Factory</h2>
<p>Another way of creating messaging clients (QueueClient, TopicClient or SubscriptionClient) is using a MessagingFactory. It allows us to create the clients in a more abstracted way and thinking of them as senders and receivers. It is more flexible and makes it easier to change the messaging strategy without having to update the code. For example, if your application is currently using Queues and you decide to switch to Topics/Subscriptions, all you need to do is updating your endpoints if you have used messaging factory to create the clients.</p>
<p>var factory = MessagingFactory.CreateFromConnectionString(ConnectionString);</p>
<p>var messageReceiver = factory.CreateMessageReceiver("entityPath");</p>
<p>var messageSender= factory.CreateMessageSender("entityPath");</p>
<h1 id="heading-message-lifetime">Message Lifetime</h1>
<p>When a message receiver is created it specifies a Receive Mode. There are two receive modes:</p>
<ul>
<li>Receive and Delete: In this mode as soon as the receiver picks up the message, the message gets deleted from the queue. If the receiver crashes before being able to process the message, it will be lost. This At-Most-Once delivery is guaranteed.</li>
<li>PeekLock: This is the default mode and guarantees At-Least-Once delivery. When the receiver picks up the message in this mode, the service bus puts a lock on the message and hides it from other receivers, but the message still exists on the queue until one of the client completes processing the message. If the client crashes before that, the message will be visible on the queue again after the lock expires. The default lock duration is 30 seconds and it can be set on the receiver (queue/subscription).</li>
</ul>
<p>After the message receiver is done with the message, it should notify the service bus by calling one of the following methods:</p>
<ul>
<li>Complete(): The message was successfully processed and it should be deleted from the queue.</li>
<li>Abandon(): The receiver doesn’t know how to process the message and it returns the message to the queue to make it available for other receivers.</li>
<li>Differ(): The receiver doesn’t want to process the message just yet, so the message will be returned to the queue but it will not be delivered to any receiver unless they explicitly request for it by its sequence number.</li>
<li>DeadLetter(): The receiver has encountered an error processing the message and marks it as a dead-letter. Dead-letters are sent to a sub-queue within the same queue.<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1715929163488/ac4cd9f6-449a-40b8-9369-363385c23524.png" alt /></li>
</ul>
<p>The following code shows how to read a message from the dead-letter queue:</p>
<p>var factory = MessagingFactory.CreateFromConnectionString(ConnectionString);
var deadletter SubscriptionClient.FormatDeadLetterPath(TopicName, SubscriptionName);
var deadletterClient = factory.CreateMessageReceiver(deadletter);
deadletterClient.OnMessage(message =&gt;
{
    // Process dead-letter message here
});</p>
<p>A queue or subscription can be configured to move expired or erroneous messages to a dead-letter queue too.<br /><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1715929164508/02f00b9d-4dde-4f3c-8f29-4f95273a2a2f.png" alt="servicebus_edit_subscription" /></p>
<p>The OnMessage method automatically marks any received messages completed. If the client is going to take care if this itself, the <strong>AutoComplete</strong> should be disabled first:</p>
<p>messageReceiver.OnMessage(message =&gt;
{
    try
    {
        // if message processed successfully
        message.Complete();
    }
    catch (Exception exception)
    {
       // If message has an error
        message.DeadLetter();
    }</p>
<p>}, new OnMessageOptions
{
    AutoComplete = false
});</p>
<p>The longest a message can live on a queue before it is processed is determined by its <strong>time-to-live</strong> afterwhich the message gets deleted automatically. Time-to-live can be specified on the queue, topic, subscription or the message itself. A message can only live as long as the minimum time-to-live specified on its queue, topic,<br />subscription or the message itself.</p>
<p>var message = new BrokeredMessage
{
    TimeToLive = TimeSpan.FromMinutes(10)
};</p>
<h1 id="heading-duplicate-detection">Duplicate Detection</h1>
<p>When sending a message, if an error happens and the client cannot send the message, it usually retries sending and this may lead to having duplicate messages on the system. A client also re-sends the message if it doesn’t receive any acknowledgement from the queue. Enabling duplicate detection keeps track of the <code>MessageId</code> property of all messages. If a new message with identical <code>MessageId</code> as an existing one is detected within a time window (duplicate detection history), it will be ignored and dropped.</p>
<p>Duplication detection can be enabled on Queue or Topic when creating them either in the Azure portal or programmatically by setting the <code>RequiresDuplicateDetection</code> property. The duplicate detection history window can also be set on a Queue and Topic. In the code set <code>DuplicateDetectionHistoryTimeWindow</code> on a QueueDescription or TopicDescription.<br />The duplicate detection window should be kept as small as feasible, because large window size means keeping track of more message-Ids and it impacts the throughput.</p>
<h1 id="heading-filters-rules-and-actions">Filters, Rules and Actions</h1>
<p>A subscription can be created with a filter so that it delivers only a subset of messages to subscription clients. A CorrelationFilter allows for a basic filtering based on the message properties like MessageId, CorrelationId, etc.</p>
<p>namespaceManager.CreateSubscription(topicPath, subscriptionPath,
    new CorrelationFilter { Label = "red", CorrelationId = "high"});</p>
<p>You can also specify a SqlFilter which allows for Sql-like expressions:</p>
<p>namespaceManager.CreateSubscription(topicPath, subscriptionPath,
    new SqlFilter("color = 'blue' AND quantity = 10"));</p>
<p>When creating a subscription, if a filter is not explicitly specified, the subscription will be created by default with a <code>TrueFilter</code> which means the subscription accepts all messages.<br />A subscription can also be created with <code>Rule</code>. A rule executes an Action on the messages matching the filter.</p>
<p>namespaceManager.CreateSubscription(topicPath, subscriptionPath,
new RuleDescription
{
    Name = "RedRule",
    Filter = new SqlFilter("color = 'red'"),
    Action = new SqlRuleAction(
        "SET quantity = quantity / 2;" +
        "REMOVE priority;" +
        "SET sys.CorrelationId = 'low';")
});</p>
<p>In the above example, the rule will run a <code>SqlAction</code> on any messages whose ‘color’ property is ‘red’ and as a result of the action, two properties of the message will be set and one property will be removed. Read more <a target="_blank" href="http://southworks.com/blog/2012/01/06/using-rule-actions-in-windows-azure-service-bus-subscriptions/">here</a>.</p>
<h1 id="heading-shared-access-policies">Shared Access Policies</h1>
<p>Every messaging entity is associated with a set of access policies that determine what you can do with entity. When an entity is created it comes with a default policy named <code>RootManageSharedAccessKey</code> which gives you full access (Manage, Send, Receive) to the entity.<br /><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1715929165607/f46ca984-5776-4ff8-9f8b-288b685ca775.png" alt="shared-access" /><br />Each policy has a primary key and a secondary key both of which can be used to connect to the entity. If a key is compromised, you should regenerate it and update all clients to use the new key. The reason there two keys is that you switch to the other key before regenerating one to avoid a downtime in your system.<br /><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1715929166511/5a18cfa5-5295-4225-997d-32c1524b40f4.png" alt="edit-policy" /><br />It is not recommended to use your Root manage accessed key everywhere in your system. You should create custom policies with reasonable access levels (Send, Listen or Manage) and use it in clients.</p>
<h1 id="heading-auto-forwarding">Auto-forwarding</h1>
<p>You can use auto-forwarding to scale out an individual topic. Service Bus limits the number of subscriptions on a given topic to 2,000. You can accommodate additional subscriptions by creating second-level topics. Note that even if you are not bound by the Service Bus limitation on the number of subscriptions, adding a second level of topics can improve the overall throughput of your topic.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1715929167537/08805924-b972-4f65-a491-af91de9fdf26.gif" alt="Auto-forwarding scenario" /></p>
<p>You can enable auto-forwarding by setting the QueueDescription.ForwardTo or SubscriptionDescription.ForwardTo properties on the source queue/subscription:</p>
<p>var srcSubscription = new SubscriptionDescription (srcTopic, srcSubscriptionName);
srcSubscription.ForwardTo = destTopic;
namespaceManager.CreateSubscription(srcSubscription));</p>
<p>The destination entity must exist at the time the source entity is created. <a target="_blank" href="https://docs.microsoft.com/en-us/azure/service-bus-messaging/service-bus-auto-forwarding">Lear more…</a></p>
<hr />
<p>References:<br /><a target="_blank" href="https://docs.microsoft.com/en-au/azure/service-bus-messaging">Microsoft Azure service bus messaging documentation</a><br /><a target="_blank" href="https://app.pluralsight.com/library/courses/microsoft-azure-service-brokered-messaging">Microsoft Azure Service brokered messaging course on Pluralsight</a><br /><a target="_blank" href="http://southworks.com/blog/2012/01/06/using-rule-actions-in-windows-azure-service-bus-subscriptions/">Southworks by Jorge Rowies</a><br /><a target="_blank" href="http://www.cloudcasts.net/devguide/Default.aspx?id=13002">Cloudcasts by Alan Smith  
</a><a target="_blank" href="https://github.com/Azure-Samples/azure-servicebus-messaging-samples">Github samples</a></p>
]]></content:encoded></item><item><title><![CDATA[Repository Pattern]]></title><description><![CDATA[Definition
A Repository mediates between the domain and data mapping layers, acting like an in-memory domain object collection. Client objects construct query specifications declaratively and submit them to Repository for satisfaction. Objects can be...]]></description><link>https://danial.au/repository-pattern</link><guid isPermaLink="true">https://danial.au/repository-pattern</guid><category><![CDATA[architecture]]></category><category><![CDATA[General Programming]]></category><dc:creator><![CDATA[Daniel]]></dc:creator><pubDate>Fri, 31 Mar 2017 23:55:07 GMT</pubDate><content:encoded><![CDATA[<h2 id="heading-definition">Definition</h2>
<p>A <a target="_blank" href="http://martinfowler.com/eaaCatalog/repository.html">Repository</a> mediates between the domain and data mapping layers, acting like an in-memory domain object collection. Client objects construct query specifications declaratively and submit them to Repository for satisfaction. Objects can be added to and removed from the Repository, as they can from a simple collection of objects, and the mapping code encapsulated by the Repository will carry out the appropriate operations behind the scenes.</p>
<h2 id="heading-objectives">Objectives</h2>
<p>Use the Repository pattern to achieve one or more of the following objectives:</p>
<ul>
<li><p>You want to maximize the amount of code that can be tested with automation and to isolate the data layer to support unit testing.</p>
</li>
<li><p>You access the data source from many locations and want to apply centrally managed, consistent access rules and logic.</p>
</li>
<li><p>You want to implement and centralize a caching strategy for the data source.</p>
</li>
<li><p>You want to improve the code’s maintainability and readability by separating business logic from data or service access logic.</p>
</li>
<li><p>You want to use business entities that are strongly typed so that you can identify problems at compile time instead of at run time.</p>
</li>
<li><p>You want to associate a behavior with the related data. For example, you want to calculate fields or enforce complex relationships or business rules between the data elements within an entity.</p>
</li>
<li><p>You want to apply a domain model to simplify complex business logic.</p>
</li>
</ul>
<h2 id="heading-best-practices">Best Practices</h2>
<ol>
<li><p>Do not use <a target="_blank" href="https://msdn.microsoft.com/en-us/library/vstudio/bb351562(v=vs.100).aspx">IQueryable</a> as the return type of query methods. Because <a target="_blank" href="http://blog.ploeh.dk/2012/03/26/IQueryableTisTightCoupling/">it creates tight coupling</a> and you get no benefit over using the OR/M directly. Use more generic types like IEnumerable.</p>
</li>
<li><p>Create repositories for domain aggregates only not for every single entity. If you are not using Aggregates in a Bounded Context, the repository pattern may be less useful.</p>
</li>
<li><p>Creating base types for repositories is not recommended. If it is needed make sure not breaking the <a target="_blank" href="http://en.wikipedia.org/wiki/Interface_segregation_principle">Interface Segregation Principle</a>.</p>
</li>
<li><p>It is not recommended to create generic repositories, make sure you have a good reason if you want to create one.</p>
</li>
<li><p>Repositories must return domain entities which are usable in the domain services without having to be converted, so any data contracts must be converted to domain entities before the repository returns them.</p>
</li>
<li><p>Apart from CRUD operations, repositories can also have identity generator, count methods or finder methods.</p>
</li>
<li><p>A repository should only have the minimum required operations. It doesn’t even have to include all the four of CRUD operations. It can be as simple as a repository with only one operation.</p>
</li>
<li><p>It is OK to have bulk methods for adding or removing multiple items to or from the repository.</p>
</li>
<li><p>If you find that you must create many finder methods supporting use case optimal queries on multiple Repositories, it’s probably a code smell. First of all, this situation could be an indication that you’ve misjudged Aggregate boundaries and overlooked the opportunity to design one or more Aggregates of different types. However, if you encounter this situation and your analysis indicates that your Aggregate boundaries are well designed, this could point to the need to consider using <a target="_blank" href="http://martinfowler.com/bliki/CQRS.html">CQRS</a>.</p>
</li>
<li><p>Do not design a Repository to provide access to parts that the Aggregate Root would not otherwise allow access to by way of navigation.</p>
</li>
<li><p>Place the repository interface definition in the same Module (assembly) as the Aggregate type that it stores. The implementation class goes in a separate Module. The following image shows how the dependencies should be </p>
</li>
<li><p>Generally speaking, there is a one-to-one relationship between an Aggregate type and a Repository.</p>
</li>
<li><p>If the aggregate includes large members, for example, big lists of items, you can consider lazy loading.</p>
</li>
<li><p>The only responsibility of a repository is data persistence, so no business (domain) logic should be added to a repository. The operations are CRUD only. This also applies to the name of the methods.</p>
</li>
</ol>
<h2 id="heading-references">References</h2>
<ul>
<li><p><a target="_blank" href="http://www.amazon.com/gp/product/0321834577/ref=pd_lpo_sbs_dp_ss_1?pf_rd_p=1944687562&amp;pf_rd_s=lpo-top-stripe-1&amp;pf_rd_t=201&amp;pf_rd_i=0321125215&amp;pf_rd_m=ATVPDKIKX0DER&amp;pf_rd_r=0G79N0ZHABJ4Z32KF4J6">Implementing Domain-Driven Design. Vaughn Vernon</a></p>
</li>
<li><p><a target="_blank" href="http://blog.ploeh.dk/2012/03/26/IQueryableTisTightCoupling/">IQueryable is Tight Coupling by Mark Seemann</a></p>
</li>
<li><p><a target="_blank" href="http://msdn.microsoft.com/en-us/library/ff649690.aspx">MSDN Application Design Patterns – The Repository Pattern</a></p>
</li>
<li><p><a target="_blank" href="http://martinfowler.com/eaaCatalog/repository.html">Martin Fowler Website – Repository</a></p>
</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Successful Backend Architecture]]></title><description><![CDATA[This is a clean architecture and is a simplified version of onion architecture. It is also conforming to the principals of Hexagonal Architecture.
Layers
In the following diagram the arrows show the direction of the dependencies. Any outer layer can ...]]></description><link>https://danial.au/successful-backend-architecture</link><guid isPermaLink="true">https://danial.au/successful-backend-architecture</guid><category><![CDATA[architecture]]></category><dc:creator><![CDATA[Daniel]]></dc:creator><pubDate>Fri, 31 Mar 2017 23:35:27 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1715929177537/6f4ddb1c-f649-4688-9b68-535ae8a9aeac.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>This is a <a target="_blank" href="http://blog.8thlight.com/uncle-bob/2012/08/13/the-clean-architecture.html">clean architecture</a> and is a simplified version of <a target="_blank" href="http://jeffreypalermo.com/blog/the-onion-architecture-part-1/">onion architecture</a>. It is also conforming to the principals of <a target="_blank" href="http://alistair.cockburn.us/Hexagonal+architecture">Hexagonal Architecture.</a><a target="_blank" href="https://mathletics.atlassian.net/wiki/content-only/viewpage.action?pageId=66814097&amp;iframeId=fallback-mode#BackendArchitectureOverview-Adapterslayer"></a><a target="_blank" href="https://mathletics.atlassian.net/wiki/content-only/viewpage.action?pageId=66814097&amp;iframeId=fallback-mode#BackendArchitectureOverview-Applicationlayer"></a><a target="_blank" href="https://mathletics.atlassian.net/wiki/content-only/viewpage.action?pageId=66814097&amp;iframeId=fallback-mode#BackendArchitectureOverview-Domainlayer"></a></p>
<h1 id="heading-layers">Layers</h1>
<p>In the following diagram the arrows show the direction of the dependencies. Any outer layer can directly call ANY inner layer. So the yellow layer (Adapters layer) can rely on all of the other layers. The application layer can only have dependency on the domain layer. And the domain layer should NOT have any references to the other layers. Any communication with the outside word happens in the Adapters layer.</p>
<p> <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1715929173452/ad34d277-219b-4e72-ac65-caff783b6779.png" alt="Layers_overview" /></p>
<h2 id="heading-adapters-layer">Adapters layer</h2>
<p>This layer makes it possible for the application to communicate with the outside word. In order to interact with external components like databases, web, files system, etc. the application needs a layer which can convert its internal objects to something which is understandable by the external components and vice versa. For example a Data Access is needed to let the application talk to a database; or to be able to expose the application’s functionality through the Web, we need to create a Web Service which makes use of the .Net Framework web technologies. These components are called Adapters and they should reside in the Adapters layer. The inner layers or other adapters cannot have dependencies on this layer.</p>
<p> <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1715929174776/dbf4b86e-0221-4883-8442-a90a470185ee.png" alt="Adapters" /></p>
<p>As the above diagram shows, there are two groups of external components: driving actors and driven actors (external resources). A Driving actor is an actor that drives the application (take it out of quiescent state to perform one of its advertised functions). End users, automated tests, or remote clients are a few examples of driving actors. Whereas a driven actor is one that the application drives, either to get answers from or to merely notify. Database, files system or remote web services are some examples of driven actors (a.k.a external resources). The distinction between “driving” and “driven” lies in who triggers or is in charge of the conversation. These two groups of the external components require two groups of adapters: Driving adapters and Driven adapters.</p>
<h3 id="heading-driving-adapters">Driving Adapters</h3>
<p>These are the adapters that expose the applications functionality to the outside world. In other words it allows the driving actors to drive the application. The other layers of the application never need to see this layer, however the driving adapters need to have dependency on them. The following list encompasses the driving adapters:</p>
<ul>
<li>Web Service: Regardless of the web service technology, all of the web services go to this layer. Web API, WCF, or Soap (ASMX). This layer must not have any business or application logic and should be as thin as possible. The consumer of this layer is remote clients.</li>
<li>Tests: They are another residents of this layer. They call the functions of other layers and allow the test runners drive the application for test purposes. So the test runners are the driving actors of this layer.</li>
<li>Presentation: This layer can have the adapters that translates the user’s keystrokes and gestures into data understandable for the application and visualize the application’s output to the user. The actor who drives this layer is the end user.</li>
</ul>
<p>Note</p>
<p>The driving adapters are where the <a target="_blank" href="http://blog.ploeh.dk/2011/07/28/CompositionRoot/">composition root</a> of the entire application should go. Any service registration happens in this layer.</p>
<h3 id="heading-driven-adapters-infrastructure">Driven Adapters (Infrastructure)</h3>
<p>This layer has the concrete implementation of the dependencies of the other layers. Infrastructure is any code that is a commodity and does not give your application a competitive advantage. This code is most likely to change frequently as the software goes through years of maintenance. That’s why no other layer should have any dependency on this. Any dependency to this layer must be through abstractions. For example if the software needs a repository, it should use an abstract repository (i.e. an interface) and the implementation of the repository goes to this layer. We rely heavily on the <a target="_blank" href="http://en.wikipedia.org/wiki/Dependency_inversion_principle">Dependency Inversion principle</a>. The application core needs an implementation of core interfaces, and since those implementing classes reside at the edges of the application, we need <a target="_blank" href="http://en.wikipedia.org/wiki/Dependency_injection">some mechanism</a> for injecting that code at runtime.</p>
<ul>
<li>Data Access: This layer has the implementation of the <a target="_blank" href="http://martinfowler.com/eaaCatalog/repository.html">repositories</a>. They can persist and retrieve the domain objects in some storage. Depending on what storage to use, we may need adapters (different implementation for the repository).</li>
<li>Service Proxy: Whenever we add a service reference to the application, a proxy component is generated which is an adapter between the application and the remote service. It makes it possible to send and receive the messages throw the web. Depending on the messaging technology, we may need different adapters here. Be it SOAP, TCP or even a message queue, the application should not need to change because of a change in the underlying messaging technology.</li>
<li>File Access is another example of infrastructure. It makes it possible to operate the file system regardless of the contents of the files.</li>
</ul>
<p><strong>Note</strong>: The adapters in the infrastructure layer should be substituted for <a target="_blank" href="http://www.martinfowler.com/bliki/TestDouble.html">test doubles</a> when testing the application.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1715929176307/ab939022-cb17-4859-be97-75f64ceaba5c.png" alt="Layers_Details" /></p>
<h2 id="heading-application-layer-orchestrator">Application layer (Orchestrator)</h2>
<p>This layer contains the application services which are single responsibility classes that do the orchestration of the application and deal with application logic. These services are different from the web services that we have in the Web Service Layer. Please be advised that this layer is not meant to have any domain (a.k.a business) logic. Domain logic should go to the Domain Layer.</p>
<ul>
<li>We define the DTO classes (request/response) in this layer.</li>
<li>Application services are also responsible for composing the response objects.</li>
<li>As a naming convention suffix them with the word “ApplicationService” or just “Service”. But make it consistent.</li>
<li>Application services can consume repositories and other domain services.</li>
<li>Although it does’t see the infrastructure layer, it can see its abstractions.</li>
</ul>
<h2 id="heading-domain-layer-business-layer">Domain layer (Business layer)</h2>
<p>This layer will have all of the domain models: Entities, values objects, domain events, and the domain exceptions. The abstraction of the repositories also go to this layer. The business rules should be applied in this layer.</p>
<h1 id="heading-why-this-architecture">Why this architecture</h1>
<p>It is a <a target="_blank" href="http://blog.8thlight.com/uncle-bob/2012/08/13/the-clean-architecture.html">clean architecture</a> that means it can produce a system which is:</p>
<ol>
<li>Independent of Frameworks. The architecture does not depend on the existence of some library of feature laden software. This allows you to use such frameworks as tools, rather than having to cram your system into their limited constraints.</li>
<li>Testable. The business rules can be tested without the UI, Database, Web Server, or any other external element.</li>
<li>Independent of UI. The UI can change easily, without changing the rest of the system. A Web UI could be replaced with a console UI, for example, without changing the business rules.</li>
<li>Independent of Database. You can swap out Oracle or SQL Server, for Mongo, BigTable, CouchDB, or something else. Your business rules are not bound to the database.</li>
<li>Independent of any external agency. In fact your business rules simply don’t know anything at all about the outside world.</li>
</ol>
<h1 id="heading-the-dependency-rule">The Dependency Rule</h1>
<p>The concentric circles represent different areas of software. In general, the further in you go, the higher level the software becomes. The outer circles are mechanisms. The inner circles are policies.</p>
<p>The overriding rule that makes this architecture work is The Dependency Rule. This rule says that source code dependencies can only point inwards. Nothing in an inner circle can know anything at all about something in an outer circle. In particular, the name of something declared in an outer circle must not be mentioned by the code in the an inner circle. That includes, functions, classes. variables, or any other named software entity.</p>
<p>By the same token, data formats used in an outer circle should not be used by an inner circle, especially if those formats are generate by a framework in an outer circle. We don’t want anything in an outer circle to impact the inner circles.</p>
<h1 id="heading-key-tenets">Key tenets</h1>
<p>The following tenets are those of the <a target="_blank" href="http://jeffreypalermo.com/blog/the-onion-architecture-part-3/">onion architecture</a>. Our architecture should adhere to all of them as it is a simplified version of onion:</p>
<ol>
<li>The application is built around an independent object model</li>
<li>Inner layers define interfaces. Outer layers implement interfaces</li>
<li>Direction of coupling is toward the centre</li>
<li>All application core code can be compiled and run separate from infrastructure</li>
</ol>
<h2 id="heading-references">References</h2>
<hr />
<p>Hexagonal Architecture: <a target="_blank" href="http://alistair.cockburn.us/Hexagonal+architecture">http://alistair.cockburn.us/Hexagonal+architectur  
</a>Onion Architecture: <a target="_blank" href="http://jeffreypalermo.com/blog/the-onion-architecture-part-1/">http://jeffreypalermo.com/blog/the-onion-architecture-part-1/  
</a>Clean Architecture: <a target="_blank" href="http://blog.8thlight.com/uncle-bob/2012/08/13/the-clean-architecture.html">http://blog.8thlight.com/uncle-bob/2012/08/13/the-clean-architecture.html</a></p>
]]></content:encoded></item><item><title><![CDATA[Dynamic Deserialization]]></title><description><![CDATA[Binary deserialization fails with a SerializationException saying ‘Unable to find assembly’ if you try to deserialize an object whose type is not referenced in the current application domain.
The easiest way to resolve this is to reference the assemb...]]></description><link>https://danial.au/dynamic-deserialization</link><guid isPermaLink="true">https://danial.au/dynamic-deserialization</guid><category><![CDATA[C]]></category><category><![CDATA[General Programming]]></category><dc:creator><![CDATA[Daniel]]></dc:creator><pubDate>Tue, 28 Mar 2017 07:08:40 GMT</pubDate><content:encoded><![CDATA[<p>Binary deserialization fails with a <a target="_blank" href="https://msdn.microsoft.com/en-us/library/system.runtime.serialization.serializationexception(v=vs.110).aspx">SerializationException</a> saying ‘Unable to find assembly’ if you try to deserialize an object whose type is not referenced in the current application domain.</p>
<p>The easiest way to resolve this is to reference the assembly containing the required type. This way the BinaryFormatter will return an object of the same type and all you need to do is a simple cast:</p>
<p>var formatter = new BinaryFormatter();
var obj = (SourceType)formatter.Deserialize(stream);</p>
<p>However, this approach may not be possible for many reasons: You may not have access to the source assembly, the assembly may be targeting a different platform, etc. In such cases the solution is to create proxy types which have similar structure to the source type. Your BinaryFormatter then needs to be configured to deserialize the stream to a proxy type rather than the original one. This is done by creating a custom <a target="_blank" href="https://msdn.microsoft.com/en-us/library/system.runtime.serialization.serializationbinder(v=vs.110).aspx">SerializationBinder</a>:</p>
<p>sealed class MySerializationBinder : SerializationBinder
{
    public override Type BindToType(string assemblyName, string typeName)
    {
        return Type.GetType(String.Format("{0}, {1}", typeName, PROXY_ASSEMBLY_NAME);
    }
}</p>
<p>You then need to assign it to the formatter:</p>
<p>var formatter = new BinaryFormatter
{
    Binder = new MySerializationBinder ()
};</p>
<p>But there are still cases where you cannot even create proxy assemblies because the structure of the original types may be completely unknown to you. In such cases you should create a Descriptor Proxy which can represent a deserialized object in a dynamic way:</p>
<p>[Serializable]
class ObjectDescriptor : ISerializable
{
    private readonly SerializationInfoEnumerator enumerator;</p>
<p>    [SecurityPermission(SecurityAction.Demand, SerializationFormatter = true)]
    void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
    {
    }</p>
<p>    [SecurityPermission(SecurityAction.Demand, SerializationFormatter = true)]
    private ObjectDescriptor(SerializationInfo info, StreamingContext context)
    {
        this.enumerator = info.GetEnumerator();
    }</p>
<p>    public IEnumerable&lt;SerializationEntry&gt; GetMembers()
    {
        this.enumerator.Reset();
        while (this.enumerator.MoveNext())
        {
            yield return this.enumerator.Current;
        }
    }
}</p>
<p>The descriptor object can then be used to create a <a target="_blank" href="https://msdn.microsoft.com/en-us/library/dd264741.aspx">dynamic</a> object:</p>
<p>public dynamic CreateDynamicObject(ObjectDescriptor descriptor)
{
    var nameRegex = new Regex("&lt;(.+)&gt;");</p>
<p>    IDictionary&lt;string, object&gt; expando = new ExpandoObject();</p>
<p>    foreach (SerializationEntry member in descriptor.GetMembers())
    {
        string memberName = nameRegex.IsMatch(member.Name) ? nameRegex.Match(member.Name).Groups[1].Value : member.Name;
        expando[memberName] = member.Value is ObjectDescriptor complexMember ? CreateDynamicObject(complexMember) : member.Value;
    }</p>
<p>    return (ExpandoObject)expando;
}</p>
<p>Find a complete sample project implementing the above solution at <a target="_blank" href="https://github.com/baharestani/dynamic-serialization">this GitHub repository</a>.</p>
]]></content:encoded></item><item><title><![CDATA[Change The Author of Git Commits]]></title><description><![CDATA[Identify one revision before the commit you need to update. In the following example, the last two commits are going to be updated.
Run git rebase command with the identified commit number:git rebase -i 2778751
In the editor, for each commit you need...]]></description><link>https://danial.au/change-the-author-of-git-commits</link><guid isPermaLink="true">https://danial.au/change-the-author-of-git-commits</guid><category><![CDATA[Git]]></category><category><![CDATA[General Programming]]></category><dc:creator><![CDATA[Daniel]]></dc:creator><pubDate>Sun, 04 Sep 2016 07:11:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1715929182836/b6968139-ebf5-4a5e-8679-a22a51683749.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<ol>
<li>Identify one revision before the commit you need to update. In the following example, the last two commits are going to be updated.<br /><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1715929181802/03a42a40-c6b2-4abb-adef-47f3566f2881.png" alt="CommitLogs" /></li>
<li>Run git rebase command with the identified commit number:<br /><strong><code>git rebase -i 2778751</code></strong></li>
<li>In the editor, for each commit you need to update, change the word <strong><code>pick</code></strong> to <strong><code>edit</code></strong>. (Make sure you know how to use the Vim editor)</li>
<li>Run the following command to set the author to the current configured git user:<br /><strong><code>git commit --amend --reset-author --no-edit</code></strong><br />Or use the following to set it to a custom author:<br /><strong><code>git commit --amend --no-edit --author="Author Name &lt;email@address.com&gt;"</code></strong></li>
<li>Run <strong><code>git rebase --continue</code></strong></li>
<li>Repeat step 4 and 5 until all of the commits are updated.</li>
</ol>
]]></content:encoded></item><item><title><![CDATA[Install .NET Core on Ubuntu 15.10]]></title><description><![CDATA[Currently .NET Core is only supported for Ubuntu 14.04 and when you try installing it on Ubuntu 15.10 you get the following error:
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using...]]></description><link>https://danial.au/install-net-core-on-ubuntu-1510</link><guid isPermaLink="true">https://danial.au/install-net-core-on-ubuntu-1510</guid><category><![CDATA[default]]></category><dc:creator><![CDATA[Daniel]]></dc:creator><pubDate>Sun, 17 Apr 2016 04:41:37 GMT</pubDate><content:encoded><![CDATA[<p>Currently .NET Core is only <a target="_blank" href="https://dotnet.github.io/getting-started/">supported for Ubuntu 14.04</a> and when you try installing it on Ubuntu 15.10 you get the following error:</p>
<p>Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:</p>
<p>The following packages have unmet dependencies:
 dotnet : Depends: libicu52 (&gt;= 52~m1-1~) but it is not installable
E: Unable to correct problems, you have held broken packages.</p>
<p>As a workaround you can <a target="_blank" href="http://packages.ubuntu.com/vivid/amd64/libicu52/download">download and install libicu52</a> manually before <a target="_blank" href="https://dotnet.github.io/getting-started/">installing dotnet</a> .</p>
]]></content:encoded></item><item><title><![CDATA[Fix ‘xunit.core’ already has a dependency defined for ‘xunit.extensibility.core’]]></title><description><![CDATA[Problem: ‘xunit.core’ already has a dependency defined for ‘xunit.extensibility.core’
Solution:  Update to the latest version of nuget.exe by running the following command in the .nuget folder of your solution:
nuget update -self]]></description><link>https://danial.au/fix-xunitcore-already-has-a-dependency-defined-for-xunitextensibilitycore</link><guid isPermaLink="true">https://danial.au/fix-xunitcore-already-has-a-dependency-defined-for-xunitextensibilitycore</guid><category><![CDATA[default]]></category><category><![CDATA[Nuget]]></category><dc:creator><![CDATA[Daniel]]></dc:creator><pubDate>Mon, 23 Nov 2015 05:22:44 GMT</pubDate><content:encoded><![CDATA[<p><strong>Problem:</strong> ‘xunit.core’ already has a dependency defined for ‘xunit.extensibility.core’</p>
<p><strong>Solution:</strong>  Update to the latest version of <code>nuget.exe</code> by running the following command in the <code>.nuget</code> folder of your solution:</p>
<p><code>nuget update -self</code></p>
]]></content:encoded></item><item><title><![CDATA[Powershell Restriction Policy]]></title><description><![CDATA[Get-Executionpolicy -List
Set-ExecutionPolicy -Scope Process Unrestricted]]></description><link>https://danial.au/powershell-restriction-policy</link><guid isPermaLink="true">https://danial.au/powershell-restriction-policy</guid><category><![CDATA[Powershell]]></category><dc:creator><![CDATA[Daniel]]></dc:creator><pubDate>Thu, 10 Sep 2015 06:57:57 GMT</pubDate><content:encoded><![CDATA[<p><code>Get-Executionpolicy -List</code></p>
<p><code>Set-ExecutionPolicy -Scope Process Unrestricted</code></p>
]]></content:encoded></item><item><title><![CDATA[How big can a class be]]></title><description><![CDATA[A class should be so small that anyone can easily understand it. If a method is not required to be understood in order to understand the class, then that method probably doesn’t belong in there and it’s not part of the responsibility of that class.
I...]]></description><link>https://danial.au/how-big-can-a-class-be</link><guid isPermaLink="true">https://danial.au/how-big-can-a-class-be</guid><category><![CDATA[default]]></category><dc:creator><![CDATA[Daniel]]></dc:creator><pubDate>Mon, 20 Jul 2015 06:05:59 GMT</pubDate><content:encoded><![CDATA[<p>A class should be so small that anyone can easily understand it. If a method is not required to be understood in order to understand the class, then that method probably doesn’t belong in there and it’s not part of the responsibility of that class.</p>
<p>It is not a good idea to judge how big a class is based on the number of lines of code, however the following list can give you a rough estimate:</p>
<ul>
<li>Less than 100: Ideal</li>
<li>100 to 200: Ok</li>
<li>200 to 300: Warning</li>
<li>300+: The class is too big</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Identify the IIS App Pool associated with a w3wp process]]></title><description><![CDATA[When there are multiple app pools running, you see more than one w3wp.exe in the list of processes you want to attach to. The following command helps to find the process associated with your app pool:
%systemroot%\system32\inetsrv\APPCMD  LIST WP]]></description><link>https://danial.au/identify-the-iis-app-pool-associated-with-a-w3wp-process</link><guid isPermaLink="true">https://danial.au/identify-the-iis-app-pool-associated-with-a-w3wp-process</guid><category><![CDATA[default]]></category><dc:creator><![CDATA[Daniel]]></dc:creator><pubDate>Tue, 14 Jul 2015 08:07:27 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1715929192247/5ae88ff2-7bad-47ab-baf1-0269ac1faff1.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>When there are multiple app pools running, you see more than one w3wp.exe in the list of processes you want to attach to. The following command helps to find the process associated with your app pool:</p>
<p>%systemroot%\system32\inetsrv\APPCMD  LIST WP</p>
<p><a target="_blank" href="https://baharestani.com/wp-content/uploads/2015/07/appcmd.png"><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1715929191308/53b94570-3719-45dc-a7e9-5d8e6723aa6c.png" alt="Appcmd" /></a></p>
]]></content:encoded></item><item><title><![CDATA[How to install JSon.Net NuGet package]]></title><description><![CDATA[Problem:
You are going to install Json.NET NuGet package but you get the following error:
 JSON Failed to initialize the PowerShell host. If your PowerShell execution policy setting is set to AllSigned, open the Package Manager Console to initialize ...]]></description><link>https://danial.au/how-to-install-jsonnet-nuget-package</link><guid isPermaLink="true">https://danial.au/how-to-install-jsonnet-nuget-package</guid><category><![CDATA[default]]></category><dc:creator><![CDATA[Daniel]]></dc:creator><pubDate>Wed, 13 May 2015 01:36:02 GMT</pubDate><content:encoded><![CDATA[<p><strong>Problem</strong>:</p>
<p>You are going to install Json.NET NuGet package but you get the following error:</p>
<p> <em>JSON Failed to initialize the PowerShell host. If your PowerShell execution policy setting is set to AllSigned, open the Package Manager Console to initialize the host first.</em></p>
<p><strong>Solution</strong>:</p>
<ol>
<li>Open PowerShell console in Administrator mode. Note that you should open the x86 version if you are running the 32bit version of Visual Studio. Likewise open x64 if your Visual Studio is 64bit.</li>
<li>Run this command <code>start-job { Set-ExecutionPolicy Unrestricted } -RunAs32 | wait-job | Receive-Job</code></li>
<li>Reopen Visual and the issue should be fixed</li>
</ol>
]]></content:encoded></item><item><title><![CDATA[Association vs. Aggregation vs. Composition]]></title><description><![CDATA[Association
Association is the most general type of relationship and it  includes other types as well. If the relationship doesn’t fall into a more specific type, like Aggregation or Composition, it can simply be referred to as an Association.
Exampl...]]></description><link>https://danial.au/association-vs-aggregation-vs-composition</link><guid isPermaLink="true">https://danial.au/association-vs-aggregation-vs-composition</guid><category><![CDATA[default]]></category><dc:creator><![CDATA[Daniel]]></dc:creator><pubDate>Thu, 14 Aug 2014 08:04:58 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1715929199520/18a7fd0f-a680-4849-8669-804d17d06c8c.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-association">Association</h2>
<p>Association is the most general type of relationship and it  includes other types as well. If the relationship doesn’t fall into a more specific type, like Aggregation or Composition, it can simply be referred to as an Association.</p>
<p><strong>Example</strong>: When a Customer places an Order, the relationship is simply an Association.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1715929196117/726cf6be-2662-4d21-8ec5-8bd37dca8080.png" alt="Association" /></p>
<h2 id="heading-aggregation">Aggregation</h2>
<p>Aggregation is a more specific type of association. In an aggregation the children can also be shared with another owner at the same time, and even if the owner no longer exists, the children can still continue their lifetime.</p>
<p><strong>Example</strong>: The relationship between a UserGroup and the Users, is an Aggregation. A User can still have meaning in the system even if it doesn’t belong to a UserGroup, so if you delete a UserGroup you won’t delete its Users. On the other hand, the Users can belong to several UserGroups at the same time.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1715929197485/30372917-d0ff-4346-ac37-d9d0569be603.png" alt="Aggregation" /></p>
<h2 id="heading-composition">Composition</h2>
<p>Composition is a more strict type of Aggregation. In an aggregation, the children cannot be shared with a different owner and it doesn’t make sense for the children to exist without their owner. So, you usually want to delete the children if you delete their owner.</p>
<p><strong>Example</strong>: The relationship between an Order and the OrderDetails is a composition relationship. The OrderDetail items are valid only as long as there is an Order related to them. When you delete an Order you will delete it’s OrderDetails as well. An OrderDetail associated to a particular Order cannot belong to a different Order.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1715929198715/e7e5cba1-1bca-46d1-af17-8d373179196f.png" alt="Composition" /></p>
]]></content:encoded></item><item><title><![CDATA[Using Ninject in ASP.NET MVC applications]]></title><description><![CDATA[The following article is part of the chapter 4 of my book, [Mastering Ninject for Dependency Injection, [PACKT] publishing, 2013](http://www.packtpub.com/mastering-ninject-for-dependency-injection/book "Mastering Ninject for Dependency Injection").

...]]></description><link>https://danial.au/using-ninject-in-aspnet-mvc-applications</link><guid isPermaLink="true">https://danial.au/using-ninject-in-aspnet-mvc-applications</guid><category><![CDATA[General Programming]]></category><dc:creator><![CDATA[Daniel]]></dc:creator><pubDate>Sat, 05 Jul 2014 03:12:11 GMT</pubDate><content:encoded><![CDATA[<p><em>The following article is part of the chapter 4 of my book, [Mastering Ninject for Dependency Injection, [PACKT] publishing, 2013](http://www.packtpub.com/mastering-ninject-for-dependency-injection/book "Mastering Ninject for Dependency Injection").</em></p>
<hr />
<p>In this article, we will implement [the Northwind customers scenario](https://baharestani.com/northwind-customers-scenario/ "Northwind Customers scenario") using Ninject in an ASP.NET MVC 3 application. Ninject MVC extension also supports other versions of the MVC framework. (<a target="_blank" href="http://www.packtpub.com/support/13850">Download the source code</a>)</p>
<p>Add a new ASP .NET MVC3 Web application to the Northwind solution with references to the Northwind.Core project and Ninject Conventions extension.<br />We should also reference Ninject MVC extension. The easiest way is to install the Ninject.Mvc3 package using NuGet. Keep in mind that although the name of the package is Ninject.Mvc3, it is upward compatible with newer versions of the MVC framework. Alternatively, we could download the Ninject.Web.Mvc binary from GitHub and reference it from our project. In this case, we also needed to reference the Ninject and Ninject.Web.Common libraries. These libraries are referenced automatically if we install the Ninject.Mvc3 package using NuGet. NuGet also adds the App_Start folder containing a file named NinjectWebCommon.cs to the project. The NinjectWebCommon class contains a Start() method that will be the starting point of the application. It sets up everything to hook Ninject to MVC framework. So, once we have installed Ninject MVC extension using NuGet, we do not need to do anything else to set up our application, and everything will be already there for us. This is because NuGet allows packages to add files to the project as a part of their installation process. The NinjectWebCommon class has a method named CreateKernel which can be used as the Composition Root to register our services. We will talk more about this class in the next section.<br />If we reference Ninject libraries manually using separately downloaded binary files, we should make the following changes to the MvcApplication class located under the Global.asax file:</p>
<ol>
<li>The MvcApplication class should derive from the NinjectHttpApplication class, rather than System.Web.HttpApplication.</li>
<li>Instead of having the Application_Start method as the starting point, we should override the OnApplicationStarted method, and anything within Application_Start should go to OnApplicationStarted.</li>
<li>We should override CreateKernel and use it for service registration.</li>
</ol>
<p>The following code shows the CreateKernel method:</p>
<p>protected override IKernel CreateKernel()
{
    var kernel = new StandardKernel();
    kernel.Load(new ServiceRegistration());
    return kernel;
}</p>
<p>Even if we use NuGet to set up our project, we can delete the App_Start folder, and use Global.asax as described previously. In this case, we can remove references to the WebActivator and Microsoft.Web.Infrastructure libraries that NuGet has created. It is up to you which approach to use, as they do exactly the same thing in two different ways. The first one is easier to use and does not need any extra efforts to set up the application; while the second one uses the existing Global.asax file as the application startup point and doesn’t require additional files or libraries to be referenced. In this example, we use the Global.asax file as starting point. In the next section, we will use the App_Start and NinjectWebCommon classes which NuGet creates.<br />Let’s start implementing the presentation of customers list in our application. Open the HomeController class and add a constructor which introduces our ICustomerRepository interface as its parameter:</p>
<p>private readonly ICustomerRepository repository;</p>
<p>public HomeController(ICustomerRepository repository)
{
    this.repository = repository;
}</p>
<p>The next step is to modify the Index action method as follows:</p>
<p>public ActionResult Index()
{
    var customers = repository.GetAll();
    return View(customers);
}</p>
<p>It uses the ICustomerRepository interface to populate customers. Please note that we don’t need to create a new Model for customer and the one that we have already created in our domain layer is being used here. Then delete the existing Index.cshtml View and add a new one with List scaffold template and our Customer domain model as the Model class.<br />Now add the Create action methods as follows:</p>
<p>public ActionResult Create()
{
    return View();
}</p>
<p>[HttpPost]
public ActionResult Create(Customer customer)
{
    if (ModelState.IsValid)
    {
        repository.Add(customer);
        return RedirectToAction("Index");
    }
    return View();
}</p>
<p>The first one is called when the hyperlink Create New is clicked using HTTP GET method and the second one is called when the Create View is submitted using HTTP POST method. The created customer Model is passed to the Create method and can be added to the repository. Checking the ModelState.IsValid property is for server-side validation. We can now add a Create View for this action with Core.Customer as Model class and the Create scaffold template.</p>
<h2 id="heading-validator-injection">Validator injection</h2>
<p>Now we need to add some validation rules to our Customer Model class. MVC framework supports different kinds of validation including annotation-based validation in which we use validation attributes on the properties of the Model to define the validation rules:</p>
<p>public class Customer
{
    [Required]
    public string ID { get; set; }
    [Required]
    public string CompanyName { get; set; }
    public string City { get; set; }
    public string PostalCode { get; set; }
    [StringLength(10)]
    public string Phone { get; set; }
}</p>
<p>The validation attributes are not part of MVC library and this makes it possible to apply them to our Customer Model within our domain layer. This way, we can share these validation rules among other UI frameworks as well. We just need to reference the System.ComponentModel.DataAnnotations library in our domain project. MVC framework automatically validates the Model based on the provided attributes. But these attributes are limited to basic validation rules. What if we need to check whether the provided ID for our customer is not duplicated? In such scenarios we need to create our custom validation attributes:</p>
<p>public class UniqueCustomerIdAttribute : ValidationAttribute
{
    [Inject]
    public ICustomerValidator Validator { get; set; }</p>
<p>    public override bool IsValid(object value)
    {
        if (Validator == null)
        {
            throw new Exception("Validator is not specified.");
        }
        if (string.IsNullOrEmpty(value as string))
        {
            return false;
        }
        return Validator.ValidateUniqueness(value as string);
    }
}</p>
<p>By deriving from ValidationAttribute and overriding its IsValid method, we can define a custom validation attribute. This validator uses an object of the type ICustomerValidator to validate the given value which is a customer ID across the repository to check whether it is unique or duplicated. The following is the implementation of ICustomerValidator:</p>
<p>public class CustomerValidator : ICustomerValidator
{
    private readonly ICustomerRepository repository;</p>
<p>    public CustomerValidator(ICustomerRepository repository)
    {
        this.repository = repository;
    }</p>
<p>    public bool ValidateUniqueness(string customerID)
    {
        return repository.Get(customerID) == null;
    }
}</p>
<p>Validation is successful, provided the repository cannot find any existing customer with the given customer ID.<br />You may have noticed that in the UniqueCustomerIdAttribute class we didn’t introduce the ICustomerValidator interface as a dependency in the constructor. The reason is that it is not possible to apply an attribute which requires constructor parameters without providing its arguments. That’s why we used the Property Injection pattern, rather than Constructor Injection. Although this attribute should be instantiated by MVC framework, Ninject can inject the dependency before the IsValid method is called. Now you may be wondering that applying the [Inject] attribute in our domain layer, will make it dependent on Ninject. Well, it didn’t, because we didn’t use the Ninject version of the [Inject] attribute. Instead, we created another InjectAttribute class in our Core library. We discussed about how to set up Ninject to use another attribute instead of its internal [Inject] attribute in Chapter 3, Meeting real-world Requirements. This way we don’t have to have a reference to the Ninject library, and can even replace Ninject with other DI containers without needing to touch the domain layer.<br />We can now add the UniqueCustomerIdAttribute attribute to the validation rules of our Customer Model:</p>
<p>[Required, UniqueCustomerId]
public string ID { get; set; }</p>
<h2 id="heading-filter-injection">Filter injection</h2>
<p>Filters are implementations of the IActionFilter, IResultFilter, IExceptionFilter, or IAuthorizationFilter interfaces that make it possible to perform special operations while invoking an action method. ASP.NET MVC allows us to apply filters in two ways, both of which are supported by Ninject:</p>
<ul>
<li>Applying a filter attribute to the Controller or an Action method. This approach has been supported by MVC framework since its first version and doesn’t fully support DI.</li>
<li>Applying filters without attributes using filter providers which is introduced in MVC 3 and supports all DI patterns.</li>
</ul>
<p>In the first method, the filter class derives from ActionFilterAttribute and the created filter attribute will be applied to a Controller or one of its action methods. Like other attributes, a filter attribute cannot be applied if it does not have a default constructor, so we cannot use Constructor Injection in filter attributes. However, if we use Property Injection using the [Inject] attribute, the dependencies get injected by Ninject without any special configuration. The following example shows how to define an action filter attribute which can pass action information to a performance monitoring service:</p>
<p>public class PerformanceFilterAttribute : ActionFilterAttribute
{
    [Inject]
    public IPerformanceMonitoringService PerformanceMonitor
    { get; set; }</p>
<p>    public void OnActionExecuting(ActionExecutingContext filterContext)
    {
        PerformanceMonitor.BeginMonitor(filterContext);
    }</p>
<p>    public void OnActionExecuted(ActionExecutedContext filterContext)
    {
        PerformanceMonitor.EndMonitor(filterContext);
    }
}</p>
<p>The implementation of IPerformanceMonitoringService will be injected by Ninject into the property PerformanceMonitor.<br />MVC3 or later versions of MVC, however, support a new way of applying filters which is DI compatible and allows all DI patterns including Construction Injection. Thus, the previous approach is not recommended in MVC3+.<br />The following example demonstrates how to define and apply LogFilter to our actions, which can log some tracking information about the called or being called action methods. The filter uses the ILog interface of the Log4Net library as a dependency:</p>
<p>public class LogFilter : IActionFilter
{
    private readonly ILog log;
    private readonly Level logLevel;</p>
<p>    public LogFilter(ILog log, string logLevel)
    {
        this.log = log;
        this.logLevel = log.Logger.Repository.LevelMap[logLevel];
    }</p>
<p>    public void OnActionExecuting(ActionExecutingContext filterContext)
    {
        var message = string.Format(
CultureInfo.InvariantCulture,"Executing action {0}.{1}",            filterContext.ActionDescriptor.ControllerDescriptor.ControllerName, filterContext.ActionDescriptor.ActionName);
       this.log.Logger.Log(typeof(LogFilter), this.logLevel, message, null);    }</p>
<p>    public void OnActionExecuted(ActionExecutedContext filterContext)
    {
        var message = string.Format(
  CultureInfo.InvariantCulture, "Executed action {0}.{1}",
filterContext.ActionDescriptor.ControllerDescriptor.ControllerName, filterContext.ActionDescriptor.ActionName);
 this.log.Logger.Log(typeof(LogFilter),
 this.logLevel, message, null);
    }
}</p>
<p>The LogFilter class uses the provided filterContext argument to determine the name of the Action method and its enclosing Controller. It then uses the injected implementation of ILog to log the tracking information. This class introduces two dependencies, one of which is the ILog interface and the other one is the log level under which the messages should be logged.<br />In order to tell MVC to use Ninject to resolve a filter, we need to register the filter using the BindFilter method of Kernel:</p>
<p>Kernel.BindFilter(FilterScope.Action, 0)
     .WithConstructorArgument("logLevel", ("Info");</p>
<p>The first parameter defines the filter scope whose type is System.Web.Mvc.FilterScope and the second one is a number defining the order of the filter. This information is required by MVC to instantiate and apply filters. Ninject collects these information and asks MVC on our behalf to create an instance of the given filter type and apply it to the given scope. In the previous example, LogFilter will be resolved using Ninject with “Info” as an argument for the logLevel parameter and will be applied to all of the Action methods.<br />The ILog log parameter will be resolved based on how we register ILog. If you have used Log4Net before, you will remember that it can associate each logger to the type of class for which the logger is used:</p>
<p>public class MyClass
{
    private static readonly ILog log =
                       LogManager.GetLogger(typeof(MyApp));
}</p>
<p>This way, the logs can later be filtered based on their associated types.<br />In order to provide the required type for our logger, we bind it to a method rather than a concrete service. This way we can use the context object to determine the type of object requiring the log:</p>
<p>Bind().ToMethod(GetLogger);</p>
<p>The following is the code for the GetLogger method:</p>
<p>private static ILog GetLogger(IContext ctx)
{
    var filterContext = ctx.Request.ParentRequest.Parameters
                    .OfType().SingleOrDefault();
    return LogManager.GetLogger(filterContext == null ?
        ctx.Request.Target.Member.DeclaringType :
        filterContext.ActionDescriptor.ControllerDescriptor.ControllerType);
}</p>
<p>In the previous code, the context.Request is the request for resolving ILog and ParentRequest is the request for resolving LogFilter. When a filter class is registered using BindFilter, Ninject provides the request with a parameter of type FilterContextParameter, which contains information about the context of the object to which the filter is being applied, and we can then obtain the type of the Controller class from it. Otherwise, this parameter is not provided, which means the logger is not requested by a filter class, in which case, we just use the type of the class requiring the logger.</p>
<h3 id="heading-conditional-filtering-when">Conditional filtering (When)</h3>
<p>Now what if we are not going to apply the filter to all of the Controllers or the action methods? Ninject provides three groups of the WhenXXX methods to determine in which conditions to apply the filter:</p>
<ul>
<li>WhenControllerType: This method applies the filter to the specified Controller types only.</li>
<li>WhenControllerHas: This method applies the filter to those Controllers with specified attribute type</li>
<li>WhenActionMethodHas: This method applies the filter to those Action methods with the specified attribute type</li>
</ul>
<p>Apart from the mentioned three groups, Ninject offers a generic When method which can be used to define any custom conditions which cannot be applied using the previous methods.<br />The following code shows how to apply LogFilter to those action methods which have LogAttribute, given that the LogAttribute class is a simple class deriving from the Attribute class:</p>
<p>Kernel.BindFilter(FilterScope.Action, 0)
 .WhenActionMethodHas()
 .WithConstructorArgument("logLevel", ("Info");</p>
<p>This is another example that shows how to apply this filter to all of the actions of the HomeController class:</p>
<p>Kernel.BindFilter(FilterScope.Controller, 0)
 .WhenControllerType ()
 .WithConstructorArgument("logLevel", ("Info");</p>
<h3 id="heading-contextual-arguments-with">Contextual arguments (With)</h3>
<p>In the previous examples, we have always used a constant “Info” argument to be passed to the logLevel parameter. Apart from the standard WithXXX helpers, which can be used on normal bindings, Ninject provides the following WithXXX methods especially for filter binding:</p>
<ul>
<li>WithConstructorArgumentFromActionAttribute: It allows to get the constructor argument from the attribute which is applied to the action method</li>
<li>WithConstructorArgumentFromControllerAttribute: It allows to get the constructor argument from the attribute which is applied to the Controller class</li>
<li>WithPropertyValueFromActionAttribute: In case of Property Injection, it allows to set the property using a value from the attribute which is applied to the action method</li>
<li>WithPropertyValueFromControllerAttribute: In case of Property Injection, it allows to set the property using a value from the attribute which is applied to the Controller class</li>
</ul>
<p>In the following code, we get the log level from the LogAttribute class rather than always passing a constant string to the logLevel parameter:</p>
<p>Kernel.BindFilter(FilterScope.Action, 0)
    .WhenActionMethodHas()
    .WithConstructorArgumentFromActionAttribute(
        "logLevel",
        attribute =&gt; attribute.LogLevel);</p>
<p>The previous code requires the LogAttribute class to have the LogLevel property:</p>
<p>public class LogAttribute : Attribute
{
    public string LogLevel { get; set; }
}</p>
]]></content:encoded></item><item><title><![CDATA[Custom awaitable and awaiter types in C# 5.0 asynchronous]]></title><description><![CDATA[In C# 5.0 you can use the await keyword to await an awaitable object. But what is the minimum requirement for an object to be considered awaitable by C#? Interestingly there are no interfaces to be implemented in order to be considered awaitable!Havi...]]></description><link>https://danial.au/custom-awaitable-and-awaiter-types-in-c-50-asynchronous</link><guid isPermaLink="true">https://danial.au/custom-awaitable-and-awaiter-types-in-c-50-asynchronous</guid><category><![CDATA[General Programming]]></category><dc:creator><![CDATA[Daniel]]></dc:creator><pubDate>Sun, 15 Jun 2014 12:12:38 GMT</pubDate><content:encoded><![CDATA[<p>In C# 5.0 you can use the <code>await</code> keyword to await an <code>awaitable</code> object. But what is the minimum requirement for an object to be considered <code>awaitable</code> by C#? Interestingly there are no interfaces to be implemented in order to be considered <code>awaitable</code>!<br />Having a parameter-less method named <code>GetAwaiter()</code> which returns an <code>awaiter</code> object is the only convention for a type to be recognized <code>awaitable</code> by C#:</p>
<p>// This class is awaitable because it has the GetAwaiter method, provided MyAwaiter is an awaiter.
public class MyWaitable
{
    public MyAwaiter GetAwaiter()
    {
        return new MyAwaiter();
    }
}</p>
<p>Now the question is how to make a type <code>awaiter</code>? The minimum requirements for a type to be <code>awiater</code> are implementing the <code>INotifyCompletion</code> interface, and having the <code>IsCompleted</code> property and the <code>GetResult</code> method with the following signatures:</p>
<p>public class MyAwaiter : INotifyCompletion
{
    public void OnCompleted(Action continuation)
    {</p>
<p>    }</p>
<p>    public bool IsCompleted
    {
        get
        {
            return false;
        }
    }</p>
<p>    public void GetResult()
    {</p>
<p>    }
}</p>
]]></content:encoded></item><item><title><![CDATA[Batch edit TeamCity build configurations]]></title><description><![CDATA[TeamCity supports parameters, so if you are dealing with so many build configurations on your TeamCity server and you need to change something in all of your projects, the best practice is to use parameters or build templates. But what if you need to...]]></description><link>https://danial.au/batch-edit-teamcity-build-configurations</link><guid isPermaLink="true">https://danial.au/batch-edit-teamcity-build-configurations</guid><category><![CDATA[default]]></category><dc:creator><![CDATA[Daniel]]></dc:creator><pubDate>Wed, 11 Jun 2014 06:37:39 GMT</pubDate><content:encoded><![CDATA[<p>TeamCity supports parameters, so if you are dealing with so many build configurations on your TeamCity server and you need to change something in all of your projects, the best practice is to use parameters or build templates. But what if you need to change a value in multiple build configurations or multiple projects and that value cannot be (or is not) defined as a parameter? In such cases you can use the following shortcut instead of going through each build configuration to edit them:</p>
<ol>
<li>On the TeamCity machine, open the data directory. It can be identified using the <code>TEAMCITY_DATA_PATH</code> environment variable.</li>
<li>Open the corresponding directory to your required project from <code>%TEAMCITY_DATA_PATH%\config\projects</code>.</li>
<li>All of the build configurations are stored as XML files in the <code>buildTypes</code> directory.</li>
<li>Use a powerful text editor (e.g. [Notepad++](http://notepad-plus-plus.org/ "Notepad++") ) to batch edit the files.</li>
<li>From the TeamCity administration page, go to Server Administration\Diagnostics\Caches and reset buildsMetadata.</li>
</ol>
<p>After a couple of seconds the changes should be reflected in all of your build configurations.</p>
]]></content:encoded></item><item><title><![CDATA[How to delete saved network users]]></title><description><![CDATA[Using the following command you will have access to advanced user management dialogue which allows you to add,edit or delete the stored network credentials (Advanced Tab):Control Userpasswords2

Reference: http://support.microsoft.com/kb/306992]]></description><link>https://danial.au/how-to-delete-saved-network-users</link><guid isPermaLink="true">https://danial.au/how-to-delete-saved-network-users</guid><category><![CDATA[default]]></category><dc:creator><![CDATA[Daniel]]></dc:creator><pubDate>Wed, 28 May 2014 03:09:22 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1715929207004/a473acca-e065-487a-996d-d81f3143b05e.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Using the following command you will have access to advanced user management dialogue which allows you to add,edit or delete the stored network credentials (Advanced Tab):<br /><strong>Control Userpasswords2</strong></p>
<p><a target="_blank" href="https://baharestani.com/wp-content/uploads/2014/05/userpasswords2.png"><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1715929205990/43bdd649-0597-4dfa-9d73-8245e651ee50.png" alt="Userpasswords2" /></a></p>
<p>Reference: <a target="_blank" href="http://support.microsoft.com/kb/306992">http://support.microsoft.com/kb/306992</a></p>
]]></content:encoded></item></channel></rss>