Davidson Sousa http://davidsonsousa.net/ The life through the eyes of a developer en-us MultiCMS It's been 4 decades already http://davidsonsousa.net/blog/post/its-been-4-decades-already <!DOCTYPE html> <html> <head> </head> <body> <p>I remember&hellip;</p> <p>&hellip;when I was around 8 years old, still not wearing eyeglasses, but always imagining myself with them. Today I can&rsquo;t have the surgery to permanently remove them. It&rsquo;s better this way.</p> <p>&hellip;when I was around 11 years old, I had contact with English at school for the first time. It was a whole new world for me. I think it was the first time I was fascinated with knowing new words that, at the time, had no meaning for me. Today I use it more than my own native language.</p> <p>&hellip;when I was 15, I still wanted to become a biologist (or a paleontologist) but then I was enrolled in a technical high school, where I was able to learn IT stuff. Today I&rsquo;m a developer in a big international corporate.</p> <p>&hellip;when I was 17, I had no idea what I would do if I couldn&rsquo;t join the federal university. Today I know that it was the best thing that could have ever happened to me at the time.</p> <p>&hellip;when I was 22, I took my first flight to Rio de Janeiro, then to Prague, then to Cracow. At the time I was supposed to live in Poland. Today I live in the Czech Republic.</p> <p>&hellip;when I was 24, I was living in a small Polish town and met a lot of good people. At the time I was lost, trying to find out who I really am. Today I know that it was one of the most important periods of my life.</p> <p>&hellip;when I was 26, I learned I had to return home, to Brazil, and I did. But I felt like a foreigner in my own land, so I returned to the Czech Republic. Today I have 2 homes.</p> <p>&hellip;when I was 33, I learned that workmates are just people you interact with daily, and they aren&rsquo;t necessarily gonna be your friends. Sometimes they may even throw you under the bus. Today I prefer to keep a safe and professional distance from them.</p> <p>&hellip;when I was 35, I learned that my work as a developer is nothing more than an office job. I go to work, do my things, and get back home. Rinse and repeat. Salary comes at the beginning of every month. Today the sentence &ldquo;It&rsquo;s just an office job&rdquo; is my mantra.</p> <p>&hellip;when I was 37, I learned that people you think you know extremely well are still able to surprise you. That may be good or bad, depending on where you stand. Today I feel like having fewer friends and I think it&rsquo;s better this way.</p> <p>Today I am 40.</p> <p><img style="display: block; margin-left: auto; margin-right: auto;" src="/image/post/leo_toasting_meme.jpg" alt="leo_toasting_meme.jpg" /></p> </body> </html> Wed, 21 Jun 2023 11:16:00 GMT http://davidsonsousa.net/blog/post/its-been-4-decades-already This article was written by an AI and reviewed by a human http://davidsonsousa.net/blog/post/this-article-was-written-by-an-ai-and-reviewed-by-a-human <!DOCTYPE html> <html> <head> </head> <body> <p>My life at work has become much calmer over the past year. I changed jobs and the new company has a more relaxed and focused work environment, which has been a welcome change after the stress and pressure of my previous job. This has helped me to feel more at ease and able to concentrate on my tasks, allowing me to be more productive and efficient in my work. Having a more balanced and enjoyable work experience has been a great feeling.</p> <p>In my free time, I've been able to devote more energy to my hobby of photography. I even created <a href="https://www.instagram.com/davidsonsousa.jpg">a new Instagram account</a> to showcase my photos and connect with other photographers. The feedback and support from the community have been motivating and have helped me to improve even more. I've been practicing photography and editing regularly and have noticed a significant improvement in my skills and the quality of my photos in the last 12 months. I've also been able to expand my portfolio and try out new techniques and styles, which has been a lot of fun.</p> <p>This year, I was fortunate enough to be able to travel to two amazing destinations: Varna (Bulgaria) and Iceland. Both places were beautiful and offered unique and breathtaking landscapes that were perfect for photography. I captured some truly stunning shots and created lasting memories through my photos. I'm already planning to travel more next year, and I am looking forward to discovering even more beautiful places and capturing them through my lenses.</p> <p>Overall, my life has become more balanced and fulfilling&nbsp;compared to the past years. I can find a good balance between work and my hobbies, and I can fully enjoy my travels and capture the beauty of the world. Changing jobs and starting my Instagram account for my photography hobby were both big steps for me and I'm glad that they have had such a positive impact on my overall well-being. It's been a great year and I'm looking forward to continuing to grow and improve in the coming years.</p> <p><em>This entire text was generated using <a href="https://chat.openai.com/chat">ChatGPT</a>. I made some minor changes but, overall, the result is stunning!</em></p> </body> </html> Wed, 21 Dec 2022 12:00:00 GMT http://davidsonsousa.net/blog/post/this-article-was-written-by-an-ai-and-reviewed-by-a-human I'm not good at New Year's resolution http://davidsonsousa.net/blog/post/im-not-good-at-new-years-resolution <!DOCTYPE html> <html> <head> </head> <body> <p>364 days ago, I wrote about <a href="/blog/post/my-plan-for-2021">my plan for 2021</a>. It was relatively ambitious, but totally feasible. And I was really going for it. But I was not counting with the lack of mental capacity to do most of those.</p> <p>Do you know what is it like to feel your brain melting when you start doing something? Yep, it was like that.</p> <p>The first 2 items (Pass some MS Exams and Teach at least 80 hours of MS content) could be easily achievable if I had would just put a little bit of extra effort in my daily life and used some of my free time to go beyond my daily work routine. I can say I had a relative freedom for that due to calmer times (end of project) but, well, apparently my mental health had other plans.</p> <p>The next 2 items in my list were partially achieved. I did shoot a video explaining about <a href="/blog/post/use-regular-expressions-on-visual-studio-to-find-and-replace-anything">regular expressions in Visual Studio</a>. And I did get a little bit better in photography. But then, again, completely far from what I expected.</p> <p>The last 3 items were a total disaster: I did nothing to improve my home office (apart from buying some pictures and not hanging them), barely wrote more in here and my Czech continues to be on a 2-year-old child level.</p> <p>As I am a failure when it comes to new year&rsquo;s resolution, I decided to not make any this time. I will just enjoy and do whatever pleases me while learning how to deal with whatever my mental health will throw at me.</p> </body> </html> Sat, 01 Jan 2022 11:11:00 GMT http://davidsonsousa.net/blog/post/im-not-good-at-new-years-resolution You need to read this if you want to become a programmer http://davidsonsousa.net/blog/post/you-need-to-read-this-if-you-want-to-become-a-programmer <!DOCTYPE html> <html> <head> </head> <body> <p>Chances are that you are looking for information on how to become a programmer. Perhaps you&rsquo;ve considered to make a career change and programming is a good choice. Or you are about to start your university degree and see yourself creating apps or websites. Either way, let me give you some hints of what is expected of you in the beginning of your journey.</p> <p>There are 2 main ways you can become a programmer nowadays:</p> <ul> <li>By having a formal education (university degree, bootcamp, etc.)</li> <li>Through self-learning (online trainings, books, etc.)</li> </ul> <h2>Get a formal education?</h2> <p>A formal education is going to give you the structure you&rsquo;ll need to achieve your goals: You enter a classroom, the teacher is going to deliver the content, you take notes and practice. That is for a certain amount of time and for a certain depth, depending on what kind of formal education you are going for.</p> <p>And here is where the difference across formal education systems is more evident: Bootcamps tend to be shorter and more work specific than a full university degree since the goals are different &ndash; one will give you the right tools for the job, the other will give you a broader knowledge about languages, architecture, theory, etc.</p> <p>They are all good, but it&rsquo;s just about where you are going with your career.</p> <h2>What about self-learning?</h2> <p>One of the biggest issues with self-learning is lack of a proper structure, followed closely by lack of motivation: Often you will not know from where to start learning a subject and any difficulty can throw you off your path. And even if you can keep yourself motivated, you will be wandering around the subject until you find a way to overcome that difficulty.</p> <p>Let&rsquo;s see how you can optimize your self-learning.</p> <h3>Find your motivation</h3> <p>You surely have a reason to think about becoming a programmer. Either financial or passion, you must tap into this motivation and understand that you are in a marathon, not a sprint. Whatever your goal is, you will achieve. But you need to have patience to endure hours of studying (reading and practicing) in your career while thinking about long term achievements.</p> <p>The idea is to always <strong>remember why you are pursuing this career</strong> and use it whenever you feel like giving up. It pays off greatly in the end.</p> <h3>You will need to learn how to learn</h3> <p>As previously mentioned, we usually have everything structured when we go for a formal education. However, you need to develop our own strategies when self-learning. The easiest way to do it is to follow roughly the same pattern you are used to (formal education) by:</p> <ul> <li><strong>Finding good books</strong>: Any book should give you the easiest subject in the beginning and complementing it in the next chapters. If you follow it from beginning to end, you will be able to have enough structure to keep yourself motivated to continue, considering you wouldn&rsquo;t normally know from where to start to learn. Online courses can also help as books, but most of them tend to be more specific, requiring you to get more trainings to complete your learnings</li> <li><strong>Practicing whenever you can</strong>: You must be coding whenever you have an opportunity. If you are following a book or training, you will have exercises. Otherwise, you can create a small project to apply your newly acquired knowledge. Anything works: A small system to control the inventory of your friend&rsquo;s shop, a small website that shows pictures of cats, etc. The most important here is to challenge yourself and practice what you are learning</li> </ul> <p>I&rsquo;d recommend starting with books if you want to learn something broad (such as &ldquo;ASP.NET&rdquo;) and online courses if you want to learn something more specific (such as &ldquo;Building optimized APIs with ASP.NET&rdquo;). And practice as much as you can. I&rsquo;d suggest creating small projects that would solve an imaginary or a real problem.</p> <h3>You will always need an update</h3> <p>As a programmer, you will have to keep up with the new versions of your favorite language/framework/tools if you want to keep yourself employable. That means: <strong>The learning is a constant even if you already feel comfortable with your knowledge.</strong> Of course, I don&rsquo;t mean you will need to learn everything from scratch every year. Think of it as &ldquo;knowledge maintenance&rdquo;.</p> <p>A good way to keep yourself up to date is through online conferences (mostly free) and the official channels of your favorite technology (blogs and YouTube).</p> <p>If you &ndash; like me &ndash; are a .NET developer, check the <a href="https://docs.microsoft.com/en-us/learn/">Microsoft Learn</a> website and the <a href="https://devblogs.microsoft.com/dotnet/">.NET Blog</a> to see what&rsquo;s new. Also, Microsoft organizes their dev event (<a href="https://channel9.msdn.com/events/BUILD">Microsoft Build</a>) yearly announcing some good stuff. Otherwise, there is a good chance that your favorite framework/language/tool (if non-Microsoft) has similar options.</p> <h3>Find a mentor (or a &ldquo;hero&rdquo;)</h3> <p>As much as it seems I am telling you to just go on an adventure by yourself, it&rsquo;s good to have someone that will help or, at least, inspire you. <strong>Having a mentor to guide you is very important</strong> since he/she will point you to the right directions and prevent you to make the mistakes he/she made in their career. In another words, a mentor will help you to cut some corners.</p> <p>However, sometimes you won&rsquo;t be able to have a mentor. Could be either because of the location you are at, or you just don&rsquo;t know anyone who could guide you. For that I&rsquo;d recommend a &ldquo;hero&rdquo; or, simply, <strong>look up to somebody who is in the field and try to follow his/her path</strong>. You may not be able to cut corners but, at least, you will be able to follow the directions your &ldquo;hero&rdquo; is going.</p> <h3>Find a community</h3> <p>It&rsquo;s very important to <strong>find a community where you belong</strong>. It can be either a group at your location (where you can meet in person) or even a virtual one (Facebook groups, forums, etc.). You will be able exchange experiences with other people and, consequently, learn more about your technology of choice and your career. This is going to help you a lot as a beginner and, as you gain experience and knowledge, you will be able to help others as well.</p> </body> </html> Mon, 04 Oct 2021 17:43:00 GMT http://davidsonsousa.net/blog/post/you-need-to-read-this-if-you-want-to-become-a-programmer Use regular expressions in Visual Studio to find (and replace) anything http://davidsonsousa.net/blog/post/use-regular-expressions-on-visual-studio-to-find-and-replace-anything <!DOCTYPE html> <html> <head> </head> <body> <p>It doesn&rsquo;t matter what you do. If you are writing any sort of code, you will eventually use the Find/Replace functionality (also known as <kbd>Ctrl+H</kbd> or <kbd>Ctrl+Shift+H</kbd>). The most basic situation is to, for example, make all <code>public</code> methods into <code>protected</code>. But what if you would want to invert the values of a ternary condition or change the order of parameters in multiple methods?</p> <p>Regular expressions to the rescue.</p> <p>Yes, I know. You normally use regular expressions in your code when trying to find something. But bear with me.</p> <h2>What are Regular Expressions?</h2> <p>If you are not familiar, a regular expression (or <strong>regex</strong>) is a sequence of characters that specifies a search pattern. A regex can be used for anything: Find, find/replace, or even input validation. For example:</p> <table style="border-collapse: collapse; width: 99.8395%; height: 107px;" border="1"> <tbody> <tr> <td><strong>Regex</strong></td> <td><strong>Explanation</strong></td> </tr> <tr> <td><code>gr(a|e)y</code></td> <td>Matches 'gray' or 'grey'</td> </tr> <tr> <td><code>\d{5}(-\d{4})?</code></td> <td>Matches US zip codes</td> </tr> <tr> <td><code>//[^\r\n]*[\r\n]</code></td> <td>Matches a comment starting with slash-slash (C# or Java)</td> </tr> </tbody> </table> <p>&nbsp;</p> <p>As you can see, they are not very friendly and, honestly, there is a very low number of people who know them by heart. If you want to create your own regex I&rsquo;d recommend to use websites like <a href="https://regex101.com/">Regex101</a>, which can also help you to test it.</p> <p style="text-align: center;"><img src="/image/post/mceu_87064995821632746834583.png" /></p> <h2>Find with Regex</h2> <p>Look at the method below:</p> <pre class="language-csharp"><code>public override void Process(TagHelperContext context, TagHelperOutput output) { if (Items == null) { return; } output.TagName = "div"; output.Attributes.SetAttribute("class", OuterContainerClass); InnerContainerClass = !string.IsNullOrWhiteSpace(InnerContainerClass) ? $" class=\"{InnerContainerClass}\"" : ""; LabelClass = !string.IsNullOrWhiteSpace(LabelClass) ? $" class=\"{LabelClass}\"" : ""; InputClass = !string.IsNullOrWhiteSpace(InputClass) ? $" class=\"{InputClass}\"" : ""; string isChecked; string isEnabled; var sb = new StringBuilder(); foreach (var item in Items) { isChecked = item.Selected ? " checked" : ""; isEnabled = item.Enabled ? "" : " disabled"; sb.Append("&lt;div").Append(InnerContainerClass).Append(isEnabled).Append('&gt;'); sb.Append("&lt;label").Append(LabelClass).Append('&gt;'); sb.Append("&lt;input type=\"checkbox\" id=\"").Append(item.Value).Append("\" value=\"").Append(item.Value).Append("\" name=\"") .Append(Name).Append('"').Append(InputClass).Append(isChecked).Append('&gt;').Append(item.Label); sb.Append("&lt;/label&gt;&lt;/div&gt;"); } output.Content.SetHtmlContent(sb.ToString()); output.TagMode = TagMode.StartTagAndEndTag; }</code></pre> <p>If you want to find <code>LabelClass</code> you will simply do a <kbd>Ctrl+F</kbd> and type the text in there. Like this:</p> <p><img style="display: block; margin-left: auto; margin-right: auto;" src="/image/post/mceu_49271089511632753507501.png" /></p> <p>But how will you find every occurrence of any line which has <code>class=\"{***Class}</code>, with the asterisks being any text (<em>Input</em>, <em>Label</em>, etc.)? For that we will have to use regex, like in the example below:</p> <p><img style="display: block; margin-left: auto; margin-right: auto;" src="/image/post/mceu_44555973421632753630834.png" /></p> <p>Attention to the red arrows. The one on the bottom indicates the option we should select in order to use regex. The other one, on the left of the search box, shows the regex I used: <code>class=\\"{.*Class}</code>. I used the string I was looking for with 2 minor differences: First, I needed to escape the backslash. And second, I needed to add the <code><strong><em>.*</em></strong></code> before <code>Class</code>. In regex, the <strong>.</strong> (period) will match any character while the <strong>*</strong> (asterisk) indicates repetition. Together they mean something like &ldquo;match any character for an infinite number of times&rdquo;. And if I want to find only letters, I should change to this:</p> <p><img style="display: block; margin-left: auto; margin-right: auto;" src="/image/post/mceu_31563833931632754120925.png" /></p> <p>The regex <code>class=\\"{[a-zA-Z]*Class}</code> means something like &ldquo;match the characters in the range a-z and A-Z&rdquo;. We must specify both upper and lower cases since regex is case-sensitive.</p> <h2>Replace with Regex</h2> <p>The only difference here is the shortcut key used to open the window (<kbd>Ctrl+H</kbd>). Once we found the text we want to replace, we simply press <kbd>Alt+R</kbd> (replace next) or <kbd>Alt+A</kbd> (replace all):</p> <p><img style="display: block; margin-left: auto; margin-right: auto;" src="/image/post/mceu_79570131311632754944422.png" /></p> <p>Done, but that&rsquo;s not all. What if you want to invert the values in those ternary conditionals all at once? For that we need to use capturing groups.</p> <p>Capturing groups are pieces of regex inside parenthesis, like this: <code>(.*)([a-z])</code>. In this basic example we have 2 different capturing groups in the &ldquo;find&rdquo;, which can be referenced in the &ldquo;replace&rdquo; by the dollar sign ($) followed by a number (1, 2, etc.). For example: <strong>$1</strong>. Important to mention that capturing groups are 1-based indexing, which brings us to our example:</p> <p><strong>Before</strong></p> <p><img style="display: block; margin-left: auto; margin-right: auto;" src="/image/post/mceu_81957141231632755307606.png" /></p> <p>As you can see, we have 2 groups, each one of them matching an item in the conditional.</p> <p><strong>After</strong></p> <p><img style="display: block; margin-left: auto; margin-right: auto;" src="/image/post/mceu_61260098821632755212343.png" /></p> <p>And here you see the result, by simply building the &ldquo;replace&rdquo; with the inverted groups.</p> <h2>Using in other editors</h2> <p>It is possible to use regex in other places too, such as <a href="https://notepad-plus-plus.org/">Notepad++</a> and <a href="https://code.visualstudio.com/">Visual Studio Code</a>. However you have to consider the "flavor" of the regex. The core idea is the same, but there may be a couple of minor differences which will be enough to drive anyone crazy.</p> <p><a href="https://devopedia.org/regular-expression">Check Devopedia for more information on regex</a>.</p> </body> </html> Mon, 27 Sep 2021 14:32:00 GMT http://davidsonsousa.net/blog/post/use-regular-expressions-on-visual-studio-to-find-and-replace-anything Amazon got me again: From Kindle 4 to Kindle Oasis 3 http://davidsonsousa.net/blog/post/amazon-got-me-again-from-kindle-4-to-kindle-oasis-3 <!DOCTYPE html> <html> <head> </head> <body> <p>I got introduced to the Kindle back in 2011. I even made a <a href="/blog/post/review-amazon-kindle-4">short review</a> back then. I was so happy with it that it is the gadget I had for the longest time &ndash; nearly 10 years. It has followed me to work, trips, vacation, and parks. And I stand by every word I said back in 2011: Amazing display, good size and incredible battery.</p> <p>Some time ago, somehow, I stopped reading novels regularly, giving preference to more technical books. And the Kindle was &ldquo;replaced&rdquo; by my computer screen as I needed to read the book while practicing some code. As I am slowly returning to novels, I decided to upgrade my reading device.</p> <p>Enter the <a href="https://www.amazon.com/All-new-Kindle-Oasis-now-with-adjustable-warm-light/dp/B07L5GDTYY/">Kindle Oasis 3</a>.</p> <p><img style="display: block; margin-left: auto; margin-right: auto;" src="/image/post/mceu_23714027311618870576547.jpg" /></p> <p>So many things have changed that within the last 10 years that I decided to go to the most expensive from the series, surely expecting it will last more 10 years with me.</p> <p>It is impossible to compare a Kindle 4 with a Kindle Oasis. It&rsquo;s like comparing, I don&rsquo;t know, a bike and a car: Both will take you from point A to B but one will be faster and more comfortable. Meaning: One can still read a book with the Kindle 4 without any problems, but the experience with the Kindle Oasis is far better!</p> <p>Now, I could do a full review telling how this and that is amazing, but I have it for less than a week and I didn&rsquo;t even manage to finish a full book yet (reading <a href="https://www.amazon.com/World-War-Oral-History-Zombie-ebook/dp/B000JMKQX0">World War Z</a>, by the way). All I can do is to tell you that getting it was the best thing I could have done, but I found 2 problems:</p> <ol> <li>The battery drains much faster than my old Kindle. That's probably because it has more features, including the display brightness (my old one didn't have it).</li> <li><span style="font-size: 1rem; display: inline !important;">It feels cold and slippery as the back is made of aluminum. But any cover will solve the problem, as the one I have.</span></li> </ol> <p>For more details on the device, I&rsquo;m going to refer you to 2 videos from <a href="https://www.youtube.com/channel/UCm_DGonIiSrLBGLz0ProiWA">Mike&rsquo;s Book Reviews</a>, which helped me to decide (or convinced me) to buy my Oasis:</p> <p style="text-align: center;"><iframe title="YouTube video player" src="https://www.youtube.com/embed/lxl1OTDKnxM" width="560" height="315" frameborder="0" allowfullscreen="allowfullscreen"></iframe></p> <p style="text-align: center;"><iframe title="YouTube video player" src="https://www.youtube.com/embed/-3aBFWqkdaE" width="560" height="315" frameborder="0" allowfullscreen="allowfullscreen"></iframe></p> </body> </html> Tue, 20 Apr 2021 00:12:00 GMT http://davidsonsousa.net/blog/post/amazon-got-me-again-from-kindle-4-to-kindle-oasis-3 The smart world needs dumb redundancy http://davidsonsousa.net/blog/post/the-smart-world-needs-dumb-redundancy <!DOCTYPE html> <html> <head> </head> <body> <p>I have been complaining about smartwatches forever. I never understood how we decided that it is ok to recharge it every day. Yes, I understand they have plenty of features that a normal watch does not have and they need to use a reduced size battery. But I am from the time when mobile phones could hold the battery for a week. So why can&rsquo;t smartwatch be the same? Considering we are using it to show our health status, we need smartwatches with better battery usage.</p> <p>Some days ago, I forgot to charge my watch and I only noticed when the app said I slept only for 2h while I had a full night of sleep. The problem is that the battery died in the middle of the night. As I was at home, I could easily charge it at the moment I noticed. Also, luckily, I have a hybrid smartwatch &ndash; <a href="https://buy.garmin.com/en-US/US/p/662825/pn/010-02240-03">Garmin v&iacute;vomove Style</a> &ndash; and it is the best thing ever. It is called hybrid smartwatch because it has the features of a smartwatch while still behaving like a normal watch. And the battery is wonderful. It lasts close to 6 days with my sedentary life and takes not more than 30mins to charge (I am never paying attention but it's "fast"). The nicest thing is: The battery dies but the analog hands will still work for one more week. Not sure how or why. But it is fascinating that I can still see the time even if the watch is dead.</p> <p>As you can see, I forgot to charge for nearly a week. Cool, right?</p> <p>This is one of the things what make me think that we are blindly delegating everything that used to work perfectly fine to electronic smart devices that may fail us at some point. For example, a connected doorbell that locks the door when doesn&rsquo;t recognize a face and is unable to recognize its owner (<a href="https://twitter.com/bjmay/status/1041833853852311553">here</a>), doorbells with touchscreens (<a href="https://twitter.com/jaapstronks/status/1336633995212304390">here</a>) and many others. I am not against having smart devices. I have some, including a <a href="https://www.cnet.com/reviews/google-nest-hub-max-the-bigger-nest-hub-isnt-the-better-one-review/">Google Nest Hub Max</a> in my kitchen. I am against not having redundancy for the smart devices that are being released in the last years and can directly affect our lives.</p> <p><img style="display: block; margin-left: auto; margin-right: auto;" src="/image/post/mceu_75523679221610663137737.jpg" /></p> <p>Mobile phones have a similar problem (lack of coverage) when we&nbsp;go to some places.</p> <p>By the end of 2012, I was invited for a teambuilding and the company booked a hotel outside of Prague. It was amazing: Good food, nice people, plenty of fun. When I wanted to make a phone call, I had no signal. Look, I am not talking about internet. I am talking about regular voice call and SMS. It did not work because my operator did not have a good coverage in that area. I had a couple of redundancies if I needed: Colleagues using a different operator and the phones from the hotel in case of emergency. And that is a technology that is around for many years.</p> <p>In the end, it is simple: Do not blindly trust your smart devices. They will fail you. Maybe it will be something small like battery ending while you are asleep or your smart fridge not showing the news on the display. But if you rely on that for safety or health, you must consider if you have a redundancy. Because you will not like when your smart lock opens the main door because of an old firmware. Or, maybe, your home gets freezing cold during a winter night because your smart thermostat lost Wi-Fi connection.</p> <figure style="text-align: center;"><img style="display: block; margin-left: auto; margin-right: auto;" src="/image/post/imagetools0.jpg" width="709" height="573" /> <figcaption class="figure-caption">"Please knock because Google is down" (from <a href="https://twitter.com/rubengmrs/status/1338459614967439363">here</a>)</figcaption> </figure> </body> </html> Thu, 14 Jan 2021 23:06:00 GMT http://davidsonsousa.net/blog/post/the-smart-world-needs-dumb-redundancy My plan for 2021 http://davidsonsousa.net/blog/post/my-plan-for-2021 <!DOCTYPE html> <html> <head> </head> <body> <p>I had a plan for 2020 and most of it involved travelling. See, <strong>I was planning to visit 12 countries in 12 months</strong>. The first country was supposed to be Italy and the last would be Maldives. In that way I would have a tropical Christmas and New Years Eve. All I could do was to <a href="https://www.instagram.com/p/B8hYlKWlVXY/">visit Budapest for holidays</a> and <a href="https://www.instagram.com/p/B9Ti6rih43z/">London for business</a>. Because, just as <a href="https://youtu.be/sAn7baRbhx4">nobody expects the Spanish inquisition</a>, nobody expects a global pandemic.</p> <p>This year &ndash; 2021 &ndash; is going to be different as there is absolutely no possibility to make travel plans. I can book something for March, but nobody knows how it&rsquo;s going to be. So, instead, I&rsquo;m going to focus on what I can do from and around my home. After all, I suppose I&rsquo;m going to spend a lot of time at home anyway since many people think that Bill Gates and George Soros want to inject microchips and force The Great Reset or whatever bullshit people believe these days&hellip; 🙄</p> <p>Anyway, back to the 2021 plan, with goals listed in no specific order.</p> <h2>Pass some Microsoft Exams</h2> <p>My last passed exam is from 2016. Many things changed in the last 4 years and I need to keep my knowledge up to date. Although I was not frozen in time and my knowledge is pretty much updated thanks to my work, a MS exam which grants me a certification will&hellip; Well&hellip; Certify that.</p> <h2>Teach at least 80 hours of MS content</h2> <p>As my MCT was recently reactivated, I think it&rsquo;s fair to assume I want to return to teaching. Not full time, but at least 80 hours. I could do that during my vacation time in my regular job or during the weekends. But that&rsquo;s something I&rsquo;m definitely going look into.</p> <p style="text-align: center;"><a title="MCT - Microsoft Certified Trainer" href="https://www.youracclaim.com/badges/1f1e627b-57af-4ea5-bd91-c899213c9a30/public_url"><img src="/image/post/mceu_72850084911609602494329.png" /></a></p> <h2>Shoot some coding videos</h2> <p>Still on the teaching path, I want to start shooting some educational content. There are a lot of how-to videos on YouTube already but the more, the merrier. It&rsquo;s a bit far-fetched but I believe that if I have my content out there in video it will help me with my long term goals in the near future.</p> <h2>Get better at photography</h2> <p>That&rsquo;s an old passion that only now I decided to live. I bought a mirrorless camera in the end of 2020 and I intend to get better at knowing how to take pictures and use proper lenses. Fun fact: The camera alone already helps me to take better pictures than anything I&rsquo;ve used before. So, I guess I am in the right path. And yes, all pictures will go to <a href="https://www.instagram.com/davidsonsousadev/">my Instagram</a>.</p> <p><img style="display: block; margin-left: auto; margin-right: auto;" src="/image/post/mceu_92469819221609602866480.jpg" /></p> <h2>Improve my home office</h2> <p>Even though I have everything I need in my home office space, I need to improve the environment. Most of my flat is in the &ldquo;just moved in&rdquo; situation since 2018 and the home office isn&rsquo;t that different. Maybe have hang some pictures in the wall and organize some shelves will help.</p> <h2>Write more articles in this blog</h2> <p>I mean, really. Look at the dates of the last 10 articles&hellip;</p> <h2>Learn Czech</h2> <p>Well, it&rsquo;s about time&hellip; 😁</p> <p>Except the photography, none of these goals would require me even to leave my flat. That&rsquo;s a total 180 degrees turn from my 2020 plan. But think about it: If I really get better at photography, I will be able to take better pictures when I will travel around the world in 2022. 😉</p> </body> </html> Sat, 02 Jan 2021 16:39:00 GMT http://davidsonsousa.net/blog/post/my-plan-for-2021 Changes after 9 months into the COVID-19 pandemic http://davidsonsousa.net/blog/post/changes-after-9-months-into-the-covid19-pandemic <!DOCTYPE html> <html> <head> </head> <body> <p>Back in April I decided to write about <a href="/blog/post/working-from-home-during-the-covid19-pandemic">working from home</a>. Even though I did not mention, the main idea was to write monthly about it. We are in an exceptional situation and I figured it would be important. The problem is: I did not consider that the boundaries I tried to set in my work/personal life would just fade away because of the changes we had in the project I am working on.</p> <p>Honestly, this year made me a physical and mental wreck and I will probably need to schedule some visits to a good psychiatrist. Or probably take a 1-year sabbatical in a paradise island.</p> <p>But, well, let&rsquo;s go through some good stuff while this doesn&rsquo;t happen.</p> <p>As having the best tool for the job is important, <a href="/blog/post/building-my-new-pc-going-back-to-amd-and-feeling-good-about-it">my computer</a> got an upgrade: I decided to double the RAM and storage. Even though I use the company notebook for working, I figure I would be more efficient by having a more powerful machine on the side whenever necessary. And it is being particularly useful, especially when I need to do some heavy processing that my work notebook would normally struggle with.</p> <p>The 3-monitor setup was replaced by a single super ultrawide screen, the <a href="https://www.trustedreviews.com/reviews/samsung-crg90">Samsung C49RG9</a>. And now I use <a href="https://www.techrepublic.com/article/windows-10-powertoys-how-to-use-and-configure-fancyzones/">Microsoft PowerToys with FancyZones</a> to manage the windows positioning. As result, I get a better view without having to move my neck so much. The only problem is screen sharing thanks to the 5120x1440 resolution. You can <a href="https://youtu.be/J4KwHpIeNrA">play this video in full screen</a> to know what I am talking about. I may need to add a second screen with a more normal resolution in the future if I want to do any sort of screen share.</p> <p>With the new computer and screen, new games. I am splitting my gaming time between my Xbox and my PC. Game Pass Ultimate is a blessing in that matter.</p> <p><img style="display: block; margin-left: auto; margin-right: auto;" title="Forza Motorsport 7 on a super ultrawide screen" src="/image/post/mceu_81684481311608383864757.jpg" alt="Forza Motorsport 7 on a super ultrawide screen" width="800" height="600" /></p> <p>Now in December I decided to gift myself a <a href="https://www.amazon.com/Canon-Mirrorless-Camera-EF-M15-45mm-Video/dp/B079Y45KTJ">Canon EOS M50</a>. For long time I wanted to learn about photography and, well, the time is now. It&rsquo;s been pretty refreshing to learn something new and completely unrelated with my line of work. And yes, phones today are already taking really nice pictures. But nothing will replace a good camera. Otherwise we would see wedding pictures taken by an iPhone.</p> <p>Also, I will get to walk outside more when looking for the perfect shot. Perhaps <a title="Visit my Instagram" href="https://www.instagram.com/davidsonsousadev/">my Instagram</a> will have better pictures from now on.</p> <p style="text-align: center;"><img src="/image/post/mceu_79630781611608385854540.jpg" /><br /><a href="https://www.instagram.com/p/CIY2TGxsrQp/">https://www.instagram.com/p/CIY2TGxsrQp/</a></p> <p>On the physical side, I decided to do some jogging during summer even though I was not doing that for 20 years. Of course, I felt muscles that I didn&rsquo;t remember they existed. But once I got used to, it was easier. Summer ended and I stopped as I am still not ready to run when it&rsquo;s under 15C.</p> <p>My home exercises increased with the end of summer: Push-ups whenever I have time, get up and stretch every hour. I am trying to keep as natural as possible, fitting into my routine. Meaning: If I need to deploy something, I exercise. I am waiting for the food in the microwave, I exercise. Sometimes even in meetings (on mute, no camera). I am not following any sort of routine, I am just trying to move as much as I feel like. But as I completely ignored my exercises in October and November, my body started complaining: I started feeling an excruciating thigh pain in both legs which only stopped when I started walking outside again.</p> <p style="text-align: center;"><img src="/image/post/mceu_42514214521608385868333.jpg" /><br /><a href="https://www.instagram.com/p/CIbNKnksZ-l/">https://www.instagram.com/p/CIbNKnksZ-l/</a></p> <p><span style="font-size: 1rem; display: inline !important;">In conclusion, what to say. It&rsquo;s far from perfect but it was a good learning. I will definitely change some things for next year, especially when concerning the work/personal life boundaries. Probably adding more exercise/walking time into the routine so I don't become an atrophied potato bag.</span></p> <p>I still look forward for when we can move freely again. Do I miss the office? Not really, but because I am able to work in a nice environment at home. But I&rsquo;d still visit it once a week. 😉</p> </body> </html> Sat, 19 Dec 2020 12:55:00 GMT http://davidsonsousa.net/blog/post/changes-after-9-months-into-the-covid19-pandemic How to invert the parameters of a method using Regular Expressions http://davidsonsousa.net/blog/post/how-to-invert-the-parameters-of-a-method-using-regular-expressions <!DOCTYPE html> <html> <head> </head> <body> <p>Today I noticed that all <code>Assert.Equal()</code> in our unit tests had inverted parameters. Meaning that we had <code>Assert.Equal(actual, expected)</code> instead of having <code>Assert.Equal(expected, actual)</code>. The result does not change when the test passes, but it can lead to mistakes or misunderstandings when <code>Assert.Equal()</code> returns false.</p> <p>Changing the order of the parameters is simple but it can be both annoying and time consuming if we have a lot of method calls.</p> <p>What to do?</p> <p>Since <strong>Visual Studio allows Find/Replace using regular expressions</strong>, we can do it easily. First, we will need to enable the regex mode in the Find/Replace:</p> <p style="text-align: center;"><img src="/image/post/mceu_80621603711595362553605.png" /></p> <p>Then we prepare a regex like the one below and place it on <em>Find</em>:</p> <p><code>\((.*?)(, )(.*?)\);</code></p> <p>This regex finds everything what is between the first parentheses and the semicolon, which allows you to have some method calls as parameters like <code>expectedPerson.GetFullName()</code>, for example. Also, it separates the result in 3 groups - first parameter (<code>$1</code>), coma and space (<code>$2</code>), second parameter (<code>$3</code>) - which we will have in the <em>Replace</em> like this:</p> <p><code>($3, $1);</code></p> <p>As mentioned previously, we had 3 groups. We could include the group <code>$2</code> but ut it's not necessary in this case as we can "hard code" the comma and space for better understanding.</p> <p>Here is how the Find/Replace is going to look like with our regex and replacements:</p> <p><img style="display: block; margin-left: auto; margin-right: auto;" src="/image/post/mceu_9576659921595362608420.png" /></p> <p>And here is how the selection looks in the code:</p> <p><img style="display: block; margin-left: auto; margin-right: auto;" src="/image/post/mceu_88309956931595362884088.png" /></p> <p><strong>Important:</strong> Don't forget to change the Find/Replace scope to Selection in case you want to invert the parameters of a method otherwise you will have unintended consequences.</p> <p><img style="display: block; margin-left: auto; margin-right: auto;" src="/image/post/mceu_28727273841595362922836.png" /></p> <p>You can check <a href="https://regex101.com/r/iGWMb2/2">this regex in the Regex101.com website</a> if you want to play around before using it.</p> </body> </html> Tue, 21 Jul 2020 22:07:00 GMT http://davidsonsousa.net/blog/post/how-to-invert-the-parameters-of-a-method-using-regular-expressions Working from home during the COVID-19 pandemic http://davidsonsousa.net/blog/post/working-from-home-during-the-covid19-pandemic <!DOCTYPE html> <html> <head> </head> <body> <p>It&rsquo;s safe to say that most of us are trying to practice as much social distancing as possible, even though sometimes we need to buy food. And while some countries like Italy and Spain are enforcing strict rules, here in Czech Republic things are relatively relaxed: We are still able to go out &ndash; wearing masks &ndash; and sit in parks. Although it&rsquo;s recommended to try to keep as much distance as possible from people.</p> <p>We can all agree that some people are unable to work. But I, as developer, can work from home. And it&rsquo;s a privilege to have a career that allows you such flexibility. I could be stranded anywhere and still be able to work &ndash; as long as I have a computer and internet.</p> <p>I am using my home office space since the return from my business trip to London, in the beginning of March. That is a bit more than a month already.</p> <p>My home office space was one of the first things I had finished in the flat since I needed to be here when the furniture was being delivered. At that time, I was also working from home and it was a pretty good test-drive.</p> <p><img style="display: block; margin-left: auto; margin-right: auto;" title="My home office space" src="/image/post/mceu_71028814211586701304221.jpg" alt="My home office space" width="800" height="600" /></p> <p>During this quarantine I used it to:</p> <ul> <li>Produce the code for <a title="Tennis TV" href="https://www.tennistv.com/">Tennis TV</a>: That&rsquo;s the project I am working on. Pretty cool, if you ask me.</li> <li>Join meetings: Necessary, especially nowadays. Catch up with colleagues and coordinate actions is a must for a productive day.</li> <li>Deliver trainings: That happened recently. Some folks from a company I worked some years ago asked for a .NET Core training and I was more than happy to do it &ndash; virtually.</li> </ul> <p>Important note about the meetings: Sometimes I prefer to take the notebook for a while and walk around the flat. It doesn&rsquo;t matter as long as I don&rsquo;t spend more than the meeting&rsquo;s length out of my home office space. Balcony is good too, especially when the noise is low.</p> <p><img style="display: block; margin-left: auto; margin-right: auto;" title="My balcony, with fake grass" src="/image/post/mceu_80084339321586701474991.jpg" alt="My balcony, with fake grass" width="800" height="450" /></p> <p>Having a separated office space helps with context: Since I don&rsquo;t see things that remind me &ldquo;home&rdquo; and &ldquo;leisure&rdquo;, I am able to work more productively. That helps even on lunch time, when I go to prepare some food and watch TV. Cooking during lunch time is time consuming but pretty good. It&rsquo;s a different activity in a different context. It helps me to be sane in times like these.</p> <p>In the end, I am looking forward for when the pandemic stops to be a threat and we will be able to move freely again. As for going back to the real office&hellip; Hm&hellip; Maybe once a week would be good enough. 😉</p> </body> </html> Sun, 12 Apr 2020 16:08:00 GMT http://davidsonsousa.net/blog/post/working-from-home-during-the-covid19-pandemic NDepend Review: A great tool to expose the technical debt in your projects http://davidsonsousa.net/blog/post/ndepend-review-a-great-tool-to-expose-the-technical-debt-in-your-projects <!DOCTYPE html> <html> <head> </head> <body> <p>Some weeks ago, I was contacted by a representant from <a href="https://www.ndepend.com/">NDepend</a> to check their product out. Long story short, the tool is amazing! But let me give you more details.</p> <p><img style="display: block; margin-left: auto; margin-right: auto;" src="/image/post/mceu_59214750011575836160633.png" /></p> <h2>What is it</h2> <p>NDepend is a Visual Studio extension that helps you to know the amount of technical debt is being produced in the code. I am not talking about legacy code or old technologies here. I am specifically talking about code that needs to be refactored at some point.</p> <p>A simple example is an enormous method that was created and, for sure, you will need to break it into smaller methods. NDepend will catch that and flag it as technical debt so you can fix it before it becomes a code smell.</p> <h2>How install and to use it</h2> <p>They have a <a href="https://www.youtube.com/channel/UCYBq7oAWczUhkJmr-SqKvwA/videos">YouTube channel</a> with short videos to guide you, aside from an <a href="https://www.ndepend.com/docs/getting-started-with-ndepend">extensive documentation</a> that will help you to walk through the tool.</p> <h2>Using it in my projects</h2> <p>After I got it installed and going through some of the documentation and tutorials, I decided to give a first try with the source code of my own website, <a href="https://github.com/davidsonsousa/CmsEngine">which is available on GitHub</a>. It turns out that I got rating A, which means that it&rsquo;s quite alright and it doesn&rsquo;t seem to have so much technical debt.</p> <p style="text-align: center;"><img src="/image/post/mceu_89283106821575836188996.png" /></p> <p>Then I tried another one, <a href="https://github.com/davidsonsousa/DataTables-With-AspNetCore">also available on GitHub</a>, which I used to write <a href="/blog/post/create-complete-reports-using-datatables-and-aspnet-mvc-core">this article about the Datatables component</a>. As the rating was B I saw this as an opportunity to improve it.</p> <p style="text-align: center;"><img src="/image/post/mceu_34997385731575836206194.png" /></p> <p>As I went through some rule and started fixing some issues, I noticed that the debt was increasing, instead of decreasing.</p> <p style="text-align: center;"><img src="/image/post/mceu_15541620641575836227563.png" /></p> <p>It turns out that my changes were affecting the code more than I expected as they were breaking changes. I mean, transforming an instantiable class into static is kind of a big deal. From all the changes I made &ndash; which solved some problems &ndash; this was the one that caught me of guard. Mostly because we do this all the time being sure that we are not breaking anything, but we are.</p> <p>On a brighter note, I had this method which NDepend claimed to be complicated:</p> <pre class="language-csharp"><code>public static void Order(ref IEnumerable&lt;PersonTableViewModel&gt; items, int orderColumn, string orderDirection) { switch (orderColumn) { case 0: items = orderDirection == "asc" ? items.OrderBy(o =&gt; o.FullName) : items.OrderByDescending(o =&gt; o.FullName); break; case 1: items = orderDirection == "asc" ? items.OrderBy(o =&gt; o.PreferredName) : items.OrderByDescending(o =&gt; o.PreferredName); break; case 2: items = orderDirection == "asc" ? items.OrderBy(o =&gt; o.Phone) : items.OrderByDescending(o =&gt; o.Phone); break; case 3: items = orderDirection == "asc" ? items.OrderBy(o =&gt; o.Email) : items.OrderByDescending(o =&gt; o.Email); break; case 4: items = orderDirection == "asc" ? items.OrderBy(o =&gt; o.Age) : items.OrderByDescending(o =&gt; o.Age); break; case 5: items = orderDirection == "asc" ? items.OrderBy(o =&gt; o.Status) : items.OrderByDescending(o =&gt; o.Status); break; default: items = items.OrderBy(o =&gt; o.FullName); break; } }</code></pre> <p>I made a small refactoring, trying to abstract away its logic and now it looks like this:</p> <pre class="language-csharp"><code>public static void Order(ref IEnumerable&lt;PersonTableViewModel&gt; items, int orderColumn, string orderDirection) { switch (orderColumn) { case 0: items = ApplyOrder(items, o =&gt; o.FullName, orderDirection); break; case 1: items = ApplyOrder(items, o =&gt; o.PreferredName, orderDirection); break; case 2: items = ApplyOrder(items, o =&gt; o.Phone, orderDirection); break; case 3: items = ApplyOrder(items, o =&gt; o.Email, orderDirection); break; case 4: items = ApplyOrder(items, o =&gt; o.Age, orderDirection); break; case 5: items = ApplyOrder(items, o =&gt; o.Status, orderDirection); break; default: items = items.OrderBy(o =&gt; o.FullName); break; } } private static IEnumerable&lt;PersonTableViewModel&gt; ApplyOrder(IEnumerable&lt;PersonTableViewModel&gt; items, Func&lt;PersonTableViewModel, string&gt; orderBy, string orderDirection) { items = orderDirection == "asc" ? items.OrderBy(orderBy) : items.OrderByDescending(orderBy); return items; }</code></pre> <p>Boom! The dashboard is saying that the technical debt decreased. I am sure that if I insist I can decrease it even more.</p> <p><img style="display: block; margin-left: auto; margin-right: auto;" src="/image/post/mceu_30830030851575836320434.png" /></p> <h2>Performance</h2> <p>Let me be honest: I like to keep my IDE simple and fast, which means that anything that degrade its performance will not be installed. Yeah, I know, <a href="/blog/post/building-my-new-pc-going-back-to-amd-and-feeling-good-about-it">I recently built my new computer</a>. But it&rsquo;s an old habit which may be difficult to overcome. So, I was concerned that I wouldn&rsquo;t be able to even open my VS after installing NDepend but, for my amusement, NDepend is very fast.</p> <p>The tool is not intrusive, and you barely notice unless you trigger it on the menu (Extensions &gt; NDepend) or in the red circle in the bottom right. Alternatively, you can have its windows stacked on your Visual Studio.</p> <p style="text-align: center;"><img src="/image/post/mceu_2447112561575836345883.png" /></p> <h2>Miscellaneous</h2> <p>I couldn&rsquo;t check some things because of how my projects are built, but I will talk about them.</p> <h3>Code coverage</h3> <p>My projects don&rsquo;t have unit tests. Yeah, I know, they should. But I will work on that. The thing is that NDepend allows you to import your code coverage data into the dashboard and see how you are doing. This should increase your issues since NDepend will start warning you about the methods which are not being tested.</p> <h3>Rules</h3> <p>You can &ndash; and perhaps you should &ndash; edit the rules NDepend uses to assess your code. The rules they use are general, but it&rsquo;s well known that each team or company will have their own code standards.</p> <h2>Conclusion</h2> <p>I like NDepend and I am going to use with everything I can. It&rsquo;s nice to have a tool which groups all useful information in a single dashboard. There is still a lot to learn and use, but I think I am in a good path. Unfortunately, I didn&rsquo;t have a big enough project in my computer to fully test it. Not to mention that some things would need much more time to use such as trending charts. Also, I&rsquo;d love to see how NDepend would behave when coding with more people.</p> <p>Bu the most important is: The more I use, more my code will improve. 🤓</p> </body> </html> Sun, 08 Dec 2019 21:11:00 GMT http://davidsonsousa.net/blog/post/ndepend-review-a-great-tool-to-expose-the-technical-debt-in-your-projects How to stop your computer with Windows 10 waking up during the night? http://davidsonsousa.net/blog/post/how-to-stop-your-computer-with-windows-10-waking-up-during-the-night <!DOCTYPE html> <html> <head> </head> <body> <p>It happens quite often. You put your computer to sleep in the evening and, in the morning, it&rsquo;s awake. And you have no idea why.</p> <p>But wait, there is a way to know what woke the computer up! Open your favorite command line tool and run this: <strong><span style="font-family: terminal, monaco, monospace;">powercfg /lastwake</span></strong>. You should see exactly what woke your computer up. In my case, this is what I got:</p> <p><img src="/image/post/mceu_74641865511575195993618.png" /></p> <p>The <em>UpdateOrchestrator</em>, or <em>Update Orchestrator Service</em>, is the services that will coordinate the Windows Update for your computer. You can read more about it <a href="https://appuals.com/what-is-update-orchestrator-service-and-should-it-be-disabled/">here</a>.</p> <blockquote> <p>Now that we know the culprit, we can work on the solution. But before we start, you will need to download the <a href="https://docs.microsoft.com/en-us/sysinternals/downloads/psexec">PsExec tool</a>. This tool is going to help you to acquire the necessary permissions to disable what we need to disable. Once you downloaded, you should extract everything into a folder. For example: C:\tools\psexec.</p> </blockquote> <p>Now we can start:</p> <ol> <li>Open your command line in administrator mode and navigate into the folder you extracted PsExec;</li> <li>Run the following command: <ol> <li>Cmd: <span style="font-family: terminal, monaco, monospace;">psexec.exe -i -s %windir%\system32\mmc.exe /s taskschd.msc</span></li> <li>Powershell: <span style="font-family: terminal, monaco, monospace;">.\psexec.exe -i -s $env:windir\system32\mmc.exe /s taskschd.msc</span></li> </ol> </li> <li>Once the Task Scheduler opens, navigate to Task Scheduler Library &gt; Microsoft &gt; Windows &gt; UpdateOrchestrator</li> <li>Double click the item on the list and go to the tab Conditions</li> <li>Uncheck &ldquo;<strong>Wake the computer to run this task</strong>&rdquo;</li> <li>Click OK</li> <li>Repeat for all items you need/want</li> </ol> <p>That&rsquo;s it. A relatively simple solution for a very annoying problem.</p> </body> </html> Sun, 01 Dec 2019 11:25:00 GMT http://davidsonsousa.net/blog/post/how-to-stop-your-computer-with-windows-10-waking-up-during-the-night Why do we see websites in a language that we didn't choose? http://davidsonsousa.net/blog/post/why-do-we-see-websites-in-a-language-that-we-didnt-choose <!DOCTYPE html> <html> <head> </head> <body> <p>Imagine: You are living in the country you were born, speaking the language you grew up with when, for unforeseen reasons, you start living in another place which has a language you barely understand. That means you will need to make some changes in your life, which include updating online profiles.</p> <p>Every profile that you need to update normally should have 2 fields: <em>Country</em> (or <em>Region</em>) and <em>Language</em>. That means you will change your country to, let&rsquo;s say, Czech Republic, while still being able to access the website in your native language (English, for example).</p> <p style="text-align: center;"><img title="Settings from Microsoft Account" src="/image/post/mceu_55352565811572547252965.png" alt="Czechia, English (United States)" width="542" height="114" /></p> <p>But sometimes that&rsquo;s not enough.</p> <p>Many companies struggle with translation. And I am not talking about small companies. I am talking about big companies that still don&rsquo;t seem to know what language I speak despite I specifically mark &ldquo;English (United States)&rdquo; everywhere. I am talking every single company that doesn&rsquo;t seem to care about their customers when they provide a subpar language change service.</p> <p>That is different than being redirect to a local online store, which is something I understand and even agree.</p> <p><img style="display: block; margin-left: auto; margin-right: auto;" title="Microsoft Store redirect" src="/image/post/mceu_29725310021572547469465.png" alt="Microsoft Store redirect" width="656" height="266" /></p> <p>Online stores like the Xbox Live will redirect me the country I am living in because of specific commercial rules, currency, taxes, etc. What I don&rsquo;t agree is that I need to understand the local language only because of that. I don&rsquo;t know if they can be sued because of that but I am not a lawyer and I am lazy to check. 🙃</p> <p style="text-align: center;"><img title="Friday The 13th in Czech" src="/image/post/mceu_80808657331572547567990.png" alt="Friday The 13th in Czech" width="304" height="436" /></p> <p>I've seen this many times since I moved to Europe, including:</p> <ul> <li>Microsoft sending me e-mails in English, Portuguese and Czech; Also redirecting me to Czech or Portuguese language websites</li> <li>Google sending me e-mails in English and Czech; Sometimes redirecting me to websites in Portuguese</li> <li>EA, more recently, sent me a confirmation e-mail in Czech with the date in Portuguese (!!!)</li> </ul> <p><img style="display: block; margin-left: auto; margin-right: auto;" src="/image/post/mceu_30968953141572547674394.png" /></p> <p>I believe there are some reasons for this to happen. For example:</p> <ul> <li>They have many systems which are not fully interconnected</li> <li>Some systems got updates and &ldquo;decided&rdquo; to ignore the language field</li> <li>Systems simply assume that you speak the language of the country you live in</li> <li>The company didn&rsquo;t get the full translation for that language (mostly when a product enters a new market)</li> </ul> <p>If you came here for a solution, I have some recommendations that may work for you:</p> <ul> <li>Look for and try to change the language in every website you can find in that company</li> <li>Switch the country back to your home country, unless this will affect you somehow</li> <li>Call their customer service and file a complaint</li> </ul> <p>That&rsquo;s it. Maybe the people working in these systems should spend some time abroad. Or maybe the testers should just try to switch the language to something they can&rsquo;t understand, so they can see this problem.</p> </body> </html> Thu, 31 Oct 2019 19:38:00 GMT http://davidsonsousa.net/blog/post/why-do-we-see-websites-in-a-language-that-we-didnt-choose The importance of having coding standards in a project http://davidsonsousa.net/blog/post/the-importance-of-having-coding-standards-in-a-project <!DOCTYPE html> <html> <head> </head> <body> <p>If someone asks me how much time we should dedicate to the creation of standards for a project, I will say &ldquo;as much as we need&rdquo;. Why? Because everything in our lives is standardized. The colors of the traffic lights, the ways we drive, the places we need to go in order to use public transportation and so on. And we are satisfied with it.</p> <p><img style="display: block; margin-left: auto; margin-right: auto;" src="/image/post/wells-baum-l-n-sivqbhw-unsplash.jpg" alt="wells-baum-l-n-sivqbhw-unsplash.jpg" /></p> <p>The main problem of the lack of standards is that everyone will do the same thing, but in a different way. And that is the recipe for disaster. For example: Sizes of clothes. We are often advised to buy clothes in the same stores or from the same brands because the sizes may differ from one store/brand to another. A shirt size &ldquo;L&rdquo; in the store A may fit you well, while size &ldquo;L&rdquo; of the same model of shirt in the store B may expose your belly.</p> <p>And in software development standards are often neglected by teams because &ldquo;we don&rsquo;t have time for that&rdquo; or &ldquo;the client is not paying for standards&rdquo; or even &ldquo;if you need you can copy from someone else&rsquo;s code&rdquo;. This is a mistake because standards are the only thing that will make a group of different people coming from different backgrounds to work in a large codebase with consistence.</p> <p>If you still don&rsquo;t think this is a problem, think about this: There are some people who prefer to use <code>if</code>, <code>for</code> and <code>foreach</code> without curly braces (and people who prefer them with), there are people who don&rsquo;t care about the length of the lines (those who enable word wrap) while others prefer to break it after a number of characters. Not to mention those who prefer <a href="https://www.youtube.com/watch?v=V7PLxL8jIl8"><em>tabs</em> instead of <em>spaces</em></a> (or vice-versa). Just imagine how messy a file touched by all those different people in different moments of the project would look like. Tabs and spaces mixed up, inconsistence on the look of conditions, etc. What can prevent that? A simple set of rules.</p> <p><img style="display: block; margin-left: auto; margin-right: auto;" src="/image/post/foreach-nonstandard.png" alt="foreach-nonstandard.png" /></p> <p>If this doesn&rsquo;t happen in your team, congratulations. You are lucky to work in a place where everybody codes in the same way. But I&rsquo;m going to feel bad for the new employee who will join coding differently as he will be labeled as &ldquo;the guy with ugly code&rdquo; until he gets used to the code the team produces.</p> <p>There are multiple ways to enforce code consistence, but I normally stick to a simple one: The <em><a href="https://editorconfig.org/">.editorconfig</a></em> file. If you are not familiar with it, the <em>.editorconfig</em> is a file containing the styling rules of your code. You may want to check if your editor/IDE has support for it. It&rsquo;s free and the file can work in scenarios where a project has people working in multiple technologies and operating systems. Commit to your repository along with your project and everyone will code in the same way. I could also mention <a href="https://www.jetbrains.com/resharper/">ReSharper</a>, but this one is paid and specific for .NET Development.</p> <p>I understand it&rsquo;s boring and/or annoying to sit with the team and go over standards. I&rsquo;d expect to do this just once, in the beginning, but leaving the door open to discuss some changes as the project progresses. After a while the changes will come to a minimum and you will even spread the standards across projects and teams. As it should be.</p> <p>What do you think?</p> </body> </html> Fri, 25 Oct 2019 17:13:00 GMT http://davidsonsousa.net/blog/post/the-importance-of-having-coding-standards-in-a-project How the renovation of a room exposed resistance to change in the workplace http://davidsonsousa.net/blog/post/how-the-renovation-of-a-room-exposed-resistance-to-change-in-the-workplace <p>Some months ago we got an e-mail saying that both our big meeting room and social room would face some renovations, aside from the fact that they would exchange places: While the social room was in the ground floor, the meeting room was right above it and had a door to the terrace. The exchange made sense, especially in the warmer days when we could just &ldquo;extend&rdquo; the social room with the terrace. And a quick access to the meeting room from the ground floor would be more than welcome.</p> <p>After some delay, both rooms were finally ready-ish. But we knew it wasn't 100% because we got an e-mail explaining everything what we should know: There were unexpected problems that caused the delay, the rooms are in a &ldquo;minimum viable product&rdquo; state and that we would be missing a couple of things.</p> <p>For context:</p> <ul> <li>The old social room had a dark grey carpet, 2 couches, a small library with technical books and plenty of chairs around a big improvised table made from smaller tables. There was a small kitchen outside, but next to the room. Thanks to the dark tone of the carpet and the only 2 windows as natural source of light, the room always seemed dark. It kinda looked like a meeting room with some social cues.</li> <li>The new social room, however, has a white-ish floor (no carpet), no library (I don&rsquo;t know where it is), plenty of chairs close to plenty of smaller tables spread around the room. Since we got more space, the kitchen was moved inside. And now we have more sources of natural light as we have a door and a big window to the terrace. Now it feels we are getting into a caf&eacute; with open kitchen.</li> </ul> <p>Let me be clear: I fully support this kind of change. There is more light, more energy, and more possibility to roam and talk to different groups. It may still lack some things but the potential is enormous!</p> <figure class="figure" style="text-align: center;"><img src="/image/post/healthier-workplace-lessthanfive-17-0078374.jpg" alt="healthier-workplace-lessthanfive-17-0078374.jpg" /> <figcaption class="figure-caption">Not quite what we got, just an example (<a href="https://www.coalesse.com/blog/the-shift-toward-healthier-workplace-environments/">from here</a>)</figcaption> </figure> <p>Looking at the business side of the story, the company took all necessary steps. Including:</p> <ul> <li>Acknowledge that we would be in a bumpy ride. Especially with meetings, breakfasts and the usage of the coffee machine.</li> <li>Explain people what we got and what was missing. The message that there would be more work (decoration) was clear.</li> </ul> <p>Still, some people were not happy.</p> <p>I heard a lot of different things from random people in random conversations. Mostly ranging from &ldquo;the room is not even finished&rdquo; (we knew) to &ldquo;this is an anti-social room&rdquo;. And those were not just people pointing out issues, which would be relatively normal. They were real complaints. And every complaint had a comparison with the old social room.</p> <p>It seemed personal. Most likely from a very loud minority.</p> <p>I know that some people have hard time to cope with changes, especially at work. But this is getting ridiculous. I am talking about rooms that we wouldn&rsquo;t spend more than 6h per week in the average. Some of us, really only go there to grab a cup of coffee or some fruits and leave.</p> <p>I were responsible for the changes I would probably try to:</p> <ul> <li>Send an e-mail explaining the line of thought for the changes and opening a communication channel for whoever wants to make suggestions.</li> <li>Get the unsatisfied people and talk individually with them. It should be easier to dissuade some of the random complaints when having a 1-1 dialog.</li> <li>Enlist the people who insist on the complaints to help to solve the issue &ndash; either by moving stuff, assembling furniture or painting the walls (if needed, who knows)</li> </ul> <p>That&rsquo;s all.</p> <p>As empathetic as I am trying to be, I still think it&rsquo;s too much crying for much welcome changes. But if everything is open source these days, why not room renovation?</p> Mon, 21 Oct 2019 13:29:00 GMT http://davidsonsousa.net/blog/post/how-the-renovation-of-a-room-exposed-resistance-to-change-in-the-workplace Using Powershell scripts to start and stop Windows Services http://davidsonsousa.net/blog/post/using-powershell-scripts-to-start-and-stop-windows-services <p>As a developer, once you finish setting up your development environment, you are going to have services running in the background. And depending on what kind of developer you are or the tools you have, you will have them taking up resources. That's fine if your primary use is software development. But what if you also use it as a gaming machine or, say, this is the family computer? Would you need to have the SQL Server service running all the time?</p> <p>I know I wouldn&rsquo;t.</p> <p>Since <a href="/blog/post/building-my-new-pc-going-back-to-amd-and-feeling-good-about-it">I got a new machine</a> I decided to investigate on how to make it easier to start and stop services and I realized that doing it through PowerShell would help me. Let's say that I would want to stop the SQL Server. I would use PowerShell in this way.</p> <ol> <li>Open PowerShell <em>as administrator</em></li> <li>Get the service, just to make sure<br /><code>Get-Service -Name 'MSSQLSERVER'</code></li> <li>Then stop it<br /><code>Stop-Service&nbsp;'MSSQLSERVER'</code></li> </ol> <p>And the same for whenever I would start the service (<code>Start-Service 'MSSQLSERVER'</code>).</p> <p>There are 2 ways to get the name of the service in your machine:</p> <ol> <li>Via PowerShell<br /><code>Get-Service</code></li> <li>Via Services<br />Win+R (Run), type services.msc, double click on the service and check the Service Name<br /><img src="/image/post/mssqlserver-name.png" alt="mssqlserver-name.png" /><br /><br /></li> </ol> <p>But then I thought: How can I scale this? Because, see, I currently have 3 services I don't want to have enabled all the time. Maybe next week I will have 10. How can I know?</p> <p>I ended up creating 2 PowerShell scripts for that. Yes, I know, I needed only one and I could pass start or stop as parameter. But my PowerShell skills are very poor so I did what I could. Maybe I will come back to that later. Or maybe you can help, why not? 😉</p> <p>The scripts are on <a href="https://github.com/davidsonsousa">my GitHub</a>, more precisely in this repository: <a href="https://github.com/davidsonsousa/Start-Stop-Dev-Services">https://github.com/davidsonsousa/Start-Stop-Dev-Services</a></p> <p>Great! It's automated enough. But I needed more.</p> <p>The next step was to create a shortcut for each script in the desktop. Since I need to execute the scripts as Administrator, I needed to create a very special kind of shortcut. Something like this:</p> <p><code>C:\Windows\SysWOW64\WindowsPowerShell\v1.0\powershell.exe -ExecutionPolicy Bypass -File "<strong>C:\Foo\Bar\XXXX-services.ps1</strong>" -WindowsStyle Hidden</code></p> <p>Notice the part in bold: This is where I have the path and name of the script.</p> <p>Added some fancy icons to reminded me what is what:</p> <p><img src="/image/post/script-shortcuts.png" alt="script-shortcuts.png" /></p> <p><em>Et voil&agrave;</em>. Now I can start or stop my services whenever I want:</p> <p><img src="/image/post/script-stopped.png" alt="script-stopped.png" /></p> <p>Important to note that the warning on the screenshot comes from RabbitMQ itself. Other services may have the same kind of message, which is fine.</p> Sun, 22 Sep 2019 12:17:00 GMT http://davidsonsousa.net/blog/post/using-powershell-scripts-to-start-and-stop-windows-services Building my new PC - Going back to AMD and feeling good about it http://davidsonsousa.net/blog/post/building-my-new-pc-going-back-to-amd-and-feeling-good-about-it <p>When it comes to software development, I need a good keyboard, a good mouse and nice set of screens. And I managed to have all that in the last years because I got a good notebook (<a href="https://www.lenovo.com/us/en/laptops/lenovo/z-series/z710/">Lenovo Z710</a>) and a decent docking station (<a href="https://us.dynabook.com/accessory/PA3927U-1PRP">Toshiba Dynadock U3.0</a>). I was able, with them, to use up to 3 screens without much hassle. I mean&hellip; It was great for working while not very good for gaming.</p> <p>But it all changed last week, when I finally built my desktop computer. It&rsquo;s been 15 years I&rsquo;ve done it from scratch so I was quite worried that I would do something wrong. Besides, since I wasn&rsquo;t really following the hardware advances over the years, I had to catch up with a lot of new stuff in order to build something decent.</p> <p>The original plan was to go with the combo Intel/Nvidia, but I was a bit concerned with the price. Also, the release of AMD&rsquo;s Zen 2 made me rethink my strategy, so I ended up going full AMD.</p> <h2>Specifications</h2> <ul> <li><strong>Processor:</strong> <a href="https://www.amd.com/en/products/cpu/amd-ryzen-7-3700x">AMD Ryzen 7 3700X</a></li> <li><strong>Cooler:</strong> <a href="https://www.amd.com/en/technologies/cpu-cooler-solution">AMD Wraith Prism</a> (comes with the processor)</li> <li><strong>Mother board:</strong> <a href="https://www.msi.com/Motherboard/X570-A-PRO">MSI X570-A PRO</a></li> <li><strong>Graphic card:</strong> <a href="https://www.sapphiretech.com/en/consumer/21294-01-20g-radeon-rx-5700-8g-gddr6">Sapphire Radeon RX 5700 8G</a></li> <li><strong>HD:</strong> <a href="https://www.crucial.com/usa/en/CT1000P1SSD8">Crucial P1 3D NVMe PCIe M.2 1TB</a></li> <li><strong>RAM:</strong> <a href="https://www.hyperxgaming.com/en/memory/fury-ddr4">Kingston HyperX DDR4 3200 C16 2x8GB</a></li> <li><strong>Case:</strong> <a href="https://www.silentiumpc.com/en/product/regnum-rg4t/">SilentiumPC Regnum RG4T Pure Black</a></li> </ul> <p>The building process was relatively ok even though I am very rusty with hardware, but everything ended well. After installing everything I needed and tweaking the memory in the BIOS for optimum performance, I made a couple of tests and I have to say that I am very happy with the result. The pc runs smooth and the temperature is always in a good level.</p> <h2>Performance</h2> <p>The overall performance is much better than expected: Opening and using the Visual Studio 2019 has been a breeze, the debug times decreased considerably and playing games has been a pleasure. Especially now that I can finally use the 3 screens in the same graphic card without a dock as workaround.</p> <p>So far, I didn&rsquo;t feel the need for overclocking but I don&rsquo;t really see it happening anytime soon. But in case that happen I will probably use the <a href="https://www.youtube.com/watch?v=prAaADB9Kck">Performance Boost Overdrive</a> just to make things easier.</p> <h2>Wrapping up</h2> <p>The best of this build is: It will take longer to upgrade and now it will be just on the part basis.</p> <p>Oh yes, I am now officially a gamer, thanks to AMD&rsquo;s stock cooler. After all, one is a true gammer when the PC has RGB 😁</p> <p><img style="display: block; margin-left: auto; margin-right: auto;" src="/image/post/img_20190824_120357.jpg" alt="img_20190824_120357.jpg" width="351" height="349" /></p> Wed, 28 Aug 2019 23:25:00 GMT http://davidsonsousa.net/blog/post/building-my-new-pc-going-back-to-amd-and-feeling-good-about-it The problem of debugging a Docker project in Visual Studio http://davidsonsousa.net/blog/post/the-problem-of-debugging-a-docker-project-in-visual-studio <p>I&rsquo;ve been reading about <a href="https://www.docker.com/">Docker</a> for a couple of weeks already and, few days ago, I decided to create a small proof of concept. You know, just to make sure that I understood everything well. But I ended up running into problems which resulted in a <a href="https://twitter.com/DavidsonSousa/status/1162087779523801088">small thread on Twitter</a> that I am expanding here.</p> <p>Everything started when I decided to use Visual Studio 2019 to take care of Docker for me. In case you don&rsquo;t know, you can &ldquo;dockerize&rdquo; existing projects&hellip;</p> <p><img style="display: block; margin-left: auto; margin-right: auto;" src="/image/post/add-docker-support.png" alt="add-docker-support.png" width="501" height="336" /></p> <p>&hellip;or create a &ldquo;dockerized&rdquo; project from scratch.</p> <p><img style="display: block; margin-left: auto; margin-right: auto;" src="/image/post/enable-docker-support.png" alt="enable-docker-support.png" width="685" height="340" /></p> <p>I decided to do both since I was just playing around. The result was a couple of duplicated files that I ended up deleting later. Perhaps the best option is to &ldquo;dockerize&rdquo; a project after it&rsquo;s been created. Anyway, here is the result so far:</p> <p><img style="display: block; margin-left: auto; margin-right: auto;" src="/image/post/solution-explorer.png" alt="solution-explorer.png" /></p> <p>From that point I just wanted to see if what would happen when I run the project. So, I did my usual: Start the project without debugging (Ctrl+F5). I prefer to do that because it gives me the feeling that I am running closer to a real application. Not to mention that I would not hit random breakpoints I&rsquo;ve added and forgot to disable.</p> <p><img style="display: block; margin-left: auto; margin-right: auto;" src="/image/post/debug-menu.png" alt="debug-menu.png" /></p> <p>Whenever I want to debug, I simply attach the Visual Studio to the process of the project (Ctrl+Alt+P).</p> <p><img style="display: block; margin-left: auto; margin-right: auto;" src="/image/post/debug-menu-attach.png" alt="debug-menu-attach.png" /></p> <p>That opens a dialog where I can select the process. But since I am using Docker, I must select the connection target, which is the name of the container, and the process, which is &ldquo;dotnet&rdquo;.</p> <p><img style="display: block; margin-left: auto; margin-right: auto;" src="/image/post/connection-target.png" alt="connection-target.png" width="623" height="266" /></p> <p>There is one extra step here which is the type of the code. Since I am using <strong>Linux Containers*</strong>, I will choose the only option available.</p> <p><img style="display: block; margin-left: auto; margin-right: auto;" src="/image/post/code-type.png" alt="code-type.png" /></p> <p>That should be it. The code would be attached, and I would be able to debug. Unfortunately, I got an exception after a couple of seconds saying that the launch debug adapter failed to launch.</p> <p><img style="display: block; margin-left: auto; margin-right: auto;" src="/image/post/exception.png" alt="exception.png" /></p> <p>Since the exception was also pointing to the Output Window, it was a good idea to check there too. And that was the moment I regret that I don&rsquo;t really know Linux:</p> <p><img style="display: block; margin-left: auto; margin-right: auto;" src="/image/post/output-window.png" alt="output-window.png" width="757" height="325" /></p> <p>The most important part of the whole text from the Output Window is written in red, at the bottom:</p> <pre>ERROR: Command 'unzip' not found. Install 'unzip' for this script to work.</pre> <p>It turns out that I didn&rsquo;t have that &ldquo;unzip&rdquo; installed in my container. How to install? No idea. But after some investigation <a href="https://github.com/dotnet/dotnet-docker/blob/master/2.2/aspnet/stretch-slim/amd64/Dockerfile">I found a <em>dockerfile</em></a> that <strong>could</strong> help me as it seemed to match mine. Or at least had the same principle. The most important thing for me in that file was what seemed to install &ldquo;curl&rdquo;. So, I copied that part and pasted into my own <em>dockerfile</em>, just being careful to replace <em>unzip</em> with <em>curl</em>.</p> <p><img style="display: block; margin-left: auto; margin-right: auto;" src="/image/post/dockerfile.png" alt="dockerfile.png" width="523" height="164" /></p> <p>Once I&rsquo;ve done that, I repeated my debugging steps: run without debug and attach. At this time it works without any problem. For someone who isn&rsquo;t used to work with Docker I noticed that it takes a couple of seconds to attach when compared with a normal run. But when I detach and reattach it goes as fast as I am used to. And all breakpoints were hit.</p> <p>Maybe this is a small bug in the <em>dockerfile</em> generated by Visual Studio, which means I should learn how to create my own <em>dockerfile</em> manually until it&rsquo;s fixed. Or maybe I am missing something. Another thing I noticed: The attach doesn&rsquo;t work with Windows Containers and I would have to use F5 to debug it.</p> <p>I am still learning and there is a lot to understand there.</p> <p><em><strong>*Note:</strong> I am using Linux Containers because Windows Containers didn't even allow me to debug properly. My best guess is that VS and Docker still need to work on their relationship.</em></p> Sun, 25 Aug 2019 17:48:00 GMT http://davidsonsousa.net/blog/post/the-problem-of-debugging-a-docker-project-in-visual-studio Create complete reports using DataTables and ASP.NET MVC Core http://davidsonsousa.net/blog/post/create-complete-reports-using-datatables-and-aspnet-mvc-core <!DOCTYPE html> <html> <head> </head> <body> <h1>A bit of history</h1> <p>One of the most important things when we think of reporting is a table with plenty of features. Such as ordering, filtering, selecting and so on. Back in the good old days of webforms and <a href="https://en.wikipedia.org/wiki/Rapid_application_development">Rapid Application Development</a> we had a very good control called <strong>GridView</strong>. It was clunky and, thanks to its ViewState, the page was getting very heavy after some interactions. In case you are not familiar with what I said, I'm talking about times where a simple ordering would trigger a page refresh (<a href="https://www.c-sharpcorner.com/uploadfile/2f73dd/what-is-postback-in-Asp-Net/">PostBack</a>) and the state of the page controls was kept in a hidden field (the ViewState).</p> <p>Some time later we had the infamous <a href="https://en.wikipedia.org/wiki/ASP.NET_AJAX">ASP.NET AJAX</a>, which allowed us to use webform controls without page refresh. Unfortunately, all it did was to send the whole ViewState through Ajax. Meaning: We didn&rsquo;t see the PostBack anymore but it was still happening in the background. The Ajax way. However, the page was still heavy.</p> <figure style="text-align: center;"><img src="/image/post/gridview3.jpg" alt="Gridview" width="557" height="145" /> <figcaption>Source: <a href="https://www.youtube.com/watch?v=_Ms5_6e7Fu4">https://www.youtube.com/watch?v=_Ms5_6e7Fu4</a></figcaption> </figure> <p>&nbsp;</p> <p>With ASP.NET MVC we gained more control over the HTML output but we had to say goodbye to the Gridview control. Instead, we must use HTML table which, in all fairness, does the job. However, in more advanced scenarios, we would have to go for external libraries. And I am going to show you how to use my favorite one - <a href="https://datatables.net/">DataTables</a>.</p> <h1>DataTables</h1> <p>The DataTables is one of the many JavaScript libraries we can use to enrich the tables in our web projects. In its basic implementation it allows the user to view, filter and order the data with ease. And better yet, without so much extra work for us. And if you are working with more advanced scenarios, you can customize it without problems.</p> <p><img style="display: block; margin-left: auto; margin-right: auto;" src="/image/post/datatables-example.png" alt="datatables-example.png" /></p> <p>Let&rsquo;s see below how to implement it in a simple ASP.NET MVC Core website. You can get <a href="https://github.com/davidsonsousa/DataTables-With-AspNetCore">the demo on GitHub</a>.</p> <h1>Implementation</h1> <p>The normal implementation is relatively simple. All you need is a data source and a View. However, my implementation has some extra things to consider since I am going for a more flexible scenario. The whole idea is to have the backend do most of the data work and leave the library with the formatting. And for that we will use:</p> <ol> <li>Data source &ndash; No matter which. Memory, SQL Server, Oracle. Your choice;</li> <li>Models and ViewModels &ndash; We need some specific objects to make our job easier;</li> <li>Attributes &ndash; Important if we want to control the columns in the DataTable;</li> <li>Service, Helpers &ndash; Used to transform the raw data into something we can use;</li> <li>Reflection &ndash; Because we want the implementation to be as dynamic as possible;</li> <li>JavaScript configuration &ndash; Important as we will need to customize a bit the implementation;</li> <li>The API &ndash; We will load the data via Ajax, so we need a small API to work with;</li> <li>A View &ndash; Because we need to show the DataTable at some point</li> </ol> <h2>Data source</h2> <p>If you need to implement a data table it means you have a data source of some sort. In this demo we are going to use in-memory data but it could easily come from any kind of database. Here it is:</p> <p> <script src="https://gist.github.com/davidsonsousa/27f246991dc8cb26d9552f5b57bba36f.js"></script> </p> <p>As you can see the <em>PersonRepository</em> should return all people (read only) and return the total amount of people in the imaginary &ldquo;People table&rdquo;.</p> <h2>Models and ViewModels</h2> <p>Some of these objects should help with data binding, others to help with the data formatting. <a href="https://github.com/davidsonsousa/DataTables-With-AspNetCore/tree/master/ReportsUsingDataTables/ReportsWeb/Models/DataTable">You can find all of them here</a> but the most important are:</p> <p><strong>DataParameters</strong></p> <p>We will use it to help with the data binding coming from the UI. It contains all we need to filter and order our data.</p> <p> <script src="https://gist.github.com/davidsonsousa/9c5a702cb1afe288d03944874282d037.js"></script> </p> <p><strong>PersonTableViewModel</strong></p> <p>Used to shape the <em>Person</em> data coming from the data source into exactly what we need for the UI. It uses some custom attributes to help shaping the data and also some static methods to help with ordering and filtering.</p> <p> <script src="https://gist.github.com/davidsonsousa/99030880343e6616f549bac966a08c53.js"></script> </p> <p><strong>TableViewModel</strong></p> <p>This is the DataTable itself.</p> <p> <script src="https://gist.github.com/davidsonsousa/d2e3a66ace70f35f2de4daef5a4a5280.js"></script> </p> <h2>Attributes</h2> <p>Since I am generating the DataTable information on the backend I decided to create some custom attributes to help me with it. <a href="https://github.com/davidsonsousa/DataTables-With-AspNetCore/tree/master/ReportsUsingDataTables/ReportsWeb/Attributes">You can see them here</a> but, for short, they are:</p> <ul> <li>Orderable &ndash; In case the property has this attribute it means we can order our data;</li> <li>Searchable &ndash; The property containing this attribute will be used in the search field;</li> <li>ShowOnDataTable &ndash; It allows the property to be shown in the UI. You can also use it to set the order it will appear and a custom column name.</li> </ul> <h2>Service and Helpers</h2> <p>The Service is just a small mock of a Service Layer but it could be anything depending on the architecture you are following in your project. The most important is to create a specific method which return values formatted for the DataTable, as you can see below:</p> <p> <script src="https://gist.github.com/davidsonsousa/aec0b7db495046be91ef7837c0dedfc1.js"></script> </p> <p>Notice that:</p> <ul> <li>The method accepts an argument of type <em>DataParameters</em>, which contains the values coming from the UI control;</li> <li>The static methods of <em>PersonTableViewModel</em> are being used to filter and order the data;</li> <li>The return type is a tuple.</li> </ul> <p>As for the Helpers I have 2 classes. The first one is the <em><a href="https://github.com/davidsonsousa/DataTables-With-AspNetCore/blob/master/ReportsUsingDataTables/ReportsWeb/Helpers/ExpressionBuilder.cs">ExpressionBuilder</a></em> (bad name, I know), which will help us to build the expression queries for filtering. I am using because since the query is handling the data in-memory. Another scenario where the <em>ExpressionBuilder</em> would be useful is when we are using Entity Framework as we would dynamically build the query before sending to the database.</p> <p>The other helper is the <em>DataTableHelper</em>. It will prepare both header and content for the UI based on the custom attributes we have in each property of PersonTableViewModel.</p> <p> <script src="https://gist.github.com/davidsonsousa/ce11a48dd2abcf09e4f07b6a4b3261f2.js"></script> </p> <h2>Reflection</h2> <p>As you could see I am using a little bit of reflection to get the properties and custom attributes. In this way we would be able to add and remove columns by simply editing the <em>PersonTableViewModel</em> without breaking the UI.</p> <h2>JavaScript configuration</h2> <p>As of now, there is no web without JavaScript. And since DataTables is a JavaScript library we need to do a small configuration. Here we will enable a couple of things:</p> <p> <script src="https://gist.github.com/davidsonsousa/67def4654e11335cd2a4257bfdd00650.js"></script> </p> <ul> <li>processing &ndash; Enables the process indicator;</li> <li>serverSide &ndash; Enables server-side processing of data;</li> <li>ajax &ndash; Loads the data from an Ajax source. In our case a dedicated method in the HomeController.</li> </ul> <h2>The API</h2> <p>There are 2 things we need to make it happen in order to make the DataTable look good. The first is to setup the table headers. We will achieve that by returning a List&lt;string&gt; values when we call the page. That is done by using the <em>BuildDataTableHeader</em> method we made in the <em>DataTableHelper</em>, as seen below:</p> <p> <script src="https://gist.github.com/davidsonsousa/3980834a8b3c6968fa440a8244138b03.js"></script> </p> <p>The second is to return the content data. We will create a specific method for that and name it <em>GetPeopleData</em>:</p> <p> <script src="https://gist.github.com/davidsonsousa/2b04c83c791e9a27fa7ef8e4ff059721.js"></script> </p> <p>The idea here is to load the data and pass it into the <em>BuildDataTable</em> method in order to make it compatible with the DataTable library. The library, then, will get the data we are returning and format it into the HTML table.</p> <h2>A View</h2> <p>Our view should be very simple &ndash; a &lt;table&gt; tag, a CSS call and some JavaScript configuration. However, since we are aiming for some flexibility, let&rsquo;s tweak the View a little bit:</p> <p> <script src="https://gist.github.com/davidsonsousa/b50ef39eca1836e389de5bc67a5e9ab4.js"></script> </p> <p>From the top of the View:</p> <ul> <li>@model List&lt;string&gt; &ndash; Since we need to load the table headers in the beginning, we are passing it in the first request.</li> <li>The @foreach loop &ndash; Not the best place to do this but we need to prepare the header and footer tags in order to use it in the DataTable</li> <li>&lt;table&gt; &ndash; A the simple HTML table with some styles and the header/footer we just created</li> <li>@section Scripts &ndash; With the library and our JavaScript configuration</li> </ul> <p>Don&rsquo;t forget that the data coming via Ajax should match our columns perfectly, thanks to the DataTable script and the preparation we made in the backend.</p> <h2>Conclusion</h2> <p>And here we have, ladies and gentleman. A nice table with search and ordering:</p> <p><img style="display: block; margin-left: auto; margin-right: auto;" src="/image/post/conclusion.png" alt="conclusion.png" /></p> <p>The demo may seem overly complex for such a small thing but it scales quite well. I am using it both in my website and in a project at work with zero problems so far. Of course, some tweaks will be necessary when adapting to your project but it should be a no brainer. And once you grasp the concept it&rsquo;s very easy to replicate it.</p> <p>Once again, you can get the source code here:&nbsp;<a href="https://github.com/davidsonsousa/DataTables-With-AspNetCore">https://github.com/davidsonsousa/DataTables-With-AspNetCore</a></p> <p>Maybe I will create a NuGet out of it someday 😉</p> </body> </html> Tue, 16 Jul 2019 00:10:00 GMT http://davidsonsousa.net/blog/post/create-complete-reports-using-datatables-and-aspnet-mvc-core My first impressions of Razor Components (server-side Blazor) http://davidsonsousa.net/blog/post/my-first-impressions-of-razor-components <!DOCTYPE html> <html> <head> </head> <body> <p>First of all, let me say that <a title="Scott Hanselman's twitter" href="https://twitter.com/shanselman">Scott Hanselman</a> put together a great explanation of <a title="What is Blazor and what is Razor Components?" href="https://www.hanselman.com/blog/WhatIsBlazorAndWhatIsRazorComponents.aspx">What is Blazor and what is Razor Components</a>. You should check it out if you don't know what I am talking about since, here, I will only talk about my experiences so far, without getting into definitions.</p> <p>It was the end of last year that I started to hear about the growing support for <strong>Blazor</strong>, which is an experimental framework which compiles C# and HTML into <a href="https://webassembly.org/">Web Assembly</a> (Wasm). But it was at the same period that I also heard about the Server Side Blazor &ndash; which was later renamed to <strong>Razor Components</strong>.</p> <p>At the time I am writing this article <a title="Blazor 0.9.0 experimental release now available" href="https://devblogs.microsoft.com/aspnet/blazor-0-9-0-experimental-release-now-available/">Blazor is still experimental (version 0.9.0)</a> and apps made with it should not be used in production. Razor Components, on the other hand, should be released this year with the new .NET Core. And since both works almost in the same way I decided to give Razor Components a try.</p> <h2>Tooling</h2> <p>As of now I am using:</p> <ul> <li>SDK: .NET Core 3.0.100 Preview 3 (010431)</li> <li>Runtimes: .NET Core 3.0.0 Preview 3 (27503-5) / ASP.NET Core 3.0.0 Preview 3 (19153-02)</li> <li>IDE: Visual Studio 2019 RC.2</li> </ul> <p>The SDK and runtimes can be downloaded <a title="Download .NET Core 3.0" href="https://dotnet.microsoft.com/download/dotnet-core/3.0">here</a>, while Visual Studio 2019 RC can be downloaded <a title="Visual Studio 2019 RC" href="https://visualstudio.microsoft.com/downloads/#2019rc">here</a>.</p> <p>The very first thing I needed to do after installing VS 2019 was to enable it to use the preview libraries. I did that by going to Options -&gt; Projects and Solutions -&gt; .NET Core and enabling <em>Use previews of .NET Core SDK</em>. Only then I was able to create my first Razor Component app.</p> <p><img src="/image/post/vs-preview-options.png" alt="Enabling .NET Core preview versions on Visual Studio 2019" width="605" height="162" /></p> <p>With the app created there are a couple of things to be observed:</p> <ul> <li>The file structure, which contains only <strong>Components</strong>, <strong>Pages</strong> and their respective subfolders;</li> <li>The <strong>.razor</strong> files, which somehow reminds me of the old ASP 3 (or PHP) files. But I will talk more about them later;</li> <li>The Startup.cs, Program.cs and appsettings.cs files, which are the same as seen in the regular ASP.NET Core website</li> </ul> <p><img src="/image/post/vs-solution-explorer-razor-components.png" alt="vs-solution-explorer-razor-components.png" /></p> <h2>The project</h2> <p>As afore mentioned, the file structure is simple &ndash; containing only <strong>Components</strong>, <strong>Pages</strong> and their respective subfolders. The Pages folder is going to look familiar to an ASP.NET Developer as it contains _ViewImports.cshtml and Index.cshtml &ndash; both seen in previous versions of MVC. The catch here is with Index.cshtml. We must remember that Razor Components works like a SPA, which means that our Index.cshtml will contain the whole web app.</p> <p><img src="/image/post/razor-components-index-file-smaller.png" alt="razor-components-index-file-smaller.png" /></p> <p>The Components folder contains multiple _ViewImports.cshtml files in their respective folders, but also multiple .razor files. These files are the &ldquo;pages&rdquo; of our application. They may contain both markups (HTML and Razor) and C# code.</p> <p><img src="/image/post/razor-components-counter-file.png" alt="razor-components-counter-file.png" /></p> <h2>Compilation</h2> <p>One thing I&rsquo;ve noticed when I was creating my small prototype is how the files are compiled into a C# class with <strong>.g.cs</strong> extension and placed on <strong>/Razor</strong> and <strong>/RazorDeclaration</strong> folders, both on <strong>/obj/Debug/netcoreapp3.0</strong>. While I&rsquo;ve seen such extension before (don&rsquo;t remember where) it helps us to see how the files Razor files are converted into C# classes and how the tags are setup.</p> <p>My theory is that the files on /RazorDeclaration folder are there to make sure they exist since the only method they have is an override of <strong>BuildRenderTree</strong>, which is empty. As for the files on /Razor folder you can see the same method (BuildRenderTree) building the entire html page with its elements and binders. Perhaps this is a technique used in a different type of .NET project and they decided to bring it to Razor Components. I don&rsquo;t know, I will need to do some research in order to understand what is really happening there.</p> <p>In addition, the content added into <em>@functions</em> is also in that class.</p> <p><img src="/image/post/razor-components-g-cs-file-side-by-side.png" alt="razor-components-g-cs-file-side-by-side.png" /></p> <h2>Sort of code-behind, if you want</h2> <p>If you don&rsquo;t want to mix C# syntax and Razor markup, you can create a separated C# file and inherit from the <strong>ComponentBase</strong> class. Then, in your .razor file, you should add a line to explicitly say that you are going to use that class as code-behind. The line is <em>@inherits YourCodeBehindClass</em>. My personal convention is to end the C# class with <em>Base</em>. That means: If my .razor file is <em>CreateEdit</em> my C# class will be called <em>CreateEditBase</em>.</p> <p><img src="/image/post/razor-components-code-behind-side-by-side.png" alt="razor-components-code-behind-side-by-side.png" /></p> <p>That helps to keep your code a bit more organized and create a real separation there, so you can bring other people to work on your markup.</p> <h2>Problems (so far)</h2> <p>I think the most annoying problem I encountered happened when I was trying to add a .razor file to create a list of calendars. I did the usual: Added a .razor file, named it and started to work on it. When I tried to compile it, I got an error claiming that my class didn&rsquo;t exist. I was only able to solve it by adding a .cshtml file, compiling the project and then renaming it to .razor.</p> <p>Another annoyance is the fact that you must rebuild the whole app if you want to make changes in the markup. That&rsquo;s understandable when you remember that all .razor and .cshtml files are transformed into .g.cs files during compilation. Maybe in the future they will allow .razor files trigger the building, as we do now with .cs files.</p> <h2>Conclusion</h2> <p>Any .NET Developer who worked at least a little with MVC would find easy to understand what is going on. After all, it&rsquo;s still ASP.NET. Sort of. Besides, Microsoft has a very nice documentation and, soon enough, some books might start to appear.</p> <p>I can picture some scenarios where Razor Components could be used, such as intranets or any kind of internal web apps which are used in small scale. Still, the possibilities are endless.</p> <p>But there is still a lot of work to be done in order to be production ready. Once done it goes prod, I am gonna use it. And probably advocate for that.</p> </body> </html> Sat, 23 Mar 2019 11:03:00 GMT http://davidsonsousa.net/blog/post/my-first-impressions-of-razor-components Fellow developer: The lack of empathy may be killing your career http://davidsonsousa.net/blog/post/fellow-developer-the-lack-of-empathy-may-be-killing-your-career <!DOCTYPE html> <html> <head> </head> <body> <p>We, developers, are often practicing the best technology of today while trying to learn the best technology of tomorrow. The problem is that not so many of us focus on the other part of our work. Mostly understanding the client needs and improving our soft skills.</p> <p>If a developer is not able to understand the client and have a decent overview about its business, he will be unable to create an appropriate solution. And that sadly means he will not be so different from a monkey with a keyboard.</p> <p style="text-align: center;"><img src="/image/post/mceu_69593323911572282005098.jpg" /></p> <p>The key for cultivating deep understanding is to create empathy and try to care about what is important for the client as we care about what is important for us but, unfortunately, the development culture is wrong.</p> <p>Part of the blame goes to the schools. &ldquo;Oh, this school has a great Computer Science program&rdquo; or &ldquo;Many people working in this amazing company come from that school&rdquo; are common things to hear when you are about to pick a college. The problem is that most of the schools have an excessive focus on technical subjects making some of the future professionals with almost zero people skills as they are leaving the more &ldquo;human&rdquo; topics aside.</p> <p>The other part of the blame I put on the people we look up to &ndash; Famous developers, our colleagues, seniors in our own companies and so on. When we start getting into software development for real we hear things like &ldquo;clients never knows what they want&rdquo; or, often, stories about developers who stayed overnight to deliver a project and are regarded as heroes.</p> <p>Bullshit.</p> <p>The real heroes in software development are those who actually try and succeed to understand what the client wants and are able to translate this into a well written code. Understand the client is not difficult, we just need to empathize with them. Just like we should empathize with everybody else.</p> <p>To put this into a context, imagine if you need to visit a doctor: You don&rsquo;t know what you have when you go to the doctor. You describe how you feel and the doctor will make the diagnosis based on what he hears and what he checks. Then he will prescribe some medicaments or send you to a specialist. We tend to trust doctors because we know that, even if they are pressed with time, they know what they are doing.</p> <p>I know there are bad doctors. There are also bad developers. Just stick with me.</p> <p>Can you imagine how you would feel if you go to the doctor with a broken arm and the only thing they do is to give you an antibiotic? That&rsquo;s more lack of interest of taking care of you than very poor diagnostic skills. In another words, he is a monkey with a stethoscope.</p> <p><img style="display: block; margin-left: auto; margin-right: auto;" src="/image/articles/e1c4e9963f99592965f1205490f9d2e7--evan-sharp-feel-better.jpg" alt="" /></p> <p>I guess you know what I mean: We are the doctors and the clients are the patients. The same empathy which connects the doctors to their patients, should connect developers with clients. Only then we will be able to understand what the client wants and actually do something useful about it.</p> <p>Oh, and by the way, if you don't understand the needs of your client you most likely don't understand your colleagues either.</p> </body> </html> Sun, 13 May 2018 19:32:00 GMT http://davidsonsousa.net/blog/post/fellow-developer-the-lack-of-empathy-may-be-killing-your-career We need to talk about communication issues in development teams http://davidsonsousa.net/blog/post/we-need-to-talk-about-communication-issues-in-development-teams <p>Communication is, by far, one of the most important characteristics of human beings. It all started when a monkey asked &ldquo;Ugh?&rdquo; and a second monkey answered &ldquo;Agh!&rdquo;. Everything changed in that moment. See, if you think about it, the very fact that you are reading this article is thanks to that very conversation.</p> <p>According to the dictionary (Google), <em>communication is the imparting or exchanging of information by speaking, writing, or using some other medium</em>. Which means that if I am writing this article I am communicating with you.</p> <p>And this is exactly what happens in software development, but mostly that&rsquo;s not enough.</p> <p>We have all the possible tools available to communicate (chat, commit messages, comments, team meetings, etc.) but, somehow, we fail to do so. Why? I don&rsquo;t know, but I have some theories.</p> <h2>Developers like to create stuff, not to talk about it</h2> <p>That means we don&rsquo;t have enough &ldquo;feature-conversation&rdquo; (talking about features in a project) within the team outside of formal meetings. The lack of &ldquo;technology-conversation&rdquo; (talking about new technology knowledge) is also an issue for the most part. Not to mention the lack of a normal conversation which, well, doesn&rsquo;t need to be explained.</p> <p>In a development team this might be one of the causes of delays in projects since, sometimes, a colleague might have the solution of a problem nobody expected to have because nobody ever heard him saying that he was trying some different technology. Not to mention the missed opportunities as someone might come to you to ask about that technology you tested at home and were proud enough to talk about it.</p> <p>You can address this by talking more about the things you are learning. If possible, check with your team leader the possibility to organize some formal knowledge sharing meeting. I am sure everybody is learning something interesting on their free time, even if it&rsquo;s a new cake recipe.</p> <h2>There is a lot of misinformation going on</h2> <p>A common problem is when a feature is misinterpreted and implemented in different ways by different people. In the long run, problems like this will cause the team to stop being a productive unit and become just a bunch of people working in the same room.</p> <p style="text-align: center;"><img src="/image/articles/funny-communication-quotes-500x321.png" alt="" /></p> <p>One of the causes is what I call &ldquo;selective sharing&rdquo;, which happens when only some people of the team are chosen to know something relevant to the project. That might not be on purpose but it&rsquo;s still an issue.</p> <p>A way to address this issue is to have everything clear from the very beginning: Clear features, clear communication path, clear responsibilities and so on. Also, a clear documentation helps quite a lot as it reduces the already classic &ldquo;But X told me that 2 weeks ago, I remember&rdquo;. In this way the volume of misinformation should decrease, reducing the chances of internal conflicts. Or, at least, they will be solved faster.</p> <h2>If someone is working remotely, everybody is working remotely</h2> <p>We always have that person who is working remotely either because decided to take a home office or because he/she is telecommuting. In this case a lot of information is missed due to lack of empathy.</p> <p>You need to understand that someone (or an entire team) is sitting on the other side of the network and also craving for information. And probably being more productive in one hour more than you are in one entire day.</p> <p><img style="margin-right: auto; margin-left: auto; display: block;" src="/image/articles/pyramid.jpg" alt="" /></p> <p>This can be addressed with a couple of measures:</p> <ul> <li>Have empathy &ndash; You might be the one taking home office and working &ldquo;alone&rdquo; some day.</li> <li>Make video calls whenever possible &ndash; This will always make the ones not sitting in the office an important part of the team.</li> <li>Stop the impromptu meetings in the office &ndash; Nobody needs them, not even you. Even if you will share the information later. Schedule a video-call.</li> </ul> <p>Of course I didn&rsquo;t cover everything as I could write a book about it. But I am sure you have a lot to work in your ability to communicate within your team, just like everybody else (me included). This kind of work is a never ending process but it should be done if we want to keep the teams in a healthy state.</p> Fri, 28 Jul 2017 12:15:00 GMT http://davidsonsousa.net/blog/post/we-need-to-talk-about-communication-issues-in-development-teams What is the difference between Reference Types and Value Types? http://davidsonsousa.net/blog/post/what-is-the-difference-between-reference-types-and-value-types <!DOCTYPE html> <html> <head> </head> <body> <p>Before we talk about the differences between <strong>Reference Type</strong> and <strong>Value Type</strong> we need to understand some basic things.</p> <h2>What is a data type?</h2> <p>A data type is a format which can contain some specific type or range of values. Basically, whenever you are declaring your variables you must assign some specific data type, <a href="/en/post/what-are-and-how-to-use-variables-in-c">as described here</a>. On .NET Framework we have 2 data types: Reference Type and Value Type.</p> <h2>Stack Memory and Heap Memory</h2> <p>There are 2 different types of memory we will talk about: Stack Memory and Heap Memory. While the Stack Memory receives the values using FILO (First In, Last Out) the Heap Memory is much more like an unorganized set of boxes in a room. This means that the access to the Stack Memory will be much faster than the Heap Memory. And here is the catch: The Stack Memory is where the Value Type stays. And the Heap Memory is where the Reference Type stays.</p> <p>One thing to keep in mind: The Heap Memory is cleaned by the Garbage Collector, which means that Reference Types will be disposed automatically.</p> <h2>What is Reference Type?</h2> <p>Reference Type is the type of data which makes a reference to where the value is placed.</p> <p>A class is an example of reference type. If we copy a class into another class of the same type and change the values of the latter we will end up changing the values of the first one. This happens because the 2 classes are pointing to exactly the same place.</p> <h2>What is Value Type?</h2> <p>Value Type is the type of data which holds the actual value of the object.</p> <p>A struct is a good example of value type. If we follow the logic used above (copy a struct into another struct and change the values of the latter) we will realize that we didn&rsquo;t change the value of the first struct. This happens because we literally copied the values from one object to another.</p> <p>If you want to see it working make sure to go to&nbsp;<a href="https://github.com/davidsonsousa">my GitHub repository</a> and download the code: <a href="https://github.com/davidsonsousa/Back-To-Basics/tree/master/ValueAndReferenceType">https://github.com/davidsonsousa/Back-To-Basics/tree/master/ValueAndReferenceType</a></p> </body> </html> Sat, 12 Sep 2015 15:41:00 GMT http://davidsonsousa.net/blog/post/what-is-the-difference-between-reference-types-and-value-types What are and how to use variables in C# http://davidsonsousa.net/blog/post/what-are-and-how-to-use-variables-in-c <p>Every program you decide to write will use data at some point. I am not talking about databases nor web services. I am talking about plain simple variables.</p> <p>To put it simple: <strong>Variables are nothing more than a named place in the memory where you store something to use later</strong>. Think of a box with a name in it and which accepts only certain kind of objects. For example: A box named "balls" which accepts only spherical objects.</p> <p>In C# we have the following types:</p> <ul> <li><strong><a href="https://msdn.microsoft.com/en-us/library/exx3b86w.aspx">Integral</a>:</strong> sbyte, byte, short, ushort, int, uint, long, ulong, and char</li> <li><strong><a href="https://msdn.microsoft.com/en-us/library/9ahet949.aspx">Floating point</a>:</strong> float and double</li> <li><strong>Decimal:</strong> decimal</li> <li><strong>Boolean:</strong> true or false values, as assigned</li> <li><strong>Nullable:</strong> Nullable data types</li> </ul> <h2>Define your variables</h2> <p>You can define your variables in 2 ways:</p> <ol> <li>[type] [variable_name], [variable_name]; (eg.: <em>string</em> name, surname;)</li> <li>[type] [variable_name] = [variable_value]; (eg.: <em>string</em> name = "Joe";)</li> </ol> <p>The first one is used when you want to define one or many variables at once, without setting a value. The second alternative can be used when you want to initialize the variable already during its declaration.</p> <h2>Default values</h2> <p>As mentioned above, we can define our variables without initializing it (setting a value). In case we do it, however, we need to pay attention to the default values which each object has. See below:</p> <ul> <li>bool: false</li> <li>byte: 0</li> <li>char: '\0'</li> <li>decimal: 0.0<strong><em>M</em></strong></li> <li>double: 0.0<strong><em>D</em></strong></li> <li>float: 0.0<strong><em>F</em></strong></li> <li>int: 0</li> <li>long: 0<strong><em>L</em></strong></li> <li>sbyte: 0</li> <li>short: 0</li> <li>uint: 0</li> <li>ulong: 0</li> <li>ushort: 0</li> </ul> <div> <p>Notice the letters beside some of those default values. Normally the compiler will require you to specify what kind of value you are assigning to a type. And in order to tell it to the compiler that you want to assign a, for example, double instead of a float you need to add the <strong><em>D</em></strong> in the end of the number.</p> <p>Sources: <a href="https://msdn.microsoft.com/en-us/library/s1ax56ch.aspx">MSDN</a>, <a href="http://www.tutorialspoint.com/csharp/csharp_variables.htm">Tutorials point</a></p> </div> Sun, 06 Sep 2015 19:01:53 GMT http://davidsonsousa.net/blog/post/what-are-and-how-to-use-variables-in-c Could not load file or assembly ‘Antlr3.Runtime’ or one of its dependencies. The parameter is incorr http://davidsonsousa.net/blog/post/could-not-load-file-or-assembly-antlr3runtime-or-one-of-its-dependencies-the-parameter-is-incorrect- <p>I just had a weird issue with my project: I&rsquo;ve hit Ctrl+F5 to run and the browser opens. So far, everything ok. When I was going to attach the process I got a BSOD.</p> <p><img style="display: block; margin-left: auto; margin-right: auto;" src="/image/articles/humoristic_windows_8_bsod_by_ivofajardo-d56i3qu.png" alt="" /></p> <p>As if that wasn&rsquo;t weird enough I got the error below after restarting everything and running my project again:</p> <p><strong><em>Could not load file or assembly &lsquo;Antlr3.Runtime&rsquo; or one of its dependencies. The parameter is incorrect. (Exception from HRESULT: 0x80070057 (E_INVALIDARG)) Antlr3.Runtime</em></strong></p> <p>Luckily someone had this issue before (thanks <a href="http://www.cloud-developer.eu/blog/2013/06/26/could-not-load-file-or-assembly-antlr3-runtime-or-one-of-its-dependencies-the-parameter-is-incorrect-exception-from-hresult-0x80070057-e_invalidarg/">Cloud Developer</a>!) and I was able to solve it easily. What is the solution? <strong>Just empty your %TEMP% folder</strong>. Here is how:</p> <ol> <li>Click the Start button and then Run (or press Win+R)</li> <li>Type: %TEMP% in the box</li> <li>Click the OK button (The directory for temporary files opens)</li> <li>Select all files (press CTRL+A)</li> <li>Press the DELETE key on your keyboard</li> </ol> <p>You don&rsquo;t need to delete all files, but just the right ones. In case it doesn&rsquo;t work and you need to delete all files it&rsquo;s recommended to close all programs (even those on the system tray &ndash; beside the clock) and repeat the steps above.</p> Thu, 27 Aug 2015 13:45:00 GMT http://davidsonsousa.net/blog/post/could-not-load-file-or-assembly-antlr3runtime-or-one-of-its-dependencies-the-parameter-is-incorrect- An open letter to all recruiters http://davidsonsousa.net/blog/post/an-open-letter-to-all-recruiters <p>Dear recruiters,</p> <p>Sometimes you call. In this call you offer the supposed perfect job opportunity to work in the outstanding perfect company: The company has amazing benefits, the salary is great and the environment is outstanding.</p> <p>Sometimes you are serious and focus only about the position. Sometimes you are friendly and love to talk about your dog. And, of course, sometimes we can notice that you don&rsquo;t want to talk. That&rsquo;s ok, everybody has the right to be different. And we all have bad days. Personally, I prefer the friendly ones. Only because they make me believe that I am the most special person in the world. And when you call me in my bad day to make me feel special, you totally won. But the serious ones are good too.</p> <p>There is only one thing: Apparently you have some issues on matching my profile with the job offers you are presenting to me.</p> <p>Allow me to explain.</p> <p>Most of the offers I get from you are &ldquo;C# Developer&rdquo;. And yes, I know C#. But the problem lies in the field and also the projects. Mostly this kind of position would lead me to work in a company where I will go very deep into C# and never see anything else. For example, some company where I should work on a system to control, let&rsquo;s say, traffic lights. Would I work there? Maybe. But it's not a good fit.</p> <p>See, I am a web person specialized on the <a href="http://www.slideshare.net/imperugo/aspnet-web-stack">ASP.NET stack</a>. In my line of work I need to understand a bit of front-end so I can make a good quality back-end, matching them together in a nice result for the client. This is what I have been doing most of my career.&nbsp;If you doubt just check <a title="Davidson Sousa - Linked In" href="http://linkd.in/DavisSousaIN">my Linked In profile</a>. Go to my specialties and certifications so you will see that they are mostly focused on web.</p> <p>But it's alright, I still like you.</p> <p style="text-align: center;"><img src="/image/articles/keep_calm_and_hug_a_recruiter_business_card.jpg" alt="" /></p> <p>I believe it&rsquo;s not your fault. You might have goals to reach and you might not have enough time to check a a lot of profiles thoroughly. All of this is understandable. And it&rsquo;s ok for me as I can say that I am not interested in case you offer something which is not a good fit.</p> <p>But I care about you. I care about the time you are devoting with me and other candidates which are not a good fit for the positions you are presenting. We know that every candidate you interview who is not a fit makes you lose money (time = money). And your company is losing money as well.</p> <p>So, here is the advice: Try to understand the position you are going to offer and also try to learn a little bit more about the candidates before the call. And don't shoot e-mails crazily about random job offers only because there is one key word matching.&nbsp;It's not about keywords anymore - it's about meaning. Of course,&nbsp;sometimes I would be motivated to change everything. It can even happen that, some day, I will really be interested to work programming for&nbsp;<a href="http://www.nasa.gov/">NASA</a> and see my code going to other galaxies.</p> <p>But not yet.</p> <p>In my perticular case, I am focused on web. After all, I am a web person. And since I am a web person you can talk with me about&nbsp;websites developed and I will gladly listen to any offer you will present&nbsp;related with the&nbsp;<a href="http://www.slideshare.net/imperugo/aspnet-web-stack">ASP.NET stack</a>.</p> <p>Sincerely,</p> <p>Davidson Sousa</p> Sat, 08 Aug 2015 11:46:00 GMT http://davidsonsousa.net/blog/post/an-open-letter-to-all-recruiters WordPress - Escolha fácil, mas nem sempre o melhor caminho http://davidsonsousa.net/blog/post/wordpress-escolha-facil-mas-nem-sempre-o-melhor-caminho <p><img style="float: right;" src="/image/articles/wordpress-logo-simplified-rgb.png" alt="" /></p> <p>A algum tempo atrás precisamos usar <a href="https://wordpress.org/">WordPress</a> para fazer o site de um cliente. Deu tudo certo e entregamos sem maiores problemas. Mas poderia ter sido muito pior e vou tentar ilustrar os motivos neste artigo. E vou fazer isso mostrando as coisas boas também, obviamente.</p> <h2>A plataforma</h2> <p>WordPress é uma plataforma de blogs feita em PHP <a href="http://en.wikipedia.org/wiki/WordPress">criada em 2003</a> (isso mesmo, 11 anos atrás). Usado mundialmente, muitos blogueiros famosos – pra não dizer a maioria deles – usa WordPress como plataforma preferida. Existem, claro, alguns motivos pra isso: Facilidade de personalização, variedade de themes e plug-ins, sem falar do baixo custo e o fato de estar no mercado por muito tempo.</p> <h2>Personalização</h2> <p>Uma de suas grandes qualidades é o nível de personalização oferecido. Qualquer pessoa com algum tempo de imersão pode criar um theme para WordPress, desde que tenha algum conhecimento sobre HTML, CSS e PHP.</p> <h2>Variedade de themes e plug-ins</h2> <p>Existem diversos <a href="https://wordpress.org/themes/">themes</a> e <a href="https://wordpress.org/plugins/">plug-ins</a> para WordPress pela internet – grátis ou pagos. Muitos desses themes alteram completamente o layout do blog, fazendo com que ele se pareça até com um grande site de notícias. Muitos desses themes, inclusive, tem plug-ins específicos para eles, agregando valor aos themes. Aliás, os plug-ins são um show à parte.</p> <h2>Baixo custo</h2> <p>Existe um motivo pra isso: <a href="https://wordpress.org/hosting/">Diversas empresas tem planos baratos</a> pra sites criados em PHP pois o combo PHP / MySQL é instalado em um servidor Linux, que não exige pagamento de licença. Aliás, nem mesmo o MySQL precisa de licença pra ser instalado. É importante também mencionar que o custo das ferramentas de desenvolvimentos são baixos justamente por muita coisa ser barata ou de graça no mundo Linux.</p> <p>Como você pôde ver WordPress é uma plataforma relativamente boa e barata. Mas, como toda plataforma, ela sofre problemas relacionados a ideia que as pessoas tem do seu uso.</p> <h2>Os problemas</h2> <p>É muito comum ver empresas optando por usar WordPress achando que isso vai acelerar o desenvolvimento de seus projetos. Isso pode ser verdade inicialmente, dada a base de conhecimento que se tem no mercado hoje. O problema está no custo de manutenção.</p> <p>Explico.</p> <p>Quando o projeto é feito do zero a empresa tem controle total sobre o código-fonte, o que significa que a base de conhecimento do software é alta. Isso faz com que o os desenvolvedores já saibam onde está o problema e como resolver assim que recebem o ticket do suporte. Quando se usa componentes de terceiros (plug-ins, por exemplo) o desenvolvedor está assumindo um risco: Se o plugin parar de funcionar, ele precisa dar um jeito de consertar. O cliente não quer saber se o plugin não é atualizado desde 2005. Ele quer o projeto funcionando.</p> <p>Outra coisa que encarece a manutenção é o fato de os desenvolvedores optarem por WordPress sem ter um conhecimento aprofundado da plataforma. Logo, mesmo sem usar componentes de terceiros ele pode ter problemas com coisas simples como Custom Types e WP_Query, entre outros. Isso sem dúvida pode afetar a performance do site, fazendo com que o cliente perca dinheiro no fim do dia.</p> <p>E cliente nenhum quer perder dinheiro.</p> <p>Na melhor das hipóteses o cliente nunca vai pedir alterações e o site feito em WordPress só vai ficar devagar, se comparado com um site feito usando ASP.NET. Digo isso pois como WordPress é feito em PHP, que é uma linguagem interpretada, o servidor precisa “ler” o PHP a cada execução. No caso de um site feito em ASP.NET, que é compilado, só a primeira execução do primeiro usuário vai demorar. As outras serão mais rápidas.</p> <p>Na minha humilde opinião o arquiteto responsável pelo projeto deveria escolher a solução que se encaixe melhor com a necessidade do cliente, salvo quando o cliente exige alguma solução específica. No meu caso, sempre procuro explicar ao cliente os prós e contras de determinada solução, caso a mesma seja imposta por ele. As vezes funciona, as vezes não. Eu acredito que existem soluções melhores e mais seguras do que WordPress até para blogs. Mas eu não hesitaria em recomendá-lo se ele encaixasse direitinho no escopo do cliente.</p> Thu, 23 Apr 2015 07:39:48 GMT http://davidsonsousa.net/blog/post/wordpress-escolha-facil-mas-nem-sempre-o-melhor-caminho The best way to use DropDownListFor with ASP.NET MVC http://davidsonsousa.net/blog/post/the-best-way-to-use-dropdownlistfor-with-aspnet-mvc <p>One of the most annoying things on ASP.NET MVC is to create a decent dropdown list, and <a href="http://odetocode.com/">Scott Allen</a> already covered it <a href="http://odetocode.com/blogs/scott/archive/2013/03/11/dropdownlistfor-with-asp-net-mvc.aspx">here</a> nicely. While I like his explanation I often see people facing different scenarios. What I will describe here is the way I use to create the dropdown lists for all my projects.</p> <h2>The problems</h2> <ol> <li>Create a common place dropdowns will be placed, so we can maintain it easily;</li> <li>Get the data from somewhere;</li> <li>Put the minimum necessary logic into the Controller;</li> <li>Show it in the View.</li> </ol> <h2>The solution</h2> <p>First of all, we need a class. I will use a Model, as example, since this data can also come from the database.</p> <p> <script src="https://gist.github.com/davidsonsousa/bd928c1b9c5e35d05a57.js"></script> </p> <p>This class has only 2 properties since it’s all you need to use with a <a href="https://msdn.microsoft.com/en-us/library/ee703573.aspx">DropDownListFor</a>. But keep in mind that your class can have other properties.</p> <p>Now, we need the code to generate the items for the DropDownListFor.</p> <p> <script src="https://gist.github.com/davidsonsousa/7790a4220cf3b8c82541.js"></script> </p> <p>I have this code in a helper specially build for dropdown lists. In this way, as mentioned before, I can ease the maintenance of the project. And if you didn't notice, this code is concatenating with the DefaultItem property, which I show below.</p> <p> <script src="https://gist.github.com/davidsonsousa/0dc19966000fb68fa14e.js"></script> </p> <p>This property will add the standard "-SELECT-" item at the first position in our dropdown list.</p> <p>Also, you will see once you download the code that I am hard coding the items in the DropDownListHelper's constructor. In the real world I would load the data directly in the property.</p> <p>Now that we have the class (Model) and the helper, we will go for the ViewModel. This is a pretty standard situation: I personally like to keep my Model exclusively for database while my ViewModel is the one going to create the forms. The reason is that I can customize the ViewModel for my needs, not needing to have a Model with a lot of properties using <a href="https://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.schema.notmappedattribute.aspx">[NotMapped]</a> on the top.</p> <p> <script src="https://gist.github.com/davidsonsousa/67721b505f7070db0c14.js"></script> </p> <p>Here is what we need in the ActionMethod.</p> <p> <script src="https://gist.github.com/davidsonsousa/f66f8cd8d9845c3daf7b.js"></script> </p> <p>And here is the View.</p> <p> <script src="https://gist.github.com/davidsonsousa/d99206e52421e6c234e9.js"></script> </p> <p>Some might say it’s an unnecessary effort, and I would agree if we would use only one dropdown list. However, when we start building bigger systems which are going to use multiple dropdown lists, this approach comes in handy.</p> <p>You can check the full code in my GitHub repository: <a href="https://github.com/davidsonsousa/DropDownList">https://github.com/davidsonsousa/DropDownList</a></p> Wed, 22 Apr 2015 01:00:00 GMT http://davidsonsousa.net/blog/post/the-best-way-to-use-dropdownlistfor-with-aspnet-mvc Create a video gallery with modal using ASP.NET and Bootstrap http://davidsonsousa.net/blog/post/create-a-video-gallery-with-modal-using-aspnet-and-bootstrap <p><img style="display: block; margin-left: auto; margin-right: auto;" src="/image/articles/youtube_logo_standard_white.jpg" alt="" /></p> <p>We are in the 3<sup>rd</sup> article of the series about Youtube API. The articles are:</p> <ol> <li><a href="/en/post/how-to-use-the-youtube-api-to-load-a-single-video">Load a single predefined video</a></li> <li><a href="/en/post/load-a-custom-video-with-the-youtube-api-using-aspnet">Load a custom video with the Youtube API in ASP.NET</a></li> <li>Create a video gallery with modal using ASP.NET and Bootstrap (this article)</li> </ol> <p>We saw in the previous how to load a custom video from the backend using ASP.NET. For this one we will use the same approach to create our gallery, plus <a href="http://getbootstrap.com">Bootstrap</a> for the modal.</p> <h2>The player</h2> <p>We will need to put the player we saw on the first article in the <a href="http://getbootstrap.com/javascript/#modals">Bootstrap modal</a>, as it’s shown below.</p> <p> <script src="https://gist.github.com/davidsonsousa/499c63e4e1f697010570.js"></script> </p> <h2>The Javascript</h2> <p>There are 2 scripts to be used. The first one is the <a href="https://gist.github.com/davidsonsousa/3387dfdcccc8128cd0db#file-general_youtube_api_call-js">general script</a>, which I've shown in the previous articles and it didn't change. The second one is the script below, which will handle the video gallery.</p> <p> <script src="https://gist.github.com/davidsonsousa/408f2671445b5ef93ecd.js"></script> </p> <h2>The View</h2> <p>As you saw in the javascript above we are using only one modal. The magic happens in the code below, where I am passing all parameters via <strong>data-* attribute</strong>. I am using the same Model from the <a href="/en/post/load-a-custom-video-with-the-youtube-api-using-aspnet">previous article</a>.</p> <p> <script src="https://gist.github.com/davidsonsousa/b1c3d1ccd17de326209e.js"></script> </p> <p>As you can see there is no mystery on working with Youtube API and ASP.NET. And the next article will show how you can detect the state of the videos, which is very important for tagging and user interaction.</p> <p><span class="download-link">Check the full code here: <a href="https://github.com/davidsonsousa/YoutubeAPI">https://github.com/davidsonsousa/YoutubeAPI</a></span></p> Sun, 19 Apr 2015 11:39:47 GMT http://davidsonsousa.net/blog/post/create-a-video-gallery-with-modal-using-aspnet-and-bootstrap Load a custom video with the Youtube API using ASP.NET http://davidsonsousa.net/blog/post/load-a-custom-video-with-the-youtube-api-using-aspnet <p><img style="display: block; margin-left: auto; margin-right: auto;" src="/image/articles/youtube_logo_standard_white.jpg" alt="" /></p> <p>Let’s continue with this very simple series of articles about the <a href="https://developers.google.com/youtube/">Youtube API</a>. The articles are:</p> <ol> <li><a href="/en/post/how-to-use-the-youtube-api-to-load-a-single-video">Load a single predefined video</a></li> <li>Load a custom video with the Youtube API in ASP.NET (this article)</li> <li><a href="/en/post/create-a-video-gallery-with-modal-using-aspnet-and-bootstrap">Create a video gallery with modal using ASP.NET and Bootstrap</a></li> </ol> <p>On the <a href="/en/post/how-to-use-the-youtube-api-to-load-a-single-video">previous article</a>, we saw how to load a predefined video using the API. It was simple and clean, while we could load only that specific video. In the real world that would be a bit different since we would have to load the video from diferent sources, by using the backend. In this article we will see how we load the from the backend using ASP.NET</p> <h2>The player</h2> <p>We will use a <strong><em>div</em></strong> tag as player, which should be handled by the javascript later.</p> <pre style="background: white; color: black; font-family: Consolas;"><span style="color: blue;"><</span><span style="color: maroon;">div</span> <span style="color: red;">id</span><span style="color: blue;">=</span><span style="color: blue;">"player"</span><span style="color: blue;">><<span style="color: maroon;">div</span><span style="color: blue;">></span></span></pre> <h2>The Javascript</h2> <p>We will split this script in 2 parts: The general script, which makes the API calls and the Video script, which actually calls the video.</p> <h3>General script</h3> <p>We use this one just once, as we did before.</p> <p> <script src="https://gist.github.com/davidsonsousa/3387dfdcccc8128cd0db.js"></script> </p> <h3>Video script</h3> <p>Here is the trick. Since I am using ASP.NET MVC here and I need to have some flexibility since we are using the back end to bring the video, I will need to put the script in a partial view. Also, I am passing the Video model, which should bring all the parameters needed for the video.</p> <p> <script src="https://gist.github.com/davidsonsousa/c52921b028669d558ca0.js"></script> </p> <h2>Video model</h2> <p>Here is the model I am using. Keep in mind that such model could bring the video data from a database, for example. Or some web service.</p> <p> <script src="https://gist.github.com/davidsonsousa/33f5df0e2f8c3edec85c.js"></script> </p> <p>That's it.</p> <p>Next article will be about a video gallery opening a video in a modal window. All of it using videos loaded from the backend in ASP.NET MVC and bootstrap.</p> <p><span class="download-link">Check the full code here: <a href="https://github.com/davidsonsousa/YoutubeAPI">https://github.com/davidsonsousa/YoutubeAPI</a></span></p> Sun, 29 Mar 2015 07:32:12 GMT http://davidsonsousa.net/blog/post/load-a-custom-video-with-the-youtube-api-using-aspnet Ser brasileiro é ser amado no exterior http://davidsonsousa.net/blog/post/ser-brasileiro-e-ser-amado-no-exterior <p>Ontem, dia internacional da mulher, foi um daqueles dias onde se sai pra andar no shopping e se vê um monte de gente (homens, em maioria) comprando flores para suas parceiras. Não que o cidadão tcheco seja romântico (e não é), mas o que vale é a intenção.</p> <p>E, bem, eu estava lá pra fazer a mesma coisa: Comprar flores.</p> <p>Estou estudando tcheco mas ainda não consigo falar muito bem. Digamos que meu diálogo funciona por 3 minutos antes de eu começar a falar coisa sem sentido ou parar de entender o interlocutor. Por causa disso eu sempre prefiro perguntar se a pessoa fala inglês logo de cara. Quando não, bem, bate o desespero e vamos que vamos em tcheco mesmo.</p> <p>Voltando às flores: Depois de andar um pouco no shopping e comprar algumas coisas pra mim, consegui achar uma floricultura. E, como disse acima, lotada de namorados/maridos desesperados. Cheguei na porta e fiquei observando as flores que lá estavam. Não queria algo muito sofisticado e nem as clássicas "rosas vermelhas". Talvez um vasinho com algumas flores que vão resistir por algumas semanas já estaria bom demais.</p> <p><img style="display: block; margin-left: auto; margin-right: auto;" src="/image/articles/carmen_miranda_by_leopradanoyuutsu-d6912i9-small.jpg" alt="" /></p> <p>Depois de uns 10 minutos esperando ser atendido, uma vendedora chega até mim:</p> <p>- Boa tarde! Em que posso ajudar? (em tcheco)<br />- Boa tarde. Você fala inglês? (em inglês)<br />- Sim, falo.<br />- Ótimo! Gostaria de saber um pouco sobre essas flores aqui...</p> <p>E ficamos conversando por um tempo sobre flores até que eu conseguisse escolher algo e ela perguntasse se eu queria embrulhar pra presente. Como as flores eram pra minha namorada, bem, claro que eu queria embrulhar pra presente. E, olha, ela realmente estava com vontade de embrulhar as flores: Corta papel daqui, mede um pedaço de pano ali, faz o laço agressivamente, se concentra pra medir mais papel, etc. Parecia aqueles chefes franceses extremamente concentrados em preparar a comida do presidente.</p> <p>Depois daquele show (sério) chegou a hora de pagar 229 coroas tchecas (por volta de 28 reais):</p> <p>- São duzentos e vinte oito coroas.<br />- Ok, cartão por favor.<br />- Aham.</p> <p>Quando eu olho pra maquininha e vejo que ela colocou 229 ao invés dos 228 que ela falou:<br />- Er... Então, acho que você errou um número aí.<br />- Oi?<br />- Sim, olha. Você falou 228 mas colocou 229.<br />- Ah, desculpa. Eu tenho problemas com números em inglês. São 229, olha aqui - me mostrando a lista de preços<br />- Tudo bem, sem problemas - digo - também tenho problemas com os números em tcheco. Principalmente com <em>dvanáct</em> (12) e <em>devatenáct</em> (19).<br />- Esses números são difíceis mesmo. De onde você é?</p> <p>Pausa.</p> <p>Normalmente, quando eu respondo essa pergunta, vejo o mesmo tipo de reação: Pessoas perguntando falando sobre samba, sobre o Ronaldinho, sobre o carnaval, etc. As vezes perguntam sobre as praias ou se eu falo espanhol. E sinceramente já esperava por isso. Mas:</p> <p>- Eu sou do Brasil.<br />- Brasil?! - abre os braços e começa a "cantar" e dançar <a href="https://www.youtube.com/watch?v=5DBA5tnAJDk">Aquarela do Brasil</a>.</p> <p><iframe style="display: block; margin-left: auto; margin-right: auto;" src="https://www.youtube.com/embed/5DBA5tnAJDk" width="420" height="315" frameborder="0" allowfullscreen="allowfullscreen"></iframe></p> <p>Eu fiquei sem saber o que fazer. Foi completamente inesperado. Todo mundo na loja olhando pra gente e ela não tava nem aí. E ela só parou depois que outra funcionária da loja começou a rir e implorou pra ela parar. Procurei sair logo da loja. Vai que ela tira um cavaquinho detrás do balcão e começa a tocar <a href="https://www.youtube.com/watch?v=Si5y0QGSjTY">Brasileirinho</a>?</p> <p>Conclusão: Ainda somos amados mas não sei se volto naquela loja.</p> Mon, 09 Mar 2015 03:54:35 GMT http://davidsonsousa.net/blog/post/ser-brasileiro-e-ser-amado-no-exterior How to use the Youtube API to load a single video http://davidsonsousa.net/blog/post/how-to-use-the-youtube-api-to-load-a-single-video <p><img style="display: block; margin-left: auto; margin-right: auto;" src="/image/articles/youtube_logo_standard_white.jpg" alt="" /></p> <p>The most common way to embed any video on <a href="http://www.youtube.com">Youtube</a> is: Click in Share, Embed, copy the code and place in the website. I guess everybody used this at least once but let’s be realistic: This is not the best approach when you are working with clients as you never know what the client is going to ask in the future. It might happen the client will not request anything extra. Or he might ask to record the time the user paused the video.</p> <p>My idea here is to make a very simple series of 4 articles which should cover the most basic usage of <a href="https://developers.google.com/youtube/">Youtube API</a>. And they are:</p> <ol> <li>Load a single predefined video (this article)</li> <li><a href="/en/post/load-a-custom-video-with-the-youtube-api-using-aspnet">Load a custom video with the Youtube API in ASP.NET</a></li> <li><a href="/en/post/create-a-video-gallery-with-modal-using-aspnet-and-bootstrap">Create a video gallery with modal using ASP.NET and Bootstrap</a></li> </ol> <p>For this series I am going to use the Youtube API for iframe embeds which forces the HTML5 player and it’s better for compatibility with mobile. You will find the code to download in the end of the article.</p> <h2>The player</h2> <p>When embedding a video we normally get a code like this:</p> <pre style="font-family: Consolas; font-size: 16; color: black; background: white;"><span style="color: blue;"><</span><span style="color: maroon;">iframe</span> <span style="color: red;">width</span><span style="color: blue;">=</span><span style="color: blue;">"560"</span> <span style="color: red;">height</span><span style="color: blue;">=</span><span style="color: blue;">"315"</span> <span style="color: red;">src</span><span style="color: blue;">=</span><span style="color: blue;">"https://www.youtube.com/embed/XdlmoLAbbiQ"</span> <span style="color: red;">frameborder</span><span style="color: blue;">=</span><span style="color: blue;">"0"</span> <span style="color: red;">allowfullscreen</span><span style="color: blue;">><<span style="color: maroon;">iframe</span><span style="color: blue;">></span> </span></pre> <p>However, since we are going to use the Youtube API, we will need a very simple code:</p> <pre style="font-family: Consolas; font-size: 16; color: black; background: white;"><span style="color: blue;"><</span><span style="color: maroon;">div</span> <span style="color: red;">id</span><span style="color: blue;">=</span><span style="color: blue;">"player"</span><span style="color: blue;">><<span style="color: maroon;">div</span><span style="color: blue;">></span> </span></pre> <h2>The Javascript</h2> <p>Here is where the magic happens. The javascript code will load the video we want and replace that div with the proper embed code. However, I will split this script in 2 parts.</p> <h3>General script</h3> <p>This script is used only to make the API calls. Note that we are using this approach since <a href="http://stackoverflow.com/questions/1834077/which-browsers-support-script-async-async">we still don’t have full support for async javascript calls straight from the script tag</a>, so this script should take care of this for us. We need to call it just once.</p> <p> <script src="https://gist.github.com/davidsonsousa/3387dfdcccc8128cd0db.js"></script> </p> <h3>Video Script</h3> <p>After setting the API call we need to load the video and the way we will do that is also through javascript. So far, in this example, all we will need is the video dimensions (height and width) and also the ID. We will set this up in the function <em>onYouTubeIframeAPIReady()</em>, which is executed once the API is ready to be used.</p> <p> <script src="https://gist.github.com/davidsonsousa/54b00503a75087cda9fb.js"></script> </p> <p>That’s it for now. In the <a href="/en/post/load-a-custom-video-with-the-youtube-api-using-aspnet">next article</a> I will show a very simple way to load a custom video. And for that I will use ASP.NET to simulate some database retrieval. But you can use your language/framework of choice.</p> <p><span class="download-link">Check the full code here: <a href="https://github.com/davidsonsousa/YoutubeAPI">https://github.com/davidsonsousa/YoutubeAPI</a></span></p> Sun, 01 Mar 2015 15:13:48 GMT http://davidsonsousa.net/blog/post/how-to-use-the-youtube-api-to-load-a-single-video How philosophy is related with business and why we should care about it http://davidsonsousa.net/blog/post/how-philosophy-is-related-with-business-and-why-we-should-care-about-it <p>Back in 2003, when I was starting my unfinished business degree, I had philosophy classes. Probably I was one of the few enjoying to listen to things we thought we would never use in our lives. Don’t get me wrong: Philosophy is a very cool topic. The main problem was the mentality we had at that time – We were all aspiring to become executives in some company right after the university. In addition, as far we thought, an executive doesn’t need philosophy.</p> <p>That was a horrible mistake, but I will get to that later.</p> <p>One day our professor turned to the class and asked a question which I will never forget. “Who do you think is able to make more damage – a bad teacher or a bad doctor?”. The whole class answered what seemed obvious: The doctor. The professor asked why and we all said that a doctor’s mistake could cost lives while a teacher’s mistake can just make a person not understand some subject.</p> <p><img style="display: block; margin-left: auto; margin-right: auto;" src="/image/articles/plato-socrates-aristotle.jpg" alt="" /></p> <p>The right answer is the bad teacher and it’s simple to understand why: While a bad doctor will make the mistake a couple of times before his license will be revoked, a bad teacher can stay in the school for decades teaching badly, damaging the education of hundreds of students. In the end, we would have many uneducated people wandering around the job market. And, in the best case scenario, the bad teacher will have his license revoked only after an entire year of work with, for example, 40 students.</p> <p>We were all surprised with the explanation and we understood at that moment how important a good education is.</p> <p>Now, I believe you might be confused about why I mentioned that an executive not needing philosophy is a horrible mistake. Let me explain.</p> <p>Philosophy is the study of problems related with existence, moral values, knowledge and the mind. The advantage of the philosophical thought is the way the problems are treated. Mostly the philosophical thought is overloaded of logic and rational thought, which differ itself from the religious thought. And what an executive must be in order to succeed?</p> <p>Logic and rational.</p> <p>Mostly, in the corporate world, the companies are targeting the “bad doctors” – those professionals who didn’t bring results. For example: Developers who were unable to deliver some project; Designers, who couldn’t finish some art in the way the client wanted; Testers who couldn’t identify some bug in the project. And so on. Firing any of them would be just the easy way to solve the problem but, since we should be logic and rational, there are some points that we should consider. After all, philosophy teaches us how to deal with any situation – personal or professional:</p> <ol> <li>Why were they hired if they lacked knowledge?</li> <li>How did they get the materials/documentation? And from who?</li> <li>Was the environment good for them to work?</li> <li>Does the department have high number of hires and dismissals?</li> </ol> <p>As you can see it’s no easy task to identify the problem. If I would be in this position I’d start to investigate the department itself. In that way I could:</p> <ol> <li>Be sure they really had the knowledge to join the company</li> <li>Check if the materials/documentation was giving full condition for a good work</li> <li>Know if the environment was motivating enough for success</li> <li>Check if the department has a low rate of hires/dismissals</li> </ol> <p>Why? Because it could be a case of “bad teacher”. Or bad management, if you prefer.</p> Sun, 08 Feb 2015 14:31:25 GMT http://davidsonsousa.net/blog/post/how-philosophy-is-related-with-business-and-why-we-should-care-about-it O que é, quanto custa e quais as vantagens do Microsoft Azure http://davidsonsousa.net/blog/post/o-que-e-quanto-custa-e-quais-as-vantagens-do-microsoft-azure <p>Muitas empresas hoje em dia precisam de soluções rápidas e com possibilidade de escalar rapidamente de acordo com o aumento de demanda. Para isso existem <a href="http://en.wikipedia.org/wiki/Category:Cloud_computing_providers">várias empresas com serviços de computação na nuvem</a>. Mas vamos falar aqui do serviço da Microsoft, o <strong><a href="http://azure.microsoft.com/">Microsoft Azure</a></strong>.</p> <p>Antes de qualquer coisa: Eu entendo que existe um estigma - <a title="Windows 98 crashes" href="https://www.youtube.com/watch?v=UNqWpz5kh6o">adquirido na década de 90</a> e as vezes <a title="Newly Introduced Surface Tablet Freezes Live On Stage Crashes the Opening Presentation" href="https://www.youtube.com/watch?v=Gl7XMixlK1E">ainda acontecendo</a> - de que tudo que a Microsoft faz é ruim. Só que convenhamos, o Azure é bom pra caramba! Sem falar nos valores que podem não ser baixos à primeira vista mas compensam quando olhamos a longo prazo.</p> <p>Vou fazer tentar contar de maneira bem básica e resumida o que é e quais as vantagens do Microsoft Azure.</p> <p style="text-align: center;"><img style="display: block; margin-left: auto; margin-right: auto;" src="/image/articles/microsoft-azure-management-portal.png" alt="" width="525" height="327" /><em>Eis o novo portal - ainda beta</em></p> <h2>O que é Microsoft Azure?</h2> <p>Microsoft Azure (antigamente conhecido como Windows Azure) é a solução da Microsoft para computação em nuvem (cloud computing) e engloba desde websites até active directory, passando por banco de dados SQL e <a href="http://en.wikipedia.org/wiki/Machine_learning">machine learning</a>.</p> <p>Além disso ele pode ser usado tanto como IaaS (Infrastructure-as-a-Service) quando como PaaS (Platform-as-a-Service), é flexível (qualquer linguagem de programação e qualquer sistema operacional) e escala facilmente.</p> <p><a title="What is Azure" href="http://azure.microsoft.com/en-us/overview/what-is-azure/">Clique aqui para saber com mais detalhes o que é Microsoft Azure</a>.</p> <h2>Quais são as vantagens do Microsoft Azure?</h2> <p>A principal vantagem é a possibilidade de escalar rapidamente o projeto de acordo com a demanda. Suponhamos que o cliente tenha um site com 1.000 acessos diários e, um dia, o site começa a ter uma demanda de 10.000 acessos por hora. Se o cliente estiver usando Microsoft Azure ele poderá escalar o servidor automaticamente para poder aguentar essa quantidade de acessos. Caso contrário ele vai ter que ligar para a empresa onde o website está hospedado e comprar um plano maior.</p> <p>Outra vantagem é poder contar com o conteúdo em múltiplos servidores, agilizando a entrega de conteúdo, já que o servidor de entrega vai ser escolhido de acordo com a localização do usuário. Isso faz com que o site esteja rápido tanto para mim, aqui em Praga, quanto para alguém que esteja na Nova Zelândia.</p> <h2>Que serviços o Microsoft Azure tem para oferecer?</h2> <p>São <a href="http://azure.microsoft.com/en-us/services/">mais de 30 serviços</a> que já deixaria qualquer empresa mais do que satisfeita. Como desenvolvedor os que eu mais usaria são: <a href="http://azure.microsoft.com/services/websites/">Azure Websites</a>, <a href="http://azure.microsoft.com/en-us/services/visual-studio-online/">Visual Studio Online</a> (source code control), <a href="http://azure.microsoft.com/en-us/services/virtual-machines/">Virtual Machines</a> (VM), <a href="http://azure.microsoft.com/en-us/services/sql-database/">SQL Database</a>, <a href="http://azure.microsoft.com/en-us/services/cdn">CDN</a>, <a href="http://azure.microsoft.com/en-us/services/backup/">Backup</a> e <a href="http://azure.microsoft.com/en-us/services/api-management/">API Management</a>. Mas pode acontecer de um dia eu precisar de algum outro serviço que não citei. Sei lá, <a href="http://azure.microsoft.com/en-us/services/stream-analytics/">Stream Analytics</a>.</p> <h2>Quanto custa assinar o Microsoft Azure?</h2> <p><a href="http://azure.microsoft.com/en-us/pricing/details/virtual-machines/">A Azure VM mais barata tá saindo por 13 USD</a> por mês enquanto o <a href="http://azure.microsoft.com/en-us/pricing/details/sql-database/">SQL Database mais barato sai por pouco menos de 5 USD ao mês</a>. Só que os valores vão mudar de acordo com sua demanda e região. Lembrando que cada serviço tem uma métrica diferente, o que motiva a usar a <a href="http://azure.microsoft.com/en-us/pricing/calculator/">Calculadora de Preços</a> que eles disponibilizam no site.</p> <p><img style="display: block; margin-left: auto; margin-right: auto;" src="/image/articles/azure-calculator.png" alt="" width="497" height="355" /></p> <h2>Assinar o Microsoft Azure compensa?</h2> <p>Na minha humilde opinião isso depende alguns fatores, como por exemplo:</p> <ol> <li><strong>Tamanho do seu projeto</strong> – Microsoft Azure vai, com certeza, aceitar qualquer tamanho de projeto. Só que se for um projeto pequeno faria mais sentido pegar o plano free. Mas para, por exemplo, poder customizar a URL você precisaria pegar o plano mais básico que sairia mais caro que uma hospedagem normal. Veja bem: Eu pago 5 USD por mês para hospedar meu blog na <a href="http://www.easyhost1.com/">EasyHost1</a>, o que está de bom tamanho pra mim já que tem banco de dados incluído. No caso do Azure Websites eu teria que pagar pelo banco de dados separado. Eu adoraria ir para o Azure mas no meu caso não compensa. Ainda.</li> <li><strong>Previsão de acessos diários e/ou transferência de dados</strong> – Em teoria eu não estou usando nem 2% do total mensal de transferência que contratei. Sem contar que meu blog não usa lá tanta memória e processamento. Mas se pensarmos em uma web app que precisa de bastante memória e processamento, além de transferência mensal, já seria negócio migrar pro Microsoft Azure. Quando falo transferência mensal me refiro a franquia de transferência de dados. Todos os planos têm uma e, caso exceder, você vai pagar o proporcional ao excedente. Já no caso de um servidor como o meu seria necessário contratar um plano maior sem nem saber se seria o suficiente.</li> <li><strong>Quantidade de web apps você pretende hospedar</strong> – Olha que coisa interessante. Existem 2 possíveis cenários aqui: 1) Você pega um servidor com um plano parrudo e cria várias pastas, cada uma contendo uma web app diferente, pra economizar dinheiro; 2) Você pega uma VM no Azure e pode hospedar quantos web apps quiser, cada um com sua App Pool. Se eu tivesse que hospedar várias web apps eu iria pegaria uma Azure VM.</li> </ol> <h2>O Microsoft Azure aceita outras tecnologias (não Microsoft)?</h2> <p><strong>Sim</strong>. Como exemplo temos várias distros de Linux como VM, além de Joomla e Wordpress para instalar nas instâncias de Websites e Git no Visual Studio Online.</p> <h2>Existem certificações pra Microsoft Azure?</h2> <p>Sim, <a title="Microsoft Azure Certifications" href="https://www.microsoft.com/learning/en-us/azure-certification.aspx">existem</a>. Eu, perticularmente, quero fazer a prova <a href="https://www.microsoft.com/learning/en-us/exam-70-532.aspx">70-532 (Developing Microsoft Azure Solutions)</a> até o final do ano.</p> <h2>Considerações finais</h2> <p>Eu gostaria de mencionar que estou focando mais em web apps pois esta é a <a href="/pt/page/sobre-mim">minha realidade</a>. Mas podemos imaginar qualquer tipo de cenário onde o Microsoft Azure se encaixaria perfeitamente. Como por exemplo uma startup que deseja ter um ambiente de desenvolvimento Microsoft (Active Directory, Visual Studio Online), uma empresa que deseja ganhar dinheiro hospedando sites (VMs, SQL Database, Backup), um programador independente que quer um ambiente de testes online (Websites, SQL Database), etc.</p> <h2>Recomendações</h2> <ul> <li>Caso você esteja interessado em Azure Websites, ver o post que <a title="Penny Pinching in the Cloud: When do Azure Websites make sense?" href="http://www.hanselman.com/blog/PennyPinchingInTheCloudWhenDoAzureWebsitesMakeSense.aspx">Scott Hanselman fez sobre o Azure Websites</a> no blog dele.</li> <li>Dê uma olhada na <a title="Azure Documentation Center" href="http://azure.microsoft.com/en-us/documentation/">documentação do Azure</a>.</li> <li><a href="http://www.microsoftvirtualacademy.com/product-training/microsoft-azure">Tem vários cursos de Azure</a> na <a href="http://www.microsoftvirtualacademy.com">Microsoft Virtual Academy</a>, mas tem <a title="Microsoft Azure Fundamentals" href="http://www.microsoftvirtualacademy.com/training-courses/microsoft-azure-fundamentals">um curso em especial</a> que explica bastante coisa.</li> <li>Você já baixou o <a href="http://www.visualstudio.com/en-us/news/vs2013-community-vs.aspx">Visual Studio 2013 Community Edition</a>? É de graça.</li> </ul> Mon, 12 Jan 2015 11:56:30 GMT http://davidsonsousa.net/blog/post/o-que-e-quanto-custa-e-quais-as-vantagens-do-microsoft-azure Setting folder permissions using Web Deploy http://davidsonsousa.net/blog/post/setting-folder-permissions-using-web-deploy <p>I was running into a very odd problem recently: I couldn't upload files to my website because of an error saying that I didn’t have permission to write files into the App_Data folder. I’ve decided to look into it and I realized that it began since I started using <a href="http://www.iis.net/downloads/microsoft/web-deploy">Web Deploy</a>.</p> <p>For those unfamiliar with Web Deploy I will tell you something: This is the best deployment tool for ASP.NET websites so far. It checks the files before you send to the server so it will send only those which had some change, publish entire databases and even pre-populate the tables.</p> <p><img style="display: block; margin-left: auto; margin-right: auto;" src="/image/articles/web-deploy.png" alt="" width="440" height="345" /></p> <p>The problem is that <strong>Web Deploy resets all folder permissions</strong>, which basically broke my file upload. And since ELMAH couldn't log the errors I spent some time thinking that my website was running flawlessly perfect. Silly me...</p> <p>The solution I found was to create a .targets file in order to set the permissions during the deployment time. Let’s see how to do it:</p> <ol> <li>Create a .wpp.targets file in the root of your web project. You may not find this file in your File -> New window. In that case just create a normal Text File, change the extension and add XML content in it, as you can see in the gist below:<br /> <script src="https://gist.github.com/davidsonsousa/721d4991118a20e9e115.js"></script> </li> <li>Set the permissions to the folders you want. In my case, the App_Data was just enough but you can add other folders as well (lines 15 to 29).</li> <li>Deploy through Web Deploy. A very simple explanation of this step: When you deploy the MSBuild will run, pass through the .targets file you’ve created and set the permissions to the folders you’ve defined.</li> </ol> <p>You might keep some things in mind:</p> <ul> <li>Visual Studio caches the .targets files, which means that you will have to restart Visual Studio every time you want to make changes and see the effects when you are building the deployment package.</li> <li>The package will not be rebuild unless you actually make changes in the .targets file.</li> <li>Remember to always use Clean Solution in case you want to rebuild the deployment package.</li> </ul> <p>For more information visit the <a href="http://sedodream.com/2011/11/08/settingfolderpermissionsonwebpublish.aspx">Sayed Ibrahim Hashimi</a>’s website.</p> Sun, 11 Jan 2015 08:45:40 GMT http://davidsonsousa.net/blog/post/setting-folder-permissions-using-web-deploy Unprofessional people and the oxymoron effect http://davidsonsousa.net/blog/post/unprofessional-people-and-the-oxymoron-effect <p>The first time I heard the word oxymoron was during a job interview in 2010. We were talking about my skills and how it was my previous job when he asked me if I had some difficulties here in Prague, while working. At that time I said that I didn’t notice anything so drastic but, yes, I had some problems. At that time thought it could be culture related since I am from Brazil. When I described which problems he said that I was facing a common oxymoron around here. I asked what is it and he gave me some examples. The last example was “Czech professional”.</p> <p><em>Disclaimer: I am not targeting any nationality, but as I live in Prague the percentage of local oxymoron is higher. For sure someone living in a different country will see this pattern in a different nationality.</em></p> <p>Oxymoron, if you don’t know, is when contradictory set of words appear in the same sentence. Like civil war, noisy silence, living dead, seriously funny and so on.</p> <p><img style="display: block; margin-left: auto; margin-right: auto;" src="/image/articles/professionalism-that-is-not-my-job-motivatinal1.jpg" alt="" /></p> <p>The problem I was facing was related with people who were thinking they own the office space and you would break the status quo. We all know people like this, no matter the place in the world they come from. I have 2 examples very vivid in my memory:</p> <ul> <li>A person who goes beyond his/her job description and gets activities from other people thinking it’s doing something good, but then blames others when things start to be problematic because of his/her own proactivity (“this was your job!”);</li> <li>A person who treats the office like his/her home and takes everything personally (“I’ll not do anything for him/her because he/she screamed at me last week”).</li> </ul> <p>Of course, there are situations where both examples are in the same person.</p> <p>When people behave as mentioned above the office starts to become a toxic place. And it’s easy to notice: The team leader (or manager) only needs to pay attention on where is the bottleneck. Sometimes, in some projects, a bottleneck is caused by performance of 1 or more team members. But in a toxic office the performance is not the issue, but the person itself.</p> <p>If you want to recognize this behavior you should pay attention to:</p> <ol> <li>Self-proclaimed office stars (“Nothing would work without me”);</li> <li>The one who makes himself/herself busy by getting tasks from other colleagues, and blame them when something goes wrong;</li> <li>A person who takes everything personal in the office;</li> <li>The classic apple polishers.</li> </ol> <p>How to deal with them?</p> <p>If you are not a team leader or manager I’d recommend you to report it. The leader should be responsible for this kind of conversation. But, still, it’s difficult even for the leader as it doesn’t depend only on him. The person should be willing to understand the issues and change. Not everybody has enough self-awareness and also not everybody would be willing to accept that he/she is part of the problem. But as we say back in my country, there is always an old shoe to a tired foot. Which means this person might be a perfect fit in another department or company.</p> Mon, 05 Jan 2015 05:18:51 GMT http://davidsonsousa.net/blog/post/unprofessional-people-and-the-oxymoron-effect Produção para o Digital com Davidson Sousa http://davidsonsousa.net/blog/post/producao-para-o-digital-com-davidson-sousa <p>Ano passado, mais especificamente em setembro, eu fui convidado para o programa <a href="https://www.youtube.com/user/socialplusbr?sub_confirmation=1">Social+ Entrevistas</a> que meu amigo <a href="https://www.facebook.com/juliomoraes">Julio Moraes</a> faz no Youtube toda semana. Conversamos por quase 1 hora sobre como o marketing e a tecnologia andam de mãos dadas, sobre como os processos entre o departamento de marketing e o departamento de tecnologia podem ser otimizados se houver diálogo entre ambos. E, claro, tivemos alguns momentos de descontração.</p> <p>Veja o video abaixo:</p> <p><iframe src="//www.youtube.com/embed/EBEM53pLs40" width="640" height="360" frameborder="0" allowfullscreen="allowfullscreen"></iframe></p> <p>Tirando a minha <a href="https://www.youtube.com/watch?v=Ld5-PR8SevU">fala estilo Ronaldo Fenômeno</a> por conta do sono eu considero a entrevista bastante produtiva e, de verdade, espero que ajude a jogar uma luz sobre a rotina de algumas agências. Afinal, o departamento de tecnologia não morde.</p> <p>A propósito: A terceira temporada do <a href="https://www.youtube.com/user/socialplusbr?sub_confirmation=1">Social+ Entrevistas</a> começa em fevereiro. Mas agora <a href="https://www.facebook.com/events/817966318261447/?ref_newsfeed_story_type=regular">dia 15 de janeiro tem um episódio especial (em inglês) com David Baker</a>, professor na <a href="http://www.theschooloflife.com/saopaulo/shop/classroom/love/intensivo-the-school-of-life.html">The School of Life</a>.</p> Fri, 02 Jan 2015 08:26:18 GMT http://davidsonsousa.net/blog/post/producao-para-o-digital-com-davidson-sousa Leave the office! See what you need to work anywhere you want http://davidsonsousa.net/blog/post/leave-the-office-see-what-you-need-to-work-anywhere-you-want <p>When I started my career as software developer all I could have was a big desktop computer. It was an Intel Celeron 300 MHz with 32 MB of RAM and a HDD of 4 GB. Such beauty would never let me to have the mobility I am able to have today, although I am still far from being as mobile as I want.</p> <p>But what do you need to become a “work anywhere professional”?</p> <p>The basic checklist is this:</p> <ul> <li>A nice place</li> <li>Good devices</li> <li>Internet connection</li> <li>Tools</li> <li>Concentration</li> </ul> <p>Now, let’s talk about each item.</p> <p><img style="display: block; margin-left: auto; margin-right: auto;" src="/image/articles/office-desk-laptop-forest-7329369.jpg" alt="" width="296" height="450" /></p> <h2>Place</h2> <p>The place must be nice, preferably with a table where it's possible to place all your devices (more on that later), and calm unless you have a good concentration level (more on that later). Most of people think of places like Starbucks or McDonalds but, actually, it would depend on the kind of work you do and how connected you must be. For a writer, who doesn’t need to be online all the time, work in the woods would be a nice thing. But for a software developer, who depends on internet connection, it would be a bit more complicated.</p> <h2>Good devices</h2> <p>The very basic is a notebook and a mobile phone with a good data plan. In my particular case I have a <a href="http://shop.lenovo.com/us/en/laptops/lenovo/z-series/z710/">17” Lenovo</a> as main computer and a <a href="http://www.asus.com/my/Notebooks_Ultrabooks/ASUS_Transformer_Book_T100TA/">10” ASUS Transformer</a> as side computer. If I am traveling or going to a place where I know I will need a computer, I take the ASUS. The keyboard is comfortable enough to write and the touchscreen replaces in a very nice way. In addition, I have Visual Studio Express here and it works fine for me.</p> <p>Another thing to keep in mind is battery time. My Lenovo can work up to 3h with Wi-Fi turned on while my ASUS works up to 10h in the same conditions. Given that I assume I will not find sockets anywhere I go a good battery time is very important. Not to mention that I can it also to recharge my phone, at least to keep alive for longer time (if necessary).</p> <h2>Internet connection</h2> <p>You have 3 possibilities here: Connect over Wi-Fi, use your mobile data plan and share the internet with your notebook or work offline.</p> <p>It’s clear that Wi-Fi is the best alternative here. However, you can’t expect to find free Wi-Fi with a good speed anywhere. And I am not even talking about how unsafe that would be. Connect over mobile and sharing the internet to your notebook is to be the best option if you have a good (big and fast) data plan, except if you are on roaming.</p> <h2>Tools</h2> <p>The idea here is to have everything to make the transition from your portable machine to your stationary machine as seamless as possible. Except, of course, for some software you can’t install on both due hardware limitations.</p> <p>Assuming that you have internet connection, you can make use of tools like a private VPN, online file services (<a href="https://onedrive.live.com/">OneDrive</a>, <a href="https://www.dropbox.com/">DropBox</a>, <a href="https://www.google.com/drive/">Google Drive</a>), online repository (<a href="http://www.visualstudio.com/">TFS Online</a>, <a href="https://github.com/">GitHub</a>) and others. As a developer, I consider all of them important, although I don’t have a private VPN. Yet.</p> <h2>Concentration</h2> <p>The best here is to be self-aware: If you know how much concentration you are able to have in the moment you decide to leave the office, you will pick the perfect place for you. For those who can work only in a silent environment a Starbucks would not be the best place.</p> <h2>Conclusion</h2> <p>My case is a very specific one. I love what I do but I am far from being workaholic. But sometimes I need to work on something small or go somewhere where I could use a computer. Today, for example, I started this article watching children play indoor soccer in the morning. It was noisy, messy and I was using my ASUS on my laps. Luckily, that place had a good internet connection and I could save this text in my OneDrive in order to finish on my notebook later.</p> <p>Keep something in mind: Find balance. It doesn’t matter if you have an outstanding data plan if you are abroad most of the time as you will need to use roaming. Or even, you have the best of everything but you can’t concentrate in a café.</p> <p>And remember: The best alternative is always the alternative that suits you.</p> <p> </p> Sun, 14 Dec 2014 11:12:56 GMT http://davidsonsousa.net/blog/post/leave-the-office-see-what-you-need-to-work-anywhere-you-want Ship of fools http://davidsonsousa.net/blog/post/ship-of-fools <!DOCTYPE html> <html> <head> </head> <body> <!-- google_ad_section_start(weight=ignore) --> <p><em>Published by OFF! Magazine, a zine produced by students at SUNY Binghamton and edited by Tim La Pietra.</em></p> <p>Once upon a time, the captain and the mates of a ship grew so vain of their seamanship, so full of hubris and so impressed with themselves, that they went mad. They turned the ship north and sailed until they met with icebergs and dangerous floes, and they kept sailing north into more and more perilous waters, solely in order to give themselves opportunities to perform ever-more-brilliant feats of seamanship.</p> <p>As the ship reached higher and higher latitudes, the passengers and crew became increasingly uncomfortable. They began quarreling among themselves and complaining of the conditions under which they lived.</p> <p>"Shiver me timbers," said an able seaman, "if this ain&rsquo;t the worst voyage I&rsquo;ve ever been on. The deck is slick with ice; when I&rsquo;m on lookout the wind cuts through me jacket like a knife; every time I reef the foresail I blamed-near freeze me fingers; and all I get for it is a miserable five shillings a month!"</p> <p>"You think you have it bad!" said a lady passenger. "I can&rsquo;t sleep at night for the cold. Ladies on this ship don&rsquo;t get as many blankets as the men. It isn&rsquo;t fair!"</p> <p>A Mexican sailor chimed in: "&iexcl;Chingado! I&rsquo;m only getting half the wages of the Anglo seamen. We need plenty of food to keep us warm in this climate, and I&rsquo;m not getting my share; the Anglos get more. And the worst of it is that the mates always give me orders in English instead of Spanish."</p> <p>"I have more reason to complain than anybody," said an American Indian sailor. "If the palefaces hadn&rsquo;t robbed me of my ancestral lands, I wouldn&rsquo;t even be on this ship, here among the icebergs and arctic winds. I would just be paddling a canoe on a nice, placid lake. I deserve compensation. At the very least, the captain should let me run a crap game so that I can make some money."</p> <p>The bosun spoke up: "Yesterday the first mate called me a &lsquo;fruit&rsquo; just because I suck cocks. I have a right to suck cocks without being called names for it!"</p> <p>It&rsquo;s not only humans who are mistreated on this ship," interjected an animal-lover among the passengers, her voice quivering with indignation. "Why, last week I saw the second mate kick the ship&rsquo;s dog twice!"</p> <p>One of the passengers was a college professor. Wringing his hands he exclaimed,</p> <p>"All this is just awful! It&rsquo;s immoral! It&rsquo;s racism, sexism, speciesism, homophobia, and exploitation of the working class! It&rsquo;s discrimination! We must have social justice: Equal wages for the Mexican sailor, higher wages for all sailors, compensation for the Indian, equal blankets for the ladies, a guaranteed right to suck cocks, and no more kicking the dog!"</p> <p>"Yes, yes!" shouted the passengers. "Aye-aye!" shouted the crew. "It&rsquo;s discrimination! We have to demand our rights!"</p> <p>The cabin boy cleared his throat.</p> <p>"Ahem. You all have good reasons to complain. But it seems to me that what we really have to do is get this ship turned around and headed back south, because if we keep going north we&rsquo;re sure to be wrecked sooner or later, and then your wages, your blankets, and your right to suck cocks won&rsquo;t do you any good, because we&rsquo;ll all drown."</p> <p>But no one paid any attention to him, because he was only the cabin boy.</p> <p>The captain and the mates, from their station on the poop deck, had been watching and listening. Now they smiled and winked at one another, and at a gesture from the captain the third mate came down from the poop deck, sauntered over to where the passengers and crew were gathered, and shouldered his way in amongst them. He put a very serious expression on his face and spoke thusly:</p> <p>"We officers have to admit that some really inexcusable things have been happening on this ship. We hadn&rsquo;t realized how bad the situation was until we heard your complaints. We are men of good will and want to do right by you. But &ndash; well &ndash; the captain is rather conservative and set in his ways, and may have to be prodded a bit before he&rsquo;ll make any substantial changes. My personal opinion is that if you protest vigorously &ndash; but always peacefully and without violating any of the ship&rsquo;s rules &ndash; you would shake the captain out of his inertia and force him to address the problems of which you so justly complain."</p> <p>Having said this, the third mate headed back toward the poop deck. As he went, the passengers and crew called after him, "Moderate! Reformer! Goody-liberal! Captain&rsquo;s stooge!" But they nevertheless did as he said. They gathered in a body before the poop deck, shouted insults at the officers, and demanded their rights: "I want higher wages and better working conditions," cried the able seaman. "Equal blankets for women," cried the lady passenger. "I want to receive my orders in Spanish," cried the Mexican sailor. "I want the right to run a crap game," cried the Indian sailor. "I don&rsquo;t want to be called a fruit," cried the bosun. "No more kicking the dog," cried the animal lover. "Revolution now," cried the professor.</p> <p>The captain and the mates huddled together and conferred for several minutes, winking, nodding and smiling at one another all the while. Then the captain stepped to the front of the poop deck and, with a great show of benevolence, announced that the able seaman&rsquo;s wages would be raised to six shillings a month; the Mexican sailor&rsquo;s wages would be raised to two-thirds the wages of an Anglo seaman, and the order to reef the foresail would be given in Spanish; lady passengers would receive one more blanket; the Indian sailor would be allowed to run a crap game on Saturday nights; the bosun wouldn&rsquo;t be called a fruit as long as he kept his cocksucking strictly private; and the dog wouldn&rsquo;t be kicked unless he did something really naughty, such as stealing food from the galley.</p> <p>The passengers and crew celebrated these concessions as a great victory, but the next morning, they were again feeling dissatisfied.</p> <p>"Six shillings a month is a pittance, and I still freeze me fingers when I reef the foresail," grumbled the able seaman. "I&rsquo;m still not getting the same wages as the Anglos, or enough food for this climate," said the Mexican sailor. "We women still don&rsquo;t have enough blankets to keep us warm," said the lady passenger. The other crewmen and passengers voiced similar complaints, and the professor egged them on.</p> <p>When they were done, the cabin boy spoke up &ndash; louder this time so that the others could not easily ignore him:</p> <p>"It&rsquo;s really terrible that the dog gets kicked for stealing a bit of bread from the galley, and that women don&rsquo;t have equal blankets, and that the able seaman gets his fingers frozen; and I don&rsquo;t see why the bosun shouldn&rsquo;t suck cocks if he wants to. But look how thick the icebergs are now, and how the wind blows harder and harder! We&rsquo;ve got to turn this ship back toward the south, because if we keep going north we&rsquo;ll be wrecked and drowned."</p> <p>"Oh yes," said the bosun, "It&rsquo;s just so awful that we keep heading north. But why should I have to keep cocksucking in the closet? Why should I be called a fruit? Ain&rsquo;t I as good as everyone else?"</p> <p>"Sailing north is terrible," said the lady passenger. "But don&rsquo;t you see? That&rsquo;s exactly why women need more blankets to keep them warm. I demand equal blankets for women now!"</p> <p>"It&rsquo;s quite true," said the professor, "that sailing to the north imposes great hardships on all of us. But changing course toward the south would be unrealistic. You can&rsquo;t turn back the clock. We must find a mature way of dealing with the situation."</p> <p>"Look," said the cabin boy, "If we let those four madmen up on the poop deck have their way, we&rsquo;ll all be drowned. If we ever get the ship out of danger, then we can worry about working conditions, blankets for women, and the right to suck cocks. But first we&rsquo;ve got to get this vessel turned around. If a few of us get together, make a plan, and show some courage, we can save ourselves. It wouldn&rsquo;t take many of us &ndash; six or eight would do. We could charge the poop, chuck those lunatics overboard, and turn the ship to the south."</p> <p>The professor elevated his nose and said sternly, "I don&rsquo;t believe in violence. It&rsquo;s immoral."</p> <p>"It&rsquo;s unethical ever to use violence," said the bosun.</p> <p>"I&rsquo;m terrified of violence," said the lady passenger.</p> <p>The captain and the mates had been watching and listening all the while. At a signal from the captain, the third mate stepped down to the main deck. He went about among the passengers and crew, telling them that there were still many problems on the ship.</p> <p>"We have made much progress," he said, "But much remains to be done. Working conditions for the able seaman are still hard, the Mexican still isn&rsquo;t getting the same wages as the Anglos, the women still don&rsquo;t have quite as many blankets as the men, the Indian&rsquo;s Saturday-night crap game is a paltry compensation for his lost lands, it&rsquo;s unfair to the bosun that he has to keep his cocksucking in the closet, and the dog still gets kicked at times.</p> <p>"I think the captain needs to be prodded again. It would help if you all would put on another protest &ndash; as long as it remains nonviolent."</p> <p>As the third mate walked back toward the stern, the passengers and the crew shouted insults after him, but they nevertheless did what he said and gathered in front of the poop deck for another protest. They ranted and raved and brandished their fists, and they even threw a rotten egg at the captain (which he skillfully dodged).</p> <p>After hearing their complaints, the captain and the mates huddled for a conference, during which they winked and grinned broadly at one another. Then the captain stepped to the front of the poop deck and announced that the able seaman would be given gloves to keep his fingers warm, the Mexican sailor would receive wages equal to three-fourths the wages of an Anglo seaman, the women would receive yet another blanket, the Indian sailor could run a crap game on Saturday and Sunday nights, the bosun would be allowed to suck cocks publicly after dark, and no one could kick the dog without special permission from the captain.</p> <p>The passengers and crew were ecstatic over this great revolutionary victory, but by the next morning they were again feeling dissatisfied and began grumbling about the same old hardships.</p> <p>The cabin boy this time was getting angry.</p> <p>"You damn fools!" he shouted. "Don&rsquo;t you see what the captain and the mates are doing? They&rsquo;re keeping you occupied with your trivial grievances about blankets and wages and the dog being kicked so that you won&rsquo;t think about what is really wrong with this ship --&ndash; that it&rsquo;s getting farther and farther to the north and we&rsquo;re all going to be drowned. If just a few of you would come to your senses, get together, and charge the poop deck, we could turn this ship around and save ourselves. But all you do is whine about petty little issues like working conditions and crap games and the right to suck cocks."</p> <p>The passengers and the crew were incensed.</p> <p>"Petty!!" cried the Mexican, "Do you think it&rsquo;s reasonable that I get only three-fourths the wages of an Anglo sailor? Is that petty?</p> <p>"How can you call my grievance trivial? shouted the bosun. "Don&rsquo;t you know how humiliating it is to be called a fruit?"</p> <p>"Kicking the dog is not a &lsquo;petty little issue!&rsquo;" screamed the animal-lover. "It&rsquo;s heartless, cruel, and brutal!"</p> <p>"Alright then," answered the cabin boy. "These issues are not petty and trivial. Kicking the dog is cruel and brutal and it is humiliating to be called a fruit. But in comparison to our real problem &ndash; in comparison to the fact that the ship is still heading north &ndash; your grievances are petty and trivial, because if we don&rsquo;t get this ship turned around soon, we&rsquo;re all going to drown.</p> <p>"Fascist!" said the professor.</p> <p>"Counterrevolutionary!" said the lady passenger. And all of the passengers and crew chimed in one after another, calling the cabin boy a fascist and a counterrevolutionary. They pushed him away and went back to grumbling about wages, and about blankets for women, and about the right to suck cocks, and about how the dog was treated. The ship kept sailing north, and after a while it was crushed between two icebergs and everyone drowned.</p> <p><em>&copy; Ted Kaczynski, 1999</em></p> <p><span style="font-size: 8pt;"><em>The featured image is &ldquo;Ship of Fools&rdquo; (2012), by A.N. Mironov (<a href="https://commons.wikimedia.org/wiki/File:Ship_of_fools._A.N._Mironov.jpg" target="_blank" rel="noopener">Wikimedia Commons</a>)</em></span></p> <!-- google_ad_section_end --> </body> </html> Wed, 10 Dec 2014 07:41:00 GMT http://davidsonsousa.net/blog/post/ship-of-fools Adding an external link message to all links with jQuery http://davidsonsousa.net/blog/post/adding-an-external-link-message-to-all-links-with-jquery <p>Sometimes we face some situations where we have to tell the user he is leaving our website. This can be achieved with CSS selector without so much problem. But what if the external link is in a button? For that situation we should use JavaScript.</p> <p>Let's see how to do it in this very short tutorial.</p> <h2>Objective</h2> <p>We need to create a script where a message will be shown whenever the user clicks in some link which will lead him outside of the website. And this must be done <a href="http://en.wikipedia.org/wiki/Unobtrusive_JavaScript">unobtrusively</a>.</p> <h2>The foundation</h2> <p>First we need to prepare the foundation of our code. Given the objective we will need to:</p> <ol> <li>Loop through all "a" elements</li> <li>Get the href value</li> <li>Compare if the host matches with the href host</li> <li>Assign the click button</li> </ol> <h3>1. Loop through all "a" elements</h3> <p>Since we are using jQuery we can make use of the <a href="http://api.jquery.com/jquery.each/">jQuery.each()</a>, as seen below, to loop through all "a" elements:</p> <pre style="background: white; color: black; font-family: Consolas; font-size: 14px;">$(<span style="color: #a31515;">'a'</span>).each(<span style="color: blue;">function</span> () { <span style="color: green;">// something</span> }); </pre> <h3>2. Get the href value</h3> <p>This is a bit trickier but, to make it easier, we will create a function to do the job:</p> <pre style="background: white; color: black; font-family: Consolas; font-size: 14px;"><span style="color: blue;">var</span> getLocation = <span style="color: blue;">function</span> (href) { <span style="color: blue;">var</span> l = document.createElement(<span style="color: #a31515;">"a"</span>); l.href = href; <span style="color: blue;">return</span> l; }; </pre> <p>And we will call it like this:</p> <pre style="background: white; color: black; font-family: Consolas; font-size: 14px;"><span style="color: blue;">var</span> a = getLocation($(<span style="color: blue;">this</span>).attr(<span style="color: #a31515;">'href'</span>));</pre> <h3>3. Compare if the host matches with the href host</h3> <pre style="background: white; color: black; font-family: Consolas; font-size: 14px;"><span style="color: blue;">var</span> retValue = a.href && a.hostname !== window.location.hostname && a.href.indexOf(<span style="color: #a31515;">'mailto'</span>) == -1; </pre> <p>Here you have to use a set of rules which will make the code work properly. For the sake of the example I’ve decided to keep it simple, but you can (and should) extend according to your project. </p> <h3>4. Assign the click button</h3> <p>For those who are already aware of jQuery this is an easy piece. But I will leave it here anyway.</p> <pre style="background: white; color: black; font-family: Consolas; font-size: 14px;"><span style="color: blue;">if</span> (retValue === <span style="color: blue;">true</span>) { $(<span style="color: blue;">this</span>).on(<span style="color: #a31515;">'click'</span>, <span style="color: blue;">function</span> () { <span style="color: green;">// something</span> }); } </pre> <p>Now that we have the foundation ready you can see it working <a href="http://fiddle.jshell.net/L4qxcc6c/">in this JSFiddle</a>. When you click the links you will see that one of them shows an alert() message. Now the things will get more interesting, by implementing our confirmation message. </p> <h2>Showing the message</h2> <p>Now that we have everything in place we can start to work with the message. For this example I will keep it simple and use a simple confirm(), as seen below:</p> <pre style="background: white; color: black; font-family: Consolas; font-size: 14px;"><span style="color: blue;">return</span> confirm(<span style="color: #a31515;">'Do you really want to leave this website and go to '</span> + a.href + <span style="color: #a31515;">'?'</span>); </pre> <h2>Conclusion</h2> <p>Here is the whole code:</p> <pre style="background: white; color: black; font-family: Consolas; font-size: 14px;"><span style="color: blue;">var</span> getLocation = <span style="color: blue;">function</span> (href) { <span style="color: blue;">var</span> l = document.createElement(<span style="color: #a31515;">"a"</span>); l.href = href; <span style="color: blue;">return</span> l; };</pre> <pre style="background: white; color: black; font-family: Consolas; font-size: 14px;">$(<span style="color: blue;">function</span> () { $(<span style="color: #a31515;">'a'</span>).each(<span style="color: blue;">function</span> () { <span style="color: blue;">var</span> a = getLocation($(<span style="color: blue;">this</span>).attr(<span style="color: #a31515;">'href'</span>)); <strong> <span style="color: green;">// IE fix</span> a = getLocation(a.href);</strong> <span style="color: blue;">var</span> retValue = a.href && a.hostname !== window.location.hostname && a.href.indexOf(<span style="color: #a31515;">'mailto'</span>) == -1; <span style="color: blue;">if</span> (retValue === <span style="color: blue;">true</span>) { $(<span style="color: blue;">this</span>).on(<span style="color: #a31515;">'click'</span>, <span style="color: blue;">function</span> () { <span style="color: blue;">return</span> confirm(<span style="color: #a31515;">'Do you really want to leave this website and go to '</span> + a.href + <span style="color: #a31515;">'?'</span>); }); } }); });</pre> <p>As you can see it is very simple to make and even simpler to use. Once you call it in all pages it will scan all your links and check if they should have this extra event or not. Also, for most of the projects we don’t need more than this. And when you have the need of more customization (Bootstrap Modal or jQuery UI Dialog) you can just replace the confirm() by something else.</p> <p>I will show how to do it in the future articles.</p> <p><em><strong>EDIT:</strong> I've made a small change on the script (bold, see above) as IE11 had some problems to get the a.hostname.</em></p> Thu, 25 Sep 2014 06:46:40 GMT http://davidsonsousa.net/blog/post/adding-an-external-link-message-to-all-links-with-jquery Criando páginas de erro 404 personalizadas no ASP.NET MVC http://davidsonsousa.net/blog/post/criando-paginas-de-erro-404-personalizadas-no-aspnet-mvc <p>Todo mundo que trabalha fazendo sites sabe que ter páginas de erro é indispensável. Só que quando se trabalha com ASP.NET MVC é muito complicado se acertar na hora de configurar as páginas de erro. Sim, usar o web.config é o recomendado. Mas você tem certeza de que está funcionando?</p> <h2>Objetivo</h2> <p>O nosso objetivo aqui é aprender a fazer uma página personalizada de erro 404 e retornar o HTTP status code correspondente (404) sem alterar a url.</p> <h2>O que aprendemos sobre erros no começo</h2> <p>Normalmente, quando estamos iniciando no ASP.NET, aprendemos que temos que colocar a tag no web.config, configurar os parâmetros e esperar o erro aparecer. Veja o exemplo abaixo:</p> <pre style="background: white; color: black; font-family: Consolas; font-size: 16px;"><span style="color: blue;"><</span><span style="color: #a31515;">customErrors</span><span style="color: blue;"> </span><span style="color: red;">mode</span><span style="color: blue;">=</span>"<span style="color: blue;">On</span>"<span style="color: blue;">></span> <span style="color: blue;"> <</span><span style="color: #a31515;">error</span><span style="color: blue;"> </span><span style="color: red;">statusCode</span><span style="color: blue;">=</span>"<span style="color: blue;">404</span>"<span style="color: blue;"> </span><span style="color: red;">path</span><span style="color: blue;">=</span>"<span style="color: blue;">erro404.html</span>"<span style="color: blue;"> /></span> <span style="color: blue;"><span style="color: #a31515;">customErrors</span><span style="color: blue;">></span> </span></pre> <h2>Páginas 404 personalizadas</h2> <p>Normalmente quando uma página não existe o site retorna o erro 404, não importa se a página é estática (página html simples) ou dinâmica (página gerada pelo backend). No caso do exemplo acima o ASP.NET a gente está dizendo para o site para redirecionar para uma página amigável quando acontecer algum erro 404.</p> <p>Até aí tudo bem.</p> <h2>O problema do MVC</h2> <p>No caso do MVC o buraco acaba sendo mais embaixo: Como o MVC é baseado em routes, controles e actions uma url como /lala/lele não vai passar pelo . O resultado vai ser aquele erro 404 padrão do ASP.NET.</p> <p>A solução pra esse problema é simples, mas não é a mais correta. Basta colocar um redirect=”~/ erro404.html” no lugar do path, como no exemplo abaixo:</p> <pre style="background: white; color: black; font-family: Consolas; font-size: 16px;"><span style="color: blue;"><</span><span style="color: #a31515;">customErrors</span><span style="color: blue;"> </span><span style="color: red;">mode</span><span style="color: blue;">=</span>"<span style="color: blue;">On</span>"<span style="color: blue;">></span> <span style="color: blue;"> <</span><span style="color: #a31515;">error</span><span style="color: blue;"> </span><span style="color: red;">statusCode</span><span style="color: blue;">=</span>"<span style="color: blue;">404</span>"<span style="color: blue;"> </span><span style="color: red;">redirect</span><span style="color: blue;">=</span>"<span style="color: blue;">~/erro404.html</span>"<span style="color: blue;">/></span> <span style="color: blue;"><span style="color: #a31515;">customErrors</span><span style="color: blue;">></span> </span></pre> <p>Agora, se você navegar pra uma url aleatória (lala/lele) você vai ser capaz de ver a sua página personalizada de erro. Só que, além da url se tornar /erro404.html?aspxerrorpath=/lala/lele você vai ver que o HTTP status code da página é 200.</p> <p>E isso é muito longe do objetivo que traçamos no começo.</p> <p>Não sou especialista em SEO mas deixa eu tentar explicar o problema: Se por um acaso a página que os indexadores acharem não existe, mas estamos retornando 200, eles vão achar que a página existe e vão indexar a página 404 personalizada como se ela fizesse parte da navegação do site.</p> <h2>A solução ideal</h2> <p>Como eu disse no começo, a ideia é retornar uma página de erro 404 personalizada junto com o HTTP status code correto, que é 404. E obviamente não podemos alterar a url. A maneira mais prática de se fazer isso é mexer direto no IIS. Claro que eu não vou tentar te convencer a ligar no seu host e pedir pra mudar alguma configuração. Para isso vamos usar o .</p> <p>Simplificando: Enquanto o funciona no mesmo nível do ASP.NET, o funciona mais próximo ao IIS. O que significa que as alterações no vão afetar até mesmo arquivos estáticos. Logo, se quisermos fazer alguma alteração que seja mais próxima do servidor, é lá que devemos mexer.</p> <p>Para fazer com que nossa página de erro 404 personalizada funcione no MVC devemos fazer como no exemplo a seguir:</p> <pre style="background: white; color: black; font-family: Consolas; font-size: 16px;"><span style="color: blue;"><</span><span style="color: #a31515;">httpErrors</span><span style="color: blue;"> </span><span style="color: red;">errorMode</span><span style="color: blue;">=</span>"<span style="color: blue;">Custom</span>"<span style="color: blue;">></span> <span style="color: blue;"> <</span><span style="color: #a31515;">remove</span><span style="color: blue;"> </span><span style="color: red;">statusCode</span><span style="color: blue;">=</span>"<span style="color: blue;">404</span>"<span style="color: blue;">/></span> <span style="color: blue;"> <</span><span style="color: #a31515;">error</span><span style="color: blue;"> </span><span style="color: red;">statusCode</span><span style="color: blue;">=</span>"<span style="color: blue;">404</span>"<span style="color: blue;"> </span><span style="color: red;">path</span><span style="color: blue;">=</span>"<span style="color: blue;">/erro404.html</span>"<span style="color: blue;"> </span><span style="color: red;">responseMode</span><span style="color: blue;">=</span>"<span style="color: blue;">File</span>"<span style="color: blue;">/></span> <span style="color: blue;"><span style="color: #a31515;">httpErrors</span><span style="color: blue;">></span> </span></pre> <p>Reparou que eu usei um antes? Isso evita erros caso já tenha algum statusCode=”404” definido. E, apesar de eu estar usando uma página html simples (o ideal), podemos usar uma rota específica para a página 404. Como por exemplo /erro/404. Só que nesse caso é recomendado usar o responseMode=”ExecuteUrl”.</p> <p>Agora, se formos acessar uma url aleatória /lala/lele vamos ver que:</p> <ol> <li>A página 404 foi chamada</li> <li>O HTTP status code é 404</li> <li>A url não foi alterada</li> </ol> <p>Pronto. Espero que isso tenha sanado suas dúvidas. De qualquer forma fique à vontade para comentar e perguntar.</p> Mon, 22 Sep 2014 13:07:20 GMT http://davidsonsousa.net/blog/post/criando-paginas-de-erro-404-personalizadas-no-aspnet-mvc Como fazer com que a sessão não expire usando Forms Authentication http://davidsonsousa.net/blog/post/como-fazer-com-que-a-sessao-nao-expire-usando-forms-authentication <p>Tem dias que a gente tem que voltar ao básico pra resolver um problema. E hoje foi um desses dias.</p> <p>Temos um projeto onde usamos Forms Authentication para login. Nada muito complexo: É um sistema de avaliação com algumas perguntas de multipla escolha. Não customizamos o Forms Authentication pois só queríamos um nível básico de autenticação. Só que os usuáros começou a ter problemas e, depois de algum tempo, achamos a solução.</p> <h2>O problema</h2> <p>O usuário logava, trabalhava mas, depois de um tempo, o sistema voltava automaticamente para a tela de login sem salvar as informações.</p> <h2>A solução</h2> <p>No nosso caso, como o sistema é pequeno e só ficava inconveniente para o usuário ter que colocar as respostas novamente, resolvemos o problema colocando a sessão para expirar em 1 ano. Eu sei, é muito. Mas dá pra trabalhar com folga. Eis o código:</p> <pre style="background: white; color: black; font-family: Consolas; font-size: 14px;"><span style="color: blue;"><</span><span style="color: #a31515;">authentication</span><span style="color: blue;"> </span><span style="color: red;">mode</span><span style="color: blue;">=</span>"<span style="color: blue;">Forms</span>"<span style="color: blue;">></span> <span style="color: blue;"> <</span><span style="color: #a31515;">forms</span><span style="color: blue;"> </span><span style="color: red;">loginUrl</span><span style="color: blue;">=</span>"<span style="color: blue;">~/</span>"<span style="color: blue;"> </span><span style="color: red;">timeout</span><span style="color: blue;">=</span>"<span style="color: blue;">525949</span>"<span style="color: blue;"> /> <!--</span><span style="color: green;"> 1 year expiration </span><span style="color: blue;">--></span> <span style="color: blue;"><span style="color: #a31515;"><span style="color: blue;"><</span>authentication</span><span style="color: blue;">></span> </span></pre> <p>Existem, no entanto, outras soluções. Tem uma que chamam de "<a href="http://stackoverflow.com/questions/1431733/keeping-asp-net-session-open-alive">heartbeat</a>" onde a sessão é atualizada a cada 5 minutos via ajax. Talvez eu faça mini projeto em forma de tutorial e poste aqui qualquer dia desses. ;-)</p> Mon, 15 Sep 2014 05:04:06 GMT http://davidsonsousa.net/blog/post/como-fazer-com-que-a-sessao-nao-expire-usando-forms-authentication Write and read XML files by serializing and deserializing objects with C# http://davidsonsousa.net/blog/post/serializedeserialize-objects-to-xml-with-c <p>Have you ever wondered how to write an XML file easily? And what about reading the XML file and mapping into an object? There are cases we need to generate XML in order to send information here and there. Or even to use as a kind of database. And the most used approach (by my friends, at least) is to create the XML manually, defining every single node. Pro: More control of the output. Con: Time consuming.</p> <p>And that brings us to the situation we had in the office.</p> <p>We have access to a SQL database. But due the amount of security layers we end up taking a huge amount of time to develop against the database. Besides, we wanted to make something flexible and easy to be edited by anyone with more than 2 brain cells. That's why we decided that it would be much more flexible if we would use XML files for the data.</p> <p>All we need is a well structured class, which could be a Model for those using MVC:</p> <pre style="font-family: Consolas; font-size: 14; color: black; background: white;"><span style="color: blue;">public</span>&nbsp;<span style="color: blue;">class</span>&nbsp;<span style="color: #2b91af;">DummyClass</span> { &nbsp;&nbsp;&nbsp; <span style="color: blue;">public</span>&nbsp;<span style="color: blue;">string</span>&nbsp;Id&nbsp;{&nbsp;<span style="color: blue;">get</span>;&nbsp;<span style="color: blue;">set</span>;&nbsp;} &nbsp;&nbsp;&nbsp; <span style="color: blue;">public</span>&nbsp;<span style="color: blue;">string</span>&nbsp;Name&nbsp;{&nbsp;<span style="color: blue;">get</span>;&nbsp;<span style="color: blue;">set</span>;&nbsp;} } </pre> <p>And the following code:</p> <pre style="font-family: Consolas; font-size: 14; color: black; background: white;"><span style="color: blue;">public</span>&nbsp;<span style="color: blue;">class</span>&nbsp;<span style="color: #2b91af;">XmlSerializerHelper</span>&lt;T&gt;&nbsp;<span style="color: blue;">where</span>&nbsp;T&nbsp;:&nbsp;<span style="color: blue;">class</span> { <span style="color: blue;">public</span>&nbsp;<span style="color: blue;">static</span>&nbsp;<span style="color: blue;">string</span>&nbsp;Serialize(T&nbsp;obj) { <span style="color: blue;">var</span>&nbsp;stringBuilder&nbsp;=&nbsp;<span style="color: blue;">new</span>&nbsp;<span style="color: #2b91af;">StringBuilder</span>(); <span style="color: blue;">try</span> { <span style="color: blue;">var</span>&nbsp;xmlWriterSettings&nbsp;=&nbsp;<span style="color: blue;">new</span>&nbsp;<span style="color: #2b91af;">XmlWriterSettings</span>&nbsp;{&nbsp;Indent&nbsp;=&nbsp;<span style="color: blue;">true</span>,&nbsp;OmitXmlDeclaration&nbsp;=&nbsp;<span style="color: blue;">true</span>&nbsp;}; <span style="color: blue;">var</span>&nbsp;ns&nbsp;=&nbsp;<span style="color: blue;">new</span>&nbsp;<span style="color: #2b91af;">XmlSerializerNamespaces</span>(); ns.Add(<span style="color: #a31515;">""</span>,&nbsp;<span style="color: #a31515;">""</span>); <span style="color: blue;">var</span>&nbsp;xs&nbsp;=&nbsp;<span style="color: blue;">new</span>&nbsp;<span style="color: #2b91af;">XmlSerializer</span>(<span style="color: blue;">typeof</span>(T),&nbsp;<span style="color: #a31515;">""</span>); <span style="color: blue;">using</span>&nbsp;(<span style="color: blue;">var</span>&nbsp;writer&nbsp;=&nbsp;<span style="color: #2b91af;">XmlWriter</span>.Create(stringBuilder,&nbsp;xmlWriterSettings)) { xs.Serialize(writer,&nbsp;obj,&nbsp;ns); } } <span style="color: blue;">catch</span> { <span style="color: blue;">throw</span>; } <span style="color: blue;">return</span>&nbsp;stringBuilder.ToString(); } <span style="color: blue;">public</span>&nbsp;<span style="color: blue;">static</span>&nbsp;T&nbsp;Deserialize(<span style="color: blue;">string</span>&nbsp;xmlString) { <span style="color: blue;">var</span>&nbsp;reader&nbsp;=&nbsp;<span style="color: blue;">new</span>&nbsp;<span style="color: #2b91af;">StringReader</span>(xmlString); <span style="color: blue;">var</span>&nbsp;serializer&nbsp;=&nbsp;<span style="color: blue;">new</span>&nbsp;<span style="color: #2b91af;">XmlSerializer</span>(<span style="color: blue;">typeof</span>(T)); <span style="color: blue;">var</span>&nbsp;instance&nbsp;=&nbsp;(T)serializer.Deserialize(reader); <span style="color: blue;">return</span>&nbsp;instance; } } </pre> <p>If you want to serialize a class to XML:</p> <pre style="font-family: Consolas; font-size: 14; color: black; background: white;">xDoc.Add(<span style="color: #2b91af;">XElement</span>.Parse(<span style="color: #2b91af;">XmlSerializerHelper</span>&lt;<span style="color: #2b91af;">DummyClass</span>&gt;.Serialize(dummy))); </pre> <p>And if you want to deserialize:</p> <pre style="font-family: Consolas; font-size: 14; color: black; background: white;"><span style="color: blue;">var</span> dummyObj =&nbsp;<span style="color: #2b91af;">XmlSerializerHelper</span>&lt;<span style="color: #2b91af;">DummyClass</span>&gt;.Deserialize(xDoc.ToString()); </pre> <p>Please note a couple of things:</p> <ol> <li>This code will generate a very simple XML file, without namespaces or declarations;</li> <li>The "type of T" is there to give you flexibility when using the serialization/deserialization methods;</li> <li>The way the XML will be generated depends entirely on the way the class is created.</li> </ol> <p>I know this code is not perfect (no try/catch on Deserialize, etc) it should give you a good head start. ;-)</p> <p>If you start to implement this code you might have noticed one thing: Everything what is in the class will be serialized into the XML with the names you defined there. We can solve this and I will show you how.</p> <h3>Renaming the XML elements</h3> <p>It might happen that you have a class with a name which wouldn't make sense after generating a XML file. In that case it would be much better if we would have the XML elements in a way that anyone can understand. After all, it's much better to read <em>&lt;Person&gt;</em> than <em>&lt;PrsnClass&gt;</em>, right?</p> <p>One easy way to do it is using Annotations over the name of the class and its properties. Here some that might be very useful:</p> <h4>XmlRoot</h4> <pre style="font-family: Consolas; font-size: 14; color: black; background: white;">[<span style="color: #2b91af;">XmlRoot</span>(<span style="color: #a31515;">"Person"</span>)] </pre> <p>XmlRoot will work in 2 ways: First by defining the root of your XML file; Second by defining its name. Recommended to be used to rename the class itself.</p> <h4>XmlAttribute</h4> <pre style="font-family: Consolas; font-size: 14; color: black; background: white;">[<span style="color: #2b91af;">XmlAttribute</span>(<span style="color: #a31515;">"Id"</span>)] </pre> <p>By default every property is serialized as XML element. By XmlAttribute you will tell the serializer that your property should be used as an attribute in the root element.</p> <h4>XmlElement</h4> <pre style="font-family: Consolas; font-size: 14; color: black; background: white;">[<span style="color: #2b91af;">XmlElement</span>(<span style="color: #a31515;">"Name"</span>)] </pre> <p>Use XmlElement in case you have a property you wish to rename. Very useful in the case you have a property called <em>PersonName</em> and you want to serialize it as <em>Name</em>.</p> <h4>XmlIgnore</h4> <pre style="font-family: Consolas; font-size: 14; color: black; background: white;">[<span style="color: #2b91af;">XmlIgnore</span>] </pre> <p>You can use XmlIgnore when you don't want a property to be serialized.</p> <h4>XmlArrayItem</h4> <pre style="font-family: Consolas; font-size: 14; color: black; background: white;">[<span style="color: #2b91af;">XmlArrayItem</span>(<span style="color: #a31515;">"Children"</span>)] </pre> <p>XmlArrayItem is used to create sub elements. You can also use it to rename your properties which contains List&lt;T&gt;, for example.</p> <p>Of course there are more. But create a kind of <em>ultimate xml serialization guide</em> was never my idea. Maybe one day I will write a book about it. But while it doesn't happen I hope this article will be able to help some people around the interwebs.</p> Tue, 15 Apr 2014 11:19:00 GMT http://davidsonsousa.net/blog/post/serializedeserialize-objects-to-xml-with-c Como entrar no mercado de trabalho .NET depois da faculdade http://davidsonsousa.net/blog/post/como-entrar-no-mercado-de-trabalho-net-depois-da-faculdade <p>Recebi a alguns dias atr&aacute;s um e-mail do Douglas Cardoso, 20 anos, rec&eacute;m formado em <strong>An&aacute;lise e Desenvolvimento de Sistemas</strong>. No e-mail ele faz algumas perguntas sobre <strong>como come&ccedil;ar a trabalhar com programa&ccedil;&atilde;o</strong>, como &eacute; o mercado de trabalho (quantidade de vagas de emprego) e <strong>que tipo de conhecimento ele deve ter</strong>. Como acho que tem muita gente com essa d&uacute;vida eu perguntei a ele se poderia colar nossa conversa aqui.</p> <p>Eis a pergunta do Douglas:</p> <p>Fala Davidson, ent&atilde;o, eu me formei agora em analise e desenvolvimento de sistemas, tenho 20 anos, e decidi seguir com programa&ccedil;&atilde;o, irei come&ccedil;ar a fazer um curso de forma&ccedil;&atilde;o .NET na K19, tenho base C#, e ASP, &eacute; o que faculdade me proporcionou, e agora vou fazer esse curso para dar uma especializada, estou fazendo ingl&ecirc;s tamb&eacute;m porque &eacute; extremamente necess&aacute;rio, at&eacute; porque quero tirar minhas certifica&ccedil;&otilde;es, eu tenho algumas d&uacute;vidas que acho que &eacute; normal, se der para voc&ecirc; me responder ficaria muito grato!</p> <ol> <li>Eu consigo entrar no mercado como programador C#, ASP.NET j&uacute;nior (j&aacute; desenvolvi, um site de uma loja virtual em&nbsp;ASP.NET e um sistema de pizzaria em C#)?</li> <li>Eu moro em Extrema - MG, mas estarei mudando para SP, em busca de mercado, o mercado para essa &aacute;rea &eacute; boa?</li> <li>Estou perdida&ccedil;o, ap&oacute;s eu estar fluente em ingl&ecirc;s, e bons conhecimentos na linguagem, como faz a certifica&ccedil;&atilde;o? A inscri&ccedil;&atilde;o, o local da prova, etc.</li> </ol> <p>Muito obrigado se der para me responder! Sou um novato e t&ocirc; com mil duvidas na minha cabe&ccedil;a haha.</p> <p>Eis minha resposta:</p> <p>Grande Douglas, tudo bem? Vamos por partes:</p> <ol> <li>Sim, voc&ecirc; consegue entrar como junior. At&eacute; porque voc&ecirc; precisa come&ccedil;ar por algum lugar.</li> <li>Sim, o mercado de SP &eacute; muito bom. Mas tamb&eacute;m pense no Sul do pa&iacute;s, eles tem melhor qualidade de vida.</li> <li>Sobre a certifica&ccedil;&atilde;o eu recomendo voc&ecirc; ter pelo menos 2 anos de experi&ecirc;ncia de mercado. N&atilde;o que, por exemplo, vai cair na prova aquele arquivo que voc&ecirc; fez pro Banco do Brasil. Mas esses 2 anos v&atilde;o te ajudar a amadurecer a tecnologia na tua cabe&ccedil;a. Voc&ecirc; pode fazer a inscri&ccedil;&atilde;o no <a href="https://www.prometric.com/en-us/clients/microsoft/Pages/landing.aspx">site da Prometric</a> e pagar uma graninha. Da &uacute;ltima vez que eu marquei uma prova tava 100 d&oacute;lares.</li> </ol> <p>O que voc&ecirc; pode fazer hoje?</p> <ul> <li><strong>Ganhar experi&ecirc;ncia de mercado</strong> - cometa erros agora, mas aprenda com eles</li> <li><strong>Aprenda a lidar com as pessoas</strong> - vai ajudar no futuro</li> <li><strong>Sempre ajude</strong> - exceto quando voc&ecirc; realmente n&atilde;o pode</li> <li><strong>Aprenda que o c&oacute;digo n&atilde;o te pertence</strong> - algu&eacute;m vai mexer e mudar tudo, mas n&atilde;o se importe (se estiver funcionando)</li> <li><strong>Estude e se atualize sempre</strong>, mesmo que voc&ecirc; n&atilde;o possa colocar em pr&aacute;tica</li> <li><strong>Tenha vida social</strong> (facebook n&atilde;o conta)</li> </ul> Sun, 16 Mar 2014 13:35:00 GMT http://davidsonsousa.net/blog/post/como-entrar-no-mercado-de-trabalho-net-depois-da-faculdade Replacing all non numeric characters from a string using Regex http://davidsonsousa.net/blog/post/removing-all-non-numeric-characters-from-a-string-using-regex <p>Everybody who works coding something must use <a href="http://en.wikipedia.org/wiki/Regular_expression">Regular Expressions</a> (<strong>RegEx</strong>) at least once in a lifetime. They can be used for a lot of things but my favorite will be always <strong>matching and removing characters from a string</strong>.</p> <p>One of the problems I always have developing softwares was with number&nbsp;formatting. While in the user interface we should allow dots and dashes as the user will never really care if he should or should not use it. In Brazil, for example, the postal code has the following format: 00000-000. Some people might put it without the dash. And that, my friend, will hurt the database.</p> <p>One way to solve this is forcing the backend to keep only the numbers. Let's take a look on how to do it using <a href="http://msdn.microsoft.com/en-us/library/xwewhkd1(v=vs.110).aspx"><strong>Regex.Replace</strong></a>:</p> <ol> <li>Add the reference<br /> <pre style="background: white; color: black; font-family: Consolas; font-size: 13px;"><span style="color: blue;">using</span>&nbsp;System.Text.RegularExpressions;</pre> </li> <li>Use this line of code<br /> <pre style="background: white; color: black; font-family: Consolas; font-size: 13px;"><span style="color: blue;">string</span>&nbsp;onlyNumbers&nbsp;=&nbsp;<span style="color: #2b91af;">Regex</span>.Replace(str,&nbsp;<span style="color: #a31515;">"[^0-9]"</span>,&nbsp;<span style="color: #a31515;">""</span>); </pre> </li> </ol> <p>And that's it!</p> Wed, 19 Feb 2014 16:57:00 GMT http://davidsonsousa.net/blog/post/removing-all-non-numeric-characters-from-a-string-using-regex A importância de selecionar um bom programador .NET http://davidsonsousa.net/blog/post/a-importancia-de-selecionar-um-bom-programador-net <p>Antes de mais nada, contexto: Vou chamar o setor onde trabalho de hub j&aacute; que todas as tarefas de cria&ccedil;&atilde;o e publica&ccedil;&atilde;o de sites &eacute; centralizada no meu escrit&oacute;rio. No caso de publica&ccedil;&atilde;o n&oacute;s temos 2 alternativas: Fazemos um teste r&aacute;pido antes de publicar ou testamos com mais cuidado e fazemos revis&atilde;o de c&oacute;digo antes de mandarmos pra produ&ccedil;&atilde;o. Isso depende do cliente.</p> <p>Pois bem. Alguns dias atr&aacute;s recebemos no hub um pedido para publicar um site. Disseram que n&atilde;o precis&aacute;vamos testar e que era s&oacute; jogar online. Assim o fiz. O problema &eacute; que o site come&ccedil;ou a gerar erro de permiss&atilde;o de pasta. Fiz as devidas corre&ccedil;&otilde;es e o problema foi resolvido.</p> <p>Eu juro que me deu vontade de xingar at&eacute; a 5&ordf; gera&ccedil;&atilde;o do cara que programou o site. Ele cometeu erros b&aacute;sicos como colocar os arquivos de dados (neste caso XML) fora de App_Data, colocou as tags do XML sem padr&atilde;o (algumas tinham mai&uacute;sculas, outras n&atilde;o) e passou bem longe de reusar o c&oacute;digo. Sim, ele criou o mesmo m&eacute;todo v&aacute;rias vezes para fazer a mesma coisa. S&oacute; que em p&aacute;ginas diferentes.</p> <p>Para evitar que outras pessoas fa&ccedil;am isso eu vou botar 3 dicas r&aacute;pidas. Guardem no cora&ccedil;&atilde;o de voc&ecirc;s:</p> <ol> <li><strong>Use App_Data para salvar arquivos</strong> &ndash; N&atilde;o importa que tipo de arquivos voc&ecirc; vai colocar l&aacute; dentro, seja XML ou at&eacute; mesmo um banco de dados SQL. Esta pasta tem nativamente permiss&otilde;es para leitura e escrita. Pode ser que localmente aquela pasta chamada &ldquo;DB&rdquo; na raiz do site funcione, mas isso n&atilde;o garante que funcionar&aacute; em produ&ccedil;&atilde;o. J&aacute; App_Data &eacute; garantido.</li> <li><strong>XML &eacute; case sensitive</strong> &ndash; Tem muita gente que n&atilde;o sabe disso porque s&oacute; usa letras min&uacute;sculas quando est&aacute; criando os nodes no XML. Mas &eacute; case sensitive sim, pode fazer o teste.</li> <li><strong>Reuse seu c&oacute;digo</strong> &ndash; Parece piada mas tem muita gente no mercado que cria aquele m&eacute;todo &ldquo;SalvaArquivo&rdquo; v&aacute;rias vezes em v&aacute;rios lugares diferentes e, pra piorar, fazendo a mesma coisa. Se o m&eacute;todo vai ser usado em v&aacute;rios lugares &eacute; bom criar em um lugar centralizado para facilitar a manuten&ccedil;&atilde;o.</li> </ol> <p>S&oacute; frisando: Isso foi em um projeto <strong>ASP.NET</strong> com <strong>Web Forms</strong>.</p> <p>N&atilde;o sei a hist&oacute;ria dele ou do projeto. Mas se formos pensar um pouco al&eacute;m do c&oacute;digo chegamos a conclus&atilde;o de que ele foi mal escalado para o projeto pois, saibam voc&ecirc;s, &eacute; um site grande de uma marca exposta internacionalmente. Claro que ele deve estar feliz de colocar no curr&iacute;culo que fez um site grande. S&oacute; que n&oacute;s do hub sabemos que <a href="http://davidsonsousa.net/pt/post/se-voc-e-um-trabalhador-mediano-seu-salario-tambem-e-mediano-e-voc-vai-ser-demitido">o cara &eacute; bem mediano</a> e que deve ter achado algum site com dicas de entrevista de emprego pra poder conseguir a vaga. Mas nada que um treinamento e <a href="http://davidsonsousa.net/pt/post/como-fazer-para-tirar-uma-certificao-microsoft-e-consequentemente-melhorar-teu-curriculo">um pouco de dedica&ccedil;&atilde;o nos estudos</a> n&atilde;o resolvam.</p> Sun, 01 Dec 2013 15:43:00 GMT http://davidsonsousa.net/blog/post/a-importancia-de-selecionar-um-bom-programador-net Using web.config to make your ASP.NET project accept LESS CSS http://davidsonsousa.net/blog/post/using-webconfig-to-make-your-aspnet-project-accept-css-less <p>Every ASP.NET developer must love the <strong>web.config</strong> file. Seriously, I will write about it some day. :-)</p> <p>Some time ago, we have faced a very interesting problem in one of our ASP.NET projects. We have decided to use <strong><a href="http://lesscss.org/">LESS CSS</a></strong> in order to optimize the front-end development and speed up the things a bit. While we knew that we should compile the LESS files before throw it to production we were facing an error during the development phase:</p> <p><em>HTTP Error 404.3 - Not Found</em></p> <p><em>The page you are requesting cannot be served because of the extension configuration. If the page is a script, add a handler. If the file should be downloaded, add a MIME map.</em></p> <p>The reason: <strong>IIS doesn’t support .less files by default</strong>.</p> <p>By this time we have 2 solutions: The first one is to call the responsible for the webserver and ask him to add a new MIME type into the IIS. But thanks to the .NET architecture we don't need to do that. All we need to do is to <strong>add some extra lines to your web.config</strong>, inside , as seen bellow:</p> <pre style="font-family: Consolas; font-size: 13; color: black; background: white;"><span style="color: blue;"><</span><span style="color: #a31515;">system.webServer</span><span style="color: blue;">></span> <span style="color: blue;">  <</span><span style="color: #a31515;">staticContent</span><span style="color: blue;">></span> <span style="color: blue;">    <</span><span style="color: #a31515;">remove</span><span style="color: blue;"> </span><span style="color: red;">fileExtension</span><span style="color: blue;">=</span>"<span style="color: blue;">.less</span>"<span style="color: blue;"> /></span> <span style="color: blue;">    <</span><span style="color: #a31515;">mimeMap</span><span style="color: blue;"> </span><span style="color: red;">fileExtension</span><span style="color: blue;">=</span>"<span style="color: blue;">.less</span>"<span style="color: blue;"> </span><span style="color: red;">mimeType</span><span style="color: blue;">=</span>"<span style="color: blue;">text/css</span>"<span style="color: blue;"> /></span> <span style="color: blue;">  <span style="color: #a31515;">staticContent</span><span style="color: blue;">></span> <span style="color: blue;"><span style="color: #a31515;">system.webServer</span><span style="color: blue;">></span> </span></span></pre> <p>As you saw it’s simple, clear and useful. Keep in mind that you can use the same method to solve the problem with other non-supported files such as webfonts (.eot, .woof), videos (.mp4, .ogg, .m4v), images (.svg, .svgx) and so on (as <a href="http://madskristensen.net/post/prepare-webconfig-for-html5-and-css3">Mads Kristensen wrote</a>).</p> Sun, 03 Nov 2013 06:21:00 GMT http://davidsonsousa.net/blog/post/using-webconfig-to-make-your-aspnet-project-accept-css-less Upload de arquivos usando ASP.NET MVC, AJAX e jQuery http://davidsonsousa.net/blog/post/como-fazer-upload-de-arquivos-usando-aspnet-mvc-3-e-ajax <p>Eu resolvi pegar meu artigo e código antigos pra atualizar. Por exemplo: Enquanto antes eu tinha usado o Visual Studio 2010 pra desenvolver um projeto em MVC3 agora eu estou usando o <strong>Visual Studio 2012</strong> pra criar um projeto em <strong>ASP.NET MVC4</strong> usando <strong>bootstrap</strong> e uma versão mais recente de todos os plugins que eu usei antes.</p> <h3>Primeiro passo</h3> <p>Antes de mais nada a gente precisa criar um Model do mesmo jeito que <a href="http://www.hanselman.com/blog/ABackToBasicsCaseStudyImplementingHTTPFileUploadWithASPNETMVCIncludingTestsAndMocks.aspx">Scott Hanselman criou em seu artigo</a>. Assim temos o nome (Name), tamanho (Length) e tipo (Type) do arquivo que vamos enviar pro servidor:</p> <pre style="font-family: Consolas; font-size: 13; color: black; background: white;"><span style="color: blue;">public</span> <span style="color: blue;">class</span> <span style="color: #2b91af;">UploadFilesResult</span> { <span style="color: blue;">public</span> <span style="color: blue;">string</span> Name { <span style="color: blue;">get</span>; <span style="color: blue;">set</span>; } <span style="color: blue;">public</span> <span style="color: blue;">int</span> Length { <span style="color: blue;">get</span>; <span style="color: blue;">set</span>; } <span style="color: blue;">public</span> <span style="color: blue;">string</span> Type { <span style="color: blue;">get</span>; <span style="color: blue;">set</span>; } } </pre> <h3>Segundo passo</h3> <p>Agora nós precisamos de uma <a href="http://msdn.microsoft.com/en-us/library/dd410269.aspx"><strong>Action Method</strong></a> que vai efetivamente pegar o arquivo, tratar e salvar no servidor. Vamos chamar esta Action Method usando o método http <strong>POST</strong>, pegar a lista de arquivos selecionados e salvar dentro de <strong>App_Data</strong>. Esta <strong>Action Method </strong>vai retornar uma string em formato json com o Name, Length and Type dos arquivos:</p> <pre style="font-family: Consolas; font-size: 13; color: black; background: white;">[<span style="color: #2b91af;">HttpPost</span>] <span style="color: blue;">public</span> <span style="color: #2b91af;">ContentResult</span> UploadFiles() { <span style="color: blue;">var</span> r = <span style="color: blue;">new</span> <span style="color: #2b91af;">List</span><<span style="color: #2b91af;">ViewDataUploadFilesResult</span>>(); <span style="color: blue;">foreach</span> (<span style="color: blue;">string</span> file <span style="color: blue;">in</span> Request.Files) { <span style="color: #2b91af;">HttpPostedFileBase</span> hpf = Request.Files[file] <span style="color: blue;">as</span> <span style="color: #2b91af;">HttpPostedFileBase</span>; <span style="color: blue;">if</span> (hpf.ContentLength == 0) <span style="color: blue;">continue</span>; <span style="color: blue;">string</span> savedFileName = <span style="color: #2b91af;">Path</span>.Combine(Server.MapPath(<span style="color: #a31515;">"~/App_Data"</span>), <span style="color: #2b91af;">Path</span>.GetFileName(hpf.FileName)); hpf.SaveAs(savedFileName); <span style="color: green;">// Save the file</span> r.Add(<span style="color: blue;">new</span> <span style="color: #2b91af;">ViewDataUploadFilesResult</span>() { Name = hpf.FileName, Length = hpf.ContentLength, Type = hpf.ContentType }); } <span style="color: green;">// Returns json</span> <span style="color: blue;">return</span> Content(<span style="color: #a31515;">"{\"name\":\""</span> + r[0].Name + <span style="color: #a31515;">"\",\"type\":\""</span> + r[0].Type + <span style="color: #a31515;">"\",\"size\":\""</span> + <span style="color: blue;">string</span>.Format(<span style="color: #a31515;">"{0} bytes"</span>, r[0].Length) + <span style="color: #a31515;">"\"}"</span>, <span style="color: #a31515;">"application/json"</span>); } </pre> <h3>Terceiro passo</h3> <p>Agora precisamos usar um plugin do <strong>jQuery</strong> chamado <a href="https://github.com/blueimp/jQuery-File-Upload">jQuery File Upload</a>. Ele já traz nativamente um monte de coisa bacana mas, para simplificar, vamos usar apenas 2 arquivos (além de outros que já estou usando): <em>jquery.fileupload.css</em> and <em>jquery.fileupload.js</em>.</p> <h3>Quarto passo</h3> <p>Com isso a gente precisa de alguma maneira de enviar os arquivos. Isso é o que eu criei - apenas para o upload - mas você pode adaptar para seu projeto:</p> <pre style="background: white; color: black; font-family: Consolas; font-size: 13px;"><span style="color: blue;"><</span><span style="color: maroon;">div</span> <span style="color: red;">class</span><span style="color: blue;">=</span><span style="color: blue;">"container"</span><span style="color: blue;">></span> <span style="color: blue;"><</span><span style="color: maroon;">span</span> <span style="color: red;">class</span><span style="color: blue;">=</span><span style="color: blue;">"btn btn-success fileinput-button"</span><span style="color: blue;">></span> <span style="color: blue;"><</span><span style="color: maroon;">i</span> <span style="color: red;">class</span><span style="color: blue;">=</span><span style="color: blue;">"glyphicon glyphicon-plus"</span><span style="color: blue;">><span style="color: maroon;">i</span><span style="color: blue;">></span> <span style="color: blue;"><</span><span style="color: maroon;">span</span><span style="color: blue;">></span>Add files...<span style="color: blue;"><span style="color: maroon;">span</span><span style="color: blue;">></span> <span style="color: blue;"><</span><span style="color: maroon;">input</span> <span style="color: red;">id</span><span style="color: blue;">=</span><span style="color: blue;">"fileupload"</span> <span style="color: red;">type</span><span style="color: blue;">=</span><span style="color: blue;">"file"</span> <span style="color: red;">name</span><span style="color: blue;">=</span><span style="color: blue;">"files[]"</span> <span style="color: red;">multiple</span><span style="color: blue;">></span> <span style="color: blue;"><span style="color: maroon;">span</span><span style="color: blue;">></span> <span style="color: blue;"><</span><span style="color: maroon;">br</span> <span style="color: blue;">/></span> <span style="color: blue;"><</span><span style="color: maroon;">div</span> <span style="color: red;">class</span><span style="color: blue;">=</span><span style="color: blue;">"progress"</span><span style="color: blue;">></span> <span style="color: blue;"><</span><span style="color: maroon;">div</span> <span style="color: red;">class</span><span style="color: blue;">=</span><span style="color: blue;">"progress-bar"</span> <span style="color: red;">role</span><span style="color: blue;">=</span><span style="color: blue;">"progressbar"</span> <span style="color: red;">aria-valuenow</span><span style="color: blue;">=</span><span style="color: blue;">"0"</span> <span style="color: red;">aria-valuemin</span><span style="color: blue;">=</span><span style="color: blue;">"0"</span> <span style="color: red;">aria-valuemax</span><span style="color: blue;">=</span><span style="color: blue;">"100"</span> <span style="color: red;">style</span><span style="color: blue;">=</span><span style="color: blue;">"</span><span style="color: red;">width</span>: <span style="color: blue;">0%</span>;<span style="color: blue;">"</span><span style="color: blue;">></span> <span style="color: blue;"><</span><span style="color: maroon;">span</span> <span style="color: red;">class</span><span style="color: blue;">=</span><span style="color: blue;">"sr-only"</span><span style="color: blue;">></span>0% complete<span style="color: blue;"><span style="color: maroon;">span</span><span style="color: blue;">></span> <span style="color: blue;"><span style="color: maroon;">div</span><span style="color: blue;">></span> <span style="color: blue;"><span style="color: maroon;">div</span><span style="color: blue;">></span> <span style="color: blue;"><</span><span style="color: maroon;">br</span> <span style="color: blue;">/></span> <span style="color: blue;"><</span><span style="color: maroon;">div</span> <span style="color: red;">class</span><span style="color: blue;">=</span><span style="color: blue;">"file_name"</span><span style="color: blue;">><span style="color: maroon;">div</span><span style="color: blue;">></span> <span style="color: blue;"><</span><span style="color: maroon;">br</span> <span style="color: blue;">/></span> <span style="color: blue;"><</span><span style="color: maroon;">div</span> <span style="color: red;">class</span><span style="color: blue;">=</span><span style="color: blue;">"file_type"</span><span style="color: blue;">><span style="color: maroon;">div</span><span style="color: blue;">></span> <span style="color: blue;"><</span><span style="color: maroon;">br</span> <span style="color: blue;">/></span> <span style="color: blue;"><</span><span style="color: maroon;">div</span> <span style="color: red;">class</span><span style="color: blue;">=</span><span style="color: blue;">"file_size"</span><span style="color: blue;">><span style="color: maroon;">div</span><span style="color: blue;">></span> <span style="color: blue;"><span style="color: maroon;">div</span><span style="color: blue;">></span> </span></span></span></span></span></span></span></span></span></span></pre> <p>Observe 4 coisas:</p> <ol> <li>Eu não usei nenhum<strong> HtmlHelper</strong> para criar o form. O motivo disso é a facilidade de se criar um form sem HtmlHelper, sem contar que não precisamos usar os HtmlHelpers o tempo todo;</li> <li>Eu <strong>não estou usando form tag</strong>. O plugin toma conta de tudo o que precisamos;</li> <li>A barra de progresso graças ao <a href="http://getbootstrap.com/components/#progress">bootstrap</a>;</li> <li>As <em>divs</em> no final. Elas só estão lá pra receber e mostrar o que o json trouxe..</li> </ol> <h3>Último passo</h3> <p>Depois de organizarmos é hora de fazer o javascript pra fazer isso tudo funcionar. Eu estou usando o plugin jQuery File Upload chamando a Action method <strong>UploadFiles</strong> criado no <strong>HomeController</strong>. Some isso ao evento que coloquei no javascript mostrando o status do upload usando a barra de progresso do bootstrap:</p> <pre style="background: white; color: black; font-family: Consolas; font-size: 13px;"><span style="color: blue;"><</span><span style="color: maroon;">script</span> <span style="color: red;">type</span><span style="color: blue;">=</span><span style="color: blue;">"text/javascript"</span><span style="color: blue;">></span> $(document).ready(<span style="color: blue;">function</span> () { $(<span style="color: #a31515;">'#fileupload'</span>).fileupload({ dataType: <span style="color: #a31515;">'json'</span>, url: <span style="color: #a31515;">'/Home/UploadFiles'</span>, autoUpload: <span style="color: blue;">true</span>, done: <span style="color: blue;">function</span> (e, data) { $(<span style="color: #a31515;">'.file_name'</span>).html(data.result.name); $(<span style="color: #a31515;">'.file_type'</span>).html(data.result.type); $(<span style="color: #a31515;">'.file_size'</span>).html(data.result.size); } }).on(<span style="color: #a31515;">'fileuploadprogressall'</span>, <span style="color: blue;">function</span> (e, data) { <span style="color: blue;">var</span> progress = parseInt(data.loaded / data.total * 100, 10); $(<span style="color: #a31515;">'.progress .progress-bar'</span>).css(<span style="color: #a31515;">'width'</span>, progress + <span style="color: #a31515;">'%'</span>); }); }); <span style="color: blue;"><span style="color: maroon;">script</span><span style="color: blue;">></span> </span></pre> <p>É isso. Agora você está pronto pra colocar esse recurso no seu site. E sem postback!</p> <p>Você pode baixar o código aqui: <a href="/file/articles/jQueryFileUploadMVC4.zip">jQueryFileUploadMVC4.zip (5.84 MB)</a>. Sim, quase 6MB, graças aos packages do NuGet.</p> Sun, 03 Nov 2013 02:00:00 GMT http://davidsonsousa.net/blog/post/como-fazer-upload-de-arquivos-usando-aspnet-mvc-3-e-ajax How to upload a file using ASP.NET MVC and AJAX http://davidsonsousa.net/blog/post/how-to-upload-a-file-using-mvc-3-and-ajax <p>I've decided to get my old <strong>upload</strong> post and upgrade the components I am using. For example: Before it was an MVC3 project made on Visual Studio 2010 using the old version of everything. Now it's a <strong>Visual Studio 2012</strong> project, <strong>ASP.NET MVC4</strong>, using <strong>bootstrap</strong> and the newest version of each plugin I've used before.</p> <h3>First step</h3> <p>First of all we need to create a Model just like <a href="http://www.hanselman.com/blog/ABackToBasicsCaseStudyImplementingHTTPFileUploadWithASPNETMVCIncludingTestsAndMocks.aspx">Scott Hanselman made in his article</a>. Then we will have the name, length and type of our file:</p> <pre style="font-family: Consolas; font-size: 13; color: black; background: white;"><span style="color: blue;">public</span> <span style="color: blue;">class</span> <span style="color: #2b91af;">UploadFilesResult</span> { <span style="color: blue;">public</span> <span style="color: blue;">string</span> Name { <span style="color: blue;">get</span>; <span style="color: blue;">set</span>; } <span style="color: blue;">public</span> <span style="color: blue;">int</span> Length { <span style="color: blue;">get</span>; <span style="color: blue;">set</span>; } <span style="color: blue;">public</span> <span style="color: blue;">string</span> Type { <span style="color: blue;">get</span>; <span style="color: blue;">set</span>; } } </pre> <h3>Second step</h3> <p>We will need to create an <a href="http://msdn.microsoft.com/en-us/library/dd410269.aspx"><strong>Action Method</strong></a> which will take care of the upload. It will be called by using the http <strong>POST</strong> method, get the list of selected files and save into <strong>App_Data</strong>. This <strong>Action Method </strong>should return a json informing the name, length and type of the files:</p> <pre style="font-family: Consolas; font-size: 13; color: black; background: white;">[<span style="color: #2b91af;">HttpPost</span>] <span style="color: blue;">public</span> <span style="color: #2b91af;">ContentResult</span> UploadFiles() { <span style="color: blue;">var</span> r = <span style="color: blue;">new</span> <span style="color: #2b91af;">List</span><<span style="color: #2b91af;">ViewDataUploadFilesResult</span>>(); <span style="color: blue;">foreach</span> (<span style="color: blue;">string</span> file <span style="color: blue;">in</span> Request.Files) { <span style="color: #2b91af;">HttpPostedFileBase</span> hpf = Request.Files[file] <span style="color: blue;">as</span> <span style="color: #2b91af;">HttpPostedFileBase</span>; <span style="color: blue;">if</span> (hpf.ContentLength == 0) <span style="color: blue;">continue</span>; <span style="color: blue;">string</span> savedFileName = <span style="color: #2b91af;">Path</span>.Combine(Server.MapPath(<span style="color: #a31515;">"~/App_Data"</span>), <span style="color: #2b91af;">Path</span>.GetFileName(hpf.FileName)); hpf.SaveAs(savedFileName); <span style="color: green;">// Save the file</span> r.Add(<span style="color: blue;">new</span> <span style="color: #2b91af;">ViewDataUploadFilesResult</span>() { Name = hpf.FileName, Length = hpf.ContentLength, Type = hpf.ContentType }); } <span style="color: green;">// Returns json</span> <span style="color: blue;">return</span> Content(<span style="color: #a31515;">"{\"name\":\""</span> + r[0].Name + <span style="color: #a31515;">"\",\"type\":\""</span> + r[0].Type + <span style="color: #a31515;">"\",\"size\":\""</span> + <span style="color: blue;">string</span>.Format(<span style="color: #a31515;">"{0} bytes"</span>, r[0].Length) + <span style="color: #a31515;">"\"}"</span>, <span style="color: #a31515;">"application/json"</span>); } </pre> <h3>Third step</h3> <p>After that we only need to download a <strong>jQuery</strong> plugin called <a href="https://github.com/blueimp/jQuery-File-Upload">jQuery File Upload</a>. It brings us lots of cool stuff but, for the sake of simplicity, we are gonna use only 2 files (apart from the others I am already using): <em>jquery.fileupload.css</em> and <em>jquery.fileupload.js</em>:</p> <h3>Fourth step</h3> <p>We need now a way to send these files. This is what I've created - just for the upload - but you can adapt into your page:</p> <pre style="background: white; color: black; font-family: Consolas; font-size: 13px;"><span style="color: blue;"><</span><span style="color: maroon;">div</span> <span style="color: red;">class</span><span style="color: blue;">=</span><span style="color: blue;">"container"</span><span style="color: blue;">></span> <span style="color: blue;"><</span><span style="color: maroon;">span</span> <span style="color: red;">class</span><span style="color: blue;">=</span><span style="color: blue;">"btn btn-success fileinput-button"</span><span style="color: blue;">></span> <span style="color: blue;"><</span><span style="color: maroon;">i</span> <span style="color: red;">class</span><span style="color: blue;">=</span><span style="color: blue;">"glyphicon glyphicon-plus"</span><span style="color: blue;">><span style="color: maroon;">i</span><span style="color: blue;">></span> <span style="color: blue;"><</span><span style="color: maroon;">span</span><span style="color: blue;">></span>Add files...<span style="color: blue;"><span style="color: maroon;">span</span><span style="color: blue;">></span> <span style="color: blue;"><</span><span style="color: maroon;">input</span> <span style="color: red;">id</span><span style="color: blue;">=</span><span style="color: blue;">"fileupload"</span> <span style="color: red;">type</span><span style="color: blue;">=</span><span style="color: blue;">"file"</span> <span style="color: red;">name</span><span style="color: blue;">=</span><span style="color: blue;">"files[]"</span> <span style="color: red;">multiple</span><span style="color: blue;">></span> <span style="color: blue;"><span style="color: maroon;">span</span><span style="color: blue;">></span> <span style="color: blue;"><</span><span style="color: maroon;">br</span> <span style="color: blue;">/></span> <span style="color: blue;"><</span><span style="color: maroon;">div</span> <span style="color: red;">class</span><span style="color: blue;">=</span><span style="color: blue;">"progress"</span><span style="color: blue;">></span> <span style="color: blue;"><</span><span style="color: maroon;">div</span> <span style="color: red;">class</span><span style="color: blue;">=</span><span style="color: blue;">"progress-bar"</span> <span style="color: red;">role</span><span style="color: blue;">=</span><span style="color: blue;">"progressbar"</span> <span style="color: red;">aria-valuenow</span><span style="color: blue;">=</span><span style="color: blue;">"0"</span> <span style="color: red;">aria-valuemin</span><span style="color: blue;">=</span><span style="color: blue;">"0"</span> <span style="color: red;">aria-valuemax</span><span style="color: blue;">=</span><span style="color: blue;">"100"</span> <span style="color: red;">style</span><span style="color: blue;">=</span><span style="color: blue;">"</span><span style="color: red;">width</span>: <span style="color: blue;">0%</span>;<span style="color: blue;">"</span><span style="color: blue;">></span> <span style="color: blue;"><</span><span style="color: maroon;">span</span> <span style="color: red;">class</span><span style="color: blue;">=</span><span style="color: blue;">"sr-only"</span><span style="color: blue;">></span>0% complete<span style="color: blue;"><span style="color: maroon;">span</span><span style="color: blue;">></span> <span style="color: blue;"><span style="color: maroon;">div</span><span style="color: blue;">></span> <span style="color: blue;"><span style="color: maroon;">div</span><span style="color: blue;">></span> <span style="color: blue;"><</span><span style="color: maroon;">br</span> <span style="color: blue;">/></span> <span style="color: blue;"><</span><span style="color: maroon;">div</span> <span style="color: red;">class</span><span style="color: blue;">=</span><span style="color: blue;">"file_name"</span><span style="color: blue;">><span style="color: maroon;">div</span><span style="color: blue;">></span> <span style="color: blue;"><</span><span style="color: maroon;">br</span> <span style="color: blue;">/></span> <span style="color: blue;"><</span><span style="color: maroon;">div</span> <span style="color: red;">class</span><span style="color: blue;">=</span><span style="color: blue;">"file_type"</span><span style="color: blue;">><span style="color: maroon;">div</span><span style="color: blue;">></span> <span style="color: blue;"><</span><span style="color: maroon;">br</span> <span style="color: blue;">/></span> <span style="color: blue;"><</span><span style="color: maroon;">div</span> <span style="color: red;">class</span><span style="color: blue;">=</span><span style="color: blue;">"file_size"</span><span style="color: blue;">><span style="color: maroon;">div</span><span style="color: blue;">></span> <span style="color: blue;"><span style="color: maroon;">div</span><span style="color: blue;">></span> </span></span></span></span></span></span></span></span></span></span></pre> <p>Notice 4 things:</p> <ol> <li>I didn't use <strong>HtmlHelper</strong> to create the form. The reason is the ease to create the form without it. Also, we don't need to use HtmlHelpers all the time;</li> <li>I am <strong>not using a form tag</strong>. The plugin takes care of everything;</li> <li>The progress bar, thanks to <a href="http://getbootstrap.com/components/#progress">bootstrap</a>;</li> <li>The <em>divs</em> at the end, which will only receive the json data.</li> </ol> <h3>Last step</h3> <p>Now we need to make the javascript in order to make this work. I am using the jQuery File Upload plugin calling the Action Method <strong>UploadFiles</strong> created in the <strong>HomeController</strong>. In addition I have also attached an event which shows the upload status to the user by using the bootstrap progressbar component:</p> <pre style="background: white; color: black; font-family: Consolas; font-size: 13px;"><span style="color: blue;"><</span><span style="color: maroon;">script</span> <span style="color: red;">type</span><span style="color: blue;">=</span><span style="color: blue;">"text/javascript"</span><span style="color: blue;">></span> $(document).ready(<span style="color: blue;">function</span> () { $(<span style="color: #a31515;">'#fileupload'</span>).fileupload({ dataType: <span style="color: #a31515;">'json'</span>, url: <span style="color: #a31515;">'/Home/UploadFiles'</span>, autoUpload: <span style="color: blue;">true</span>, done: <span style="color: blue;">function</span> (e, data) { $(<span style="color: #a31515;">'.file_name'</span>).html(data.result.name); $(<span style="color: #a31515;">'.file_type'</span>).html(data.result.type); $(<span style="color: #a31515;">'.file_size'</span>).html(data.result.size); } }).on(<span style="color: #a31515;">'fileuploadprogressall'</span>, <span style="color: blue;">function</span> (e, data) { <span style="color: blue;">var</span> progress = parseInt(data.loaded / data.total * 100, 10); $(<span style="color: #a31515;">'.progress .progress-bar'</span>).css(<span style="color: #a31515;">'width'</span>, progress + <span style="color: #a31515;">'%'</span>); }); }); <span style="color: blue;"><span style="color: maroon;">script</span><span style="color: blue;">></span> </span></pre> <p>That's it. Now you are ready to add this feature to your website, without any postback.</p> <p>Download the code here: <a href="/file/articles/jQueryFileUploadMVC4.zip">jQueryFileUploadMVC4.zip (5.84 MB)</a>. Yes, almost 6MB thanks to the packages.</p> Sun, 06 Oct 2013 06:30:00 GMT http://davidsonsousa.net/blog/post/how-to-upload-a-file-using-mvc-3-and-ajax How to reduce the size of a word document by optimizing the images in 5 easy steps http://davidsonsousa.net/blog/post/how-to-reduce-the-size-of-a-word-document-by-optimizing-the-images-in-5-easy-steps <p>Some time ago, I got a <strong>word document</strong> with around 36 MB and a request to <strong>resize</strong> this file in order to be <strong>lighter</strong> as it be sent via e-mail. The first thing I thought was the obvious: Why not compact the file? I use <a href="http://www.7-zip.org/">7-zip</a>, which is the best compression utility I have ever used. It did not work as expected since the file went down to 30 MB.</p> <h3>The problem&nbsp;</h3> <p>When I&rsquo;ve opened the document I could see that it had only 10 pages, each with 2 images. So it could be possible the images were way too heavy, meaning, not optimized for internet or text documents. Do you know those people who take a picture using all megapixels of the digital camera and start to send those 4 MB files to everybody? This was more or less the case.</p> <h3>The solution</h3> <p>It&rsquo;s simple: All we need is to reduce the dimensions of the images in the word document. But I am not saying about simply resizing, but editing. By editing we will be able to reduce every of those heavy images into something more acceptable. For that, I will use my favorite image visualizer, the <a href="http://www.xnview.com/en/index.php">XnView</a>.</p> <p>So, with the word document open:</p> <ol> <li> <p>Right click on the image, select &ldquo;Save as picture&hellip;&rdquo;, define a name and save itd</p> </li> <li> <p>Open the saved image in the XnView</p> </li> <li> <p>Click on the menu &ldquo;Image&rdquo; and then &ldquo;Resize&rdquo; (or Shift + S)</p> </li> <li> <p>Choose the appropriated size and press Ok. Here is a bit tricky since it depends on the width/height the image actually should have according to your word document</p> </li> <li> <p>Save the image (File -&gt; Save or Ctrl + S)</p> </li> </ol> <p>I&rsquo;ve used 800 x 400 with this image and its size decreased from 7 MB to 65 KB. Now it is only about deleting the huge picture from the word document and add the new resized one. The result is a document with 78 KB, which is much better to send around the internet.</p> <p><em>Note: This problem is going to happen if you insert the images by drag &amp; drop. If you use the menu (Insert -&gt; Pictures) the image will go through a process of optimization and the document will not be so heavy.</em></p> Thu, 26 Sep 2013 17:00:00 GMT http://davidsonsousa.net/blog/post/how-to-reduce-the-size-of-a-word-document-by-optimizing-the-images-in-5-easy-steps Por que escolhi trabalhar com ASP.NET? http://davidsonsousa.net/blog/post/por-que-escolhi-trabalhar-com-aspnet <p>Acho que j&aacute; est&aacute; mais do que claro que eu sou focado nas tecnologias Microsoft e, sendo mais espec&iacute;fico, em ASP.NET. Como muita gente me pergunta porque segui este caminho resolvi criar um artigo contando mais ou menos o que aconteceu para eu chegar no combo ASP.NET / C#. Ah sim, &eacute; bom adiantar que n&atilde;o vou entrar em detalhes t&eacute;cnicos neste texto.</p> <p>Tudo come&ccedil;ou l&aacute; pelo ano 2000, quando estava terminando o segundo grau t&eacute;cnico. Na &eacute;poca eu estava estudando <a href="http://en.wikipedia.org/wiki/Embarcadero_Delphi">Delphi</a> e <a href="http://en.wikipedia.org/wiki/Visual_Basic">Visual Basic (VB)</a> enquanto era muito curioso com rela&ccedil;&atilde;o a web. Nada de servidores ou rede e sim como as p&aacute;ginas funcionavam. Por&eacute;m, o que eu sabia de web na &eacute;poca era o b&aacute;sico de HTML, zero de Javascript e menos ainda de CSS. Se falarmos de linguagem de servidor eu citaria o <a href="http://en.wikipedia.org/wiki/Common_Gateway_Interface">CGI</a> mas s&oacute; porque um colega de classe enchia o saco falando que ele fez um formul&aacute;rio de contato, formul&aacute;rio de cadastro e por a&iacute; vai. Enquanto isso eu tinha um site com 5 p&aacute;ginas no <a href="http://www.forumcpanel.com.br/topic/9261-portal-de-hospedagem-gratis-hpg-chega-ao-fim/">HPG</a>.</p> <p>S&oacute; fui perceber que a web seria algo que teria mercado bem no final do curso. E o caminho natural foi o ASP cl&aacute;ssico j&aacute; que eu sabia VB. Veja bem: Eu gostava mais de Delphi do que de VB. Descontando o fato de ter sido apresentado antes para o ASP do que para o PHP, o que me ajudou nessa migra&ccedil;&atilde;o foi o finado <a href="http://en.wikipedia.org/wiki/Microsoft_FrontPage">Front Page 2000</a>. Na &eacute;poca bastava ter um banco de dados Access que ele o leria e criaria o formul&aacute;rio para, depois, s&oacute; precisar de uma customiza&ccedil;&atilde;o b&aacute;sica. Algo que o ASP.NET MVC tem hoje e a Microsoft chama de <a href="http://blog.stevensanderson.com/2011/01/13/scaffold-your-aspnet-mvc-3-project-with-the-mvcscaffolding-package/">scaffolding</a>.</p> <p>Da&iacute; eu resolvi investir: Comprei um <a href="http://www.wook.pt/ficha/asp-3-guia-de-referencia/a/id/88785">livro de ASP 3</a> (era esse mesmo do link!!). Apesar de n&atilde;o ter avan&ccedil;ado tanto quanto gostaria eu tive uma boa no&ccedil;&atilde;o de qu&atilde;o ruim era o ASP. E juro que desanimei depois de um tempo. Nem tanto pela qualidade duvidosa do ASP 3 (quem se lembra do erro &ldquo;<a href="http://forum.wmonline.com.br/topic/133552-eram-esperados-1-s/">Par&acirc;metros insuficientes. Eram esperados 1</a>"?), mas pela p&eacute;ssima qualidade do mercado de desenvolvimento web em Vit&oacute;ria. Naquela &eacute;poca eu me sentia muito confort&aacute;vel por l&aacute;. N&atilde;o me via saindo da casa da minha m&atilde;e e indo pra S&atilde;o Paulo, por exemplo. Ou at&eacute; mesmo pra outro pa&iacute;s. E foi justamente nesse per&iacute;odo sab&aacute;tico de programa&ccedil;&atilde;o que <a href="http://en.wikipedia.org/wiki/.NET_Framework#History">saiu o .NET Framework</a>.</p> <p>J&aacute; na Pol&ocirc;nia, em 2006, eu comecei a me reciclar e percebi que tinha que aprender muito mais do que eu achava que deveria: ASP.NET, AJAX, C#, HTML avan&ccedil;ado, CSS e por a&iacute; vai.</p> <p>N&atilde;o foi f&aacute;cil.</p> <p>S&oacute; que a partir da&iacute; o caminho foi mais natural e a Microsoft ajudou bastante com isso. Para quem n&atilde;o sabe ela facilita muito na hora de se come&ccedil;ar a desenvolver um projeto. As op&ccedil;&otilde;es que o Visual Studio tem para um projeto web, por exemplo, s&atilde;o bem variadas. E boa parte das bibliotecas Javascript necess&aacute;rias j&aacute; s&atilde;o copiadas por padr&atilde;o durante a cria&ccedil;&atilde;o do projeto. Some isso ao fato do Visual Studio ter o <a href="http://davidsonsousa.net/pt/post/o-que-e-e-como-instalar-pacotes-usando-o-nuget-usando-o-visual-studio-2010">Nuget facilitando na hora de adicionar novas bibliotecas</a>.</p> <p>Sem falar do pr&oacute;prio .NET Framework que j&aacute; existe em todas as m&aacute;quinas que rodam Windows.</p> <p>Em 2012 eu tirei meu MCT e passei 6 meses dando aula em S&atilde;o Paulo. Tive a oportunidade de conhecer gente de v&aacute;rios n&iacute;veis &ndash; b&aacute;sico a avan&ccedil;ado &ndash; que trabalhavam nas mais variadas tecnologias. Foi &oacute;timo pois me deu uma boa vis&atilde;o de como anda o mercado ASP.NET no Brasil: Paga bem, mas tem que conhecer v&aacute;rias tecnologias diferentes. O m&iacute;nimo que um programador ASP.NET normalmente tem que saber &eacute;: ASP.NET/C#, Web Forms/MVC, Javascript, CSS, SQL Server. Variando de b&aacute;sico pra avan&ccedil;ado, al&eacute;m de ter conhecimento te&oacute;rico e pr&aacute;tico.</p> <p>Enfim... &Eacute; bom deixar claro que n&atilde;o estou dizendo que ASP.NET &eacute; melhor do que o que existe por a&iacute;. ASP.NET &eacute; melhor pra mim pois ela quem valorizou meu curr&iacute;culo, al&eacute;m de pagar minhas contas no fim do m&ecirc;s.</p> Mon, 02 Sep 2013 16:15:57 GMT http://davidsonsousa.net/blog/post/por-que-escolhi-trabalhar-com-aspnet Horizontal scrolling with jQuery http://davidsonsousa.net/blog/post/horizontal-scrolling-with-jquery <p>I've got a freelance job from a Brazilian company few days ago. The project is fine, nothing so different than the usual. Except for one thing: They want the page to <strong>scroll horizontally</strong>.</p> <p>The clients are getting creative these days...</p> <p>My biggest problem is the main menu: If the page would be normal I could use anchor. But I can't since anchors don't work on the horizontal.</p> <p>Fortunatelly the solution is easy: <a href="http://api.jquery.com/scrollLeft/">.scrollLeft()</a></p> <p>What <em>.scrollLeft()</em> does is simple: It returns the position of the horizontal&nbsp;scroll bar. And if we pass a parameter it will set the scroll bar where we want.</p> <p>I have an example on how it's done. Let's walk through it:</p> <h2>HTML</h2> <p>Very simple, no problem at all. Only one navigation and a couple of divs just to give something to work with:</p> <pre style="background: white; color: black; font-family: Consolas; font-size: 10pt;"><span style="color: #4f76ac;">&lt;</span><span style="color: #823125;">header</span><span style="color: #4f76ac;">&gt;</span> <span style="color: #4f76ac;">&lt;</span><span style="color: #823125;">nav</span><span style="color: #4f76ac;">&gt;</span> <span style="color: #4f76ac;">&lt;</span><span style="color: #823125;">ul</span><span style="color: #4f76ac;">&gt;</span> <span style="color: #4f76ac;">&lt;</span><span style="color: #823125;">li</span><span style="color: #4f76ac;">&gt;&lt;</span><span style="color: #823125;">a</span> <span style="color: #cf4820;">class</span><span style="color: #4f76ac;">=</span><span style="color: #4f76ac;">"nav-item1"</span> <span style="color: #cf4820;">href</span><span style="color: #4f76ac;">=</span><span style="color: #4f76ac;">"#"</span><span style="color: #4f76ac;">&gt;</span>Item 1<span style="color: #4f76ac;">&lt;/</span><span style="color: #823125;">a</span><span style="color: #4f76ac;">&gt;&lt;/</span><span style="color: #823125;">li</span><span style="color: #4f76ac;">&gt;</span> <span style="color: #4f76ac;">&lt;</span><span style="color: #823125;">li</span><span style="color: #4f76ac;">&gt;&lt;</span><span style="color: #823125;">a</span> <span style="color: #cf4820;">class</span><span style="color: #4f76ac;">=</span><span style="color: #4f76ac;">"nav-item2"</span> <span style="color: #cf4820;">href</span><span style="color: #4f76ac;">=</span><span style="color: #4f76ac;">"#"</span><span style="color: #4f76ac;">&gt;</span>Item 2<span style="color: #4f76ac;">&lt;/</span><span style="color: #823125;">a</span><span style="color: #4f76ac;">&gt;&lt;/</span><span style="color: #823125;">li</span><span style="color: #4f76ac;">&gt;</span> <span style="color: #4f76ac;">&lt;</span><span style="color: #823125;">li</span><span style="color: #4f76ac;">&gt;&lt;</span><span style="color: #823125;">a</span> <span style="color: #cf4820;">class</span><span style="color: #4f76ac;">=</span><span style="color: #4f76ac;">"nav-item3"</span> <span style="color: #cf4820;">href</span><span style="color: #4f76ac;">=</span><span style="color: #4f76ac;">"#"</span><span style="color: #4f76ac;">&gt;</span>Item 3<span style="color: #4f76ac;">&lt;/</span><span style="color: #823125;">a</span><span style="color: #4f76ac;">&gt;&lt;/</span><span style="color: #823125;">li</span><span style="color: #4f76ac;">&gt;</span> <span style="color: #4f76ac;">&lt;/</span><span style="color: #823125;">ul</span><span style="color: #4f76ac;">&gt;</span> <span style="color: #4f76ac;">&lt;/</span><span style="color: #823125;">nav</span><span style="color: #4f76ac;">&gt;</span> <span style="color: #4f76ac;">&lt;/</span><span style="color: #823125;">header</span><span style="color: #4f76ac;">&gt;</span> <span style="color: #4f76ac;">&lt;</span><span style="color: #823125;">section</span><span style="color: #4f76ac;">&gt;</span> <span style="color: #4f76ac;">&lt;</span><span style="color: #823125;">div</span> <span style="color: #cf4820;">class</span><span style="color: #4f76ac;">=</span><span style="color: #4f76ac;">"item item1"</span><span style="color: #4f76ac;">&gt;</span>Item 1<span style="color: #4f76ac;">&lt;/</span><span style="color: #823125;">div</span><span style="color: #4f76ac;">&gt;</span> <span style="color: #4f76ac;">&lt;</span><span style="color: #823125;">div</span> <span style="color: #cf4820;">class</span><span style="color: #4f76ac;">=</span><span style="color: #4f76ac;">"item item2"</span><span style="color: #4f76ac;">&gt;</span>Item 2<span style="color: #4f76ac;">&lt;/</span><span style="color: #823125;">div</span><span style="color: #4f76ac;">&gt;</span> <span style="color: #4f76ac;">&lt;</span><span style="color: #823125;">div</span> <span style="color: #cf4820;">class</span><span style="color: #4f76ac;">=</span><span style="color: #4f76ac;">"item item3"</span><span style="color: #4f76ac;">&gt;</span>Item 3<span style="color: #4f76ac;">&lt;/</span><span style="color: #823125;">div</span><span style="color: #4f76ac;">&gt;</span> <span style="color: #4f76ac;">&lt;/</span><span style="color: #823125;">section</span><span style="color: #4f76ac;">&gt;</span> </pre> <h2>CSS</h2> <p>The CSS is very basic, just to give some formatting:</p> <pre style="background: white; color: black; font-family: Consolas; font-size: 10pt;"><span style="color: #4f76ac;">&lt;</span><span style="color: #823125;">style</span> <span style="color: #cf4820;">type</span><span style="color: #4f76ac;">=</span><span style="color: #4f76ac;">"text/css"</span><span style="color: #4f76ac;">&gt;</span> <span style="color: #823125;">nav</span> <span style="color: #222222;">{</span> <span style="color: #cf4820;">position</span>: <span style="color: #4f76ac;">fixed</span>; <span style="color: #cf4820;">z-index</span>: <span style="color: #4f76ac;">1030</span>; <span style="color: #222222;">}</span> <span style="color: #823125;">section</span> <span style="color: #222222;">{</span> <span style="color: #cf4820;">width</span>: <span style="color: #4f76ac;">3600</span><span style="color: #4f76ac;">px</span>; <span style="color: #cf4820;">top</span>: <span style="color: #4f76ac;">100</span><span style="color: #4f76ac;">px</span>; <span style="color: #cf4820;">position</span>: <span style="color: #4f76ac;">relative</span>; <span style="color: #cf4820;">overflow</span>: <span style="color: #4f76ac;">auto</span>; <span style="color: #222222;">}</span> <span style="color: #823125;">.item</span><span style="color: #222222;">{</span> <span style="color: #cf4820;">float</span>: <span style="color: #4f76ac;">left</span>; <span style="color: #cf4820;">position</span>: <span style="color: #4f76ac;">relative</span>; <span style="color: #cf4820;">width</span>: <span style="color: #4f76ac;">900</span><span style="color: #4f76ac;">px</span>; <span style="color: #cf4820;">height</span>: <span style="color: #4f76ac;">500</span><span style="color: #4f76ac;">px</span>; <span style="color: #cf4820;">font-size</span>: <span style="color: #4f76ac;">200</span><span style="color: #4f76ac;">px</span>; <span style="color: #222222;">}</span> <span style="color: #823125;">.item1</span> <span style="color: #222222;">{</span> <span style="color: #cf4820;">background</span>: <span style="color: #4f76ac;">#f00</span>; <span style="color: #222222;">}</span> <span style="color: #823125;">.item2</span> <span style="color: #222222;">{</span> <span style="color: #cf4820;">background</span>: <span style="color: #4f76ac;">#0f0</span>; <span style="color: #222222;">}</span> <span style="color: #823125;">.item3</span> <span style="color: #222222;">{</span> <span style="color: #cf4820;">background</span>: <span style="color: #4f76ac;">#00f</span>; <span style="color: #222222;">}</span> <span style="color: #4f76ac;">&lt;/</span><span style="color: #823125;">style</span><span style="color: #4f76ac;">&gt;</span> </pre> <h2>Javascript</h2> <p>Since we have 3 items I've created a function which groups everything. In that way I am able to keep the code clean, without repeating important parts:</p> <pre style="background: white; color: black; font-family: Consolas; font-size: 10pt;"><span style="color: #4f76ac;">function</span> horizontalNavigation<span style="color: #1e7c70;">(</span>position<span style="color: #1e7c70;">,</span> event<span style="color: #1e7c70;">)</span> <span style="color: #1e7c70;">{</span> $<span style="color: #1e7c70;">(</span><span style="color: #823125;">'html'</span><span style="color: #1e7c70;">)</span>.scrollLeft<span style="color: #1e7c70;">(</span>position<span style="color: #1e7c70;">);</span> event.preventDefault<span style="color: #1e7c70;">();</span> <span style="color: #1e7c70;">}</span> </pre> <p>And here is where the magic happens:</p> <pre style="background: white; color: black; font-family: Consolas; font-size: 10pt;">$<span style="color: #1e7c70;">(</span><span style="color: #823125;">'.nav-item1'</span><span style="color: #1e7c70;">)</span>.click<span style="color: #1e7c70;">(</span><span style="color: #4f76ac;">function</span> <span style="color: #1e7c70;">(</span>event<span style="color: #1e7c70;">)</span> <span style="color: #1e7c70;">{</span> horizontalNavigation<span style="color: #1e7c70;">(</span><span style="color: #9b5f9b;">0</span><span style="color: #1e7c70;">,</span> event<span style="color: #1e7c70;">);</span> <span style="color: #1e7c70;">});</span> $<span style="color: #1e7c70;">(</span><span style="color: #823125;">'.nav-item2'</span><span style="color: #1e7c70;">)</span>.click<span style="color: #1e7c70;">(</span><span style="color: #4f76ac;">function</span> <span style="color: #1e7c70;">(</span>event<span style="color: #1e7c70;">)</span> <span style="color: #1e7c70;">{</span> horizontalNavigation<span style="color: #1e7c70;">(</span><span style="color: #9b5f9b;">900</span><span style="color: #1e7c70;">,</span> event<span style="color: #1e7c70;">);</span> <span style="color: #1e7c70;">});</span> $<span style="color: #1e7c70;">(</span><span style="color: #823125;">'.nav-item3'</span><span style="color: #1e7c70;">)</span>.click<span style="color: #1e7c70;">(</span><span style="color: #4f76ac;">function</span> <span style="color: #1e7c70;">(</span>event<span style="color: #1e7c70;">)</span> <span style="color: #1e7c70;">{</span> horizontalNavigation<span style="color: #1e7c70;">(</span><span style="color: #9b5f9b;">1800</span><span style="color: #1e7c70;">,</span> event<span style="color: #1e7c70;">);</span> <span style="color: #1e7c70;">});</span> </pre> <p><a href="http://jsfiddle.net/davidsonsousa/jbGHA/">See the working example</a>.</p> <p>There is only one problem with this code: What if I want to have a smoothly horizontal scrolling? For that we can use <a href="http://api.jquery.com/animate/">.animate()</a>. Solution in bold&nbsp;bellow:</p> <pre style="background: white; color: black; font-family: Consolas; font-size: 10pt;"><span style="color: #4f76ac;">function</span> horizontalNavigation<span style="color: #1e7c70;">(</span>position<span style="color: #1e7c70;">,</span> event<span style="color: #1e7c70;">)</span> <span style="color: #1e7c70;">{</span> <strong>$<span style="color: #1e7c70;">(</span><span style="color: #823125;">'html'</span><span style="color: #1e7c70;">)</span>.animate<span style="color: #1e7c70;">({</span>scrollLeft<span style="color: #1e7c70;">:</span> position<span style="color: #1e7c70;">},</span> <span style="color: #9b5f9b;">800</span></strong><span style="color: #1e7c70;"><strong>);</strong><br /></span> event.preventDefault<span style="color: #1e7c70;">();</span> <span style="color: #1e7c70;">}</span> </pre> <p><a href="http://jsfiddle.net/davidsonsousa/KVs94/">See the working example</a>.</p> <p>As you can see it is not so complicated as it looks. Just a bit of work, but quite easy.</p> Sat, 24 Aug 2013 20:14:00 GMT http://davidsonsousa.net/blog/post/horizontal-scrolling-with-jquery How to uncheck all radio buttons and checkboxes using jQuery http://davidsonsousa.net/blog/post/how-to-uncheck-all-radio-buttons-and-checkboxes-using-jquery <p><strong>- UPDATE -</strong></p> <p>My friend Wellington sent me this code right after I've published this post:</p> <pre style="font-family: Consolas; font-size: 13px;"><strong>$(<span style="color: #a31515;">'input:checked'</span>).removeAttr(<span style="color: #a31515;">'checked'</span>);</strong></pre> <p>This should get all the checked items and remove the "checked" attribute.</p> <p><strong>- Original post -</strong></p> <p>Recently I have come across a very interesting problem in a project I am working on. I had to <strong>uncheck all checkboxes</strong> at once. It was fine by using a simple <a href="http://api.jquery.com/jQuery.each/">.each</a> on <a href="http://jquery.com/">jQuery</a>. After that the requirements changed and I had to add radio buttons and they weren't working with the code I already had. That was fixed with one more line. Let's see how it was done.</p> <p>Suppose I have 3 checkboxes and I want to clear all of them at once. Normally I would do something like this:</p> <pre style="background: white; color: black; font-family: Consolas; font-size: 13px;">$(<span style="color: #a31515;">'#clear-all'</span>).click(<span style="color: blue;">function</span> () { $(<span style="color: #a31515;">':checkbox'</span>).each(<span style="color: blue;">function</span> () { $(<span style="color: blue;">this</span>).removeAttr(<span style="color: #a31515;">'checked'</span>); }) }); </pre> <p>Very simple, very generic and it works like a charm. However, suppose that I have to add some radio buttons. The code above will not work with radio buttons, as mentioned before. If you want to <strong>uncheck all the radio buttons and checkboxes</strong> you will need to add one single line (in bold):</p> <pre style="background: white; color: black; font-family: Consolas; font-size: 13px;">$(<span style="color: #a31515;">'#clear-all'</span>).click(<span style="color: blue;">function</span> () { $(<span style="color: #a31515;">':checkbox'</span>).each(<span style="color: blue;">function</span> () { $(<span style="color: blue;">this</span>).removeAttr(<span style="color: #a31515;">'checked'</span>); <strong>$(<span style="color: #a31515;">'input[type="radio"]'</span>).prop(<span style="color: #a31515;">'checked'</span>, <span style="color: blue;">false</span>); </strong> }) }); </pre> <p>According to jQuery website the <a href="http://api.jquery.com/prop/">.prop</a> is gets the value of a property for the first element in the set of matched elements or set one or more properties for every matched element. In another words it will look for the "checked" property and, if you want, it can change its value as well.</p> <p>Easy, simple and clean.</p> Mon, 19 Aug 2013 18:41:00 GMT http://davidsonsousa.net/blog/post/how-to-uncheck-all-radio-buttons-and-checkboxes-using-jquery How to insert many records into the database using Entity Framework (bulk insert) http://davidsonsousa.net/blog/post/how-to-insert-a-many-records-into-the-database-using-entity-framework <p><a href="http://msdn.microsoft.com/en-us/library/bb399572.aspx"><strong>Entity Framework</strong></a> (EF) is a Microsoft ORM which allows programmers to develop against a <strong>conceptual data model</strong> instead of developing anything inside the database. In this way any change done in this conceptual data model must be persisted as this is not done automatically. For EF we have to use <a href="http://msdn.microsoft.com/en-us/library/bb336792.aspx">SaveChanges</a>.</p> <p>To understand EF is simple: A SQL script is generated for every action done against the conceptual model. For example: In case we want to add some record into the <em>User</em> table. For that we would have to use the <a href="http://msdn.microsoft.com/en-us/library/system.data.objects.objectcontext.addobject.aspx">AddObject</a> method and pass the properties of the <em>User</em> (name, surname, etc) along. Behind the scenes the EF will generate an INSERT and will execute it in the database with the properties of <em>User</em>.</p> <p>And what about inserting 3.000 records at once?</p> <p>In this case we have 2 options:</p> <ol> <li>We do a loop and use AddObject for every one of the 3.000 records (not recommended)</li> <li>We use a class called <a href="http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlbulkcopy.aspx">SqlBulkCopy</a> (deeply recommended)</li> </ol> <p>But why?</p> <p>The EF doesn't have a native method in case we want to make a bulk insert but, as it was built on top of ADO.NET, there is no problem to use SqlBulkCopy. Not to mention the performance gain if we compare with the multiple INSERTs.</p> <p>An example of <strong>SqlBulkCopy</strong>:</p> <p> <script src="https://gist.github.com/davidsonsousa/0686df47ce804d98a824.js"></script> </p> <p>Let's just hope Microsoft will add a similar feature into the Entity Framework in the future.</p> Sat, 10 Aug 2013 18:47:00 GMT http://davidsonsousa.net/blog/post/how-to-insert-a-many-records-into-the-database-using-entity-framework How to drive a web developer crazy in 20 easy steps http://davidsonsousa.net/blog/post/20-things-that-drive-web-developers-crazy <p style="text-align: left;">Let me tell you something: Once upon a time, <a href="http://davidsonsousa.net/page/about-me">I wanted to be a biologist</a>. That was a long time ago. Then things changed and I became a programmer. Not bad for someone who wanted to make research the whole day but did not have enough patience for the results.</p> <p class="MsoNormal">Little I knew about the problems I would face as programmer. In addition, they are quite different when you move from desktop to <strong>web development</strong>. A very common problem for web developers is dealing with the design team. We understand they follow the requests of the client but in 100% of the cases they just think we can do miracles with their graphics while creating the website.</p> <p class="MsoNormal"><img style="margin-right: auto; margin-left: auto; display: block;" src="http://davidsonsousa.net/image/articles/15a68ed7-8d29-4ce1-8f64-ef8692476370.jpg" alt="" width="350" height="293" /></p> <p>Rafael Mumme, from the <a href="http://www.netmagazine.com">.net magazine</a>, wrote an amazing article about the <a href="http://www.netmagazine.com/opinions/20-things-drive-web-developers-crazy">20 things that drive web developers crazy</a>. They are so real that I&rsquo;ve seen at least 20 of them in the last 2 projects I was working on:</p> <ol> <li>Add rounded corners to every single element on the page. While you're at it, add shadows and gradients too.</li> <li>Use the same PSD as a starting point for every project. Hide unused layers, but don't delete them. Make sure your PSD is at least 100MB.</li> <li>Use sIFR on every piece of text. Bonus points if you choose a font that's very similar to Arial.</li> <li>Never use the same dimensions on elements. Give each a different font size and colour (for black, use #000000, #111111, #121212 ...).</li> <li>Use a lot of breakout images with transparency. Web developers love graphics breaking out of boxes and columns. Bonus points if you add text wrapping around images.</li> <li>Add a modal window. At least half the site should happen in a modal window.</li> <li>Add a Facebook Connect button. It's just a button. How hard can it be to implement?</li> <li>Hide important PSD layers. Later, tell the developer that they missed a hidden element.</li> <li>Create buttons with rollover, active and clicked states. Then don't tell anyone you've done this. Create a separate file for them and send it on at the last minute. We love surprises.</li> <li>Tell the developer about some fancy functionality you read about somewhere on a blog. Then tell them to build it, because, if you saw it somewhere, clearly it's possible.</li> <li>Add a carousel. Oh yeah, and make sure it's a full-screen carousel.</li> <li>Use Lorem Ipsum instead of real copy. And make sure the reserved space is not big enough for real copy.</li> <li>Randomly merge PSD layers. Why not? (But don't merge too many. It'll take you further away from the magic 100MB target).</li> <li>Name all your files 'final', plus a date and a random letter (final-2010-12-01a.psd, final- 2010-12-01r.psd, final-2010-12-02b.psd).</li> <li>Don't worry about making changes once everything is signed off. When we're done with a page, send another, completely different version of it. And tell us that those changes are necessary and essential for user experience.</li> <li>Don't name or organize your PSD layers and folders.</li> <li>If you're designing a form, forget about error and success states. We'll squeeze that stuff in somewhere. We love guessing your intentions.</li> <li>When you're designing a website, don't invite any developers for brainstorming or design meetings. Make sure we're the last ones to see the layout. Show it to the client first, so it will be too late to introduce even a modicum of sanity into your work.</li> <li>We should hang out more, so during QA don't use bug tracking software. Come sit with us for an entire day and point out changes you want made over our shoulders. Use the opportunity for some impromptu design updates as well.</li> <li>And finally, this is the most important thing: don't learn anything about HTML, CSS, JavaScript or browser issues. The less you know about it, the more important we seem.</li> </ol> <p><em>Image from <a href="http://www.shinyshiny.tv">ShinyShiny.tv</a></em></p> Wed, 07 Aug 2013 13:20:33 GMT http://davidsonsousa.net/blog/post/20-things-that-drive-web-developers-crazy My opinion about Windows 8 RTM http://davidsonsousa.net/blog/post/my-thoughts-on-windows-8-rtm <p>I&rsquo;ve been using <strong>Windows 8 RTM</strong> since its release (August 15<sup>th</sup>) as main OS on my notebook due my TechNet subscription. That means: I have installed everything I need to &ldquo;survive&rdquo; in my computer. I mean things like Office, Visual Studio, SQL Server, few games (The Sims 3) and few other utilities. So, what do I think about Windows 8 so far? Let&rsquo;s start from the beginning.</p> <h3>Installation</h3> <p>First of all: If you plan to make a clean installation it&rsquo;s better to <strong>keep the serial key in a piece of paper beside you</strong>. The reason is that Windows 8 asks for the serial during the installation process but, unlike Windows 7, it doesn&rsquo;t allow us to skip.</p> <p>I have chosen to make a clean install and it ran very nicely except by one thing: When I was creating the disk partitions the installer threw me an error related with <a href="http://en.wikipedia.org/wiki/Unified_Extensible_Firmware_Interface">UEFI</a>. As result I couldn&rsquo;t format them. To solve this problem I had to restart my notebook, go to the BIOS and disable the UEFI. After the installation I turned that on and everything is working perfectly fine. I don&rsquo;t really know how and what that would affect the installation but&hellip; It&rsquo;s working without any problems here.</p> <p>At the end of the installation process <strong>you are required to enter your Windows Live ID</strong> or create one if you don't have. It&rsquo;s important since some apps will need the information stored there. But be aware that you can&rsquo;t change the Windows Live ID you entered there at first unless you create another user in your computer.</p> <h3>Lock screen</h3> <p style="text-align: center;"><img style="display: block; margin-left: auto; margin-right: auto;" src="http://davidsonsousa.net/image/articles/4af3cca7-befb-41e0-a05c-ea57a974efd2.jpg" alt="" /></p> <p>We've got a very beautiful lock screen which shows the battery status , email/messages counter and other things if we want (it's customizable!). And it&rsquo;s really "locked" since there is no button to press, absolutely nothing. Windows Phone users will naturally swipe to type the password, but it isn&rsquo;t necessary: We can just click or type to make the lock screen slides up right away.</p> <h3>Start Menu aka Modern UI (former Metro)</h3> <p><img style="display: block; margin-left: auto; margin-right: auto;" src="http://davidsonsousa.net/image/articles/14a45500-1e06-4072-aef8-cdcd402a2e79.jpg" alt="" /></p> <p>The classic Start button we all know and love is gone for good. Microsoft has replaced the Start Menu by a very cool UI called <strong>Modern UI</strong> (before called Metro, but changed due <a href="http://www.knowyourmobile.com/blog/1535563/microsoft_metro_ui_is_now_called_modern_ui.html">legal problems</a>). The Modern UI is much more than a fancy menu, it is a whole system which works in parallel with the classic desktop we are used to know (let&rsquo;s call it &ldquo;Desktop mode&rdquo;). It comes with its own applications (Weather App, News App, Sports App, etc.) and we can install much more through the <a href="http://windows8beta.com/2012/08/windows-store-growing-at-a-moderate-rate">Windows Store</a> (which is growing).</p> <p>Of course nothing is going to prevent you to install your favorite software, even if they seem redundant with the apps Windows 8 has by default. For example the Photos app (images). It&rsquo;s very limited if we compare with <a href="http://www.xnview.com/">XnView</a> since I can&rsquo;t resize or convert the images I need. Or the Reader app (pdf) in comparison with <a href="http://get.adobe.com/reader/">Adobe Reader</a> or <a href="http://www.foxitsoftware.com/Secure_PDF_Reader/">Foxit Reader</a>.</p> <p>And why do we have such limited apps?</p> <p>Remember few lines above when I said that <strong>Modern UI is a system which works in parallel with the classic desktop</strong>? The Windows 8 will come in 3 flavors: Windows 8, Windows 8 Pro and Windows 8 RT. The RT version carries only the Modern UI (and all of its apps) installed in the <a href="http://www.microsoft.com/surface/en/us/default.aspx">Surface</a>, the tablet Microsoft is bringing to the market until the end of this year. It basically means that we will have the basic of <strong>everything we need</strong> to use the tablet. But I believe that soon or later the companies with desktop version of their productivity softwares are going to create apps for the tablet.</p> <h3>Changes in the Desktop mode</h3> <p>The Desktop mode has got some nice changes as well. One of them was the drop of <a href="http://en.wikipedia.org/wiki/Windows_Aero#Aero_Glass_theme">Aero Glass</a>. For those who are unaware of the name, the Aero Glass is that translucent effect which Windows 7 had. This gives you a much more flat impression, which fits quite well with the Modern UI. We also got the menus and toolbars changed by the <a href="http://en.wikipedia.org/wiki/Ribbon_(computing)">ribbon</a>, which was seen for the first time in the Office 2007. It was a very nice change, indeed.</p> <p>But one of the things I really appreciated was the <strong>new Task Manager</strong>. Now it shows the processes in a much more detailed way, highlighting which process is using more memory or processor with different colors. I would like also to point the addition to the tab App history which shows all apps you have used so far.</p> <p><img style="display: block; margin-left: auto; margin-right: auto;" src="http://davidsonsousa.net/image/articles/48367d50-5134-49b2-9f3c-dd706a70943b.jpg" alt="" /></p> <p>The gadgets we had on Windows Vista and 7 were dropped. The reason seems logical: Since we now have the Apps used in Modern UI there was no need to pollute the desktop with things which would do basically the same thing (Weather App, for example).</p> <p><strong>Compatibility and Administrator mode</strong></p> <p>So far everything I am using is working but let&rsquo;s keep in mind that we don&rsquo;t have anything for Windows 8 yet. For the very few applications which don&rsquo;t work properly on the fly we have 2 options:</p> <ul> <li><strong>Use the Windows 7 compatibility mode</strong>: Right-click on the shortcut, go to <em>Properties</em>, choose the tab <em>Compatibility</em>, tick &ldquo;<em>Run this program in compatibility mode for</em>&rdquo; and choose <em>Windows 7</em>;</li> <li><strong>Run the program as Administrator</strong>: Right-click on the shortcut, click on &ldquo;<em>Run this program as Administrator</em>&rdquo;.</li> </ul> <p>I&rsquo;ve used both solutions to run HostsMan and The Sims 3 on Windows 8. For the first, I couldn&rsquo;t access the HOSTS file to make the changes I needed. For the second, I couldn&rsquo;t load and save the configurations. I am not sure if the Administrator thing is intentional (I hope so) but I couldn&rsquo;t find any article talking about this.</p> <p><img style="display: block; margin-left: auto; margin-right: auto;" src="http://davidsonsousa.net/image/articles/8a30bd4e-d258-4813-b99a-0d4a6e84f8c2.jpg" alt="" /></p> <p>As for the drivers, the Windows 7 version works perfectly fine. No voodoo necessary to make it work.</p> <p><strong>Less battery usage</strong></p> <p>It&rsquo;s important to mention that everything which isn&rsquo;t used ends up suspended. In practical terms the app or software is still open and running, but not using any of the system resources. This, among the end of Aero Glass, helps the OS to use less battery than the others which is very important these days.</p> <p><strong>Verdict</strong></p> <p>It takes some time to get used to the whole Modern UI/Desktop thing but everything becomes very smoothly after 1 week using non-stop. And since some keyboard shortcuts will help you to be as productive as with any Windows version I would recommend you to <a href="http://www.hanselman.com/blog/Windows8ProductivityWhoMovedMyCheeseOhThereItIs.aspx">take a look at them</a>.</p> <p>There are few small bugs but it&rsquo;s expected since it&rsquo;s the very first version. Not even Windows 7 was perfect on its release. But still, the idea of integrating all of systems (videogame, mobile phone, computer and tablet) is amazing. Those who have Windows Phone and Xbox will enjoy a lot. As I do.</p> <p><em><strong>One tiny addition:</strong> Credits to Alena who discovered and taught me about clicking on the lock screen, change the temperature of the Weather App to Celsius (right-click inside the app, bottom bar) and also define a picture standard for the Photos App (right-click on the open image, Set as, App tile).</em></p> Sun, 26 Aug 2012 06:40:00 GMT http://davidsonsousa.net/blog/post/my-thoughts-on-windows-8-rtm A short story about my return to Czech Republic http://davidsonsousa.net/blog/post/a-short-story-about-my-return-to-czech-republic <p><img style="float: right;" src="../../../../image/bef9f5b0-0a2a-4a7a-81be-420ade4bf529.jpg" alt="" />Hibernation. This is what defines what I was doing during the last 30 days. No, I wasn&rsquo;t in deep sleep like bears&hellip; I meant that I toke some vacations from myself in order to make some analysis of the environment here in Czech Republic as I needed to get back on track. And since I spent 6 months in Brazil you can imagine how different these countries are&hellip;</p> <p>The first thing I&rsquo;ve done after arrive was to <a href="../../../post/review-notebook-lenovo-ideapad-z580">get a new notebook</a>. My old one now belongs to Alena but she doesn&rsquo;t seem to get along well with it. It seems that she has created a kind of bond with her old machine but, after some time, she will accept the change. I hope :)</p> <p>Another thing I&rsquo;ve started to do is to try to move a bit more. And since I have a Kinect at home I started playing <a href="http://www.youtube.com/watch?v=2tSNsb7l0AM"><em>Your Shape: Fitness Evolved</em></a> often, in addition to walking outside. I have to confess: The first week was very painful but now everything seems fine. And I feel a bit more alive, less anxious and with better concentration. Maybe I am going to write few articles about this soon. A huge maybe because sometimes I really need an extra motivation for exercises. But I guess my current 91kg are very motivational...</p> <p>Then we have <strong>Windows 8 RTM</strong> releasing! Since I am an MCT I could get it on August 15<sup>th</sup> via my TechNet subscription. How does it feel? Is it amazing? Do I like it? Well, I am going to write kind of review about that in few days but the answer is: I <strong>love</strong> it! But stay tuned for the review.</p> <p>So far this is everything what happened during the last weeks. Yes, I know... I didn't do anything so much interesting since I spent 99% of my time at home. We have even planned a <a href="https://twitter.com/DavidsonSousa2/status/233160212691968000">short trip to Belgium</a> but, unfortunately, we couldn't go.</p> <p>Ah, of course... I have started looking for a job while waiting for 2 great things which might happen in few weeks. Whichever seems better (money + environment), I will pick it. But let&rsquo;s see. Whatever happens I will post here. But probably all recruiters are on vacation around here or, which could be worse, there are really few .NET positions around here.</p> <p>Stay tuned!</p> Wed, 22 Aug 2012 14:10:00 GMT http://davidsonsousa.net/blog/post/a-short-story-about-my-return-to-czech-republic Review: Notebook Lenovo IdeaPad Z580 http://davidsonsousa.net/blog/post/review-notebook-lenovo-ideapad-z580 <p><img style="float: right;" src="http://davidsonsousa.net/image/articles/f28aea08-8e5b-4e3f-a1d7-51ff3c5d91f5.jpg" alt="" />It has been a long time since I wanted to replace my old <a href="http://www.msi.com/product/nb/EX620.html">MSI EX620</a> by something new. My plan was to do it as soon I got back to Czech Republic since the prices in Brazil aren&rsquo;t so good if we compare with the prices here in Europe. After few weeks reading reviews, comparing prices and looking for the best option which my wallet would handle, I&rsquo;ve stumbled upon the <a href="http://www.lenovo.com/products/us/laptop/ideapad/z-series/z580/">Lenovo IdeaPad Z580</a>.</p> <p><span style="color: #ff0000;"><em><strong>Update: I do not intend to make a professional review. It's just my opinion about something I have bought for myself.</strong></em></span></p> <p>This notebook has very good specifications and an affordable price. Here in Czech Republic I paid 16.000 CZK (640 EUR) in <a href="http://www.alza.cz/lenovo-ideapad-z580-metal-d330097.htm">Alza</a>, which is one of the best shops around here.</p> <h3>Specifications</h3> <ul> <li><strong>Processor: </strong>Intel Core i5 3210 with a frequency of 2.5 GHz; 3 MB L3 Cache</li> <li><strong>Memory:</strong> 2x 4 GB DDR3 1333 MHz; Up to 8 GB in 2 slots</li> <li><strong>Display:</strong> 15.6" LED; 1366 x 768 pixels</li> <li><strong>Graphic card: </strong>NVIDIA GeForce GT630M own 2 GB of GDDR3 memory</li> <li><strong>Hard Drive:</strong> 1TB; 5400 RPM</li> <li><strong>Optical drive:</strong> DVD SuperMulti DL</li> <li><strong>Multimedia:</strong> Support High-definition audio, 2x 2 Watt speakers (SRS Premium Sound), built-in microphone, 1 megapixel Webcam</li> <li><strong>Communication: </strong>WiFi 802nd11b/g/n, LAN Ethernet 10/100 Mbps, bluetooth fourth0</li> <li><strong>Control:</strong> Multitouch Pad, Keyboard with numeric keypad</li> <li><strong>Interface:</strong> 2x USB third0, 2x USB 20, 1x HDMI, 1x VGA, 1x Headphone/Microphone, 1x RJ-45, 1x Card Reader 5V1</li> <li><strong>Power: </strong>Li-Ion battery, 6 cells; Battery life up to 4 hours</li> <li><strong>Dimensions:</strong> 376 x 250 x 20-34 mm</li> <li><strong>Weight: </strong>approximately 2.65 kg</li> </ul> <h3>Processor</h3> <p>My notebook came with an Intel Core i5 3210 (Ivy Bridge) which is one of the most recent series. Its performance is amazing and I wouldn&rsquo;t be able to ask for more. This notebook really fits my personal use well. Oh, my personal use is basically <strong>Visual Studio</strong>, <strong>SQL Server</strong>, web browsers, music and HD movies. I made a test with Football Manager 2012 as well and it ran perfectly fine!</p> <h3>Memory</h3> <p>The notebook came with 8 GB of RAM (twice DDR3 1333 MHz of 4GB). Since my previous one had 4GB I felt a huge difference, mainly when I need to open lots of applications.</p> <h3>Display</h3> <p><img style="display: block; margin-left: auto; margin-right: auto;" src="http://davidsonsousa.net/image/articles/034864de-fd64-4c77-a6ad-b008a56236eb.jpg" alt="" /></p> <p>So, I am a guy who loves movies. And since the <strong>IdeaPad Z580</strong> comes with a LED display I am really happy! It&rsquo;s a 15.6&rdquo; display with 1366x768 resolution which performs amazingly while playing HD movies. One very interesting thing which I&rsquo;ve noticed but should be better tested is how this screen would perform outside, in a sunny day. I made a small test sitting with my backs to the window while using the notebook and it worked pretty well with the brightness in the maximum. But outside might be something different.</p> <h3>Graphic card</h3> <p>The Z580 comes with 2 graphic cards: One onboard (Intel HD Graphics 4000) and the NVIDIA GeForce GT630M. Both of them are very good, I have zero complaints about any of them. And, since you can choose which program will run with which graphic card, the GeForce ends up not being used so much. But I made a test with Football Manager and the images are great for the game. I should test with a more advanced game, though.</p> <h3>Multi-touch panel and Keyboard</h3> <p><img style="display: block; margin-left: auto; margin-right: auto;" src="http://davidsonsousa.net/image/articles/e0cbdd74-8ec5-4d3c-a910-31d2f177b175.jpg" alt="" /></p> <p>Like the MacBook Pro, this <strong>Lenovo IdeaPad Z580</strong> came with a multi-touch gesture touchpad which, in my humble opinion, sucks. First of all, it doesn&rsquo;t have physical buttons and the place we should click can be also used as touchable area. During my first week using it I made lots of mistakes, clicked in the wrong places, dragged things instead of open them&hellip; Only now, during the 3rd week, I am getting used to this thing. But I still miss the good old touchpad with physical buttons.</p> <p>The keyboard, in another hand, is very good. The keys are slightly spread and it gives a very good impression, although it also makes the typos be much more frequent than my previous notebook. Ok, ok... I am getting used to it... And the keys are a slightly noisy. But that's fine. They are physical, at least, differently than the multi-touch panel!</p> <h3>Battery</h3> <p>While my previous notebook was able to handle my activities without power during 1h40, the Lenovo IdeaPad Z580 is able to handle it for 4h. This thanks to its Li-Ion battery with 6 cells. For me was a great advance, taking in to account that from now on I would be able to spend much more time outside doing my stuff.</p> <h3>Temperature and noise</h3> <p><img style="display: block; margin-left: auto; margin-right: auto;" src="http://davidsonsousa.net/image/articles/50b19e14-ff4b-450e-bcf0-f27da5cfa6a8.jpg" alt="" /></p> <p>One of the issues I had with my previous notebook was the noise and the temperature. In order to keep it between 50C and 60C the noise was very bothering, even when I was doing absolutely nothing. But with this IdeaPad Z580 the noise is unbelievable <strong>ZERO</strong>. And I don&rsquo;t know whether the new Ivy Bridge which is cool enough or the internal layout of the notebook but this machine keeps running between 43C and 47C. In rare moments (multimedia, games) I see some temperature peaks. Ah, for measuring the temperature I use <a href="http://www.alcpu.com/CoreTemp/">CoreTemp 1.0 RC3</a>. Very good software, by the way.</p> <h3>Verdict</h3> <ul> <li><strong>Pros:</strong> Its price, light weight (2.65kg), beautiful screen, battery lifespan, fast and modern processor, amount of memory and very good for multimedia.</li> <li><strong>Cons:</strong> This strange multi-touch pad, the slightly noisy keyboard, the &ldquo;mute&rdquo; soundcard when the computer is recovered from the &ldquo;sleep mode&rdquo; and no E-SATA port to connect external HDs.</li> </ul> <p>As a final word I would say that I really needed a new notebook to keep my routine of developer so, despite the cons mentioned above, I think this notebook was a great acquisition. First because some things are just a matter of getting used to. Second, I don't use E-SATA all the time anyway. In the end this machine is great for general use, great for <strong>software development</strong>, great for multimedia and might be great for a good amount of games.</p> Wed, 08 Aug 2012 13:26:00 GMT http://davidsonsousa.net/blog/post/review-notebook-lenovo-ideapad-z580 RescueTime - Um software muito bom para medir a produtividade na frente do pc http://davidsonsousa.net/blog/post/rescuetime-um-software-muito-bom-para-medir-a-produtividade-na-frente-do-pc <p><img style="float: right;" src="http://davidsonsousa.net/image/articles/fa595921-681e-4451-a1ce-269dda3b4822.jpg" alt="" />N&atilde;o adianta mentir: Todo mundo acha que &eacute; super produtivo at&eacute; que se prove o contr&aacute;rio. E geralmente, quando se prova o contr&aacute;rio, a pessoa fica toda nervosa botando a culpa na empresa, no chefe, no cachorro do vizinho, na mulher que n&atilde;o cozinha direito e por a&iacute; vai.</p> <p>Mas, c&aacute; entre n&oacute;s, voc&ecirc; sabe quanto tempo, de fato, voc&ecirc; fica nas suas atividades?</p> <p>Para descobrir isso &eacute; muito f&aacute;cil: Basta instalar um software que contabiliza o tempo em que cada software ou site est&aacute; aberto. E ele tem nome: <a href="http://www.rescuetime.com">RescueTime</a>.</p> <p>O <strong>RescueTime</strong> &eacute; um software muito simples. Ele fica no tray (ali, ao lado do rel&oacute;gio) monitorando tudo o que voc&ecirc; faz. Quando voc&ecirc; quer puxar um relat&oacute;rio &eacute; s&oacute; acessar o site e ver o qu&atilde;o produtivo voc&ecirc; &eacute;. O pulo do gato &eacute; o sistema de categorias que ele tem. Cada software ou site &eacute; classificado em 5 n&iacute;veis: <em>Very distracting</em>, <em>distracting</em>, <em>neutral</em>, <em>productive</em> e <em>very productive</em>. O <strong>Visual Studio</strong>, por exemplo, &eacute; classificado como <em>very productive</em>. Nem precisa dizer qual a classifica&ccedil;&atilde;o do Facebook, n&eacute;?</p> <p>Estou testando no meu notebook esses dias e achei muito bom. Claro, como &eacute; meu computador pessoal d&aacute; pra ver como eu sou uma pessoa extremamente improdutiva nas imagens abaixo:</p> <p style="text-align: center;"><img src="http://davidsonsousa.net/image/articles/2c93b52b-a4d6-42e5-97c8-5b9cbd027be6.jpg" alt="" /><br /><em>Tabelinha mostrando o que eu usei no dia do teste</em></p> <p style="text-align: center;"><img style="display: block; margin-left: auto; margin-right: auto;" src="http://davidsonsousa.net/image/articles/743e7f46-327e-4d55-9bf0-c936e16dd1ae.jpg" alt="" /><em>Gr&aacute;fico mostrando o que eu usei no dia do teste</em></p> <p>Atualmente estou usando a limitad&iacute;ssima vers&atilde;o free mas que me atende perfeitamente. Para grupos de usu&aacute;rio existem v&aacute;rias vers&otilde;es pagas. Uma delas, s&oacute; pra se ter uma id&eacute;ia, custa US$ 70,00 por m&ecirc;s para 5 usu&aacute;rios. Com isso um gerente poderia monitorar o time para ver se eles est&atilde;o passando mais tempo no fazendo coisas improdutivas do que produtivas.<br />&nbsp;<br />Sugiro usar a vers&atilde;o free e fazer um teste. Vale muito a pena, at&eacute; pra se policiar.</p> Tue, 07 Aug 2012 06:00:00 GMT http://davidsonsousa.net/blog/post/rescuetime-um-software-muito-bom-para-medir-a-produtividade-na-frente-do-pc Microsoft announces a new developer certification - Get ready for Metro! http://davidsonsousa.net/blog/post/microsoft-announces-a-new-developer-certification-get-ready-for-metro <p><img style="float: right;" src="http://davidsonsousa.net/image/articles/5f2fd91e-6a4f-4475-a964-e9cfa202258b.jpg" alt="" />I've already spoken about how <a href="http://davidsonsousa.net/en/post/how-to-improve-your-resume-with-a-microsoft-certification">a certification is important for your career</a> and also about the <a href="http://davidsonsousa.net/en/post/associate-expert-and-master-the-reinvention-of-the-microsoft-certifications">reinvention Microsoft made with its certifications</a>. Now, I am going to be more specific about <strong>software development</strong>.</p> <p>Microsoft&nbsp; announces the new <a href="http://www.microsoft.com/learning/en/us/certification/mcsd.aspx">Microsoft Certified Solution Developer</a> (<strong>MCSD</strong>) credential for developers and one of its changes is the fact they are going to focus much more in the cloud. But basically this early-to-market certification addresses new skills for a broader audience, including next generation developers who thrive on bleeding edge technology.</p> <p>Needless to say, these new certifications will focus on the <strong><a href="http://www.microsoft.com/visualstudio/11/en-us">Visual Studio 2012</a></strong> development (the RC was some time ago). I was testing the beta version (when was still 2011) and all I have to say is: It's great! But one of the few things which really caugh my attention was the <strong><a href="http://msdn.microsoft.com/en-us/library/windows/apps/br211386.aspx">Metro Style Apps</a></strong>.</p> <p>We are going to have more anouncements during the next few months but the first one is already there -&nbsp; <a href="http://www.microsoft.com/learning/en/us/certification/mcsd-windows-metro-style-apps.aspx">MCSD: Windows Metro Style Apps</a>. This new certification is for developers who want the skills to create the beautiful, elegant and fast apps that are expected in today&rsquo;s exploding marketplace, using the <strong>Windows 8</strong> platform with <strong>Visual Studio</strong>, <strong>HTML5</strong>, and <strong>C#</strong>.<strong><em></em></strong></p> <p>You can start working towards the <a href="http://www.microsoft.com/learning/en/us/certification/mcsd-windows-metro-style-apps.aspx">MCSD: Windows Metro Style Apps</a> certification today by prepping for the beta exams that are coming out this summer. Here&rsquo;s a free ebook from MS Press to help you get started: <a href="http://blogs.msdn.com/b/microsoft_press/archive/2012/06/04/free-ebook-programming-windows-8-apps-with-html-css-and-javascript-first-preview.aspx">Programming Windows 8 Apps with HTML, CSS, and JavaScript (First Preview)</a>.</p> <p>How excited I am with that? A lot. First because I am really lookinf forward for a Metro certification. Second, I will apply my web knowledge to develop such apps.</p> <p>Well done, Microsoft. Well done. :)</p> Fri, 08 Jun 2012 13:15:00 GMT http://davidsonsousa.net/blog/post/microsoft-announces-a-new-developer-certification-get-ready-for-metro Como inserir vários registros no banco usando Entity Framework? http://davidsonsousa.net/blog/post/como-inserir-varios-registros-no-banco-usando-entity-framework <p><img style="float: right;" src="http://davidsonsousa.net/image/articles/7c52a479-4308-435a-926c-a9801e5695e7.png" alt="" />O <a href="http://msdn.microsoft.com/en-us/library/bb399572.aspx"><strong>Entity Framework</strong></a> (EF) &eacute; um ORM da Microsoft que permite a n&oacute;s, programadores, desenvolver dentro de um <strong>modelo conceitual</strong> de dados ao inv&eacute;s de programar direto no banco. Desse modo qualquer altera&ccedil;&atilde;o feita nos dados durante seu uso no sistema deve ser persistida no banco j&aacute; que isso n&atilde;o &eacute; feito automaticamente. No caso do Entity Framework usar&iacute;amos o m&eacute;todo <a href="http://msdn.microsoft.com/en-us/library/bb336792.aspx">SaveChanges</a>.</p> <p>Para funcionar o EF gera um script SQL para cada a&ccedil;&atilde;o. Assim, se chamarmos o m&eacute;todo <a href="http://msdn.microsoft.com/en-us/library/system.data.objects.objectcontext.addobject.aspx">AddObject</a> para inserir um objeto <em>Pessoa</em>, um INSERT &eacute; gerado e enviado ao banco de dados junto com as propriedades do objeto <em>Pessoa</em>.</p> <p>E quando vamos adicionar 3.000 registros de uma vez?</p> <p>Nesse caso temos 2 solu&ccedil;&otilde;es:</p> <ol> <li>Fazemos um loop e jogamos 3.000 INSERTs no banco de dados (n&atilde;o recomendado)</li> <li>Usamos a classe <a href="http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlbulkcopy.aspx">SqlBulkCopy</a></li> </ol> <p>Opa, pera&ecirc;: Quer dizer que n&atilde;o vamos usar o Entity Framework ent&atilde;o?</p> <p>O Entity Framework n&atilde;o tem uma maneira nativa de se fazer um bulk insert. Mas como ele foi constru&iacute;do sobre o ADO.NET n&atilde;o teria problema usarmos o SqlBulkCopy. Isso sem contar o fato que o SqlBulkCopy traz pra gente um ganho consider&aacute;vel de performance com rela&ccedil;&atilde;o aos m&uacute;ltiplos INSERTs.</p> <p>Veja um exemplo do uso do <strong>SqlBulkCopy</strong>:</p> <pre style="font-family: Consolas; font-size: 13; color: black; background: white;"><span style="color: blue;">using</span>&nbsp;(<span style="color: #2b91af;">SqlConnection</span>&nbsp;destinationConnection&nbsp;=&nbsp;<span style="color: blue;">new</span>&nbsp;<span style="color: #2b91af;">SqlConnection</span>(connectionString)) { destinationConnection.Open(); <span style="color: blue;">using</span>&nbsp;(<span style="color: #2b91af;">SqlBulkCopy</span>&nbsp;bulkCopy&nbsp;=&nbsp;<span style="color: blue;">new</span>&nbsp;<span style="color: #2b91af;">SqlBulkCopy</span>(destinationConnection)) { bulkCopy.DestinationTableName&nbsp;=&nbsp;<span style="color: #a31515;">"dbo.BulkCopyDemoMatchingColumns"</span>; <span style="color: blue;">try</span> { <span style="color: green;">//O&nbsp;reader &eacute; um&nbsp;SqlDataReader&nbsp;que&nbsp;recebeu&nbsp;todos&nbsp;os&nbsp;3.000&nbsp;registros&nbsp;anteriormente</span> bulkCopy.WriteToServer(reader); } <span style="color: blue;">catch</span>&nbsp;(<span style="color: #2b91af;">Exception</span>&nbsp;ex) { <span style="color: #2b91af;">Console</span>.WriteLine(ex.Message); } <span style="color: blue;">finally</span> { reader.Close(); } } } </pre> <p>O fato da gente precisar usar o SqlBulkCopy n&atilde;o quer dizer que o Entity Framework &eacute; ruim. Digamos que a Microsoft &ldquo;esqueceu&rdquo; de adicionar essa feature no EF...</p> Wed, 09 May 2012 15:58:00 GMT http://davidsonsousa.net/blog/post/como-inserir-varios-registros-no-banco-usando-entity-framework Associate, Expert and Master: The reinvention of the Microsoft certifications http://davidsonsousa.net/blog/post/associate-expert-and-master-the-reinvention-of-the-microsoft-certifications <p><img style="float: right;" src="http://davidsonsousa.net/image/articles/5001397d-d9b7-42f7-8e6a-872da2e3b9a9.jpg" alt="" />This is the case when the article is old &ndash; due how fast the information flows nowadays &ndash; but gold. Microsoft is changing all certifications. Again. And, at this time, they call it reinvention. You might have a feeling of d&eacute;j&agrave; vu if you saw the change from the .NET Framework 3.5 to 4. But now there is cloud technologies! So let&rsquo;s see how it works.</p> <p>As you could see on the blue pyramid, we still have 3 levels of certification, but with different names. They are:</p> <h3>Microsoft Certified Solutions Associate (MCSA)</h3> <p>The Associate level is the prerequisite certification necessary to get your Expert level certification. This certification validates the core skills you need to get your 1st job in IT. We could slightly compare with the Technology Specialist (MCTS) that we have today.</p> <h3>Microsoft Certified Solutions Expert (MCSE) &amp; Microsoft Certified Solutions Developer (MCSD)</h3> <p>The Expert level is Microsoft&rsquo;s flagship set of certifications validating that your skills are relevant in the constantly changing tech environment. The Microsoft Certified Solutions Expert (MCSE) is the destination for established IT Professionals who have expertise working with Microsoft technology solutions. The Microsoft Certified Solutions Developer (MCSD) is the destination for established Developers who have expertise developing solutions with Microsoft tools. Does that sound familiar? Yes! IT Professional (MCITP) and Professional Developer (MCPD).</p> <h3>Microsoft Certified Solutions Master (MCSM)</h3> <p>After you have achieved your Expert level certification, Master is the next destination. This certification is for the select few who wish to further differentiate themselves from their peers and achieve the highest level of skills validation. But this one is a bit dubious for me as we already had Master (MCM) but only for server technologies. I don&rsquo;t know if they will keep it in this way or if they will also extend that for developers (which would be great!).</p> <p>But don&rsquo;t be fool thinking it&rsquo;s only this. Since Microsoft is moving almost everything to the cloud this rearrangement seem quite right for the purpose. For example, if a person wants to become an <a href="http://aka.ms/MCSEDP">MCSE: Data Platform</a> he/she will have to be <a href="http://www.microsoft.com/learning/en/us/certification/cert-sql-server-mcsa.aspx">MCSA: SQL Server 2012</a> and then make 2 exams. To upgrade from the previous certification the person must make 3 transition exams. Seems harder, hum? I can&rsquo;t wait to see what they will do with the developer certifications... :)</p> <p>More information:</p> <ul> <li><a href="http://aka.ms/MSCerts">Microsoft Certification overview page</a></li> <li><a href="http://aka.ms/MCSE">MCSE information page</a></li> <li><a href="http://aka.ms/Prometric241">Prometric 2-for-1 offer</a>: <a href="http://aka.ms/Prometric241"></a>Take an exam until June 30 and get a voucher for the MCSA!</li> </ul> Mon, 16 Apr 2012 10:36:00 GMT http://davidsonsousa.net/blog/post/associate-expert-and-master-the-reinvention-of-the-microsoft-certifications Prove yourself with a Microsoft SQL Server 2012 certification! http://davidsonsousa.net/blog/post/prove-yourself-with-a-microsoft-sql-server-2012-certification <p><img style="float: right;" src="http://davidsonsousa.net/image/articles/f1bf07bd-c36e-4067-b367-99decdae7f32.png" alt="" />Since some time ago we can notice a natural migration to the cloud. The cloud makes the integration between different devices much easier as all data would be stored there. Microsoft SQL Server 2012 gives organizations the foundation to the cloud-ready information platform, quickly build solutions and extend their data from the server to the cloud with advanced capabilities for mission critical confidence. But where are the professionals?</p> <p>While the data is growing fast the number of IT professionals is growing very slow. Even now there is already a good demand of professionals with SQL skills able to work with cloud. But are they qualified?</p> <p>To answer that Microsoft has created the certifications which assure the professionals must have a deep understanding of the chosen technology. And this is assured by:</p> <ul> <li>Designing certifications that test the skills that employers and hiring managers acknowledge as most essential to their employees&rsquo; success on the job.</li> <li>Developing exams that focus on the real world use of Microsoft technologies in organizations.</li> <li>Delivering our exams using appropriate security measures, so employers and candidates know that each certification earned carries solid value in the marketplace.</li> <li>Defending our certifications by keeping our design, development and delivery processes secure.&nbsp; </li> </ul> <p>This all means that when you earn a Microsoft certification, your employers and peers know that you have up-to-date technological knowledge, and can bring more insightful problem solving skills to the workplace.</p> <p>So, what are you waiting for? Go and get your <a href="http://www.microsoft.com/learning/en/us/certification/cert-sql-server.aspx#tab2">SQL 2012 certification</a>!</p> Sun, 01 Apr 2012 09:35:00 GMT http://davidsonsousa.net/blog/post/prove-yourself-with-a-microsoft-sql-server-2012-certification Como corrigir o erro "Error in processing. The server response was: Greylisted, please try again in http://davidsonsousa.net/blog/post/como-corrigir-o-erro-error-in-processing-the-server-response-was-greylisted-please-try-again-in-x-se <p><img style="float: right;" src="http://davidsonsousa.net/image/articles/f29b830c-f38b-49dc-903a-af40c0f1e52d.jpg" alt="" /></p> <p>Eu tive uma sexta-feira interessante. Foi o &uacute;ltimo dia com uma turma onde eu tive que substituir o instrutor. Eles tiveram alguns problemas com ele e eu fui o escolhido para a substitui&ccedil;&atilde;o. Tudo correu bem. Depois eu fui olhar o log de erros do meu blog (eu uso <a href="https://nuget.org/packages/ELMAH">Elmah</a>, a prop&oacute;sito) e vi um erro que nunca tinha visto antes:</p> <p><span style="color: #ff0000;"><em><strong>System.Net.Mail.SmtpException</strong></em></span><br /><span style="color: #ff0000;"><em><strong>Error in processing. The server response was: Greylisted, please try again in 240 seconds</strong></em></span></p> <p>O tempo varia mas, depois de procurar no google por alguns instantes, achei a solu&ccedil;&atilde;o. Meu servidor tinha implementado algo chamado&nbsp;<a href="http://en.wikipedia.org/wiki/Greylisting">Greylisting</a> que, de acordo com a Wikipedia, &eacute; uma maneira de defender os usu&aacute;rios de e-mail contra spam. Logo, e-mails n&atilde;o reconhecidos pelo sistema s&atilde;o automaticamente rejeitados por um tempo.</p> <p>Como corrigir?</p> <p>Tudo que precisei fazer foi criar uma conta de e-mail no meu servidor e adiciona-la no meu <strong>web.config</strong> da seguinte maneira:</p> <pre style="font-family: Consolas; font-size: 13; color: black; background: white;"><span style="color: blue;">&lt;</span><span style="color: #a31515;">system.net</span><span style="color: blue;">&gt;</span> <span style="color: blue;"> &lt;</span><span style="color: #a31515;">mailSettings</span><span style="color: blue;">&gt;</span> <span style="color: blue;"> &lt;</span><span style="color: #a31515;">smtp</span><span style="color: blue;">&gt;</span> <span style="color: blue;"> &lt;</span><span style="color: #a31515;">network</span><span style="color: blue;">&nbsp;</span><span style="color: red;">defaultCredentials</span><span style="color: blue;">=</span>"<span style="color: blue;">false</span>"<span style="color: blue;">&nbsp;</span><span style="color: red;">host</span><span style="color: blue;">=</span>"<span style="color: blue;">Mail@DomainName.com</span>"<span style="color: blue;">&nbsp;</span><span style="color: red;">port</span><span style="color: blue;">=</span>"<span style="color: blue;">25</span>"<span style="color: blue;">&nbsp;</span><span style="color: red;">userName</span><span style="color: blue;">=</span>"<span style="color: blue;">username@DomainName.com</span>"<span style="color: blue;">&nbsp;</span><span style="color: red;">password</span><span style="color: blue;">=</span>"<span style="color: blue;">ThisIsAPassword</span>"<span style="color: blue;">/&gt;</span> <span style="color: blue;"> &lt;/</span><span style="color: #a31515;">smtp</span><span style="color: blue;">&gt;</span> <span style="color: blue;"> &lt;/</span><span style="color: #a31515;">mailSettings</span><span style="color: blue;">&gt;</span> <span style="color: blue;">&lt;/</span><span style="color: #a31515;">system.net</span><span style="color: blue;">&gt;</span> </pre> <p>Obviamente voc&ecirc; precisa colocar seu pr&oacute;prio <strong>host</strong>, <strong>username</strong> e <strong>password</strong>. :-)</p> <p>E &eacute; isso.</p> <p>Em tempo: A solu&ccedil;&atilde;o eu achei aqui <a href="http://forums.asp.net/t/1488256.aspx/1">here</a>.</p> <div id="_mcePaste" class="mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow: hidden;"> <pre style="font-family: Consolas; font-size: 13; color: black; background: white;"><span style="color: blue;"> &lt;</span><span style="color: #a31515;">system.net</span><span style="color: blue;">&gt;</span> <span style="color: blue;"> &lt;</span><span style="color: #a31515;">mailSettings</span><span style="color: blue;">&gt;</span> <span style="color: blue;"> &lt;</span><span style="color: #a31515;">smtp</span><span style="color: blue;">&gt;</span> <span style="color: blue;"> &lt;</span><span style="color: #a31515;">network</span><span style="color: blue;">&nbsp;</span><span style="color: red;">defaultCredentials</span><span style="color: blue;">=</span>"<span style="color: blue;">false</span>"<span style="color: blue;">&nbsp;</span><span style="color: red;">host</span><span style="color: blue;">=</span>"<span style="color: blue;">mail.davidsonsousa.net</span>"<span style="color: blue;">&nbsp;</span><span style="color: red;">port</span><span style="color: blue;">=</span>"<span style="color: blue;">25</span>"<span style="color: blue;">&nbsp;</span><span style="color: red;">userName</span><span style="color: blue;">=</span>"<span style="color: blue;">contact@davidsonsousa.net</span>"<span style="color: blue;">&nbsp;</span><span style="color: red;">password</span><span style="color: blue;">=</span>"<span style="color: blue;">D#sousa12</span>"<span style="color: blue;">/&gt;</span> <span style="color: blue;"> &lt;/</span><span style="color: #a31515;">smtp</span><span style="color: blue;">&gt;</span> <span style="color: blue;"> &lt;/</span><span style="color: #a31515;">mailSettings</span><span style="color: blue;">&gt;</span> <span style="color: blue;"> &lt;/</span><span style="color: #a31515;">system.net</span><span style="color: blue;">&gt;</span> </pre> </div> Mon, 26 Mar 2012 10:50:00 GMT http://davidsonsousa.net/blog/post/como-corrigir-o-erro-error-in-processing-the-server-response-was-greylisted-please-try-again-in-x-se How to fix "Error in processing. The server response was: Greylisted, please try again in X seconds" http://davidsonsousa.net/blog/post/how-to-fix-error-in-processing-the-server-response-was-greylisted-please-try-again-in-x-seconds <p><img style="float: right;" src="http://davidsonsousa.net/image/articles/f29b830c-f38b-49dc-903a-af40c0f1e52d.jpg" alt="" />I had a quite interesting Friday. It was the last day of a class in which I had to replace the trainer. They had some problems with him and I was the choosen one for the replacement. Everything went well so far. After that I went to check the error log of my blog (I use <a href="https://nuget.org/packages/ELMAH">Elmah</a>, by the way) and I found an issue I've never seen before:</p> <p><span style="color: #ff0000;"><em><strong>System.Net.Mail.SmtpException</strong></em></span><br /><span style="color: #ff0000;"><em><strong>Error in processing. The server response was: Greylisted, please try again in 240 seconds</strong></em></span></p> <p>The time may vary. But after google it for a while I found it! My server was implementing <a href="http://en.wikipedia.org/wiki/Greylisting">Greylisting</a> which, according to Wikipedia, is a method of defending e-mail users against spam. So, the non-recognized e-mails are automatically rejected for a while.</p> <p>And how to fix that?</p> <p>All I needed to do was to create a mail account on my server and add it to my <strong>web.config</strong> in the following way:</p> <pre style="font-family: Consolas; font-size: 13; color: black; background: white;"><span style="color: blue;">&lt;</span><span style="color: #a31515;">system.net</span><span style="color: blue;">&gt;</span> <span style="color: blue;"> &lt;</span><span style="color: #a31515;">mailSettings</span><span style="color: blue;">&gt;</span> <span style="color: blue;"> &lt;</span><span style="color: #a31515;">smtp</span><span style="color: blue;">&gt;</span> <span style="color: blue;"> &lt;</span><span style="color: #a31515;">network</span><span style="color: blue;">&nbsp;</span><span style="color: red;">defaultCredentials</span><span style="color: blue;">=</span>"<span style="color: blue;">false</span>"<span style="color: blue;">&nbsp;</span><span style="color: red;">host</span><span style="color: blue;">=</span>"<span style="color: blue;">Mail@DomainName.com</span>"<span style="color: blue;">&nbsp;</span><span style="color: red;">port</span><span style="color: blue;">=</span>"<span style="color: blue;">25</span>"<span style="color: blue;">&nbsp;</span><span style="color: red;">userName</span><span style="color: blue;">=</span>"<span style="color: blue;">username@DomainName.com</span>"<span style="color: blue;">&nbsp;</span><span style="color: red;">password</span><span style="color: blue;">=</span>"<span style="color: blue;">ThisIsAPassword</span>"<span style="color: blue;">/&gt;</span> <span style="color: blue;"> &lt;/</span><span style="color: #a31515;">smtp</span><span style="color: blue;">&gt;</span> <span style="color: blue;"> &lt;/</span><span style="color: #a31515;">mailSettings</span><span style="color: blue;">&gt;</span> <span style="color: blue;">&lt;/</span><span style="color: #a31515;">system.net</span><span style="color: blue;">&gt;</span> </pre> <p>Needless to say, you need to put your own <strong>host</strong>, <strong>username</strong> and <strong>password</strong>. :-)</p> <p>And that's it.</p> <p>In time: The answer I found <a href="http://forums.asp.net/t/1488256.aspx/1">here</a>.</p> <div id="_mcePaste" class="mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow: hidden;"> <pre style="font-family: Consolas; font-size: 13; color: black; background: white;"><span style="color: blue;"> &lt;</span><span style="color: #a31515;">system.net</span><span style="color: blue;">&gt;</span> <span style="color: blue;"> &lt;</span><span style="color: #a31515;">mailSettings</span><span style="color: blue;">&gt;</span> <span style="color: blue;"> &lt;</span><span style="color: #a31515;">smtp</span><span style="color: blue;">&gt;</span> <span style="color: blue;"> &lt;</span><span style="color: #a31515;">network</span><span style="color: blue;">&nbsp;</span><span style="color: red;">defaultCredentials</span><span style="color: blue;">=</span>"<span style="color: blue;">false</span>"<span style="color: blue;">&nbsp;</span><span style="color: red;">host</span><span style="color: blue;">=</span>"<span style="color: blue;">mail.davidsonsousa.net</span>"<span style="color: blue;">&nbsp;</span><span style="color: red;">port</span><span style="color: blue;">=</span>"<span style="color: blue;">25</span>"<span style="color: blue;">&nbsp;</span><span style="color: red;">userName</span><span style="color: blue;">=</span>"<span style="color: blue;">contact@davidsonsousa.net</span>"<span style="color: blue;">&nbsp;</span><span style="color: red;">password</span><span style="color: blue;">=</span>"<span style="color: blue;">D#sousa12</span>"<span style="color: blue;">/&gt;</span> <span style="color: blue;"> &lt;/</span><span style="color: #a31515;">smtp</span><span style="color: blue;">&gt;</span> <span style="color: blue;"> &lt;/</span><span style="color: #a31515;">mailSettings</span><span style="color: blue;">&gt;</span> <span style="color: blue;"> &lt;/</span><span style="color: #a31515;">system.net</span><span style="color: blue;">&gt;</span> </pre> </div> Sat, 24 Mar 2012 07:00:00 GMT http://davidsonsousa.net/blog/post/how-to-fix-error-in-processing-the-server-response-was-greylisted-please-try-again-in-x-seconds Private cloud: A evolução da computação nas nuvens http://davidsonsousa.net/blog/post/private-cloud-a-evoluo-da-computao-nas-nuvens <p><a href="http://davidsonsousa.net/en/post/getting-started-with-windows-azure"><img style="float: right;" src="http://davidsonsousa.net/image/articles/1a2b8835-782f-46ad-890e-285986b7df85.jpg" alt="" />Eu j&aacute; falei do Windows Azure aqui (em ingl&ecirc;s)</a>. Mas pra simplificar a id&eacute;ia do Azure: &Eacute; uma solu&ccedil;&atilde;o de computa&ccedil;&atilde;o nas nuvens e uma das suas vantagens &eacute; escalar os projetos de acordo com a necessidade das empresas. Como algumas empresas n&atilde;o se sentiriam confort&aacute;veis enviando dados para os servidores da Microsoft ela criou o conceito de <a href="http://www.microsoft.com/en-us/server-cloud/private-cloud/overview.aspx">Private Cloud</a>.</p> <p>Uma solu&ccedil;&atilde;o Private Cloud, que &eacute; feita no <a href="http://www.microsoft.com/windowsserver/">Windows Server</a> usando a tecnologia <a href="http://www.microsoft.com/systemcenter/">System Center</a> transforma sua pr&oacute;pria infra em uma nuvem interna. Isso faz com que a manuten&ccedil;&atilde;o e desenvolvimento de solu&ccedil;&otilde;es seja simplificado, diminuindo os custos enquanto se aumenta a agilidade e o poder de processamento.</p> <p>Com isso em mente tudo o que a gente precisa &eacute; uma equipe qualificada para fazer isso.</p> <p>Pois bem, a Microsoft sabe que o mercado precisa de gente qualificada pra isso e sempre ofereceu treinamentos e certifica&ccedil;&otilde;es para que os desenvolvedores e profissionais de TI possam desenvolver e validar suas habilidades. E agora temos uma certifica&ccedil;&atilde;o de Private Cloud!</p> <p>A certifica&ccedil;&atilde;o de Private Cloud vai estar dispon&iacute;vel como beta em abril e tem como funda&ccedil;&atilde;o as certifica&ccedil;&otilde;es de Windows Server 2008 que temos hoje mais as certifica&ccedil;&otilde;es de System Center 2012 (ainda em beta).</p> <p>Comece hoje dando uma olhadinha na <a href="http://www.microsoft.com/learning/en/us/certification/cert-private-cloud.aspx">p&aacute;gina da certifica&ccedil;&atilde;o de Private Cloud</a>. L&aacute; &eacute; um &oacute;timo lugar para come&ccedil;ar. Voc&ecirc; tamb&eacute;m pode se inscrever para o <a href="http://mctreadiness.com/MicrosoftCareerConferenceRegistration.aspx?pid=298">Private Cloud Jumpstart course</a> que est&aacute; vindo a&iacute;.</p> <p>T&aacute; na hora de se mexer. Certeza que vai ter muito trampo relacionado a isso em um futuro pr&oacute;ximo.</p> Sun, 18 Mar 2012 12:03:00 GMT http://davidsonsousa.net/blog/post/private-cloud-a-evoluo-da-computao-nas-nuvens Private cloud: The evolution of cloud computing http://davidsonsousa.net/blog/post/private-cloud-the-evolution-of-cloud-computing <p><img style="float: right;" src="http://davidsonsousa.net/image/articles/0be92edc-4501-4eff-a2d0-95b0b52da591.jpg" alt="" /><a href="http://davidsonsousa.net/en/post/getting-started-with-windows-azure">I have already talked a bit about Windows Azure here</a>. To simplify a lot the idea behind <a href="http://www.windowsazure.com">Windows Azure</a>: It is a cloud computing solution and one of its advantages is to escalate the project according to the needs of the company. Of course, some companies wouldn&rsquo;t feel comfortable sending important data to the Microsoft servers but there is a solution for this: <a href="http://www.microsoft.com/en-us/server-cloud/private-cloud/overview.aspx">Private Cloud</a>.</p> <p>A private cloud solution, which is built on <a href="http://www.microsoft.com/windowsserver/">Microsoft Windows Server</a> and <a href="http://www.microsoft.com/systemcenter/">System Center technology</a>, turns your datacenter infrastructure into a cloud based solution. It simplifies deployment, maintenance, and cost, while increasing agility and power.</p> <p>With that in mind all we need is a skilled team to setup everything.</p> <p>Microsoft knows about the needs of the market for professionals who matches these requirements and is offering trainings and certifications which enable IT professionals and developers to develop and validate their skills. That means we now have a private cloud certification!</p> <p>The certification will be available as beta release in April and it starts with the foundation of the Windows Server 2008 exams we have today plus the new System Center 2012 exams (still beta).</p> <p>Get started today checking the <a href="http://www.microsoft.com/learning/en/us/certification/cert-private-cloud.aspx">Microsoft Private Cloud Certification Overview</a> page. It&rsquo;s a good place to start your preparation and practice for this new certification. You can also sign up for the upcoming <a href="http://mctreadiness.com/MicrosoftCareerConferenceRegistration.aspx?pid=298">Private Cloud Jump Start course</a>.</p> <p>Think forward on your career. Surely there will be a plenty of space to work with private clouds in the near future.</p> Thu, 08 Mar 2012 09:10:00 GMT http://davidsonsousa.net/blog/post/private-cloud-the-evolution-of-cloud-computing Carrer move: From .NET Developer to Microsoft Certified Trainer http://davidsonsousa.net/blog/post/carrer-move-from-net-developer-to-microsoft-certified-trainer <p><img style="float: right;" src="../../../../image/8d230a71-4834-4cb4-b9fe-12571e9e06a5.jpg" alt="" />There were some changes since the beginning of the year. From the moment that Europe got hit really hard by the crisis I was wondering about my next career move. There was a very low demand of .NET Developers last year and some HR managers even suggested me to move to Java since its demand was much higher. But I didn&rsquo;t and still don&rsquo;t want. Nothing against the technology itself, it&rsquo;s just that I love the Microsoft stack.</p> <p>Also, if we talk about place to live, Czech Republic isn&rsquo;t such a friendly country as people might wonder. Don&rsquo;t get me wrong, the country is wonderful. But if you don&rsquo;t speak the language you will get into troubles with very simple things. Ok, there are some websites like <a href="http://expats.cz">expats.cz</a> which helps a lot but you can check with any foreigner living in Prague: Czech people seems to complicate a lot their lives over there.</p> <p>So, the first change was my return to Brazil. Not for life, but for just 6 months. The reason was the crisis &ndash; which I have mentioned above &ndash; and also invitation from my friend to come to S&atilde;o Paulo and work in a training center with him. Technically I would come to &ldquo;save his life&rdquo; as he prefers to teach Database related topics but lately was teaching.NET stuff. As result I am working with him as a trainer at <a href="http://www.kasolution.com.br/">Ka Solution</a>, which is the largest Microsoft Gold Certified Partner for Learning Solutions (CPLS) in Latin America, since January.</p> <p>As second change I became Microsoft Certified Trainer. <a href="http://www.microsoft.com/learning/en/us/certification/mct.aspx">Check the details on how to be a MCT here</a>.</p> <p>I am enjoying quite a lot this routine of trainer. I would say that the main difference between a trainer and a developer is the level of stress. While the developer is constantly under pressure the trainer&rsquo;s life is much more relaxed. The trainer has, of course, a huge responsibility since he is the one who will share his knowledge with others creating, then, a new set of developers per class.</p> <p>Of course, I am aware of this responsibility and I guess I am doing well.</p> <p>Another difference is the money at the end of the month. As developer, generally, it doesn&rsquo;t matter how much you work as you will always get the same money. As trainer I feel it&rsquo;s quite fair to get some coins according to the amount of classes I get. If I work a lot, I get a lot of money. If I work less, I get less money.</p> <p>Until this moment being a trainer is financially advantage for me.</p> <p>I have to think about my next move. As I am not planning to quit the education area I guess an English speaking country would be quite interesting. England and Ireland are some of the obvious choices. But we will see.</p> <p>Stay tunned!</p> Fri, 17 Feb 2012 15:20:00 GMT http://davidsonsousa.net/blog/post/carrer-move-from-net-developer-to-microsoft-certified-trainer Se você é um trabalhador mediano, seu salário também é mediano. E você vai ser demitido! http://davidsonsousa.net/blog/post/se-voc-e-um-trabalhador-mediano-seu-salario-tambem-e-mediano-e-voc-vai-ser-demitido <p>Hoje, com mundo globalizado, vemos o quão rápido as coisas mudam. Infelizmente para alguns a maneira como o trabalho é feito também está mudando.</p> <p>Conheço algumas pessoas que acham que trabalhar de 8 horas por dia fazendo um trabalho mediano vai garantir estabilidade no setor privado. O problema é que, além deles serem os primeiros a serem demitidos quando a empresa precisa cortar pessoal, eles nunca crescem profissionalmente.</p> <p>Sem contar com o pessoal que pensa que deve fazer pouco por que o chefe paga pouco, o que beira a irresponsabilidade e a falta de profissionalismo.</p> <p>Essas pessoas esquecem que sempre existe alguém que tem as suas mesmas qualificações e faz a mesma coisa que você, só que mais barato. E isso vai fazer com que você perca espaço no mercado ou abaixar o seu próprio valor.</p> <p>Logo, você tem que ser mais qualificado. A não ser que você passe a cobrar mais barato do que os outros. Quem é de TI sabe que isso acontece com os famosos “<a href="http://vidadeprogramador.com.br/tag/sobrinho/">sobrinhos</a>” (tipo o sobrinho do açougueiro, que sabe fazer site e cobra mais barato).</p> <p>Eu já mencionei aqui no blog <a href="/pt/post/como-fazer-para-tirar-uma-certificao-microsoft-e-consequentemente-melhorar-teu-curriculo">como tirar uma certificação Microsoft</a> e até o motivo dela ser importante no mercado de trabalho. Mas não se pode limitar a isso. Qualquer curso ou certificação que possa ser usado na sua área vale a pena.</p> <p>Sabe por quê?</p> <p>Porque, como disse <a href="http://www.sethgodin.com/sg/">Seth Godin</a>, <em>se você é diferente de alguma forma e se fez único, as pessoas vão te achar e pagar mais</em>.</p> <p>Inspirado no artigo que li no <a href="http://www.businessinsider.com/if-youre-an-average-worker-in-this-forever-recession-youre-going-straight-to-the-bottom-2012-1">Business Insider</a>.</p> Thu, 26 Jan 2012 09:28:00 GMT http://davidsonsousa.net/blog/post/se-voc-e-um-trabalhador-mediano-seu-salario-tambem-e-mediano-e-voc-vai-ser-demitido Czech Republic might get hit by hurricane Andrea http://davidsonsousa.net/blog/post/czech-republic-might-get-hit-by-hurricane-andrea <p><img style="float: right;" src="http://davidsonsousa.net/image/articles/dbb8fe1c-eebf-4854-bfb4-278d5fbf239e.jpg" alt="" />I just saw a link on Facebook about a <a href="http://www.ceskapozice.cz/en/news/society/hurricane-andrea-hit-czech-republic">hurricane which will hit Czech Republic today</a>.</p> <p>The article says that the winds are going to reach 126km/h in the region of <a href="http://g.co/maps/q8wm5">&Uacute;st&iacute; (north Bohemia)</a> while, in the rest of the country, the wind speed might reach 75 to 100 km/h. It also says that higher places can expect between 10 and 50cm of snow.</p> <p>Hurricanes in this part of Europe aren't so common. <a href="http://en.wikipedia.org/wiki/Category:Hurricanes_in_Europe">According to Wikipedia</a> most of the hurricanes that happened here were on the European coast and didn't make so much damage. Probably because they are already weaker when they get here.</p> <p>Besides, they are usually formed in the late summer when the difference of temperatures between the air and the oceans are higher than normal.</p> <p>Now, let's think: Taking in consideration the closest ocean we have here (North Atlantic) and the season of hurricanes (between June and November) I don't know if we can call that a hurricane. But <a href="http://www.climatecrisis.net/an_inconvenient_truth/about_the_film.php">maybe Al Gore was right about the global warming</a>.</p> Thu, 05 Jan 2012 07:44:00 GMT http://davidsonsousa.net/blog/post/czech-republic-might-get-hit-by-hurricane-andrea Boneco realista do Steve Jobs chega ao mercado em fevereiro http://davidsonsousa.net/blog/post/boneco-realista-do-steve-jobs-chega-ao-mercado-em-fevereiro <p><img style="float: right;" src="http://davidsonsousa.net/image/articles/fa490575-f58d-45f5-a506-169c1d7c367c.jpg" alt="Boneco do Steve Jobs" width="275" height="171" />A empresa americana <a href="http://www.inicons.com/">In Icons</a> vai lan&ccedil;ar em fevereiro desse ano um boneco extremamente detalhado de <strong>Steve Jobs</strong> "para honrar o &iacute;cone americano e grande vision&aacute;rio" que ele foi.</p> <p>Como pode ser visto nas fotos abaixo o boneco vem com a j&aacute; famosa camisa de gola rol&ecirc; preta que ele sempre usou. E acredito que o rosto deve ter sido inspirado no j&aacute; cl&aacute;ssico <a href="http://www.youtube.com/watch?v=UF8uR6Z6KLc">discurso de Steve Jobs na Universidade de Stanford em 2005</a>.</p> <p>Ainda segundo o <a href="http://mashable.com/2012/01/02/steve-jobs-action-figure-february/">Mashable</a> o boneco tamb&eacute;m vem com um painel escrito "<a href="http://www.youtube.com/watch?v=cO-2NAl7Sm0">One more thing</a>", duas ma&ccedil;&atilde;s (uma mordida), uma cadeira e um par de meias pretas. Infelizmente o iPhone n&atilde;o est&aacute; incluso.</p> <p>O boneco tem aproximadamente 30 cm de altura e vai custar US$ 99 (R$ 185) l&aacute; nos EUA. Mas tenho quase certeza que chega no Brasil custando uns R$ 500 no m&iacute;nimo, vai vendo.</p> <p>via <a href="http://mashable.com/">Mashable</a>.</p> <p>Fotos abaixo:</p> <p style="text-align: center;"><img src="http://davidsonsousa.net/image/articles/1d734e96-b717-40cb-bfe2-16ceb7b5dfe5.jpg" alt="Boneco do Steve Jobs" /></p> <p style="text-align: center;"><img src="http://davidsonsousa.net/image/articles/12f040fc-16d0-4a84-967c-bf8948d18632.jpg" alt="Boneco do Steve Jobs" /></p> <p style="text-align: center;"><img src="http://davidsonsousa.net/image/articles/13d55068-3825-4aaa-a73a-cc9a8dcfd373.jpg" alt="Boneco do Steve Jobs" /></p> <p style="text-align: center;"><img src="http://davidsonsousa.net/image/articles/511a97b0-1e2e-46c6-a021-bd1cf9c6b5ab.jpg" alt="Boneco do Steve Jobs" /></p> <p style="text-align: center;"><img src="http://davidsonsousa.net/image/articles/5f7dd9c2-e3a4-487f-953e-f6f5ff1f130a.jpg" alt="Boneco do Steve Jobs" /></p> Tue, 03 Jan 2012 08:14:00 GMT http://davidsonsousa.net/blog/post/boneco-realista-do-steve-jobs-chega-ao-mercado-em-fevereiro Análise do Kindle 4 http://davidsonsousa.net/blog/post/analise-do-kindle-4 <p><img style="float: right;" src="http://davidsonsousa.net/image/articles/78bed99c-1b3a-4dff-91ab-9ec11a524948.jpg" alt="" width="300" height="364" />H&aacute; alguns meses atr&aacute;s eu estava pensando em come&ccedil;ar a ler mais livros, mas, uma vez que o notebook n&atilde;o &eacute; t&atilde;o confort&aacute;vel para e-books e eu teria problemas de espa&ccedil;o com livros f&iacute;sicos, decidi ir para o Kindle. Ent&atilde;o eu comprei o <a href="http://www.amazon.com/gp/product/B004HZYA6E/ref=famstripe_kk3g">Kindle 3</a> (com teclado), que era o mais recente na &eacute;poca. Da&iacute;, 1 m&ecirc;s depois, a Amazon lan&ccedil;ou o <a href="http://www.amazon.com/Kindle-eReader-eBook-Reader-e-Reader-Special-Offers/dp/B0051QVESA">Kindle 4</a> (sem teclado). O que fiz? Vendi o que eu tinha e dias atr&aacute;s, finalmente, comprei a vers&atilde;o mais recente.</p> <h3>Display</h3> <p>O display <a href="http://en.wikipedia.org/wiki/E_Ink">e-ink</a> &eacute; incr&iacute;vel e ningu&eacute;m pode discutir quanto a isso. A aus&ecirc;ncia de backlight faz com que a leitura se torne muito maic confort&aacute;vel do que em um LCD normal mas o "refresh" ao mudar as p&aacute;ginas &eacute; um pouco inconsistente. Quero dizer, na vers&atilde;o anterior de anima&ccedil;&atilde;o da tela (escurece, clareia) acontecia sempre que a pessoa virava a p&aacute;gina. Com a vers&atilde;o atual isso parece meio aleat&oacute;rio, mas nada que perturbe o uso.</p> <h3>Tamanho</h3> <p style="text-align: center;"><img src="http://davidsonsousa.net/image/articles/33b39ca3-7797-4457-bf98-b7b60dd7e174.jpg" alt="" width="360" height="282" /><br />Compara&ccedil;&atilde;o de tamanho entre o Kindle 4 e o Kindle 3</p> <p style="text-align: left;">Uma das coisas que me atrairam nesse Kindle &eacute; seu tamanho reduzido quando comparado com a vers&atilde;o anterior, j&aacute; que o teclado foi removido. E como esta vers&atilde;o &eacute; menor ela caberia muito melhor em bolsas, tornando mais f&aacute;cil carreg&aacute;-lo.</p> <h3 style="text-align: left;">Conex&atilde;o com a Internet</h3> <p>O Kindle 4 n&atilde;o tem 3G, Wi-Fi apenas. Algumas pessoas podem n&atilde;o gostar da falta de 3G, mas isso n&atilde;o me afeta muito j&aacute; que eu costumo sincronizar e se conectar com a internet em casa. Caso algu&eacute;m queira um Kindle com 3G, eu recomendaria o <a href="http://www.amazon.com/gp/product/B004HZYA6E/ref=famstripe_kk3g">Kindle 3</a> ou o <a href="http://www.amazon.com/gp/product/B005890G8O/ref=famstripe_kt3g">Kindle Touch</a>.</p> <h3>&Aacute;udio</h3> <p>Esta vers&atilde;o n&atilde;o tem &aacute;udio, o que pode ser uma coisa ruim para aqueles que s&atilde;o &aacute;vidos "leitores" de audiobooks ou aqueles que gostariam de usar o Kindle como mp3 player.</p> <h3>Bateria</h3> <p>Com esta vers&atilde;o voc&ecirc; s&oacute; ser&aacute; capaz de recarregar o seu dispositivo quando conectado ao computador via USB. Na vers&atilde;o anterior voc&ecirc; tinha um pequeno adaptador que permitiria o Kindle ser conectado na parede. Mas se voc&ecirc; est&aacute; pensando em tomar toda a <a href="http://pt.wikipedia.org/wiki/Biblioteca_de_Alexandria">biblioteca de Alexandria</a> com voc&ecirc; durante uma viagem o Kindle &eacute; uma boa escolha, j&aacute; que sua bateria dura cerca de um m&ecirc;s para ser completamente descarregada.</p> <h3><br />Veredito</h3> <ul> <li>Pr&oacute;s: A tela e-ink incr&iacute;vel, longa vida &uacute;til da bateria, o peso mais leve, menor tamanho e pela facilidade de comprar / fazer download de livros no aparelho.</li> <li>Contras: Sem &aacute;udio, sem 3G, sem teclado... Mas estes s&atilde;o apenas os contras para quem gosta destas coisas.</li> </ul> <p>No final das contas eu diria que as coisas que foram retirados do Kindle incomodam nem um pouco j&aacute; que o dispositivo &eacute; exclusivamente para a leitura. Caso este seja seu objetivo o Kindle 4 &eacute; ideal para voc&ecirc;.</p> Mon, 02 Jan 2012 03:30:00 GMT http://davidsonsousa.net/blog/post/analise-do-kindle-4 Review: Amazon Kindle 4 http://davidsonsousa.net/blog/post/review-amazon-kindle-4 <p><img style="float: right;" src="http://davidsonsousa.net/image/articles/78bed99c-1b3a-4dff-91ab-9ec11a524948.jpg" alt="" /></p> <p>Few months ago I thought about start reading more books but, since the notebook isn&rsquo;t so comfortable for e-books and real books would give me some problems with space, I have decided to go for the Kindle. So I got the <a href="http://www.amazon.com/gp/product/B004HZYA6E/ref=famstripe_kk3g">Kindle 3</a> (with keyboard), which was the newest one at that time. About 1 month later Amazon has released the <a href="http://www.amazon.com/Kindle-eReader-eBook-Reader-e-Reader-Special-Offers/dp/B0051QVESA">Kindle 4</a> (without keyboard), I sold the one I had and yesterday, finally, I got the newest version.</p> <p><span style="color: #ff0000;"><em><strong>Update: I do not intend to make a professional review. It's just my opinion about something I have bought for myself.</strong></em></span></p> <h3>Display</h3> <p>The <a href="http://en.wikipedia.org/wiki/E_Ink">e-ink</a> display is amazing and nobody can say otherwise. The absence of backlight makes it very comfortable to read but the &ldquo;refresh&rdquo; when changing the pages is a bit inconsistent. I mean, on the previous version the screen&rsquo;s animation (fade to black, fade to normal) was happening whenever the person would turns the page. With the current version this seems kinda random, but nothing which would disturb the usage.</p> <h3>Size</h3> <p style="text-align: center;"><img src="http://davidsonsousa.net/image/articles/33b39ca3-7797-4457-bf98-b7b60dd7e174.jpg" alt="" /><br /><em>Kindle 4 and Kindle 3 size comparison</em></p> <p>One of the things which initially got me on this kindle is its reduced size when compared with the previous version since the keyboard was removed. And as this version is smaller it would fit much better into bags and jacket&rsquo;s pockets, making it easier to carry it around.</p> <h3>Internet connection</h3> <p>The Kindle 4 doesn&rsquo;t have 3G, only Wi-Fi. Some people might not like the lack of 3G but that doesn&rsquo;t affect me at all since I usually sync and connect with the internet at home. In case anyone wants a Kindle with 3G, it&rsquo;s recommended to get the <a href="http://www.amazon.com/gp/product/B004HZYA6E/ref=famstripe_kk3g">Kindle 3</a> or the <a href="http://www.amazon.com/gp/product/B005890G8O/ref=famstripe_kt3g">Kindle Touch</a>.</p> <h3>Audio</h3> <p>This version doesn&rsquo;t have audio, which can be a bad thing for those who are avid &ldquo;readers&rdquo; of audiobooks or those who would like to use the Kindle as mp3 player.</p> <h3>Battery</h3> <p>With this version you are only able to recharge your device when connected with the computer via USB. Before, you would have a small adapter which would enable the Kindle to be connected on the wall. But, apart from that, if you plan on taking the whole <a href="http://en.wikipedia.org/wiki/Library_of_Alexandria">Library of Alexandria</a> with you during a trip the Kindle is a nice choice since its battery takes around 1 month to be completely uncharged.</p> <h3>Verdict</h3> <ul> <li><strong>Pros</strong>: The amazing e-ink display, the long battery&rsquo;s lifespan, the lighter weight, the smaller size and the ease to buy/download books into the device.</li> <li><strong>Cons</strong>: No audio, no 3G, no keyboard&hellip; But these cons are only for those who like these things.</li> </ul> <p>As final word I would say that the things which were removed from the Kindle don&rsquo;t bother at all since the device is exclusively for reading. So, if you want to get a device exclusively for reading, the Kindle 4 is ideal for you.</p> Thu, 29 Dec 2011 10:07:00 GMT http://davidsonsousa.net/blog/post/review-amazon-kindle-4 5 coisas produtivas que você pode fazer enquanto procura emprego http://davidsonsousa.net/blog/post/5-coisas-produtivas-que-voc-pode-fazer-enquanto-procura-emprego <p><img style="float: right;" src="../../image/a44b9f86-8ce9-452d-abe9-99f152405618.jpg" alt="" />Todo mundo est&aacute; sabendo da crise europeia, seja pela TV, internet ou por parentes e amigos morando em algum dos pa&iacute;ses afetados. Aqui na Rep&uacute;blica Tcheca a coisa n&atilde;o est&aacute; t&atilde;o diferente. E isso acabou me inspirando a fazer uma lista de coisas a se fazer enquanto se procura emprego.</p> <p>Vamos aos items:</p> <ol> <li><strong>Reestruturar o curr&iacute;culo</strong>: Muitas pessoas sequer encostam no curr&iacute;culo quando est&atilde;o no mercado de trabalho. Outras simplesmente o deixam com um visual muito estranho. Saiba que muitos head-hunters ignoram os curr&iacute;culos mal estruturados ou sem padr&atilde;o (tipos de letras ou tamanhos diferentes). Se este &eacute; o seu caso &eacute; melhor aproveitar o tempo livre e organizar o curr&iacute;culo antes de come&ccedil;ar a espalh&aacute;-lo por a&iacute;. Aproveite e tire o n&uacute;mero dos documentos e endere&ccedil;o de l&aacute; j&aacute;.</li> <li><strong>Fazer cursos e/ou tirar certifica&ccedil;&otilde;es</strong>: O tempo que voc&ecirc; passa zanzando em casa pode muito bem ser usado para fazer algum curso ou tirar alguma certifica&ccedil;&atilde;o de sua &aacute;rea. Eu at&eacute; j&aacute; falei de <a href="../../pt/post/como-fazer-para-tirar-uma-certificao-microsoft-e-consequentemente-melhorar-teu-curriculo">como tirar uma certifica&ccedil;&atilde;o Microsoft</a> antes. Al&eacute;m disso, voc&ecirc; j&aacute; teria na ponta da l&iacute;ngua a resposta para quando te perguntarem o que voc&ecirc; est&aacute; fazendo desde que saiu do emprego.</li> <li><strong>Saiba como anda o mercado</strong>: Qualquer pessoa tende a se acomodar quando est&aacute; em uma empresa achando que nada vai atingi-la. Logo, quando sai, ela acaba n&atilde;o tendo no&ccedil;&atilde;o alguma de como anda o mercado para a &aacute;rea dela. Se informe lendo revistas, conversando com pessoas e olhando sites de emprego sobre sua &aacute;rea. Isso pode ser bom para um planejamento tanto de sal&aacute;rio (caso estejam pagando mais em outros lugares) quanto de mudan&ccedil;a de carreira (caso sua profiss&atilde;o est&aacute; se extinguindo, como programadores COBOL).</li> <li><strong>Pratique networking</strong>: Agora &eacute; uma boa oportunidade para ir a eventos e entrar em contato com seus amigos para jogar conversa fora. No caso dos eventos, &eacute; importante que eles estejam relacionados ou que complementem a sua profiss&atilde;o. N&atilde;o me vejo como programador indo a um evento de fazendeiros, por exemplo, e sim a um de neg&oacute;cios ou de marketing. Um detalhe aqui: Na minha humilde opini&atilde;o, o melhor networking &eacute; aquele onde as pessoas se esfor&ccedil;am para criar v&iacute;nculos. Uma vez fui a um evento de networking onde um cara chegou para conversar comigo e ficou falando de como a empresa dele presta bons servi&ccedil;os. Sinceramente, a &uacute;nica coisa que eu me lembro dele &eacute; que ele parece o Salsicha do filme Scooby Doo. E da empresa? Ah, &eacute; a empresa do Salsicha...</li> <li><strong>Cuide de sua sa&uacute;de f&iacute;sica e mental</strong>: Eu sei que &eacute; complicado de se pensar em divers&atilde;o j&aacute; que &eacute; normal ficar deprimido e/ou estressado quando se est&aacute; desempregado. S&oacute; que esse pode ser um momento muito bom para se passear com os filhos ou com o cachorro, come&ccedil;ar uma atividade f&iacute;sica (andar, correr...), fazer os exames m&eacute;dicos que voc&ecirc; nunca teve tempo de fazer, jogar videogame... Enfim, fa&ccedil;a coisas que voc&ecirc; n&atilde;o est&aacute; acostumado a fazer para poder tirar um pouco o foco do momento ruim.</li> </ol> <p>Tomando essas medidas voc&ecirc; com certeza vai conseguir melhorar sua qualidade de vida, seu curr&iacute;culo e conhecer pessoas. Tudo o que voc&ecirc; precisa para conseguir um emprego melhor do que o que voc&ecirc; tinha. Al&eacute;m do mais, nenhum head-hunter gosta de ver a pessoa chegando desmotivada para uma entrevista.</p> Tue, 27 Dec 2011 07:58:00 GMT http://davidsonsousa.net/blog/post/5-coisas-produtivas-que-voc-pode-fazer-enquanto-procura-emprego Minha opinião sobre biblioteca nas empresas http://davidsonsousa.net/blog/post/um-pequeno-devaneio-sobre-biblioteca-nas-empresas <p>Que uma empresa deve investir em uma biblioteca n&oacute;s j&aacute; sabemos. Afinal, os funcion&aacute;rios devem (ou deveriam) estar em constante atualiza&ccedil;&atilde;o. E n&atilde;o falo s&oacute; de programadores, mas tamb&eacute;m de administra&ccedil;&atilde;o, marketing, estat&iacute;sticas... O que for relevante para os funcion&aacute;rios.</p> <p>Infelizmente o fator biblioteca n&atilde;o significa que a empresa seja boa, como na tirinha abaixo:</p> <p><img src="http://davidsonsousa.net/image/articles/tirinha384.png" alt="" /><br /><em>Pr&aacute;tica comum nas empresas brasileiras, via <a href="http://vidadeprogramador.com.br">Vida de Programador</a></em></p> <p>Uma das empresas que trabalhei tinha uma biblioteca f&iacute;sica muito boa na teoria, com v&aacute;rios livros dispon&iacute;veis. O problema &eacute; que a maioria estava t&atilde;o defasada a ponto de eu achar um exemplar de Visual Basic 5. &Oacute;bvio que um livro assim faria sentido se existissem projetos usando VB5, mas n&atilde;o era o caso.</p> <p>Al&eacute;m dos livros de tecnologia serem caros e se defasarem rapidamente, existe outro problema: Espa&ccedil;o. &Eacute; muito comum ver funcion&aacute;rios apertados com mesas pequenas em uma micro empresa disputando lugar com lixeiras e gabinetes. Uma solu&ccedil;&atilde;o pra isso seria a compra de e-books. Essa alternativa se torna cada vez mais vi&aacute;vel com a populariza&ccedil;&atilde;o dos tablets e smartphones hoje em dia. Fora que os e-books s&atilde;o mais baratos (alguns at&eacute; de gra&ccedil;a) do que os livros f&iacute;sicos j&aacute; que n&atilde;o existe gasto com papel e log&iacute;stica.</p> <p>Pode soar meio &oacute;bvio mas, no final das contas, a empresa deve investir em uma biblioteca virtual. Com isso ela economiza espa&ccedil;o (um arm&aacute;rio de a&ccedil;o a menos no meio da sala de desenvolvimento), dinheiro e tamb&eacute;m evita a situa&ccedil;&atilde;o onde um funcion&aacute;rio vai pegar um livro que j&aacute; est&aacute; reservado para outro.</p> Tue, 20 Dec 2011 06:49:00 GMT http://davidsonsousa.net/blog/post/um-pequeno-devaneio-sobre-biblioteca-nas-empresas Getting started with Windows Azure http://davidsonsousa.net/blog/post/getting-started-with-windows-azure <p><img style="float: right;" src="../../Image/windowsaz_h_web.jpg" alt="" /></p><p>Some time ago a friend of mine recommended me a project which consisted in an iPhone application which would receive the news from a webservice. And, behind the webservice, should exist a <a href="http://www.windowsazure.com/en-us/">Windows Azure</a> app. I had very little time to learn the details of Windows Azure and, after a while, the project was released. The experience was very interesting and satisfying but, since Windows Azure was a very recent technology, there weren't so many material or bug reports where I could look at that time.</p><p>And why am I saying that?</p><p>Because now, after Microsoft have re-organized itself and moved some people around, <a href="http://weblogs.asp.net/scottgu/">Scott Guthrie</a> became the head of Windows Azure team and gave a <a href="http://channel9.msdn.com/Events/windowsazure/learn/Keynote-Getting-Started-with-Windows-Azure">keynote about Microsoft's newest technology</a>:</p><p><object type="application/x-silverlight-2" data="data:application/x-silverlight-2," width="478" height="242"><param name="minRuntimeVersion" value="4.0.50401.0"/><param name="source" value="http://channel9.msdn.com/scripts/Channel9.xap?v=1.9"/><param name="initParams" value="mediaurl=http://smooth.ch9.ms/ch9/5b5c/9fd4bdb2-689d-4ffe-b26f-9fb9000e5b5c/KeynoteScottGu.ism/manifest,thumbnail=http://video.ch9.ms/ch9/5b5c/9fd4bdb2-689d-4ffe-b26f-9fb9000e5b5c/KeynoteScottGu_custom_ch9.jpg,deliverymethod=adaptivestreaming,autoplay=false,entryid=9fd4bdb2689d4ffeb26f9fb9000e5b5c"/></object></p><p>The keynote is very interesting and have clarified many points about Windows Azure I didn't know or I have ignored. It's a good start for everyone who would like to dive into cloud computing using the Microsoft stack.</p> Fri, 16 Dec 2011 10:44:00 GMT http://davidsonsousa.net/blog/post/getting-started-with-windows-azure How to improve your resume with a Microsoft certification http://davidsonsousa.net/blog/post/how-to-improve-your-resume-with-a-microsoft-certification <p><img style="float: right;" src="http://davidsonsousa.net/image/articles/mcp.png" alt="" />I had 17 years old when I heard for the first time about the <a href="http://www.microsoft.com/learning/en/us/certification/cert-overview.aspx">Microsoft certifications</a>. From that time I started to think about having one. But there were 2 problems: 1) I didn't speak English; 2) I didn't know where I could find the materials to study. Few years later, already speaking English, I finally found a way to organize the materials to study for the certifications.</p> <p>Basically, a certification exists to prove your knowledge in some certain topic. But if we talk about the Microsoft certifications, there is an idea that the person who has it only passed the exam because he/she got <a href="http://en.wikipedia.org/wiki/Brain_dump">brain dumps</a>. Of course, many people use this way to make the exams. And, not criticizing who does it but, is this person a good professional? I mean, anyone can pass the Microsoft exam (as long it's from your field) since it is not as complicated as it looks. With that said, I will show you how you can reach your certification. [more]</p> <h3>Organize your study material</h3> <p>The Microsoft website lists everything which will be asked on the exam you will take (for example: <a href="http://www.microsoft.com/learning/en/us/Exam.aspx?ID=70-515&amp;Locale=en-us#tab2">70-515 - TS: Web Applications Development</a>). From the moment you have this list, collect all necessary material for your study: Look for PDFs, buy books, bookmark all websites with relevant information you see... Everything is worthy at this point. Try to have everything before you start to study as you can't waste time looking for anything during the studies. But, in case you need to complement some topic, avoid wasting time on the internet. If you open another tab on your browser you are risking to start to procrastinate.</p> <h3>Organize your time</h3> <p>You have no time. At least you always complain about that when there is something interesting to do. Actually the problem is: Some people are unable to give up some things for themselves and they don't notice how their time is misused. For example: Why not use the 30 minutes you spend on the way to work to study? Or when you go to the doctor? Or, the most obvious, during the weekend you would go to some party...</p> <h3>Focus</h3> <p>Once you finally got time to your studies, you have to get the study material (already organized) and start to work. Remember: It can happen that you have a free weekend to study and some of your friends call you asking to go to some amazing event. So, you have to make a decision: Go to the beach/party/whatever with your friends or make your shine a little bit more? You must have in mind that a certification now can result in a salary raise in the future, depending on the company you are working at. Or make easy to find another job. Thinking in this way you will see how it's easy is to have any decision.</p> <h3>Practice, practice, practice</h3> <p>Ok, this isn't new but remember: Always practice what you are learning. Today you only know that 2 + 2 = 4 because you were practicing it when you were young. When I started learning for my certifications I decided to build this blog only because I wanted to practice <a href="http://www.asp.net/mvc">ASP.NET MVC</a>. All development was following everything I was learning. Obviously I had many problems but I but that's what made me learn. And I only made the exam when I say that I had covered all study plan. As result, I have passed with 100%. Magic? No, practice.</p> <h3>Conclusion</h3> <p>It looks complicated but, as I said, it isn't. Each question of the exam has multiple choices. And since some questions contain answers for other questions I would recommend you to read the exam before start to answer. Another thing is: If you go ready for the exam you will not waste time thinking about the answers. Sometimes they are obvious and you will know the answer right away. Just study and practice and everything will be alright.</p> <p>Be sure that a certification on your resume will attract the attention of hiring managers. ;-)</p> <div id="_mcePaste" class="mcePaste" style="position: absolute; left: -10000px; top: 814px; width: 1px; height: 1px; overflow: hidden;"> <h3>Practice,</h3> </div> Mon, 05 Dec 2011 13:26:00 GMT http://davidsonsousa.net/blog/post/how-to-improve-your-resume-with-a-microsoft-certification Redimensione imagens dinamicamente em C# mantendo sua proporção http://davidsonsousa.net/blog/post/redimensione-imagens-dinamicamente-em-c-mantendo-a-proporo <p><img style="float: right;" src="http://davidsonsousa.net/image/articles/redimensionar.png" alt="" /></p> <p>Existem alguns momentos que, enquanto desenvolvendo um projeto, temos que parar de fazer o que estamos acostumados (brincar com classes e acesso a banco) para que possamos fazer algo que nunca fizemos ou que n&atilde;o fazemos com frequ&ecirc;ncia. No meu caso &eacute; edi&ccedil;&atilde;o de imagens.</p> <p>O c&oacute;digo abaixo &eacute; muito simples os poucos coment&aacute;rios que tem (em ingl&ecirc;s) podem te dar uma id&eacute;ia do que est&aacute; acontecendo. De qualquer modo, o &uacute;nico trabalho que voc&ecirc; vai ter vai ser copiar o c&oacute;digo e colar no seu projeto. Da&iacute; voc&ecirc; s&oacute; vai precisar de fazer a chamada de maneira correta e, voil&agrave;! Imagem redimensionada proporcionalmente!!</p> <p>&nbsp;</p> <pre style="font-family: Consolas; font-size: 13px; color: black; background: none repeat scroll 0% 0% white;"><span style="color: blue;">public</span>&nbsp;<span style="color: blue;">static</span>&nbsp;<span style="color: blue;">void</span>&nbsp;ResizeImage(<span style="color: blue;">string</span>&nbsp;originalFile,&nbsp;<span style="color: blue;">string</span>&nbsp;newFile,&nbsp;<span style="color: blue;">int</span>&nbsp;newWidth,&nbsp;<span style="color: blue;">int</span>&nbsp;maxHeight,&nbsp;<span style="color: blue;">bool</span>&nbsp;onlyResizeIfWider) { <span style="color: #2b91af;">Image</span>&nbsp;fullsizeImage&nbsp;=&nbsp;<span style="color: #2b91af;">Image</span>.FromFile(originalFile); <span style="color: green;">// Prevent&nbsp;using&nbsp;images&nbsp;internal&nbsp;thumbnail</span> fullsizeImage.RotateFlip(<span style="color: #2b91af;">RotateFlipType</span>.Rotate180FlipNone); fullsizeImage.RotateFlip(<span style="color: #2b91af;">RotateFlipType</span>.Rotate180FlipNone); <span style="color: blue;">if</span>&nbsp;(onlyResizeIfWider) { <span style="color: blue;">if</span>&nbsp;(fullsizeImage.Width&nbsp;&lt;=&nbsp;newWidth) { newWidth&nbsp;=&nbsp;fullsizeImage.Width; } } <span style="color: blue;">int</span>&nbsp;newHeight&nbsp;=&nbsp;fullsizeImage.Height&nbsp;*&nbsp;newWidth&nbsp;/&nbsp;fullsizeImage.Width; <span style="color: blue;">if</span>&nbsp;(newHeight&nbsp;&gt;&nbsp;maxHeight) { <span style="color: green;">//&nbsp;Resize&nbsp;with&nbsp;height&nbsp;instead</span> newWidth&nbsp;=&nbsp;fullsizeImage.Width&nbsp;*&nbsp;maxHeight&nbsp;/&nbsp;fullsizeImage.Height; newHeight&nbsp;=&nbsp;maxHeight; } <span style="color: #2b91af;">Image</span>&nbsp;newImage&nbsp;=&nbsp;fullsizeImage.GetThumbnailImage(newWidth,&nbsp;newHeight,&nbsp;<span style="color: blue;">null</span>,&nbsp;<span style="color: #2b91af;">IntPtr</span>.Zero); <span style="color: green;">//&nbsp;Clear&nbsp;handle&nbsp;to&nbsp;original&nbsp;file&nbsp;so&nbsp;that&nbsp;we&nbsp;can&nbsp;overwrite&nbsp;it&nbsp;if&nbsp;necessary</span> fullsizeImage.Dispose(); <span style="color: green;">//&nbsp;Save&nbsp;resized&nbsp;picture</span> newImage.Save(newFile); } </pre> <p>S&oacute; lembre-se de salvar as imagens em uma pasta com as permiss&otilde;es de leitura e escrita para evitar erros.</p> <p>via <a href="http://snippets.dzone.com/posts/show/4336">DZone snippets</a></p> <div id="_mcePaste" class="mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow: hidden;"> <pre style="font-family: Consolas; font-size: 13; color: black; background: white;"> <span style="color: blue;">public</span>&nbsp;<span style="color: blue;">static</span>&nbsp;<span style="color: blue;">void</span>&nbsp;ResizeImage(<span style="color: blue;">string</span>&nbsp;originalFile,&nbsp;<span style="color: blue;">string</span>&nbsp;newFile,&nbsp;<span style="color: blue;">int</span>&nbsp;newWidth,&nbsp;<span style="color: blue;">int</span>&nbsp;maxHeight,&nbsp;<span style="color: blue;">bool</span>&nbsp;onlyResizeIfWider) { <span style="color: #2b91af;">Image</span>&nbsp;fullsizeImage&nbsp;=&nbsp;<span style="color: #2b91af;">Image</span>.FromFile(originalFile); <span style="color: green;">//&nbsp;Prevent&nbsp;using&nbsp;images&nbsp;internal&nbsp;thumbnail</span> fullsizeImage.RotateFlip(<span style="color: #2b91af;">RotateFlipType</span>.Rotate180FlipNone); fullsizeImage.RotateFlip(<span style="color: #2b91af;">RotateFlipType</span>.Rotate180FlipNone); <span style="color: blue;">if</span>&nbsp;(onlyResizeIfWider) { <span style="color: blue;">if</span>&nbsp;(fullsizeImage.Width&nbsp;&lt;=&nbsp;newWidth) { newWidth&nbsp;=&nbsp;fullsizeImage.Width; } } <span style="color: blue;">int</span>&nbsp;newHeight&nbsp;=&nbsp;fullsizeImage.Height&nbsp;*&nbsp;newWidth&nbsp;/&nbsp;fullsizeImage.Width; <span style="color: blue;">if</span>&nbsp;(newHeight&nbsp;&gt;&nbsp;maxHeight) { <span style="color: green;">//&nbsp;Resize&nbsp;with&nbsp;height&nbsp;instead</span> newWidth&nbsp;=&nbsp;fullsizeImage.Width&nbsp;*&nbsp;maxHeight&nbsp;/&nbsp;fullsizeImage.Height; newHeight&nbsp;=&nbsp;maxHeight; } <span style="color: #2b91af;">Image</span>&nbsp;newImage&nbsp;=&nbsp;fullsizeImage.GetThumbnailImage(newWidth,&nbsp;newHeight,&nbsp;<span style="color: blue;">null</span>,&nbsp;<span style="color: #2b91af;">IntPtr</span>.Zero); <span style="color: green;">//&nbsp;Clear&nbsp;handle&nbsp;to&nbsp;original&nbsp;file&nbsp;so&nbsp;that&nbsp;we&nbsp;can&nbsp;overwrite&nbsp;it&nbsp;if&nbsp;necessary</span> fullsizeImage.Dispose(); <span style="color: green;">//&nbsp;Save&nbsp;resized&nbsp;picture</span> newImage.Save(newFile); } </pre> </div> Sun, 04 Dec 2011 08:48:00 GMT http://davidsonsousa.net/blog/post/redimensione-imagens-dinamicamente-em-c-mantendo-a-proporo Resize images keeping the aspect ratio in C# http://davidsonsousa.net/blog/post/resize-images-programmatically-keeping-the-aspect-ratio-in-c <p><img style="float: right;" src="http://davidsonsousa.net/image/articles/redimensionar.png" alt="" />There are some moments while developing an application that we have to stop playing with the usual (CRUD) in order to do something that we aren't used to do. One of these things (in my case) is image editing.</p> <p>The code below is plain simple and the few comments in it might give you an insight of what is happening. Apart from that, the only hard work you will have is to copy the code and paste into your app. Then you only need to make the proper call and, voil&agrave;! Resized image without changing the ratio!!</p> <p>&nbsp;</p> <pre style="font-family: Consolas; font-size: 13px; color: black; background: none repeat scroll 0% 0% white;"><span style="color: blue;">public</span>&nbsp;<span style="color: blue;">static</span>&nbsp;<span style="color: blue;">void</span>&nbsp;ResizeImage(<span style="color: blue;">string</span>&nbsp;originalFile,&nbsp;<span style="color: blue;">string</span>&nbsp;newFile,&nbsp;<span style="color: blue;">int</span>&nbsp;newWidth,&nbsp;<span style="color: blue;">int</span>&nbsp;maxHeight,&nbsp;<span style="color: blue;">bool</span>&nbsp;onlyResizeIfWider) { <span style="color: #2b91af;">Image</span>&nbsp;fullsizeImage&nbsp;=&nbsp;<span style="color: #2b91af;">Image</span>.FromFile(originalFile); <span style="color: green;">//&nbsp;Prevent&nbsp;using&nbsp;images&nbsp;internal&nbsp;thumbnail</span> fullsizeImage.RotateFlip(<span style="color: #2b91af;">RotateFlipType</span>.Rotate180FlipNone); fullsizeImage.RotateFlip(<span style="color: #2b91af;">RotateFlipType</span>.Rotate180FlipNone); <span style="color: blue;">if</span>&nbsp;(onlyResizeIfWider) { <span style="color: blue;">if</span>&nbsp;(fullsizeImage.Width&nbsp;&lt;=&nbsp;newWidth) { newWidth&nbsp;=&nbsp;fullsizeImage.Width; } } <span style="color: blue;">int</span>&nbsp;newHeight&nbsp;=&nbsp;fullsizeImage.Height&nbsp;*&nbsp;newWidth&nbsp;/&nbsp;fullsizeImage.Width; <span style="color: blue;">if</span>&nbsp;(newHeight&nbsp;&gt;&nbsp;maxHeight) { <span style="color: green;">//&nbsp;Resize&nbsp;with&nbsp;height&nbsp;instead</span> newWidth&nbsp;=&nbsp;fullsizeImage.Width&nbsp;*&nbsp;maxHeight&nbsp;/&nbsp;fullsizeImage.Height; newHeight&nbsp;=&nbsp;maxHeight; } <span style="color: #2b91af;">Image</span>&nbsp;newImage&nbsp;=&nbsp;fullsizeImage.GetThumbnailImage(newWidth,&nbsp;newHeight,&nbsp;<span style="color: blue;">null</span>,&nbsp;<span style="color: #2b91af;">IntPtr</span>.Zero); <span style="color: green;">//&nbsp;Clear&nbsp;handle&nbsp;to&nbsp;original&nbsp;file&nbsp;so&nbsp;that&nbsp;we&nbsp;can&nbsp;overwrite&nbsp;it&nbsp;if&nbsp;necessary</span> fullsizeImage.Dispose(); <span style="color: green;">//&nbsp;Save&nbsp;resized&nbsp;picture</span> newImage.Save(newFile); } </pre> <p>Only remember to save the images in a folder with the proper permissions (read/write) in order to avoid errors.</p> <p>via <a href="http://snippets.dzone.com/posts/show/4336">DZone snippets</a></p> <div id="_mcePaste" class="mcePaste" style="position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px; overflow: hidden;"> <pre style="font-family: Consolas; font-size: 13; color: black; background: white;"> <span style="color: blue;">public</span>&nbsp;<span style="color: blue;">static</span>&nbsp;<span style="color: blue;">void</span>&nbsp;ResizeImage(<span style="color: blue;">string</span>&nbsp;originalFile,&nbsp;<span style="color: blue;">string</span>&nbsp;newFile,&nbsp;<span style="color: blue;">int</span>&nbsp;newWidth,&nbsp;<span style="color: blue;">int</span>&nbsp;maxHeight,&nbsp;<span style="color: blue;">bool</span>&nbsp;onlyResizeIfWider) { <span style="color: #2b91af;">Image</span>&nbsp;fullsizeImage&nbsp;=&nbsp;<span style="color: #2b91af;">Image</span>.FromFile(originalFile); <span style="color: green;">//&nbsp;Prevent&nbsp;using&nbsp;images&nbsp;internal&nbsp;thumbnail</span> fullsizeImage.RotateFlip(<span style="color: #2b91af;">RotateFlipType</span>.Rotate180FlipNone); fullsizeImage.RotateFlip(<span style="color: #2b91af;">RotateFlipType</span>.Rotate180FlipNone); <span style="color: blue;">if</span>&nbsp;(onlyResizeIfWider) { <span style="color: blue;">if</span>&nbsp;(fullsizeImage.Width&nbsp;&lt;=&nbsp;newWidth) { newWidth&nbsp;=&nbsp;fullsizeImage.Width; } } <span style="color: blue;">int</span>&nbsp;newHeight&nbsp;=&nbsp;fullsizeImage.Height&nbsp;*&nbsp;newWidth&nbsp;/&nbsp;fullsizeImage.Width; <span style="color: blue;">if</span>&nbsp;(newHeight&nbsp;&gt;&nbsp;maxHeight) { <span style="color: green;">//&nbsp;Resize&nbsp;with&nbsp;height&nbsp;instead</span> newWidth&nbsp;=&nbsp;fullsizeImage.Width&nbsp;*&nbsp;maxHeight&nbsp;/&nbsp;fullsizeImage.Height; newHeight&nbsp;=&nbsp;maxHeight; } <span style="color: #2b91af;">Image</span>&nbsp;newImage&nbsp;=&nbsp;fullsizeImage.GetThumbnailImage(newWidth,&nbsp;newHeight,&nbsp;<span style="color: blue;">null</span>,&nbsp;<span style="color: #2b91af;">IntPtr</span>.Zero); <span style="color: green;">//&nbsp;Clear&nbsp;handle&nbsp;to&nbsp;original&nbsp;file&nbsp;so&nbsp;that&nbsp;we&nbsp;can&nbsp;overwrite&nbsp;it&nbsp;if&nbsp;necessary</span> fullsizeImage.Dispose(); <span style="color: green;">//&nbsp;Save&nbsp;resized&nbsp;picture</span> newImage.Save(newFile); } </pre> </div> Sat, 03 Dec 2011 20:21:00 GMT http://davidsonsousa.net/blog/post/resize-images-programmatically-keeping-the-aspect-ratio-in-c Como melhorar seu curriculo tirando uma certificação Microsoft? http://davidsonsousa.net/blog/post/como-fazer-para-tirar-uma-certificao-microsoft-e-consequentemente-melhorar-teu-curriculo <p><img style="float: right;" src="http://davidsonsousa.net/image/articles/mcp.png" alt="" />Eu tinha 17 anos quando ouvi pela primeira vez sobre as <a href="http://www.microsoft.com/learning/en/us/certification/cert-overview.aspx">certifica&ccedil;&otilde;es Microsoft</a>. Comecei a pensar imediatamente em tirar alguma mas vi que n&atilde;o poderia por 2 motivos: 1) Eu n&atilde;o falava ingl&ecirc;s; 2) Eu n&atilde;o sabia por onde come&ccedil;ar a estudar. Com o passar dos anos comecei a me dedicar mais ao ingl&ecirc;s e, finalmente, consegui me organizar pra poder estudar e tirar minhas certifica&ccedil;&otilde;es.</p> <p>Como o nome j&aacute; diz, uma certifica&ccedil;&atilde;o existe para certificar o seu conhecimento em determinado assunto. No caso das certifica&ccedil;&otilde;es da Microsoft existe um pr&eacute;-conceito de que a pessoa que a possui s&oacute; fez a prova porque conseguiu os chamados <a href="http://en.wikipedia.org/wiki/Brain_dump">brain dumps</a>. &Eacute; fato que muita gente usa esse artif&iacute;cio. N&atilde;o querendo criticar quem o faz mas a gente tem que entrar num acordo aqui: Isso faz com que a pessoa seja um bom profissional? Digo isso porque tirar qualquer certifica&ccedil;&atilde;o da Microsoft (desde que seja da tua &aacute;rea) n&atilde;o &eacute; t&atilde;o complicado quanto parece. Por isso vou listar aqui alguns pontos importantes para que voc&ecirc; possa alcan&ccedil;ar a sua certifica&ccedil;&atilde;o.</p> <h3>Organize o material</h3> <p>O site da Microsoft tem a lista de tudo o que pode cair na prova de certifica&ccedil;&atilde;o que voc&ecirc; quer fazer (por exemplo a <a href="http://www.microsoft.com/learning/en/us/Exam.aspx?ID=70-515&amp;Locale=en-us#tab2">70-515 - TS: Web Applications Development</a>). Com isso em m&atilde;os colete todo o material necess&aacute;rio para seus estudos: Baixe PDFs, compre livros, salve as p&aacute;ginas com material relevante que voc&ecirc; encontrar... Tudo &eacute; v&aacute;lido. Tenha sempre em m&atilde;os o material de estudo para n&atilde;o perder tempo procurando as coisas entre um t&oacute;pico e outro. Mas caso precise procurar algo complementar durante a leitura evite perder muito tempo, ainda mais se estiver lendo algum site. Abrir outra aba do navegador &eacute; um convite ao &oacute;cio.</p> <h3>Organize seu tempo</h3> <p>Voc&ecirc; n&atilde;o tem tempo pra nada. Pelo menos &eacute; o que voc&ecirc; sempre diz quando aparece algo interessante pra fazer. Na verdade o problema &eacute; a dificuldade das pessoas de abrir m&atilde;o de algumas coisas em prol delas mesmas e n&atilde;o perceber tempo mal usado em alguns momentos. Por exemplo: Por que n&atilde;o aproveitar os 30 minutos de &ocirc;nibus at&eacute; o trabalho para estudar? Ou aquele tempo na fila do banco? Ou a ida ao m&eacute;dico? Ou, o mais &oacute;bvio, o final de semana que voc&ecirc; sairia pra balada...</p> <h3>Tenha foco</h3> <p>Uma vez que voc&ecirc; finalmente conseguiu tempo para seus estudos na tua agenda &eacute; hora de pegar o material j&aacute; previamente organizado e colocar a m&atilde;o na massa. &Eacute; bom lembrar: Pode acontecer de voc&ecirc; conseguir fim de semana livre para estudar e chega algum amigo pra te chamar para aquele programa irrecus&aacute;vel. Isso &eacute; bem chato de fazer mas voc&ecirc; tem que tomar uma decis&atilde;o: Ir na praia com os amigos ou valorizar o curr&iacute;culo. Tenha em mente que uma certifica&ccedil;&atilde;o pode significar um aumento de sal&aacute;rio dependendo da empresa. Ou facilitar a entrada em uma empresa melhor. Colocando isso na equa&ccedil;&atilde;o fica muito mais f&aacute;cil de se decidir algo.</p> <h3>Pratique, pratique, pratique</h3> <p>Isso n&atilde;o &eacute; novidade mas vale lembrar: Sempre d&ecirc; um jeito de praticar o que voc&ecirc; est&aacute; estudando. Voc&ecirc; s&oacute; sabe hoje que 2 + 2 = 4 porque ficou praticando isso quando era pequeno. Quando eu comecei a estudar para as minhas certifica&ccedil;&otilde;es comecei a montar este blog para poder estudar <a href="http://www.asp.net/mvc">ASP.NET MVC</a> (que alias &eacute; um otimo exemplo de como colocar a m&atilde;o na massa). Fiz o desenvolvimento dele seguindo tudo o que aprendi. Obviamente os problemas foram aparecendo e eu fui correndo atr&aacute;s das solu&ccedil;&otilde;es. S&oacute; fiz a prova quando percebi que tinha coberto todo o cronograma de estudos. Como resultado eu passei com 100%. Foi m&aacute;gico? N&atilde;o, foi pr&aacute;tica.</p> <h3>Conclus&atilde;o</h3> <p>Parece complicado a primeira vista mas, como falei, n&atilde;o &eacute;. As provas s&atilde;o de m&uacute;ltipla escolha e, as vezes, uma l&aacute; na frente pode responder uma quest&atilde;o l&aacute; atr&aacute;s. Por isso &eacute; bom ler a prova antes de faz&ecirc;-la. Outra coisa &eacute; que se voc&ecirc; vai bem preparado para a prova n&atilde;o vai perder tanto tempo pensando nas respostas. Elas s&atilde;o &oacute;bvias e muitas delas voc&ecirc; vai saber de bate-pronto. Existem pegadinhas? Sim, v&aacute;rias. Mas &eacute; s&oacute; se preparar bem.</p> <p>Lhe garanto que certifica&ccedil;&atilde;o no curr&iacute;culo chama aten&ccedil;&atilde;o dos empregadores, al&eacute;m de fazer com que voc&ecirc; se destaque na multid&atilde;o.</p> Tue, 29 Nov 2011 19:38:00 GMT http://davidsonsousa.net/blog/post/como-fazer-para-tirar-uma-certificao-microsoft-e-consequentemente-melhorar-teu-curriculo Redimentione imagens com CSS mantendo a proporção http://davidsonsousa.net/blog/post/redimentione-imagens-com-css-mantendo-a-proporcao <p>Quando eu estava criando o blog eu não estava exatamente pensando em dispositivos móveis (celulares e afins). Na verdade eu pensava apenas em publicar o site para poder começar a escrever. Ao passar dos dias eu comecei a fazer alguns testes com o <a href="http://www.opera.com/developer/tools/mobile/">Opera Mobile Emulator</a> e eu pude notar que meu blogestava horrendo nele. Alguns ajustes depois e tudo estava perfeito.</p> <p>Até eu escrever <a href="/pt/post/o-que-e-e-como-instalar-pacotes-usando-o-nuget-usando-o-visual-studio-2010">este post</a>.</p> <p>O problema era: As imagens são publicadas usando o tamanho original que, normalmente, são maiores que o container. Para resolver esse problema eu poderia simplesmente redimensionar as imagens para que tenham a mesma largura do container. Mas e se o layout for fluido? E se a imagem também for usada em dispositivos móveis? [more]</p> <p>A solução foi simples: Colocar o max-width em 90%.</p> <pre style="font-family: Consolas; font-size: 13; color: black; background: white;"><span style="color: maroon;">#content</span> <span style="color: maroon;">article</span> <span style="color: maroon;">img</span> { <span style="color: red;">max-width</span>:<span style="color: blue;">90%</span>; } </pre> <p>Neste caso, a <em>div #content</em> e o <em>elemento article</em> (HTML5, alguém?) podem ter qualquer largura já que a imagem vai redimensionar automaticamente para 90% deles. Isso significa que se a largura da imagem tiver menos que 90% do tamanho do container ela não será redimensionada. Agora o mais importante: A proporção da imagem não muda, como você pode ver no print do emulador abaixo.</p> <p><img src="/image/articles/opera_emulator.png" alt="" /></p> <p>Essa foi a solução perfeita para o meu blog mas também pode ajudar em websites onde não temos controle sobre o tamanho das imagens que se serão publicadas.</p> Sun, 27 Nov 2011 06:36:00 GMT http://davidsonsousa.net/blog/post/redimentione-imagens-com-css-mantendo-a-proporcao How to resize images for any resolution (or fluid layout) using CSS http://davidsonsousa.net/blog/post/how-to-resize-images-for-any-resolution-or-fluid-layout-using-css <p>When I was creating this layout I wasn't really thinking of mobile devices. Actually I was only thinking about throwing something online as I wanted to start to write. As the days passed by I started to make some tests with <a href="http://www.opera.com/developer/tools/mobile/">Opera Mobile Emulator</a> and I could see that my blog looked horrible in it. Few adjustments later and everything seemed fine.</p> <p>Until I wrote <a href="../../en/post/what-is-nuget-and-how-to-install-its-packages-into-visual-studio-2010">this post</a>.</p> <p>The problem was: The images had naturally a fixed size which was bigger than their container. To solve this problem I could simply apply to the images the width of the container. But what about the mobile devices or different resolutions? [more]</p> <p>The solution for that is very simple: Set the max-width as 90%.</p> <pre style="font-family: Consolas; font-size: 13; color: black; background: white;"><span style="color: maroon;">#content</span>&nbsp;<span style="color: maroon;">article</span>&nbsp;<span style="color: maroon;">img</span>&nbsp;{&nbsp;<span style="color: red;">max-width</span>:<span style="color: blue;">90%</span>;&nbsp;} </pre> <p>In this case, the <em>div #content</em> and the <em>element article</em> (HTML5, anyone?) can have any width as the image will automatically resize until 90% of their size. It means that if the image would have less than 90% of the width it wouldn't be resized. The most important: The ratio doesn't change, as you can see on the print from the emulator bellow.</p> <p><img src="../../Image/opera_emulator.png" alt="" /></p> <p>So, this is the perfect solution for my blog and also for websites where we can't have control of the images which will be uploaded.</p> Sat, 26 Nov 2011 07:05:00 GMT http://davidsonsousa.net/blog/post/how-to-resize-images-for-any-resolution-or-fluid-layout-using-css What is NuGet and how to install its packages into Visual Studio 2010 http://davidsonsousa.net/blog/post/what-is-nuget-and-how-to-install-its-packages-into-visual-studio-2010 <p>Today I'm gonna talk about a Visual Studio extension which makes things very easy for us developers: <a href="http://nuget.org/">NuGet</a>.</p> <h3>What is Nuget?</h3> <p><img style="margin-right: auto; margin-left: auto; display: block;" src="http://davidsonsousa.net/image/articles/NuGet-Logo.png" alt="" /></p> <p>NuGet (don't mistake with <a href="https://www.google.com/search?hl=en&amp;q=nugget&amp;gs_sm=&amp;gs_upl=&amp;um=1&amp;ie=UTF-8&amp;tbm=isch&amp;source=og&amp;sa=N&amp;tab=wi&amp;biw=1366&amp;bih=656&amp;sei=Ei-9TpidMfKK4gT5pZygBA">nugget</a>) is a Visual Studio extension which helps the library management and on Visual Studio. It helps a lot to add references to a project and also to keep them up to date.</p> <p>Example: You are working on a project which needs to use Json and just found an amazing library (<a href="http://json.codeplex.com/">Json.NET</a>) which can help you to serialize all List&lt;&gt; as you want to return them in json format. You have 2 choices: 1) Add and update the reference manually always when there is a new version available; 2) Install via Nuget and let it take care of the updates.</p> <h3>Where do I download?</h3> <p>Nuget is normally installed when you download and install ASP.NET MVC 3 but, in case you don't have Nuget yet or it had some problems, you can download it directly from the <a href="http://visualstudiogallery.msdn.microsoft.com/27077b70-9dad-4c64-adcf-c7cf6bc9970c">Visual Studio Galery</a>.</p> <h3>How do I install a library via NuGet?</h3> <ol> <li>Using Visual Studio go to the <strong>Solution Explorer</strong>, right click in <strong>References</strong> and select <strong>Manage NuGet Packages<br /></strong><br /><img src="http://davidsonsousa.net/image/articles/nuget1.jpg" alt="" /><br /><br /></li> <li>When the window open you can notice 4 items on the left side:<ol> <li><strong>Installed packages:</strong> List of libraries (packages) already installed;</li> <li><strong>Online:</strong> Packages available for download;</li> <li><strong>Updates:</strong> Updates available for your installed packages;</li> <li><strong>Recent packages:</strong> List of packages which you recently used.<br /><br /></li> </ol><img src="http://davidsonsousa.net/image/articles/nuget2.jpg" alt="" /><br /><br /></li> <li>Select the <strong>Online</strong> item (normally pre selected) and use the search field at the right side (<strong>Search Online</strong>) to look for the desired package. In our case, type <em>Json.NET</em> and wait. The results will appear after few seconds (according to your connection)<br /><br /><img src="http://davidsonsousa.net/image/articles/nuget3.jpg" alt="" /><br /><br /></li> <li>Click in <strong>Install</strong> at the first item. Nuget will download the package automatically and also install it in your project<br /><br /><img src="http://davidsonsousa.net/image/articles/nuget4.jpg" alt="" /><br /><br /></li> <li>After finished you can close the Nuget window. Notice that, besides the reference to Json.NET (Newtonsoft.Json) have been added, a file named <strong>packages.config</strong> was created in the root of the project<br /><br /><img src="http://davidsonsousa.net/image/articles/nuget5.jpg" alt="" /><br /><br /></li> <li>This files has the names and versions of all Nuget packages which were added to your project. I would recommend you to not touch it. :)<br /><br /><img src="http://davidsonsousa.net/image/articles/nuget6.jpg" alt="" /><br /><br /></li> </ol> <p>There is another way to install the packages, which is via command line. If you want to do so just go to&nbsp; <strong>menu View</strong> -&gt; <strong>Other Windows</strong> -&gt; <strong>Package Manager Console</strong>. When the window open you can just type the command which is <a href="http://nuget.org/List/Packages/Newtonsoft.Json">written at the page of the project</a> you want to install. For Json.NET the command is <strong><em>Install-Package Newtonsoft.Json</em></strong>.</p> <p>I honestly prefer to install the packages using the Nuget Manager. It's more centralized and just few clicks far away. Besides, I don't need to open the Nuget website for that. ;)</p> Wed, 16 Nov 2011 11:22:00 GMT http://davidsonsousa.net/blog/post/what-is-nuget-and-how-to-install-its-packages-into-visual-studio-2010 O que é e como instalar pacotes usando o NuGet usando o Visual Studio 2010? http://davidsonsousa.net/blog/post/o-que-e-e-como-instalar-pacotes-usando-o-nuget-usando-o-visual-studio-2010 <p><img style="float: right;" src="../../Image/NuGet-Logo.png" alt="" /></p> <p>Hoje vou falar de uma extens&atilde;o do Visual Studio que &eacute; uma m&atilde;o na roda para n&oacute;s: O <a href="http://nuget.org/">NuGet</a>.</p> <h3>O que &eacute;?</h3> <p>O NuGet (n&atilde;o confundir com <a href="https://www.google.com/search?hl=en&amp;q=nugget&amp;gs_sm=&amp;gs_upl=&amp;um=1&amp;ie=UTF-8&amp;tbm=isch&amp;source=og&amp;sa=N&amp;tab=wi&amp;biw=1366&amp;bih=656&amp;sei=Ei-9TpidMfKK4gT5pZygBA">nugget</a>) &eacute; uma extens&atilde;o do Visual Studio que facilita o gerenciamento de bibliotecas open source e ferramentas no Visual Studio. Em termos pr&aacute;ticos isso facilita muito na hora de adicionar refer&ecirc;ncias em um projeto e mant&ecirc;-las atualizadas.</p> <p>Exemplo: Voc&ecirc; est&aacute; desenvolvendo um projeto que precisa usar Json e achou uma biblioteca incr&iacute;vel (<a href="http://json.codeplex.com/">Json.NET</a>) que pode te ajudar a serializar as List&lt;&gt; para que voc&ecirc; possa retornar tudo no formato Json. Diante deste cen&aacute;rio voc&ecirc; tem praticamente duas escolhas: 1) Adiciona a refer&ecirc;ncia e a atualiza manualmente sempre que sair uma nova vers&atilde;o; 2) Instalar via NuGet e deixar que ele cuide das atualiza&ccedil;&otilde;es. [more]</p> <h3>Onde eu pego?</h3> <p>O NuGet normalmente vem instalado junto com o ASP.NET MVC mas, caso voc&ecirc; n&atilde;o o tenha, pode ir direto na <a href="http://visualstudiogallery.msdn.microsoft.com/27077b70-9dad-4c64-adcf-c7cf6bc9970c">p&aacute;gina dele na Visual Studio Galery</a> e clicar em download.</p> <h3>Como eu instalo uma biblioteca pelo NuGet?</h3> <ol> <li>No Visual Studio, v&aacute; na <strong>Solution Explorer</strong> e clique com o bot&atilde;o direito em <strong>References</strong> e selecione <strong>Manage NuGet Packages</strong><br /><img src="../../Image/nuget1.jpg" alt="" /></li> <li>Quando a janela do NuGet se abrir voc&ecirc; pode notar 4 items a esquerda:<ol> <li><strong>Installed packages:</strong> Mostra a lista dos pacotes (bibliotecas) j&aacute; instalados;</li> <li><strong>Online:</strong> Mostra todos os pacotes dispon&iacute;veis na internet;</li> <li><strong>Updates:</strong> Mostra os updates para os pacotes que voc&ecirc; tem;</li> <li><strong>Recent packages:</strong> Mostra a lista de pacotes que voc&ecirc; usou recentemente nos seus projetos</li> </ol><img src="../../Image/nuget2.jpg" alt="" /></li> <li>Selecione o item <strong>Online</strong> (normalmente pr&eacute;-selecionado) e use o campo de busca a direita (<strong>Search Online</strong>) para procurar o pacote desejado. No nosso caso, digite Json.NET e espere. Os resultados aparecem em alguns segundos (dependendo da sua conex&atilde;o)<br /><img src="../../Image/nuget3.jpg" alt="" /></li> <li>Clique em <strong>Install</strong> no primeiro item. O NuGet vai fazer o download automaticamente do pacote e instalar no teu projeto<br /><img src="../../Image/nuget4.jpg" alt="" /></li> <li>Depois de terminado voc&ecirc; pode fechar a janela do NuGet. Note que, al&eacute;m da refer&ecirc;ncia ao Json.NET (Newtonsoft.Json) ter sido adicionada, um arquivo chamado <strong>packages.config</strong> foi criado na raiz do projeto<br /><img src="../../Image/nuget5.jpg" alt="" /></li> <li>Esse arquivo cont&eacute;m os nomes e vers&otilde;es de todos os pacotes do NuGet que foram adicionados ao projeto. Eu recomendaria n&atilde;o enconstar nele :)<br /><img src="../../Image/nuget6.jpg" alt="" /></li> </ol> <p>Existe tamb&eacute;m um jeito de instalar via linha de comando. Pra isso basta ir no <strong>menu View</strong> -&gt; <strong>Other Windows</strong> -&gt; <strong>Package Manager Console</strong>. Assim que a janelinha aparecer basta digitar o comando que est&aacute; <a href="http://nuget.org/List/Packages/Newtonsoft.Json">escrito na p&aacute;gina do projeto</a> que voc&ecirc; quer instalar. No caso do Json.NET o comando &eacute; <strong><em>Install-Package Newtonsoft.Json</em></strong>.</p> <p>Eu sinceramente prefiro instalar os pacotes de maneira mais visual. Pode parecer meio burocr&aacute;tico a primeira vista mas nada compensa mais do que ter tudo centralizado na IDE a apenas alguns cliques de dist&acirc;ncia. Fora que n&atilde;o preciso abrir o site pra isso. Mas, obviamente, cada caso &eacute; um caso.</p> Fri, 11 Nov 2011 08:01:00 GMT http://davidsonsousa.net/blog/post/o-que-e-e-como-instalar-pacotes-usando-o-nuget-usando-o-visual-studio-2010 DBCC Shrink e Fragmentação http://davidsonsousa.net/blog/post/dbcc-shrink-e-fragmentao <p>J&aacute; tem um tempo que eu quero fazer um post de SQL Server aqui no blog. O &uacute;nico problema &eacute; que eu praticamente s&oacute; sei fazer o b&aacute;sico j&aacute; que meu forte &eacute; ASP.NET. Logo, vou deixar SQL com quem sabe. :)</p> <p>Neste v&iacute;deo o <a href="http://br.linkedin.com/in/robertishimurasousa">Robert</a>, que al&eacute;m de meu amigo &eacute; MCT (<a href="http://www.microsoft.com/learning/en/us/certification/mct.aspx">Microsoft Certified Trainer</a>) na <a href="http://www.kasolution.com.br/">Ka Solution</a>, fala sobre como o shrink pode causar fragmenta&ccedil;&atilde;o nos &iacute;ndices do banco.</p> <p> <object width="640" height="360" data="http://www.youtube.com/v/iP8IB5apXNM?version=3&amp;hl=en_US&amp;hd=1" type="application/x-shockwave-flash"> <param name="data" value="http://www.youtube.com/v/iP8IB5apXNM?version=3&amp;hl=en_US&amp;hd=1" /> <param name="allowFullScreen" value="true" /> <param name="allowscriptaccess" value="always" /> <param name="src" value="http://www.youtube.com/v/iP8IB5apXNM?version=3&amp;hl=en_US&amp;hd=1" /> <param name="allowfullscreen" value="true" /> </object> </p> Tue, 08 Nov 2011 02:12:00 GMT http://davidsonsousa.net/blog/post/dbcc-shrink-e-fragmentao Eu, o Diners Club International e a anuidade do cartão de crédito http://davidsonsousa.net/blog/post/eu-o-diners-club-international-e-a-anuidade-do-carto-de-credito <p><img style="float: right;" src="../../../Image/cartoes-credito.jpg" alt="" width="350" height="262" />Antes de mais nada eu n&atilde;o estou falando mal e nem fazendo propaganda de nada. S&oacute; estou relatando aqui o que aconteceu.</p> <p>No ano passado eu tinha voltado ao Brasil depois de 4 anos pra passar um ano sab&aacute;tico na casa da minha m&atilde;e. O plano era ficar de bobeira em casa estudando, como se fosse um adolescente mas cansei e acabei indo trabalhar e morar em S&atilde;o Paulo j&aacute; que o mercado &eacute; melhor do que em Vit&oacute;ria.</p> <p>J&aacute; em Sampa eu abri uma conta no <a href="http://citibank.com.br/">Citibank</a> e, consequentemente, recebi um cart&atilde;o <a href="http://www.diners.com.br/">Diners</a>. Ali&aacute;s &eacute; bom frisar que o Citi &eacute; um &oacute;timo banco para quem, assim como eu, odeia filas. E o Diners &eacute; bom para... bem... Para quem gosta de cart&atilde;o de cr&eacute;dito. Que n&atilde;o &eacute; o meu caso. Eu sou controlado, sei que &eacute; bom ter cr&eacute;dito e que o cart&atilde;o pode ser usado para emerg&ecirc;ncias mas eu nunca me senti confort&aacute;vel tendo um. N&atilde;o sei, talvez seja aquele estigma de que quem tem cart&atilde;o de cr&eacute;dito entra em fal&ecirc;ncia.</p> <p>O fato &eacute; que o tal Diners s&oacute; me foi &uacute;til <strong>uma vez</strong>. Depois de usado, o Diners s&oacute; estava na carteira pra n&atilde;o pegar poeira.</p> <p>Um ano depois, mais precisamente ontem, eu estava conversando com o Robert (amigo meu com o qual eu dividia o ap&ecirc; em Sampa) quando ele me diz que chegou uma conta do Diners. A tal anuidade. <strong>Car&iacute;ssima</strong>, por sinal. Confesso que n&atilde;o lembro de terem me dito que a anuidade seria tal valor mas senti que n&atilde;o era t&atilde;o justo assim. Decidi que ia ligar pra cancelar j&aacute; que, como disse acima, o cart&atilde;o n&atilde;o me &eacute; t&atilde;o &uacute;til assim.</p> <p>Liguei pro n&uacute;mero que eles me deram (+55 11 4001 4626 - ligue do exterior), cheguei na &aacute;rea de cancelamento de cart&atilde;o e a liga&ccedil;&atilde;o caiu. Isso aconteceu <strong>duas vezes</strong>. Na terceira eu finalmente consegui falar mais que um bom dia com o cara. Conversamos, ele me explicou que eu tinha duas escolhas: Cancelar o cart&atilde;o ou zerar a anuidade. Zerando a anuidade eu poderia manter o cart&atilde;o e s&oacute; pagaria pelas eventuais compras al&eacute;m dele me ser &uacute;til em eventuais viagens (salas vip de aeroporto) ou despesas de emerg&ecirc;ncia.</p> <p>Resolvi manter o cart&atilde;o sob a condi&ccedil;&atilde;o de ter a anuidade zerada. Desse jeito o cart&atilde;o passa a ser vantajoso mas, sinceramente, estou c&eacute;tico quanto a isso. Vamos ver o que vai acontecer...</p> <p>P.S.: S&oacute; pra registrar, o <a href="http://www.anuidadezero.com/">Anuidade Zero</a> &eacute; um site muito bom falando sobre cart&otilde;es de cr&eacute;dito e anuidades. Vale a leitura.</p> Mon, 07 Nov 2011 06:17:00 GMT http://davidsonsousa.net/blog/post/eu-o-diners-club-international-e-a-anuidade-do-carto-de-credito A quick reference for the ASP.NET inline server tags. Great for beginners! http://davidsonsousa.net/blog/post/a-quick-reference-for-the-aspnet-inline-server-tags <p>I have to tell you: Sometimes I get confused on which server-side tag I should use to make my codes. Normal since I never use all of them so oftem. If you suffer from the same issue this text might be useful as a quick reference.</p> <h3><a href="http://msdn.microsoft.com/en-us/library/ms178135(v=VS.100).aspx">&lt;% ... %&gt;</a></h3> <p>The most common of the inline tags. It's used when you need to make some small code on the aspx page or render some expression there. For example:</p> <pre>&lt;% if(isAdmin) { %&gt;<br />Hello Admin!<br />&lt;% } %&gt;</pre> <h3><a href="http://msdn.microsoft.com/en-us/library/6dwsdcf5(v=VS.100).aspx">&lt;%= ... %&gt;</a></h3> <p>This is the simplest way to display some information in an ASP.NET page. The equal sign acts as Response.Write rendering the object directly on the page. For example:</p> <pre>Today is &lt;%= DateTime.Now %&gt;</pre> <h3><a href="http://haacked.com/archive/2009/09/25/html-encoding-code-nuggets.aspx">&lt;%: %&gt;</a></h3> <p>This was implemented in ASP.NET 4 and it's basically the same as above but with one small thing: This server tag automatically does the HTML Encoding for you. So, instead of using Server.HtmlEncode(htmlText) on your code you can simply use as the example:</p> <pre>Here is some html &lt;%: htmlText %&gt;</pre> <h3><a href="http://msdn.microsoft.com/en-us/library/4acf8afk.aspx">&lt;%-- ... --%&gt;</a></h3> <p>This tag is a server-side comment. Since this code is not rendered on the browser you can use it in case you don't want anyone to see the comments you leave on the system. Example:</p> <pre>&lt;%-- Nobody is gonna see this --%&gt;</pre> <h3><a href="http://msdn.microsoft.com/en-us/library/ms178366.aspx">&lt;%# ... %&gt;</a></h3> <p>If you want to do some data binding, you have to use this tag. It can be used with DataBinder.Eval(), DataBinder.Bind() or any member which you have in the page (public or protected). The only "problem" is that you have to use these tags only in server-side elements (with runat="server"). You will find this tag being used in some controls such as GridView, DetailsView and Repeater. Example:</p> <pre>&lt;asp:Repeater ID="rptUsers" DataSourceID="Users" runat="server"&gt;<br />&nbsp;&nbsp;&nbsp;&nbsp; &lt;ItemTemplate&gt;<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;%# Eval("LastName") %&gt;, &lt;%# Eval("FirstName") %&gt;<br />&nbsp;&nbsp;&nbsp;&nbsp; &lt;/ItemTemplate&gt;<br />&nbsp;&lt;/asp:Repeater&gt;</pre> <h3><a href="http://msdn.microsoft.com/en-us/library/d5bd1tad.aspx">&lt;%$ %&gt;</a></h3> <p>This one is used to evaluate expressions in a configuration file. For example:</p> <pre>&lt;asp:SqlDataSource ID="SqlDataSource1" Runat="server" <br />&nbsp;&nbsp;&nbsp; SelectCommand="SELECT * FROM [Employees]"<br />&nbsp;&nbsp;&nbsp; ConnectionString="&lt;%$ ConnectionStrings:NorthwindConnectionString1 %&gt;"&gt;<br />&lt;/asp:SqlDataSource&gt;</pre> <h3><a href="http://msdn.microsoft.com/en-us/library/xz702w3e(v=VS.100).aspx">&lt;%@ %&gt;</a></h3> <p>This tag is used to specify the settings used by the page and user controls. Example:</p> <pre>&lt;%@ Page Language="VB" ContentType="text/xml" %&gt;</pre> Thu, 03 Nov 2011 12:13:00 GMT http://davidsonsousa.net/blog/post/a-quick-reference-for-the-aspnet-inline-server-tags Tablet da vovó: A cópia quase fiel do iPad só que 17 anos mais velho http://davidsonsousa.net/blog/post/a-copia-quase-fiel-do-ipad-so-que-17-anos-mais-velho <p>Existem diversos momentos onde imaginamos produtos ideais como a <a href="http://www.mocha.uk.com/best-sellers/dunk-mug.html">caneca com espa&ccedil;o pra colocar biscoitos</a>. O problema &eacute; que, muitas vezes, nossa imagina&ccedil;&atilde;o &eacute; limitada por diversos fatores como conhecimento, ambiente, experi&ecirc;ncia de vida e necessidade. Logo, n&atilde;o &eacute; dif&iacute;cil de se imaginar que a pessoa que teve a id&eacute;ia da caneca acima estava cansada de ter que andar com um pratinho de biscoitos sempre que ele pegava caf&eacute;.</p> <p>S&oacute; que as coisas ficam s&eacute;rias quando um grupo de pessoas criativas se junta para pensar em como melhorar algo existente. [more]</p> <p>Uma editora americana chamada Knight-Ridder (n&atilde;o confunda com a s&eacute;rie <a href="http://www.youtube.com/watch?v=Mo8Qls0HnWo">Knight Rider</a>) criou, em 1994, um v&iacute;deo conceito (no final do post) mostrando como seria o jornal do futuro. At&eacute; a&iacute; tudo bem, temos v&iacute;deos conceituais da <a href="http://www.youtube.com/watch?v=IX-gTobCJHs">Nokia mostrando como vai ser o telefone do futuro</a>, da <a href="http://www.youtube.com/watch?v=a6cNdhOKwi0">Microsoft mostrando a sua vis&atilde;o do futuro</a> e por a&iacute; vai. Ou seja, nada anormal. No entanto o que mais chama aten&ccedil;&atilde;o &eacute; que o tal "jornal do futuro" que eles mostram &eacute; chamado Tablet e &eacute; <strong>id&ecirc;ntico</strong> ao iPad.</p> <p><img src="http://davidsonsousa.net/image/articles/tablet.jpg" alt="" width="350" height="289" /></p> <p>O mais interessante &eacute; que a narra&ccedil;&atilde;o do v&iacute;deo diz que o Tablet, em tradu&ccedil;&atilde;o livre, "vai pesar apenas 1 kg, ser totalmente port&aacute;til, ter a tela com uma nitidez compar&aacute;vel ao papel, ser capaz de mesclar texto, v&iacute;deo, &aacute;udio e imagens juntos e tamb&eacute;m fazer parte de nossas vidas ao mudar do s&eacute;culo". Tirando o peso, j&aacute; que o iPad &eacute; mais leve, o Tablet estava <strong>muito</strong> a frente de seu tempo. &Eacute; bom lembrar que naquela &eacute;poca o mais pr&oacute;ximo que tinhamos de algo assim eram os PDA como o <a href="http://www.google.com/search?hl=en&amp;q=palm+pilot&amp;um=1&amp;ie=UTF-8&amp;tbm=isch&amp;source=og&amp;sa=N&amp;tab=wi&amp;biw=1366&amp;bih=656&amp;sei=%209DCtToTpHJDAswaHnczTDw">Palm Pilot</a>.</p> <p>Ah, claro. No v&iacute;deo, Roger Fiddler (fundador da Knight-Ridder), diz que "todas as formas de m&iacute;dia que conhecemos hoje (1994) ser&atilde;o transformadas em 15 anos". Eu poderia at&eacute; trollar e dizer que ele errou por um ano j&aacute; que o iPad foi lan&ccedil;ado 16 anos depois (2010) mas... ;)</p> <p>Eis o v&iacute;deo:</p> <p><object width="480" height="360" type="application/x-shockwave-flash" data="http://www.youtube.com/v/JBEtPQDQNcI?version=3&amp;hl=en_US"> <param name="data" value="http://www.youtube.com/v/JBEtPQDQNcI?version=3&amp;hl=en_US" /> <param name="allowFullScreen" value="true" /> <param name="allowscriptaccess" value="always" /> <param name="src" value="http://www.youtube.com/v/JBEtPQDQNcI?version=3&amp;hl=en_US" /> <param name="allowfullscreen" value="true" /> </object></p> <p>via <a href="http://www.dailymail.co.uk/sciencetech/article-1381528/Knight-Ridder-tablet-looks-just-like-iPad-17-YEARS-OLD.html">Mail Online</a>.</p> Sun, 30 Oct 2011 07:30:00 GMT http://davidsonsousa.net/blog/post/a-copia-quase-fiel-do-ipad-so-que-17-anos-mais-velho Fixing the annoying IIS error: Cannot open database requested by the login http://davidsonsousa.net/blog/post/cannot-open-database-requested-by-the-login-the-login-failed-login-failed-for-user <p>While I was developing this blog I got a very nice error right after setup the IIS 7 on my machine:</p> <p><em>Cannot open database &lt;Database Name&gt; requested by the login. The login failed.</em><br /><em>Login failed for user 'IIS APPPOOL\davidsonsousa.net'.</em></p> <h3>Why does it happens?</h3> <p>It happens because once you create an Application Pool (in my case <em>davidsonsousa.net</em>), the IIS will create a virtual account with its name (<em>IIS APPPOOL/davidsonsousa.net</em>) and run the Application Pool's worker processes under this account. And, I suppose, as the database doesn't have this account setup you will get this error. [more]</p> <h3>How to fix it?</h3> <p>Before you run to your SQL Server and create this account there I would advice you to do the following:</p> <ol> <li>Open IIS Manager</li> <li>Go to the Application Pools node<br /><img src="http://davidsonsousa.net/image/articles/item2.jpg" alt="" width="217" height="102" /></li> <li>Right click on the Application Pool you would like to change and select "Advanced settings..."<br /><img src="http://davidsonsousa.net/image/articles/item3.jpg" alt="" width="510" height="258" /></li> <li>Select the "Identity" list item and click the button with the three dots<br /><img src="http://davidsonsousa.net/image/articles/item4.jpg" alt="" /></li> <li>In the new window, select the Identity Type "LocalSystem" from the combo box<br /><img src="http://davidsonsousa.net/image/articles/item5.jpg" alt="" width="446" height="257" /></li> <li>Confirm everything and restart the website.</li> </ol> <p>Now you will be able to run your website without any problems.</p> Sat, 29 Oct 2011 20:00:00 GMT http://davidsonsousa.net/blog/post/cannot-open-database-requested-by-the-login-the-login-failed-login-failed-for-user What is a deadlock? http://davidsonsousa.net/blog/post/what-is-a-deadlock <p>According to <a href="http://en.wikipedia.org/wiki/Deadlock">wikipedia</a>, a deadlock is a situation where in two or more competing actions are each waiting for the other to finish, and thus neither ever does. It is often seen in a paradox like the "<a href="http://en.wikipedia.org/wiki/Chicken_or_the_egg">chicken or the egg</a>". The concept of a <a href="http://en.wikipedia.org/wiki/Catch-22_(logic)">Catch-22</a> is similar.</p> <p>Or, if you prefer a visual explanation, this is a deadlock:</p> <p><img style="display: block; margin-left: auto; margin-right: auto;" title="Deadlock" src="http://img37.imageshack.us/img37/6619/citydeadlockthumb.jpg" alt="Deadlock" width="419" height="265" /></p> Thu, 27 Oct 2011 04:23:00 GMT http://davidsonsousa.net/blog/post/what-is-a-deadlock Como criar uma lista de fuso horários em C# http://davidsonsousa.net/blog/post/criando-uma-lista-de-fuso-horarios-em-c <p>Suponhamos que voc&ecirc; est&aacute; desenvolvendo um sistema que requer que o usu&aacute;rio tenha que escolher qual o fuso hor&aacute;rio em que ele est&aacute;. Agora imagine que voc&ecirc; tenha que adicionar 40 fusos em um dropdownlist manualmente.</p> <p>A n&atilde;o ser que voc&ecirc; precise de ter uma lista de fusos dentro do banco de dados voc&ecirc; pode usar o seguinte c&oacute;digo:</p> <pre style="font-family: Consolas; font-size: 13; color: black; background: white;"><span style="color: blue;">public</span>&nbsp;<span style="color: blue;">static</span>&nbsp;<span style="color: #2b91af;">IEnumerable</span>&lt;<span style="color: #2b91af;">SelectListItem</span>&gt;&nbsp;TimeZoneCollection { <span style="color: blue;">get</span> { <span style="color: blue;">return</span>&nbsp;<span style="color: blue;">new</span>&nbsp;<span style="color: #2b91af;">SelectList</span>(<span style="color: #2b91af;">TimeZoneInfo</span>.GetSystemTimeZones() .Select(q&nbsp;=&gt;&nbsp;<span style="color: blue;">new</span>&nbsp;<span style="color: #2b91af;">SelectListItem</span> { Text&nbsp;=&nbsp;q.DisplayName, Value&nbsp;=&nbsp;(q.DisplayName.Substring(0,&nbsp;5)&nbsp;!=&nbsp;<span style="color: #a31515;">"(UTC)"</span>)&nbsp;?&nbsp;q.DisplayName.Substring(4,&nbsp;3)&nbsp;:&nbsp;<span style="color: #a31515;">"0"</span> } &nbsp;&nbsp;&nbsp;&nbsp;),&nbsp;<span style="color: #a31515;">"Value"</span>,&nbsp;<span style="color: #a31515;">"Text"</span>); } } </pre> <p>Agora &eacute; s&oacute; dar bind no dropdownlist e voil&agrave;.</p> <p>P.S.: Caso voc&ecirc; melhore o c&oacute;digo me avise. :)</p> Tue, 18 Oct 2011 17:00:00 GMT http://davidsonsousa.net/blog/post/criando-uma-lista-de-fuso-horarios-em-c How to create a list of time zones programmatically http://davidsonsousa.net/blog/post/creating-a-list-of-time-zones-programmatically <p>Imagine that you are developing an application which requires the user to choose in which time zone he is located. Now picture yourself adding 40 time zones into a dropdownlist manually.</p> <p>Unless you need to have the list of time zones in the database you can just use the following code snippet:</p> <pre style="font-family: Consolas; font-size: 13; color: black; background: white;"><span style="color: blue;">public</span>&nbsp;<span style="color: blue;">static</span>&nbsp;<span style="color: #2b91af;">IEnumerable</span>&lt;<span style="color: #2b91af;">SelectListItem</span>&gt;&nbsp;TimeZoneCollection { <span style="color: blue;">get</span> { <span style="color: blue;">return</span>&nbsp;<span style="color: blue;">new</span>&nbsp;<span style="color: #2b91af;">SelectList</span>(<span style="color: #2b91af;">TimeZoneInfo</span>.GetSystemTimeZones() .Select(q&nbsp;=&gt;&nbsp;<span style="color: blue;">new</span>&nbsp;<span style="color: #2b91af;">SelectListItem</span> { Text&nbsp;=&nbsp;q.DisplayName, Value&nbsp;=&nbsp;(q.DisplayName.Substring(0,&nbsp;5)&nbsp;!=&nbsp;<span style="color: #a31515;">"(UTC)"</span>)&nbsp;?&nbsp;q.DisplayName.Substring(4,&nbsp;3)&nbsp;:&nbsp;<span style="color: #a31515;">"0"</span> } &nbsp;&nbsp;&nbsp;&nbsp;),&nbsp;<span style="color: #a31515;">"Value"</span>,&nbsp;<span style="color: #a31515;">"Text"</span>); } } </pre> <p>Now just bind it into a dropdownlist and voil&agrave;.</p> <p>P.S.: Let me know in case you have improved the code. :)</p> Mon, 17 Oct 2011 18:30:00 GMT http://davidsonsousa.net/blog/post/creating-a-list-of-time-zones-programmatically