Fagner Nunes Carvalho2021-04-04T04:41:05+00:00http://fagner.co/Fagner Nunes CarvalhoFree space on Raspberry Pi2021-04-04T00:00:00+00:00http://fagner.co//2021/04/04/Free-space-on-Raspberry-Pi<p>I have been using a 16GB SD card (I know, could be larger) in a Raspberry Pi for a few years now and never had a problem but recently I started working in a side project and decided to use Docker on this Pi. Because of this I almost filled the SD card in just a few months.</p>
<p>In this post I’m going to give you a few commands that should help you to reclaim some space in your SD card and continue your experiments or side projects. I take no responsibility for any undesired data loss and I ask you to do the proper research about any of the commands posted here. Enjoy!</p>
<p>Also, very important: please backup the contents of your SD card periodically and especially before you start doing this. To do this, run this on Linux in an unmounted partition (not tested, I’m using Windows right now. Yes I know!).</p>
<script src="https://gist.github.com/a5807675864300a2032e497fd3f7e7df.js?file=backup-raspberrypi.md"> </script>
<p>If you are using Windows use Win32DiskImager, type a file name for your backup image, select your SD card and click Read.</p>
<p>When looking for this topic online the first tip was to remove WolframAlpha and LibreOffice. The thing is, if you want to use Raspbian in a Raspberry Pi that will serve only as a server you want to choose Raspbian Lite and not the full desktop version. In any case, if you already installed the desktop version run the following commands to remove WolframAlpha and LibreOffice:</p>
<script src="https://gist.github.com/a5807675864300a2032e497fd3f7e7df.js?file=remove-wolfram-libre-office.md"> </script>
<p>If you use Pi-hole you can remove the SQLite database created by Pihole to store logs:</p>
<script src="https://gist.github.com/a5807675864300a2032e497fd3f7e7df.js?file=remove-pihole-db.md"> </script>
<p>You can also clean the APT cache and remove any unused dependencies.</p>
<script src="https://gist.github.com/a5807675864300a2032e497fd3f7e7df.js?file=clean-apt.md"> </script>
<p>And finally, run the following command to clean your Docker cache (don’t worry, you need to confirm after running the command):</p>
<script src="https://gist.github.com/a5807675864300a2032e497fd3f7e7df.js?file=clear-docker-cache.md"> </script>
<p>After cleaning everything run a command to see your available space:</p>
<script src="https://gist.github.com/a5807675864300a2032e497fd3f7e7df.js?file=see-available-space.md"> </script>
<p>If you still don’t have enough available space run this command in your root system folder for getting which folders/files are using most of the space in your card:</p>
<script src="https://gist.github.com/a5807675864300a2032e497fd3f7e7df.js?file=check-used-space.md"> </script>
<p>You will need to check these folders/file one by one and use your judgement to see if they can be deleted or not. Normally you can delete everything from your /tmp folder but I wouldn’t mess with anything else.</p>
<p>I hope this helped you, have a good day!</p>
Live reload in .NET Core2020-09-06T00:00:00+00:00http://fagner.co//2020/09/06/Live-reload-in-Dot-Net-Core<p>This week I was looking for a way to do live reloading in ASP.NET Core projects.</p>
<p>Don’t judge me but I actually never cared that much about live reloading, I lived life in a constant state of stopping and starting applications every after a few changes. What changed is that after working with React for a few months I really liked the idea of reflecting changes from your code in the application instantly (well, almost).</p>
<p>For ASP.NET Core projects you need to do a few changes in your code to enable live reloading.</p>
<p>First, you need to install the <code class="language-plaintext highlighter-rouge">Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation</code> NuGet package into your target application.</p>
<p>Then add <code class="language-plaintext highlighter-rouge">AddRazorRuntimeCompilation</code> to your <code class="language-plaintext highlighter-rouge">Startup</code> class.</p>
<script src="https://gist.github.com/61291f22668a665f7fd5ebbabf2e597a.js?file=razorruntime.cs"> </script>
<p>This will enable live reloading for Razor Pages and Views. Don’t worry, the reloading will take a few seconds in the first time but it should be faster for subsequent changes.</p>
<p>For enabling the same for C# files you have two options:</p>
<ul>
<li>Change your <code class="language-plaintext highlighter-rouge">launchSettings.json</code> in case you are using Visual Studio.</li>
<li>Use the <code class="language-plaintext highlighter-rouge">dotnet watch run</code> command.</li>
</ul>
<p>If you are using Visual Studio, change the <code class="language-plaintext highlighter-rouge">launchSettings.json</code> like this:</p>
<script src="https://gist.github.com/61291f22668a665f7fd5ebbabf2e597a.js?file=launchsettings-aspnet.json"> </script>
<p>This also works for console apps. In this case use:</p>
<script src="https://gist.github.com/61291f22668a665f7fd5ebbabf2e597a.js?file=launchsettings-console.json"> </script>
<p>In case you aren’t using Visual Studio (you could be using Rider or VS Code), you can use the <code class="language-plaintext highlighter-rouge">dotnet watch run</code> command. For this, go to your project folder via command prompt and simply run <code class="language-plaintext highlighter-rouge">dotnet watch run</code>. You should have the same experience you have in Visual Studio. Nice, isn’t it?</p>
<p>Now the .NET CLI will be listening and in case you change a C# file the application will be restarted with your changes applied. For Razor files, the .cshtml files will be recompiled and your changes will be visible in runtime.</p>
<p><img src="http://fagner.co/public/images/LiveReloading.png" alt="Live Reloading" /></p>
<p>The only missing piece here is actually doing a live reload in the browser. Until right now the changes in C# and Razor files are being reflected in runtime but you need to reload the browser manually. To change this Rick Strahl made <a href="https://weblog.west-wind.com/posts/2019/Jun/03/Building-Live-Reload-Middleware-for-ASPNET-Core">an awesome ASP.NET middleware that does this for you</a>. I will not be talking about this here but this is included in my sample.</p>
<p>If you want to get access to the source code for the ASP.NET Core and Console applications please go to <a href="https://github.com/fagnercarvalho/LiveReloadNetCore">ASP.NET Core live reloading</a> and <a href="https://github.com/fagnercarvalho/LiveReloadConsoleNetCore">Console Application live reloading</a>.</p>
Omegle clone using SignalR2016-02-28T00:00:00+00:00http://fagner.co//2016/02/28/Omegle-clone-using-SignalR<p>A few days ago I was looking through <a href="http://www.asp.net/signalr">SignalR</a> and I had the idea to build an Omegle clone. The Omegle one-on-one random chat have a good fit with SignalR, so I decided to try it.</p>
<p>Talking about my implementation in more detail, the two most important parts of my application are the SignalR Hub call <code class="language-plaintext highlighter-rouge">ChatHub</code> and the <code class="language-plaintext highlighter-rouge">chat.js</code> file where I added SignalR hub client connection code.</p>
<p>In <code class="language-plaintext highlighter-rouge">ChatHub</code> the methods <code class="language-plaintext highlighter-rouge">OnConnected</code> and <code class="language-plaintext highlighter-rouge">OnDisconnected</code> were overridden from the <code class="language-plaintext highlighter-rouge">Hub</code> base class so I could add logic for when a new user connects to chat with someone or when disconnects (abruptly or not). Every connection is stored in a static variable <code class="language-plaintext highlighter-rouge">Chats</code> that are going to be deleted in case the application closes. I also created a <code class="language-plaintext highlighter-rouge">Send</code> method for when an user sends a message to the other user.</p>
<script src="https://gist.github.com/c8997eb4d77fe91f803c.js?file=chathub.cs"> </script>
<p>The <code class="language-plaintext highlighter-rouge">Send</code> method just gets the other user and sends the message to him calling the <code class="language-plaintext highlighter-rouge">receiveMessage</code>. This method will be declared in the client, <code class="language-plaintext highlighter-rouge">chat.js</code>.</p>
<p>The <code class="language-plaintext highlighter-rouge">chat.js</code> is responsible for handling all client logic for connecting and disconnecting from the chat or sending and receiving messages. Every time you send a message your name is showed to you as “You” and “Stranger” to the other party just like Omegle and if you or your partner disconnect from the chat a message appears suggesting to begin a new chat.</p>
<p>Now, a screenshot showing the chat running:</p>
<p><img src="http://fagner.co/public/images/OmegleR.png" alt="OmegleR" /></p>
<p>If you want to get access to the source code please go to <a href="https://github.com/fagnercarvalho/OmegleR">OmegleR GitHub repository</a>.</p>
Bulk inserting data into SQL Server using C#2016-02-15T00:00:00+00:00http://fagner.co//2016/02/15/Bulk-inserting-data-into-SQL-Server-using-CSharp<p>In the last few days I had a question: what is the most fastest method to bulk insert data into a SQL Server database using C#? I decided to gather up all methods that I could find and do a very simple performance test to decide which one is the fastest.</p>
<p>Here are my results for inserting 10000 rows over 500 iterations:</p>
<table>
<thead>
<tr>
<th>Method</th>
<th>Time</th>
</tr>
</thead>
<tbody>
<tr>
<td><code class="language-plaintext highlighter-rouge">SqlBulkCopy</code> class</td>
<td>137.022 ms</td>
</tr>
<tr>
<td><code class="language-plaintext highlighter-rouge">bcp</code> utility</td>
<td>146.876 ms</td>
</tr>
<tr>
<td>Table-Valued Parameter</td>
<td>150.900 ms</td>
</tr>
<tr>
<td>Simple.Data</td>
<td>208.320 ms</td>
</tr>
<tr>
<td>XQuery</td>
<td>235.490 ms</td>
</tr>
</tbody>
</table>
<p>My configuration:</p>
<ul>
<li>i5 M460 @ 2.53GHz</li>
<li>6GB of RAM</li>
<li>500GB 7200 RPM 16MB Cache HDD</li>
</ul>
<p>SQL Server version:</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Microsoft SQL Server 2014 - 12.0.2000.8 (X64) Feb 20 2014 20:04:26 Copyright (c) Microsoft Corporation Express Edition (64-bit) on Windows NT 6.3 <X64> (Build 9600: )
</code></pre></div></div>
<p>The first thing you may notice was the <code class="language-plaintext highlighter-rouge">bcp</code> there. Yes, <code class="language-plaintext highlighter-rouge">bcp</code> wasn’t run from C# but I wanted to add to the list for comparison purposes.</p>
<p>Well, basically all methods listed had very similar results but if you are searching for the fastest one you choose <code class="language-plaintext highlighter-rouge">SqlBulkCopy</code>.
Moreover, the remaining methods got more than one disadvantage besides performance: the <code class="language-plaintext highlighter-rouge">bcp</code> needs to receive a <code class="language-plaintext highlighter-rouge">.csv</code> file, Table-Valued Parameter (TVP) needs to have a TVP Type in the target database, <code class="language-plaintext highlighter-rouge">Simple.Data</code> needs a third party library installed, <code class="language-plaintext highlighter-rouge">Simple.Data</code> and XQuery needs a <code class="language-plaintext highlighter-rouge">.xml</code> file and also a procedure created in the database.</p>
<p>If you are interested in take a look at the code that generated the results <a href="https://github.com/fagnercarvalho/bulk-insert-sqlserver-csharp/blob/master/BulkInsertSqlServer/Program.cs">I added the test code in GitHub</a>. In the code you will see that I tested Dapper but the performance was bad and I decided to remove from the test results. I also used the <code class="language-plaintext highlighter-rouge">Parallel.For</code> method but the performance was even worse.</p>
SonarQube configuration tutorial2016-02-05T00:00:00+00:00http://fagner.co//2016/02/05/SonarQube-configuration-tutorial<p>This post will be a simple tutorial to install, configure and use SonarQube to analyse your project code quality. This tutorial will be directed to C# and JavaScript projects in a Windows environment.</p>
<p><strong>1-</strong> <a href="http://www.sonarqube.org/downloads/">Download SonarQube</a></p>
<p><strong>2-</strong> Create a SQL Server database</p>
<p class="message">
If you don't have SQL Server installed download SQL Server Express, a
free and limited SQL Server edition option (<a href="https://www.microsoft.com/en-us/server-cloud/products/sql-server-editions/overview.aspx">SQL Server editions comparison here</a>).
</p>
<p>Run the following command:</p>
<figure class="highlight"><pre><code class="language-sql" data-lang="sql"><span class="k">CREATE</span> <span class="k">DATABASE</span> <span class="n">SonarQube</span><span class="p">;</span></code></pre></figure>
<p>Just after this command the collation from the recently created database needs to be changed as <a href="http://docs.sonarqube.org/display/SONAR/Installing+the+Server#InstallingtheServer-installingDatabaseInstallingtheDatabase">recommended in the SonarQube website</a>:</p>
<figure class="highlight"><pre><code class="language-sql" data-lang="sql"><span class="k">ALTER</span> <span class="k">DATABASE</span> <span class="n">SonarQube</span> <span class="k">COLLATE</span> <span class="n">SQL_Latin1_General_CP1_CS_AS</span><span class="p">;</span></code></pre></figure>
<p>If you want to see the current database collation run:</p>
<figure class="highlight"><pre><code class="language-sql" data-lang="sql"><span class="k">SELECT</span> <span class="k">CONVERT</span> <span class="p">(</span><span class="nb">varchar</span><span class="p">,</span> <span class="n">SERVERPROPERTY</span><span class="p">(</span><span class="s1">'collation'</span><span class="p">));</span></code></pre></figure>
<p><strong>3-</strong> Change the <code class="language-plaintext highlighter-rouge"><sonar_directory>/conf/sonar.properties</code> file</p>
<p>In the <code class="language-plaintext highlighter-rouge">sonar.properties</code> file you configure a lot of stuff regarding hosting and persisting data from SonarQube. We just going to configure which database SonarQube will connect and in which port will be hosted.
To do that just add the two following lines:</p>
<script src="https://gist.github.com/84fa963b266d706ada60.js?file=sonar.properties"> </script>
<p>In order to SonarQube successfully connect in the SQL Server database you are going to need to <a href="https://technet.microsoft.com/en-us/library/hh231672(v=sql.110).aspx">enable the TCP/IP protocol</a> in the database instance you are intending to use. Also make sure that the TCP port being used is the SQL Server default port 1433.</p>
<p>One more detail, if you are using SQL Authentication instead of Windows Authentication you are going to need to add the two following parameters:</p>
<script src="https://gist.github.com/84fa963b266d706ada60.js?file=sonar-user-credentials.properties"> </script>
<p><strong>4-</strong> Start SonarQube</p>
<p>Go to the <code class="language-plaintext highlighter-rouge"><sonar_directory>/bin/windows-x86-64</code> folder (or whatever Windows you are using) and run the <code class="language-plaintext highlighter-rouge">StartSonar.bat</code> file.
If everything goes well you are going to see the SonarQube dashboard.</p>
<p><strong>5-</strong> Install the C# and JavaScript plugins</p>
<p>In SonarQube login with the default admin/admin user and then follow the steps:</p>
<ul>
<li>5.1 Click in the ‘Administration’ menu;</li>
<li>5.2 Click in the ‘System’ menu and then in the ‘Update Center’ submenu;</li>
<li>5.3 Click in the ‘Available’ tab and then search for C# and click Install;</li>
<li>5.4 Restart SonarQube;</li>
<li>5.5 Go back to step 5.3 to install the JavaScript plugin.</li>
</ul>
<p><strong>6-</strong> Create a new SonarQube project</p>
<p>Just follow the steps:</p>
<ul>
<li>6.1 Click in the ‘Administration’ menu (yes, again);</li>
<li>6.2 Click in the ‘Projects’ menu and then in the ‘Management’ submenu;</li>
<li>6.3 Click in the ‘Create Project’ at the top right of the screen;</li>
<li>6.4 Type a name and a key and click ‘Create’.</li>
</ul>
<p><strong>7-</strong> <a href="http://docs.sonarqube.org/display/SONAR/Analyzing+with+SonarQube+Scanner">Download the SonarQube Scanner</a></p>
<p><strong>8-</strong> Go to the <code class="language-plaintext highlighter-rouge"><sonar_scanner_directory>/conf/sonar-runner.properties</code> and add the two following lines:</p>
<script src="https://gist.github.com/84fa963b266d706ada60.js?file=sonar-runner.properties"> </script>
<p><strong>9-</strong> Add a new environment variable called <code class="language-plaintext highlighter-rouge">SONAR_RUNNER_HOME</code> pointing to</p>
<p>the <code class="language-plaintext highlighter-rouge"><sonar_scanner_directory></code></p>
<p><strong>10-</strong> Add <code class="language-plaintext highlighter-rouge"><sonar_scanner_directory>/bin</code> to the PATH</p>
<p><strong>11-</strong> Add a new file called <code class="language-plaintext highlighter-rouge">sonar-project.properties</code> in your Visual Studio solution root folder with the following contents:</p>
<script src="https://gist.github.com/84fa963b266d706ada60.js?file=sonar-project.properties"> </script>
<p><strong>12-</strong> Move the entire <code class="language-plaintext highlighter-rouge"><sonar_scanner_directory></code> to your solution root folder</p>
<p><strong>13-</strong> Run the command <code class="language-plaintext highlighter-rouge">sonar-runner</code> in your solution root folder</p>
<p>After a successful SonarQube analysis you are going to see something similar to this:</p>
<p><img src="http://fagner.co/public/images/sonarqube-successful-analysis.png" alt="SonarQube successful analysis" /></p>
<p>Just go to the indicated link (http://localhost:9000/dashboard/index/YourProject) and then see the SonarQube analysis report.</p>
<p><img src="http://fagner.co/public/images/sonarqube-report.png" alt="SonarQube analysis report" /></p>
<p><strong>References</strong></p>
<ul>
<li><a href="http://docs.sonarqube.org/display/SONAR/Installing+the+Server">http://docs.sonarqube.org/display/SONAR/Installing+the+Server</a></li>
<li><a href="http://docs.sonarqube.org/display/SONAR/Analyzing+with+SonarQube+Scanner">http://docs.sonarqube.org/display/SONAR/Analyzing+with+SonarQube+Scanner</a></li>
</ul>
Quick tips for building a API using Nancy2016-01-07T00:00:00+00:00http://fagner.co//2016/01/07/Quick-tips-for-building-a-API-using-Nancy<p>Hello! I writing this brief post to help everyone that is using Nancy for the first time to not make the same mistakes that I did. I’m not even remotely interested in covering all possible aspects involved in developing a web application using Nancy, I just thought I’d share some of my mental notes gathered a few months ago. So, here we go.</p>
<h2 id="know-how-to-properly-use-cors">Know how to properly use CORS</h2>
<p>If you are using <a href="http://fagner.co/2014/10/07/CORS-vs-JSONP">CORS</a> avoid to use the wildcard in the Access-Control-Allow-Headers CORS header because he can have unpredictable behavior.</p>
<p>To use CORS in Nancy just do as follows (in Nancy Bootstrapper class):</p>
<script src="https://gist.github.com/906c8731394019cc04e1.js?file=cors.cs"> </script>
<h2 id="handle-circular-reference-in-json-serializer">Handle circular reference in JSON serializer</h2>
<p>In case you are using Entity Framework and you have a relationship where both entities classes have navigation properties your JSON serializer will throw the following exception:</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Self referencing loop detected for property 'propertyName' with type 'Models.Entity'.
</code></pre></div></div>
<p>In order to solve this you need to override the default serializer settings with
the ReferenceLoopHandling.Ignore option.</p>
<p>In Nancy, add the following in your Bootstrapper class:</p>
<script src="https://gist.github.com/906c8731394019cc04e1.js?file=serializer.cs"> </script>
<h2 id="use-onerror-pipeline--a-good-log-library">Use OnError pipeline + a good log library</h2>
<p>The <a href="https://github.com/NancyFx/Nancy/wiki/The-Application-Before,-After-and-OnError-pipelines#intercepting-the-request-when-an-error-occurred">OnError pipeline</a> allows you to intercept any unhandled exception in your application. From then on you can log your exception using a log library like <a href="http://nlog-project.org">Nlog</a> or <a href="https://logging.apache.org/log4net">log4net</a> along with a cloud logging service like <a href="https://exceptionless.com">ExceptionLess</a>, <a href="https://raygun.io">Raygun</a> or <a href="https://papertrailapp.com">PaperTrail</a>.</p>
<h2 id="avoid-using-data-annotations-in-favor-of-fluentvalidation">Avoid using Data Annotations in favor of FluentValidation</h2>
<p>This is more of a general advice but always use the FluentValidation library
instead of the default Data Annotations for any server-side validation in your application. FluentValidation is totally decoupled from your POCO, it’s easily testable and <a href="https://github.com/JeremySkinner/FluentValidation/wiki">offers more customization</a> for validating your classes properties.
FluentValidation is fully compatible with Nancy, you just need to install the <a href="https://www.nuget.org/packages/Nancy.Validation.FluentValidation">Nancy.FluentValidation NuGet package</a>.</p>
<h2 id="use-staticconfigurationdisableerrortraces">Use StaticConfiguration.DisableErrorTraces</h2>
<p>In case you are running your application in Debug mode you can see the whole stacktrace from any exception but if you publish your application in IIS or opt for self-host by default you are not going to see any in-depth information about any exception. To solve this problem just add the line <code class="language-plaintext highlighter-rouge">StaticConfiguration.DisableErrorTraces = false;</code> in your Nancy Bootstrapper <code class="language-plaintext highlighter-rouge">ApplicationStartup</code> method.</p>
<p>That’s all folks!</p>
Defining cross cutting concerns using the MediatR library2016-01-02T00:00:00+00:00http://fagner.co//2016/01/02/Defining-cross-cutting-concerns-using-the-MediatR-library<p>Hello! A few months ago I did a freelance gig in which I found myself having trouble to define where exactly to put things like logging, authentication, persistence common logic and so on. These elements are somehow detached from the core business logic and are very similar or exact the same in every application. If you decide to insert them in all your methods you are going to have a lot of repeated and unmaintainable code very fast.</p>
<p>This things are commonly called ‘cross-cutting concerns’, a concept brought from Aspect-Oriented programming, and they unfortunately don’t work well with Object-Oriented programming <a href="#ref1">[1]</a>. This happens because in every object you feel the need to use a cross-cutting concern you are going to reference a object that defines the concern you are looking for, like a Logger class. Now imagine that you need to audit your code and so every operation happening in your system needs to be logged. Yes, this is bad.</p>
<p><img src="http://fagner.co/public/images/cross-cutting-in-oo.png" alt="Cross-cutting in OO" />
<small>
Figure 1. Crosscutting concerns in a OO language (from Rashid, 2010, p. 24)
</small></p>
<p>Now, a great way to solve this was using a library called <a href="https://github.com/jbogard/MediatR">MediatR</a> (<a href="#note">note</a>). MediatR is mediator design-pattern implementation in .NET that allows the developer to execute commands following the <a href="http://martinfowler.com/bliki/CQRS.html">CQRS pattern</a>.
My first contact with the library was when I read a article about, guess what, <a href="https://lostechies.com/jimmybogard/2014/09/09/tackling-cross-cutting-concerns-with-a-mediator-pipeline/">Tackling cross-cutting concerns with a mediator pipeline</a>. I recommend you to read the article before continue reading this post because he defines the whole class structure that I using to build the concerns implementation below.</p>
<p>So, after I read the article I immediately decided to use the library and define a application framework for my next project and it’s been a huge success so far. I going to share code snippets from some of the concerns that I implemented. They are very simple but show how you can separate repeated cross-cutting code from what really matters in your application: the business core.</p>
<p>First, the <code class="language-plaintext highlighter-rouge">ExceptionHandler</code>, handling unexpected exceptions and throwing validation exceptions made by the Validation handler (implementation available in the Jimmy article linked above).</p>
<script src="https://gist.github.com/f6f0cb4ddf3880a8826d.js?file=exception-handler.cs"> </script>
<p>The <code class="language-plaintext highlighter-rouge">DatabaseHandler</code>, that wraps a transaction using Entity Framework for every request executed and also logs every SQL executed against the database during the transaction lifetime.</p>
<script src="https://gist.github.com/f6f0cb4ddf3880a8826d.js?file=database-handler.cs"> </script>
<p><code class="language-plaintext highlighter-rouge">LoggingHandler</code> class used to log every request and response object.</p>
<script src="https://gist.github.com/f6f0cb4ddf3880a8826d.js?file=logging-handler.cs"> </script>
<p>Last but not least, <code class="language-plaintext highlighter-rouge">Logger.cs</code> class used in both <code class="language-plaintext highlighter-rouge">LoggingHandler</code> and <code class="language-plaintext highlighter-rouge">DatabaseHandler</code> classes.</p>
<script src="https://gist.github.com/f6f0cb4ddf3880a8826d.js?file=logger.cs"> </script>
<p>So, that’s it. If you want to learn more <a href="https://www.nuget.org/packages/MediatR/">download MediatR from NuGet</a> and read <a href="https://www.google.com.br/search?q=mediatr+site:https:%2F%2Flostechies.com">Jimmy MediatR articles at LosTechies</a>.</p>
<p><a name="note"></a> <strong>Note</strong> This framework was developed by Jimmy Bogard, the same guy behind AutoMapper (please, if you don’t know what AutoMapper is please access the <a href="https://github.com/AutoMapper/AutoMapper/wiki">AutoMapper documentation here</a> and
learn the basics at least!).</p>
<p><a name="ref1"></a> [1] Rashid, Awais (2013). Aspect-Oriented Database Systems. United Kingdom: Springer.</p>
TypeScript + Webpack2016-01-01T00:00:00+00:00http://fagner.co//2016/01/01/TypeScript-+-Webpack<p>Hey, hello! As always, it’s been a long time since I posted. Anyway, probably nobody cares besides me so I just going to straight to the point to be discussed in the post, a simple integration between TypeScript and Webpack.</p>
<p>First of all, this post assumes you already know a little about JavaScript and already heard about - or used - a task-runner like Grunt or Gulp.</p>
<h2 id="defining-typescript">Defining TypeScript</h2>
<p>In a nutshell TypeScript is a javascript-based kind of language that compiles to JavaScript. TypeScript most important feature is being statically typed, bypassing JavaScript dynamic nature and allowing the development of big, scalable applications more easily.</p>
<h2 id="defining-webpack">Defining Webpack</h2>
<p>Webpack on the other hand is a library that basically wraps all your JavaScript files inside one file. Besides the concatenation itself he also builds a dependency tree to know what file needs to go first. He is also highly customizable, allowing to define distinct files between your third party dependencies and your app code and also defining what extensions should be used in the process. I assume he does a lot more things than that but I actually don’t know too much about Webpack either, I used the first time a few weeks ago.
Oh, two more details. you also can run Webpack inside Grunt/Gulp/Broccoli/whatever script and Webpack also handles CSS files if you want to concatenate your styles.</p>
<h2 id="setting-up-environment">Setting up environment</h2>
<p>We are going to use Atom and the atom-typescript package because reasons.</p>
<p>After you install both Atom and atom-typescript do the following steps:</p>
<p>1- Open a command prompt and run the following command</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>npm init
</code></pre></div></div>
<p>This will create a package.json file that will save every npm that you install from now on. Don’t close your prompt just yet, we are going to be using that until the end of this tutorial.</p>
<p>2- Install TypeScript</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>npm install typescript --save
</code></pre></div></div>
<p>3- Install TypeScript Webpack loader</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>npm install ts-loader --save
</code></pre></div></div>
<p>4- Install DefinitelyTyped</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>npm install tsd -g
</code></pre></div></div>
<p>DefinitelyTyped is a package manager for TypeScript definition files. Definition files allows the developer to define the functions of a specific library in a .d.ts file in a similar way that WSDL files do.</p>
<p>5- Install jQuery definition file</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>tsd install jquery --save
</code></pre></div></div>
<p>This will activate autocomplete capabilities to the jQuery library functions using TypeScript.</p>
<p>6- Create a tsconfig.json file.</p>
<script src="https://gist.github.com/5894313be602cbab3367.js?file=tsconfig.json"> </script>
<p>This file is self-explanatory. A TypeScript configuration file. <a href="https://github.com/Microsoft/TypeScript/wiki/tsconfig.json">Access tsconfig.json documentation here</a>.</p>
<p>7- Create 2 TypeScript files: app.ts and greeter.ts (this last inside a ts folder).</p>
<script src="https://gist.github.com/5894313be602cbab3367.js?file=app.ts"> </script>
<script src="https://gist.github.com/5894313be602cbab3367.js?file=greeter.ts"> </script>
<p>8- Create a simple index.html to see the result being generated by the app.</p>
<script src="https://gist.github.com/5894313be602cbab3367.js?file=index.html"> </script>
<p>9- Create a Webpack configuration file called, you guessed, webpack.config.js.</p>
<script src="https://gist.github.com/5894313be602cbab3367.js?file=webpack.config.js"> </script>
<p>10- In command prompt, run the command webpack. You are going to see something like this:
<img src="http://fagner.co/public/images/webpack-command-output.png" alt="Webpack command output" /></p>
<p>11- Run a local server pointing to the folder containing your newly created app. You can use anything that you got at your disposal like a <a href="https://docs.python.org/2/library/simplehttpserver.html">Python local server</a>, a <a href="https://www.npmjs.com/package/http-server">Node local server</a>, a <a href="http://apidock.com/ruby/Object/httpd">Ruby local server</a> and so on.</p>
<p>12- Access your favorite browser and see the result.
<img src="http://fagner.co/public/images/browser-app-running.png" alt="Application running" />
Noice.</p>
<p>So, that’s it! You learned how to use TypeScript and Webpack together to build a scalable frontend app. If you want to access the full code linked to this post please clone my <a href="https://github.com/fagnercarvalho/typescript-webpack">TypeScript + Webpack Github repository</a>.</p>
Resumo do primeiro dia do BrazilJS 20152015-08-22T00:00:00+00:00http://fagner.co//2015/08/22/Resumo-primeiro-dia-BrazilJS-2015<p>Daí pessoal, tudo certo? Resolvi fazer este post com um pequeno resumo das palestras do primeiro dia do BrazilJS 2015.
É importante destacar que tudo aqui escrito vem da minha experiência do evento e de tudo aquilo que pude absorver e/ou achei interessante o bastante para comentar.</p>
<p>Espero que atenda as tuas expectativas!</p>
<h2 id="palestra-1---christian-heilmann---es6---baseline-para-a-web-moderna">Palestra 1 - Christian Heilmann - ES6 - Baseline para a web moderna?</h2>
<p>O Chris procurou falar sobre dois pilares bastante discutidos entre desenvolvedores JavaScript: a nova versão do ECMAScript, o ES6 e sobre comos precisamos depositar todos os nossos esforços em trazer a maior quantidade de boas funcionalidades para o browser ao invés de ficar “apenas” criando frameworks, bibliotecas e trabalhando com JavaScript em ambientes fechados como no NodeJS.
Alguns pontos interessantes que ele levantou:</p>
<ul>
<li>Utilize novos frameworks com uma visão crítica e não se torne simplesmente um fanboy de uma determinada tecnologia</li>
<li>“This is not a fight against innovation”, se referindo aos grandes browsers do mercado (Firefox, Chrome, Edge e Safari)</li>
<li>“Deliver code to user above everything” e a “Priority of Constituencies” (preferência máxima pelo usuário definido no draft dos princípios de design do HTML da W3C). Aqui ele basicamente diz que por mais que o ES6 deva ser utilizado “in the wild” os browsers antigos precisam continuar suportando e para isso a única saída é a transpilação, o que ele também considera ruim. É UM GRANDE DILEMA!</li>
<li>Ser contra empresas que exploram o open source para fazer as suas próprias soluções fechadas para aplicativos que já conhecemos. O principal exemplo disso são as grandes fabricantes de smartphones que criam as suas próprias versões de browsers.</li>
<li>“There are people missing the great things in the web”. Aqui ele comenta um pouco sobre os desenvolvedores que não exploram tudo de novo que está surgindo e continuam outdated.</li>
<li>O comentário mais importante dele: “quando as coisas deixaram de ser desenvolvidas para produção?”, se referindo a bibliotecas e frameworks em JS que não eram consideradas production-ready</li>
<li>No final das contas ele basicamente “detona” a ideia de transpilar código ES6 para ES5, frameworks como Angular e React e ambientes fechados como o que temos em NodeJS. O que ele defende é utilizar o ES6 diretamente e principalmente no browser. Por mais que se diga que essas funcionalidades são muito novas e estariam lentas ou com problemas a ideia do Chris seria utilizá-las o quanto antes com dados reais numa aplicação real para que os problemas possam ser encontrados e corrigidos e os bottlenecks de performance possam ser elimininados.
Alguns links:
<ul>
<li><a href="https://kangax.github.io/compat-table/es6/">A boa e velha tabela de compatibilidade do ES6</a></li>
<li><a href="https://github.com/tc39/test262">Testes para “conformance” das funcionalidades do ES</a></li>
<li><a href="http://kpdecker.github.io/six-speed/">Testes de performance para do ES6</a> (várias funcionalidades estão lentas mas vão melhorar com o tempo, naturalmente)</li>
</ul>
</li>
</ul>
<h2 id="palestra-2---douglas-campos---use-lowlevel">Palestra 2 - Douglas Campos - Use lowlevel</h2>
<p>Bottom-line do talk: conheca e trabalhe com o baixo nível, isso vai te tornar um desenvolvedor melhor.
Alguns pontos legais levantados durante a palestra:</p>
<ul>
<li>“Those who don’t know history are doomed to repeat it.”, se referindo a pessoas que não se deparam com problemas de baixo nível e acabam cometendo os mesmos erros que já foram cometidos há 20 anos atrás (ou mais)</li>
<li>Saiba mais sobre compiladores, browsers, frameworks.</li>
<li>“Don’t be afraid of lowlevel”</li>
</ul>
<h2 id="palestra-3---felipe-ribeiro---javascript--spotify">Palestra 3 - Felipe Ribeiro - JavaScript @ Spotify</h2>
<p>Palestra bastante esperada, o Felipe nos conta em detalhes toda a história do aplicativo do Spotify para o desktop e como ocorreu a última migração para um codebase 100% web com JS.</p>
<p>Alguns pontos:</p>
<ul>
<li>A primeira versão da aplicação ficou sem utilização por 1 ano até que as gravadoras começassem a gradativamente aceitar o Spotify</li>
<li>O Chromium Embedded Framework (CEF) utilizado na aplicação é o mesmo que deu a base para o node-webkit e também é utilizado em aplicações como o Steam e o Slack.</li>
<li>O Spotify ainda usa iframes!! Sim, mas há um motivo: a remoção dos iframes causaria um risco e um esforço muito maior no projeto de migração da tecnologia, então eles optaram por deixar assim por enquanto e removê-los com mais calma futuramente</li>
<li>O codebase da aplicação está num único repositório e não separado em vários. No começo tentou-se criar um repositório para cada feature (playlist, radio, search) mas a fragmentação causou um esforço muito maior do desenvolvimento e eles optaram por unificar tudo.
Basicamente esta foi uma situação dentre muitas outras onde o monolito imperou sobre o novo conceito de microserviços. É a vida!</li>
</ul>
<h2 id="palestra-4---damian-schenkelman---getting-over-moores-law-parallelization-using-javascript-in-the-browser">Palestra 4 - Damian Schenkelman - Getting over Moore’s Law: Parallelization using JavaScript in the browser</h2>
<p>O Damian fala aqui basicamente sobre Web Workers, Paralelização e Concorrência em JavaScript. Sou um completo ignorante nestes tópicos e portanto não tecerei muitos comentários.
Quem sabe, sabe. Quem não sabe (como eu) que estude!</p>
<ul>
<li>Web Workers</li>
<li>função postMessage()</li>
<li>Typed Arrays</li>
<li>Links:
<ul>
<li><a href="https://jsperf.com/transferrable-vs-cloning/2">Transferrable vs cloning</a></li>
<li><a href="https://jsperf.com/simd-sum">SIDM sum</a></li>
<li><a href="https://github.com/dschenkelman/parallelism-js-talk">Link para a talk</a></li>
</ul>
</li>
</ul>
<h2 id="palestra-5---reinaldo-ferraz---a-saga-dos-12-tópicos-de-acessibilidade">Palestra 5 - Reinaldo Ferraz - A saga dos 12 tópicos de acessibilidade</h2>
<p>Palestra bem técnica com relação a elementos de acessibilidade de um cara especialista no assunto.</p>
<p><a href="http://pt.slideshare.net/reinaldoferraz/a-saga-dos-12-tpicos-de-acessibilidade-na-web">Apresentação aqui</a>.</p>
<h2 id="palestra-6---tania-gonzalez---the-javascript-toolkit">Palestra 6 - Tania Gonzalez - The Javascript Toolkit</h2>
<p>A Tania da TW falou sobre o JavaScript Toolkit, um compilado de diversos frameworks, bibliotecas e ferramentas para se trabalhar com o JavaScript. Para visualizar este compilado <a href="https://github.com/bymarkone/javascript-toolkit">clique aqui</a>.</p>
<h2 id="palestra-7---raphael-amorim---500-days-of-open-source">Palestra 7 - Raphael Amorim - 500 days of open source</h2>
<p>Aqui o Raphael basicamente faz uma palestra motivacional com o intuito de tirar nós, os desenvolvedores, de suas zonas-de-conforto e aprender mais e mais da forma que acharmos melhor. A ideia central é ter foco e manter um padrão ritmado de estudos para alcançar os nossos objetivos, seja ele o que for: aprender uma nova linguagem, técnica, pattern, framework, biblioteca, o que for!</p>
<p>No final ele comentou de um projeto criado por ele e mais alguns amigos que busca ajudar nesse objetivo, o Write Code Everyday. Para saber mais, <a href="http://writecodeeveryday.io/">clique aqui</a>.</p>
<h2 id="palestra-8---nicolas-bevacqua---high-performance-in-the-critical-rendering-path">Palestra 8 - Nicolas Bevacqua - High Performance in the Critical Rendering Path</h2>
<p>Seria praticamente uma ofensa tentar resumir essa talk nesse post. A quantidade de conteúdo foi enorme, mas o resumo é o seguinte: o Nicolas explicou várias técnicas e divulgou vários plugins que buscam tornar a performance de um site melhor. Essas técnicas vão desde minificar os nossos arquivos CSS e JS (coisinha básica!) até otimizar o TCP (eita! que isso meu deus?).</p>
<p><a href="https://speakerdeck.com/bevacqua/high-performance-in-the-critical-path">Aqui</a> a talk dele. Fortemente recomendada para quem quiser ver algo que perdeu ou não foi no evento.</p>
<h2 id="palestra-9---nick-desaulniers---improving-game-performance-on-the-web-wasm-sharedarraybuffer-simd-webgl2">Palestra 9 - Nick Desaulniers - Improving game performance on the Web: WASM, SharedArrayBuffer, SIMD, WebGL2</h2>
<p>O Nick falou sobre o Web VR, a API para gerar realidades virtuais na Web.
Ele comentou sobre alguns pontos que o Damian já havia discutido na talk dele como Web Workers, SIDM, postMessage, SharedArrayBuffer e todas essas coisas que eu não conheco e estou pensando em estudar assim que digito isso.
Ele até nos desafiou a criar alguma coisa usando o Web VR para ganharmos uma camiseta hoje (22/08), no segundo dia do evento. (sim, estou fazendo isso depois da meia-noite). <a href="http://nickdesaulniers.github.io/joshVR/">Toma aí o link</a>.</p>
<h2 id="palestra-10---david-bryant---keynote">Palestra 10 - David Bryant - Keynote</h2>
<p>Keynote sensacional com o “leader of the platform engineering team for Mozilla”, ou como ele se auto-intitula “Web Platform guy”.</p>
<p>Assim como o talk do Nicolas acho injusto tentar resumir a talk dele aqui pois ele comentou sobre bastante coisa, incluindo o Web VR, Web Assembly, WebRTC, Service Workers (offline capability, traffic interception) e coisas mais baixo nível como o JIT Coach.</p>
<p>Bom, é isso!</p>
<p>Após o segundo dia de evento pretendo complementar um pouco as informações postadas para deixar tudo mais completo, portanto continue acompanhando este link.</p>
<p>Qualquer coisa é só comentar aqui embaixo e compartilhar o conteúdo caso quiser.</p>
<p>Abraços!</p>
Using dependency injection in MongoDB CSharp Driver2015-01-14T00:00:00+00:00http://fagner.co//2015/01/14/Dependency-Injection-MongoDB-CSharp<p>Hello! So, it seems that I delayed once again new posts in here. Since I promisse to no one that I need to post here on regular basis I dont think that I need to apologize, hehe (just kidding). So, as the title says I here to talk a little about dependency injection and post a code snippet about using DI on MongoDB CSharp Driver basic classes.</p>
<h2 id="dependency-injection">Dependency Injection</h2>
<p>If you dont want to know or already know the concept behind dependency injection, <a href="#code">just jump to the code</a>.
As you may know dependency injection helps us programmers to control code dependencies easier. When you use dependency injection (or DI) depending on the language that you are using you just need to use a attribute, annotation or something else that helps to inject (like the name says, doh!) the dependencies into your code without the need to instantiate or set the objects manually.</p>
<p>For example, in Java, using Spring Framework, you just use something like this:</p>
<script src="https://gist.github.com/19a0af7b0234bf8b0b55.js?file=di.java"> </script>
<p>In AngularJS, the $scope parameter passed thought every Controller on your app that represents the DOM elements from the page are created using dependency injection:</p>
<script src="https://gist.github.com/19a0af7b0234bf8b0b55.js?file=di.js"> </script>
<p>And finally, in C#, using Ninject:</p>
<script src="https://gist.github.com/19a0af7b0234bf8b0b55.js?file=di.cs"> </script>
<p>You can have 3 types of DI:</p>
<ul>
<li>Constructor injection: most common one. Just inject your dependencies in the object constructor;</li>
<li>Setter injection: associate object dependencies using setter methods.</li>
<li>Interface injection: associate dependencies using setter methods defined in interfaces.</li>
</ul>
<p>Ninject provides a very elegant way to perform DI on C#, and my MongoDB code snippet posted right below was made using this framework, but you have many other options for use DI on C# like <a href="http://msdn.microsoft.com/en-us/library/ff647202.aspx">Unity</a> or <a href="http://autofac.org/">Autofac</a> frameworks.</p>
<h2 id="-di-on-mongodb-csharp-driver"><a name="code"></a> DI on MongoDB CSharp Driver</h2>
<p>MongoDB CSharp Driver, as the name says, is a library provived to access MongoDB databases using C#. In this library you have classes like MongoCollection, MongoDocument, MongoDatabase and so on that helps to interact with a MongoDB instance and develop a application with MongoDB and C# together as backend.</p>
<p>The code snippet below provides a simple way to use DI with Ninject to instantiate MongoDB Driver classes.
You just need to associate classes to interfaces and say to Ninject that he needs to create a Object instance when a IObject is indicated.</p>
<script src="https://gist.github.com/19a0af7b0234bf8b0b55.js?file=di-mongo.cs"> </script>
<p>Then you just need to create your code and Ninject, if properly configured, will instantiate your objects automatically.</p>
<script src="https://gist.github.com/19a0af7b0234bf8b0b55.js?file=repository.cs"> </script>
<p>So, thats it! If you have any questions you are free to ask in the commentary box below.</p>
<p>See you later!</p>
Null propagator operator on C# 6.02014-10-26T00:00:00+00:00http://fagner.co//2014/10/26/Null-propagator-operator<p>Hello again! Today I going to talk briefly about a specific feature from the next version of C#: the not so new null propagator operator. Yes, its been awhile since C# 6 was announced but I want to talk about this, so you cant do anything to stop me!
The main reason I talking about this its because since I saw the <a href="https://visualstudio.uservoice.com/forums/121579-visual-studio/suggestions/3990187-add-operator-to-c">proposal</a> for implementing the operator in C# I really liked and hoped that Microsoft implement, and he did it! In the latest Visual Studio 2014 CTP version the operator was there and of course I looked. Veredict: tested and approved!</p>
<h2 id="null-propagator-operator">Null propagator operator?</h2>
<p>So, in the first place, this operator is new only in C#. A lot of programming languages already have it.
Like <a href="http://damieng.com/blog/2013/12/09/probable-c-6-0-features-illustrated">Damien Guard</a> pointed out this operator exists in <a href="http://groovy.codehaus.org/Operators#Operators-SafeNavigationOperator%28?.%29">Groovy</a>, where is known as the ‘safe navigation operator’, that bring me to right to the usefulness of this operator: avoid Null reference exception when trying to access a null reference object, of course!
But how this is done? You all know how to do a null reference exception in your code, everyone does that once in a while. Yes, is stupid but it happens, and the new null propagator operator comes here to solve this once and for all.</p>
<p>Like Linus said someday: ‘Talk is cheap. Show me the code’. So, there it is:</p>
<script src="https://gist.github.com/75e62ba490db8ea8f0f0.js?file=null-propagator-operator.cs"> </script>
<p>The new operator is shown in line 14, where its used two times. So, what happens if the Bear object has not instantiated? Or the Friends property? If you dont use the null propagator you probably get a null reference exception in your face. But in the code above this wont happen again.</p>
<h2 id="so-why">So, why?</h2>
<p>Why you need to use this new operator? Well, because is simple and avoids a lot of boilerplate that just messes with your code. Its simple as that.</p>
<h2 id="i-love-it-how-i-starting-using-it">I love it, how I starting using it?</h2>
<p>The new operator isn’t available in a stable C# version yet. But you can test right now using the latest version of Visual Studio 2014. And you dont need to install in your machine, Microsoft already offers a Windows Server 2013 instance with Visual Studio 2014 CTP 4 pre-installed. You just needed to access <a href="http://manage.windowsazure.com">manage.windowsazure.com</a>, create a new VS 2014 VM and starting using the new Visual Studio and C# features. If you are interested in all the new features in C# 6.0 I recommend you take a look in <a href="https://roslyn.codeplex.com/discussions">this</a> and <a href="https://channel9.msdn.com/tags/CSharp/">this</a>.</p>
<p>So, thats it! If you have any questions you are free to ask in the commentary box below.</p>
<p>Bye!</p>
CORS vs JSONP2014-10-07T00:00:00+00:00http://fagner.co//2014/10/07/CORS-vs-JSONP<p>Hello!
So, here I am again! Sorry for the delay, almost 2 months since I last posted here. Anyway, I here today to talk about CORS and JSONP. Basically I will introduce the terms and cite some implementation examples using JavaScript and ASP.NET WebAPI (because I am a .NET fan, of course!).</p>
<h2 id="jsonp">JSONP</h2>
<p>First I will talk about JSONP. The acronym stands for “JSON with padding”. We have a lot of resources telling about the concept in the internet today, so I will be short. “JSON with padding” its basically a hack that makes possible inter-domain requests. And that’s it. This hack consists from return a function (often named ‘callback’ or whathever you want) that receives a JSON parameter like the following.</p>
<script src="https://gist.github.com/486e2e4765aafc04ecc7.js?file=json.js"> </script>
<p>A lot of APIs from well know companies like Instagram and Github provides JSONP APIs to developers. <a href="http://www.programmableweb.com/category/all/apis?search_id=137822&data_format=21174">Click here</a> to access a list of JSON APIs available today. The main advantage to use JSONP is the the compatibility with some old browsers like IE 7< and the main disadvantage concerns the security: like I said before JSONP is a hack created when nobody had a option to make cross-domain requests, so the creators didn’t seem to be bothered too much by security.</p>
<p>In the code below you can see a simple example using the polymer-jsonp <a href="http://customelements.io/">web component</a> to do a simple JSONP request to the Battelfield 4 API.</p>
<script src="https://gist.github.com/486e2e4765aafc04ecc7.js?file=jsonp.html"> </script>
<h2 id="cors">CORS</h2>
<p>Instead of using a hack you can use a better a safe way: CORS.
CORS stands for “Cross-Origin Resource Sharing”. CORS introduced a new HTTP header to allow cross-domain requests called “Access-Control-Allow-Origin”.</p>
<p>Using ASP.NET WebAPI, If you want to enable CORS you just need to follow this 3 simple steps:</p>
<ol>
<li>
<p>Install the package Microsoft.AspNet.WebApi.Cors using NuGet;</p>
</li>
<li>
<p>Insert the following line of code in our WebApiConfig located in the App_Start folder:</p>
</li>
</ol>
<script src="https://gist.github.com/486e2e4765aafc04ecc7.js?file=cors.cs"> </script>
<ol>
<li>Insert the EnableCorsAttribute in all ours Controllers that you interested in enabling CORS.</li>
</ol>
<script src="https://gist.github.com/486e2e4765aafc04ecc7.js?file=enable-cors.cs"> </script>
<p>So, thats it! If you have any questions you are free to ask in the commentary box below.</p>
<p>Have a nice day!</p>
Solve a simple problem during RabbitMQ setup in Windows2014-08-15T00:00:00+00:00http://fagner.co//2014/08/15/Solve-Simple-Problem-RabbitMQ-Setup<p><img src="http://fagner.co/public/images/RabbitMQLogo.png" alt="RabbitMQ" /></p>
<p>Hello!
So, for you that dont know what is exactly RabbitMQ, let me briefly explain before anything else: RabbitMQ is a framework that provides a messaging system based on the AMQP standard (<a href="http://en.wikipedia.org/wiki/Advanced_Message_Queuing_Protocol">click here to know more</a>).</p>
<p>Considering my experience developing Microsoft solutions today I got interested in learn how to use <a href="https://github.com/mikehadlow/EasyNetQ">EasyNetQ</a>, a .NET API implementation for RabbitMQ. Before trying to do anything using EasyNetQ I start following the Quick Start Guide for EasyNetQ and had some problems. This post focus on those problems and describes a simple way to solve them.</p>
<p>First you just need to follow the previously cited Quick Start Tutorial <a href="https://github.com/mikehadlow/EasyNetQ/wiki/Quick-Start">clicking here</a>.</p>
<p>If you follow this tutorial carefully everything will run smoothly but if you are like me maybe you pass through the same problems.
At first I was struggling trying to find a way to install the management plugin, a plugin that provides a nice web interface where you can manage your server queues. So, after awhile, I discover that I need to run the following command (using cmd):</p>
<script src="https://gist.github.com/d64236bf015c3a263d0d.js?file=enable-rabbitmq.cmd"> </script>
<p>This command need to be executed pointing to the ‘C:\Program Files (x86)\RabbitMQ Server\rabbitmq_server-version\sbin’ folder. But, for some reason, I cant seem to access my interface presumably located in http://localhost:15647. After spending some time I found and run a rabbitmq-server.bat located in the sbin folder, where I finally can see my error:</p>
<script src="https://gist.github.com/d64236bf015c3a263d0d.js?file=weird-error"> </script>
<p>For some reason RabbitMQ cant seem to know that MYHOST need to be translated to localhost/127.0.0.1 resulting in a server shutdown. To solve this particular problem I just needed to run the following command in cmd:</p>
<script src="https://gist.github.com/d64236bf015c3a263d0d.js?file=set-computername.cmd"> </script>
<p>After that I run this command in the sbin folder:</p>
<script src="https://gist.github.com/d64236bf015c3a263d0d.js?file=restart-rabbitmq.cmd"> </script>
<p>After that my server starts succesfully and I finally can use the EasyNetQ!</p>
<p>So, thats it! If you have any questions you are free to ask in the commentary box below.</p>
<p>Have a nice day!</p>
Hello World!2014-07-21T00:00:00+00:00http://fagner.co//2014/07/21/Hello-World<p>Olá!<br />
Bem vindo ao meu blog. Pretendo postar, como o título do blog diz,
assuntos relacionados a novas tecnologias e meu dia-a-dia no TI.</p>
<p>É isso ai!</p>