tag:blogger.com,1999:blog-26149960390401177882024-03-05T05:56:37.082-08:00{ Cloud Development, C#, JavaScript, NoSQL, Architecture, and so on ... }Developers: There are more than one hundred years solving problems that did not exist.Anonymoushttp://www.blogger.com/profile/11593196735866212585noreply@blogger.comBlogger10125tag:blogger.com,1999:blog-2614996039040117788.post-66246713404535753942015-07-30T20:01:00.000-07:002015-07-30T20:03:01.794-07:00Distributed Logging with log4net e MSMQ<div style="text-align: justify;">
<span style="font-family: Courier New, Courier, monospace;">What is Log4net?</span></div>
<div style="text-align: justify;">
<span style="font-family: Courier New, Courier, monospace;"><br /></span></div>
<div style="text-align: justify;">
<span style="font-family: Courier New, Courier, monospace;">Log4net is an open source library that allows .NET applications to log output to a variety of sources (e.g., The console, SMTP or files). Log4net is a port of the popular log4J library used in Java. </span></div>
<div style="text-align: justify;">
<span style="font-family: Courier New, Courier, monospace;"><br /></span></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgQM7Fuizsziev01TvoM_tHF5zBD9K9RA6MC8h-EQVnpe5E_t_HsySa7orpzXoI1u5IeXh1raGXVOBIKdBIgjl1vob3g72l_9f4jzSS94E1d-ji9RcMAMs6eHMofIwYw6eRzaAA4XIPX-8/s1600/log+1.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="92" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgQM7Fuizsziev01TvoM_tHF5zBD9K9RA6MC8h-EQVnpe5E_t_HsySa7orpzXoI1u5IeXh1raGXVOBIKdBIgjl1vob3g72l_9f4jzSS94E1d-ji9RcMAMs6eHMofIwYw6eRzaAA4XIPX-8/s400/log+1.jpg" width="400" /></a></div>
<div style="text-align: justify;">
<span style="font-family: Courier New, Courier, monospace;"><br /></span></div>
<div style="text-align: justify;">
<span style="font-family: Courier New, Courier, monospace;"><br /></span></div>
<div style="text-align: justify;">
<a href="http://logging.apache.org/log4net/index.html"><span style="font-family: Courier New, Courier, monospace;">http://logging.apache.org/log4net/index.html</span></a></div>
<div style="text-align: justify;">
<span style="font-family: Courier New, Courier, monospace;"><br /></span></div>
<div style="text-align: justify;">
<b><span style="font-family: Courier New, Courier, monospace;">Architecture</span></b></div>
<div style="text-align: justify;">
<span style="font-family: Courier New, Courier, monospace;"><br /></span></div>
<div style="text-align: justify;">
<span style="font-family: Courier New, Courier, monospace;">The framework is built on the concept of layers and has 4 main components: Logger, Repository, Appender, and Layout.</span></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjcmcwYOQQ8Y4pyz6z6gg5SVvS8V6_eQrqwKN2MoNOpQDmX3EDiPzKHMzNJ581Agt61EBxS3BlUBlYK3-ntZ9gxDyeBOjUkLuJXK-TjW-oBFjuxzpo53EFwLbl9oMJT_Adla3O5mpOMxA8/s1600/log4net.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><span style="font-family: Courier New, Courier, monospace;"><img border="0" height="282" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjcmcwYOQQ8Y4pyz6z6gg5SVvS8V6_eQrqwKN2MoNOpQDmX3EDiPzKHMzNJ581Agt61EBxS3BlUBlYK3-ntZ9gxDyeBOjUkLuJXK-TjW-oBFjuxzpo53EFwLbl9oMJT_Adla3O5mpOMxA8/s640/log4net.png" width="640" /></span></a></div>
<div style="text-align: justify;">
<b><span style="font-family: Courier New, Courier, monospace;">Logging Levels</span></b></div>
<div style="text-align: justify;">
<b><span style="font-family: Courier New, Courier, monospace;"><br /></span></b></div>
<div style="text-align: justify;">
<span style="font-family: Courier New, Courier, monospace;">1 - OFF - nothing gets logged (cannot be called)</span></div>
<div style="text-align: justify;">
<span style="font-family: Courier New, Courier, monospace;">2 - FATAL</span></div>
<div style="text-align: justify;">
<span style="font-family: Courier New, Courier, monospace;">3 - ERROR</span></div>
<div style="text-align: justify;">
<span style="font-family: Courier New, Courier, monospace;">4 - WARN</span></div>
<div style="text-align: justify;">
<span style="font-family: Courier New, Courier, monospace;">5 - INFO</span></div>
<div style="text-align: justify;">
<span style="font-family: Courier New, Courier, monospace;">6 - DEBUG</span></div>
<div style="text-align: justify;">
<span style="font-family: Courier New, Courier, monospace;">7 - ALL - everything gets logged (cannot be called)</span></div>
<div style="text-align: justify;">
<b><span style="font-family: Courier New, Courier, monospace;"><br /></span></b></div>
<div style="text-align: justify;">
<b><span style="font-family: Courier New, Courier, monospace;">What Appender support?</span></b></div>
<div style="text-align: justify;">
<span style="font-family: Courier New, Courier, monospace;">Console Appender, File Appender, Rolling File Appender, ADO.NET Appender, MSMQ?</span></div>
<div style="text-align: justify;">
<span style="font-family: Courier New, Courier, monospace;"><br /></span></div>
<h1 itemprop="name" style="background-color: white; border: 0px; color: #222222; line-height: 1.3; margin: 0px 0px 0.5em; padding: 0px;">
<span style="border: 0px; color: #222222; cursor: pointer; font-family: Courier New, Courier, monospace; font-size: small; line-height: 1.35; margin: 0px 0px 0.5em; padding: 0px; text-decoration: none;"><a class="question-hyperlink" href="http://stackoverflow.com/questions/400115/what-is-microsoft-message-queuing-msmq-how-does-it-work" style="border-image-outset: initial; border-image-repeat: initial; border-image-slice: initial; border-image-source: initial; border-image-width: initial; border: 0px; color: #222222; cursor: pointer; line-height: 1.35; margin: 0px 0px 0.5em; padding: 0px; text-decoration: none;">What is Microsoft Message Queuing (MSMQ)?</a></span></h1>
<div style="text-align: justify;">
<span style="color: #2a2a2a; line-height: 18px; text-align: start;"><span style="font-family: Courier New, Courier, monospace;">Message Queuing (MSMQ) technology enables applications running at different times to communicate across heterogeneous networks and systems that may be temporarily offline. Applications send messages to queues and read messages from queues. The following illustration shows how a queue can hold messages that are generated by multiple sending applications and read by multiple receiving applications.</span></span></div>
<div style="text-align: justify;">
<span style="color: #2a2a2a; line-height: 18px; text-align: start;"><span style="font-family: Courier New, Courier, monospace;"><br /></span></span></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjV_HYAJUASQapoz97Py9ilRuRhpFrJFP4ZVF4YvLBRvWVN0KhN6kBzzAKQYCXBjg0B6dwfhoCgxf8A6jztsvpNEPVxCz5JvLkB46ZVCFr8ChwCoLAvd1UM7gZYN7SuCkUtOLHdkV1T7d0/s1600/msmq.bmp" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><span style="font-family: Courier New, Courier, monospace;"><img border="0" height="247" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjV_HYAJUASQapoz97Py9ilRuRhpFrJFP4ZVF4YvLBRvWVN0KhN6kBzzAKQYCXBjg0B6dwfhoCgxf8A6jztsvpNEPVxCz5JvLkB46ZVCFr8ChwCoLAvd1UM7gZYN7SuCkUtOLHdkV1T7d0/s400/msmq.bmp" width="400" /></span></a></div>
<div class="separator" style="clear: both; text-align: center;">
<span style="font-family: Courier New, Courier, monospace;"><br /></span></div>
<div class="separator" style="clear: both; text-align: justify;">
<span style="font-family: Courier New, Courier, monospace;">Let's encode!!</span></div>
<div style="text-align: justify;">
<span style="color: #2a2a2a; line-height: 18px; text-align: start;"><span style="font-family: Courier New, Courier, monospace;"><br /></span></span></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg-c4P6JifhKJF4vkhsD-gr6dLKRsj_k4YPce9bprMoLFy_wvF-1WzystRUyLivUJrEPxeUY8s_R-aT5vDUuOD52ElfS7hhKsaFVImpsewXm80YfnmNtOf5qaINrG14_zC9ky2IfGeaz5I/s1600/nuget.PNG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><span style="font-family: Courier New, Courier, monospace;"><img border="0" height="73" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg-c4P6JifhKJF4vkhsD-gr6dLKRsj_k4YPce9bprMoLFy_wvF-1WzystRUyLivUJrEPxeUY8s_R-aT5vDUuOD52ElfS7hhKsaFVImpsewXm80YfnmNtOf5qaINrG14_zC9ky2IfGeaz5I/s640/nuget.PNG" width="640" /></span></a></div>
<div style="text-align: justify;">
<span style="color: #2a2a2a; line-height: 18px; text-align: start;"><span style="font-family: Courier New, Courier, monospace;"><br /></span></span></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjzYlgWVKPSuU_235pWsarOdSBAeE-ODeuA_UQS_Z9lAoCTUNChkBX7Y8WmXCSGBF71qJF7jxMq_2y0rf6_ZH2OiIf70oPGi3-G01iKVMHLtMYrH05WufPzTnNP5vV9_Krf1JHVVxYPsyo/s1600/appender.PNG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><span style="font-family: Courier New, Courier, monospace;"><img border="0" height="203" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjzYlgWVKPSuU_235pWsarOdSBAeE-ODeuA_UQS_Z9lAoCTUNChkBX7Y8WmXCSGBF71qJF7jxMq_2y0rf6_ZH2OiIf70oPGi3-G01iKVMHLtMYrH05WufPzTnNP5vV9_Krf1JHVVxYPsyo/s400/appender.PNG" width="400" /></span></a></div>
<div style="text-align: justify;">
<span style="color: #2a2a2a; line-height: 18px; text-align: start;"><span style="font-family: Courier New, Courier, monospace;"><br /></span></span></div>
<div style="text-align: justify;">
<span style="color: #2a2a2a; line-height: 18px; text-align: start;"><span style="font-family: Courier New, Courier, monospace;"><br /></span></span></div>
<div style="text-align: start;">
<span style="color: #2a2a2a; font-family: Courier New, Courier, monospace;"><span style="line-height: 18px;"><b>Implement override AppenderSkeleton ...</b></span></span></div>
<div style="text-align: justify;">
<span style="color: #2a2a2a; line-height: 18px; text-align: start;"><span style="font-family: Courier New, Courier, monospace;"><br /></span></span></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi8h_QGu48_gRWIp5Ov7s1f4wVZXztVwdq2-6pn0M9CP6rREt3smDri4jS9vXzTuNtFM2u2Z7lCcjtaJDJeQmugagqYNzTpF5szo9GL4oYDUty6QiwWfw6cUimlfZi-8LN8GFJBaiabsio/s1600/log+2.PNG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><span style="font-family: Courier New, Courier, monospace;"><img border="0" height="436" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi8h_QGu48_gRWIp5Ov7s1f4wVZXztVwdq2-6pn0M9CP6rREt3smDri4jS9vXzTuNtFM2u2Z7lCcjtaJDJeQmugagqYNzTpF5szo9GL4oYDUty6QiwWfw6cUimlfZi-8LN8GFJBaiabsio/s640/log+2.PNG" width="640" /></span></a></div>
<div style="text-align: justify;">
<span style="font-family: Courier New, Courier, monospace;"><br /></span></div>
<div style="text-align: justify;">
<span style="font-family: Courier New, Courier, monospace;">Don't forget RenderLayout and two config (QueueName, LabelLayout)</span></div>
<div style="text-align: justify;">
<br /></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg9oxTcv0T3TdGxx_MAv-QRp4LPRabfLGrurOloFrhheqHVKzS7x6gN45uL1AHy6cOE4KW06Q9FSxhkuAp8mp7HJwrEP5y2WAAAi-L2mTdASi3xIB2kT6r5996HvqkimPVsc9haxmvE8rY/s1600/config+2.PNG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="457" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg9oxTcv0T3TdGxx_MAv-QRp4LPRabfLGrurOloFrhheqHVKzS7x6gN45uL1AHy6cOE4KW06Q9FSxhkuAp8mp7HJwrEP5y2WAAAi-L2mTdASi3xIB2kT6r5996HvqkimPVsc9haxmvE8rY/s640/config+2.PNG" width="640" /></a></div>
<div style="text-align: justify;">
<br /></div>
<div style="text-align: justify;">
<span style="font-family: Courier New, Courier, monospace;">Add a new appender for log4net</span></div>
<div style="text-align: justify;">
<span style="font-family: Courier New, Courier, monospace;"><br /></span></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjpHs2_aymKGV7Z8mKMe6GqT7H8_p7pCcukHJezDBhQDOesSPRxyhg8JhKNk9SEKGE45cBqja7gXSNkj9zmLYQhtZjRO2TgFiZ7CxtM3VJjzb4cYNXwlu4EtsRoJr6iKwWekMqXmONkyuA/s1600/add+appender.PNG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="264" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjpHs2_aymKGV7Z8mKMe6GqT7H8_p7pCcukHJezDBhQDOesSPRxyhg8JhKNk9SEKGE45cBqja7gXSNkj9zmLYQhtZjRO2TgFiZ7CxtM3VJjzb4cYNXwlu4EtsRoJr6iKwWekMqXmONkyuA/s640/add+appender.PNG" width="640" /></a></div>
<div style="text-align: justify;">
<span style="font-family: Courier New, Courier, monospace;">Let me know if you would like me to expound on any area listed above or if you have an issue using log4net.Record information on MSMQ allows you to distribute the actions to be taken at every level of log, it's great solution of enterprise application where exist big lots of message log.</span></div>
<div style="text-align: justify;">
<span style="font-family: Courier New, Courier, monospace;"><br /></span></div>
<div style="text-align: justify;">
<span style="background-color: white; color: #666666; line-height: 18.2000007629395px; text-align: start;"><span style="font-family: Courier New, Courier, monospace;">Thanks, Happy coding :)</span></span></div>
Anonymoushttp://www.blogger.com/profile/11593196735866212585noreply@blogger.com0tag:blogger.com,1999:blog-2614996039040117788.post-4962329086441095982015-07-28T18:37:00.003-07:002015-07-28T18:40:51.410-07:00WCF ClientBase and Command Dispatcher<span style="font-family: Courier New, Courier, monospace;">What is WCF?</span><br />
<div style="text-align: justify;">
<span style="font-family: Courier New, Courier, monospace;"><br /></span></div>
<div style="text-align: justify;">
<span style="font-family: Courier New, Courier, monospace;">Windows Communication Foundation (WCF) is a unified, simplified and optimized evolution of a number of communication technologies into a single model. Most of the WCF functionalities are included in a single assembly called System.ServiceModel.dll in the System.ServiceModel namespace.</span></div>
<div style="text-align: justify;">
<span style="font-family: Courier New, Courier, monospace;"><br /></span></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjE5ClAdHG9Hz-bfcXQdm0MFq-KOmzRKY0rYOJzUpN4Jw1KugbpG0Frfw4NPj0mG7UM6Rc2w42mvHMMJ7zCTMSeDfR7hjABN2tbDVMB6bEJap2Cm_Ld7oO9Gvkf4inCQjKFbP1QcZ897jM/s1600/wcf+2.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><span style="font-family: Courier New, Courier, monospace;"><img border="0" height="204" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjE5ClAdHG9Hz-bfcXQdm0MFq-KOmzRKY0rYOJzUpN4Jw1KugbpG0Frfw4NPj0mG7UM6Rc2w42mvHMMJ7zCTMSeDfR7hjABN2tbDVMB6bEJap2Cm_Ld7oO9Gvkf4inCQjKFbP1QcZ897jM/s640/wcf+2.jpg" width="640" /></span></a></div>
<div style="text-align: justify;">
<span style="font-family: Courier New, Courier, monospace;"><br /></span></div>
<div style="text-align: justify;">
<span style="font-family: Courier New, Courier, monospace;">To run WCF service on the client side you have some options:</span></div>
<div style="text-align: justify;">
<span style="font-family: Courier New, Courier, monospace;"><br /></span></div>
<div style="text-align: justify;">
<b><span style="font-family: Courier New, Courier, monospace;">Option 1: Generate Adding Proxy Service Reference</span></b></div>
<div style="text-align: justify;">
</div>
<div style="text-align: justify;">
<span style="font-family: Courier New, Courier, monospace;"><br /></span></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjy75tR_bnQjZYpbM37gPtOewEBvaNN08k6eSBuev_UPNlRTyIkIMl_F-dluJENiBtFjiGEEaejVsgAHsg_StxU1G_CilebIII8r8t7bavw2Z5e3BvYHmJUXkwd3yrQO7oPyVjfQgARhXQ/s1600/service+reference.PNG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><span style="font-family: Courier New, Courier, monospace;"><img border="0" height="323" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjy75tR_bnQjZYpbM37gPtOewEBvaNN08k6eSBuev_UPNlRTyIkIMl_F-dluJENiBtFjiGEEaejVsgAHsg_StxU1G_CilebIII8r8t7bavw2Z5e3BvYHmJUXkwd3yrQO7oPyVjfQgARhXQ/s400/service+reference.PNG" width="400" /></span></a></div>
<div class="separator" style="clear: both; text-align: center;">
<span style="font-family: Courier New, Courier, monospace;"><br /></span></div>
<div class="separator" style="clear: both;">
<span style="color: red; font-family: Courier New, Courier, monospace;"><b>Problem for enterprise application:</b></span></div>
<div class="separator" style="clear: both;">
<span style="font-family: Courier New, Courier, monospace;"><br /></span></div>
<div class="separator" style="clear: both;">
<span style="font-family: Courier New, Courier, monospace;">- Updates on service</span></div>
<div class="separator" style="clear: both;">
<span style="font-family: Courier New, Courier, monospace;">- Changes in the service configuration</span></div>
<div style="text-align: justify;">
<span style="font-family: Courier New, Courier, monospace;"><br /></span></div>
<div style="text-align: justify;">
<b><span style="font-family: Courier New, Courier, monospace;"><br /></span></b></div>
<div style="text-align: justify;">
<b><span style="font-family: Courier New, Courier, monospace;">Option 2: Generate Proxy by implementing ClientBase<T> class</span></b></div>
<div style="text-align: justify;">
<span style="font-family: Courier New, Courier, monospace;"><br /></span></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjUCDYNXiHwoPJgLPcxWWlJpu380oI3eqsfP_GYj9arKHVGpxJr8y27COkOhlLZD7w66UMOSILL5YHw_9lOixoShOjdp2LlD5BeTFmKamYhfbF-V3bn_lvKRQIQqyXbXm4UE2ymZLvXCJ0/s1600/class1.PNG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><span style="font-family: Courier New, Courier, monospace;"><img border="0" height="160" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjUCDYNXiHwoPJgLPcxWWlJpu380oI3eqsfP_GYj9arKHVGpxJr8y27COkOhlLZD7w66UMOSILL5YHw_9lOixoShOjdp2LlD5BeTFmKamYhfbF-V3bn_lvKRQIQqyXbXm4UE2ymZLvXCJ0/s640/class1.PNG" width="640" /></span></a></div>
<div style="text-align: justify;">
<span style="font-family: Courier New, Courier, monospace;"><br /></span></div>
<div style="text-align: justify;">
<span style="font-family: Courier New, Courier, monospace;">It is a good option, but in a great architecture generation can become unproductive and without much need.</span></div>
<div style="text-align: justify;">
<span style="font-family: Courier New, Courier, monospace;"><br /></span></div>
<div style="text-align: justify;">
<b><span style="font-family: Courier New, Courier, monospace;">Option 3: Generate Dynamic Command Dispatcher</span></b></div>
<div style="text-align: justify;">
<b><span style="font-family: Courier New, Courier, monospace;"><br /></span></b></div>
<div style="text-align: justify;">
<span style="background-color: white; color: #666666; font-family: Courier New, Courier, monospace; line-height: 18.2000007629395px; text-align: start;">Let's encode!!</span></div>
<div style="text-align: justify;">
<span style="background-color: white; color: #666666; font-family: Courier New, Courier, monospace; line-height: 18.2000007629395px; text-align: start;"><br /></span></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiJwQ0-G3V9dK1Xf7n6IUONbxJxKR5fSItzWCBjNJf_E6ewoT6-Bb60HOF_B9rWA5vCa4l2TiGfEWxfWW1j6tdpUhjYfgBUi1MSAba5OYwfpg0dFGEV31bMjB1i4pumJ7PzcoimUwVAMiM/s1600/interface.PNG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><span style="font-family: Courier New, Courier, monospace;"><img border="0" height="148" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiJwQ0-G3V9dK1Xf7n6IUONbxJxKR5fSItzWCBjNJf_E6ewoT6-Bb60HOF_B9rWA5vCa4l2TiGfEWxfWW1j6tdpUhjYfgBUi1MSAba5OYwfpg0dFGEV31bMjB1i4pumJ7PzcoimUwVAMiM/s640/interface.PNG" width="640" /></span></a></div>
<div style="text-align: justify;">
<span style="font-family: Courier New, Courier, monospace;"><br /></span></div>
<div style="text-align: justify;">
<span style="background-color: white; line-height: 18.2000007629395px; text-align: start;"><span style="color: #666666; font-family: Courier New, Courier, monospace;"><br /></span></span></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg_BMjs_r9dVeEqGEYM3HNb_USgt7D5rXjL1HkIvIUyYxhvugGl2SvuIfqR95ApC1MCwE1lDyIb-4eCnUaV34jR9Gil1JjPlIyaexmxoOCFFDTO322D2kJlNBqQFbf_blKxOET26QwoJ0Q/s1600/wcf3.PNG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><span style="font-family: Courier New, Courier, monospace;"><img border="0" height="156" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg_BMjs_r9dVeEqGEYM3HNb_USgt7D5rXjL1HkIvIUyYxhvugGl2SvuIfqR95ApC1MCwE1lDyIb-4eCnUaV34jR9Gil1JjPlIyaexmxoOCFFDTO322D2kJlNBqQFbf_blKxOET26QwoJ0Q/s640/wcf3.PNG" width="640" /></span></a></div>
<div style="text-align: justify;">
</div>
<div style="text-align: justify;">
<span style="font-family: Courier New, Courier, monospace;"><br /></span>
<span style="font-family: Courier New, Courier, monospace;"><br /></span>
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjWEgDlyB2udRDTbFpftlvnMCGCuPFJHU6XYipI1K27_nDFytbrHauFoDCfmoNC3PhBXEiVbFNIBGu4anElrFL0FvW1caM85yb_D12Gs0nZT057-QAKrn4JKk4P0_S5SwGAKX8ayXxwwL8/s1600/metodo+1.PNG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><span style="font-family: Courier New, Courier, monospace;"><img border="0" height="300" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjWEgDlyB2udRDTbFpftlvnMCGCuPFJHU6XYipI1K27_nDFytbrHauFoDCfmoNC3PhBXEiVbFNIBGu4anElrFL0FvW1caM85yb_D12Gs0nZT057-QAKrn4JKk4P0_S5SwGAKX8ayXxwwL8/s640/metodo+1.PNG" width="640" /></span></a></div>
<span style="font-family: Courier New, Courier, monospace;"><br /></span>
<span style="font-family: Courier New, Courier, monospace;"><br /></span>
<b><span style="font-family: Courier New, Courier, monospace;">Method overloading sending client credencial...</span></b><br />
<b><span style="font-family: Courier New, Courier, monospace;"><br /></span></b>
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhzTudnJOUk49nv1YbsKGcIxYa2e2mNDepaDR1wWN_P7SpMlQt1sHRlVBHN1bOOTVkQzooVVKwcXEcqKHiyf9UUwAmxyPi1N8TCEbq3WpThWfn-HKHKdNF5goW7a4Cmrao-5kh0SotJzWA/s1600/metodo+2.PNG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><span style="font-family: Courier New, Courier, monospace;"><img border="0" height="392" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhzTudnJOUk49nv1YbsKGcIxYa2e2mNDepaDR1wWN_P7SpMlQt1sHRlVBHN1bOOTVkQzooVVKwcXEcqKHiyf9UUwAmxyPi1N8TCEbq3WpThWfn-HKHKdNF5goW7a4Cmrao-5kh0SotJzWA/s640/metodo+2.PNG" width="640" /></span></a></div>
<span style="font-family: Courier New, Courier, monospace;"><br /></span>
<b><span style="font-family: Courier New, Courier, monospace;">Method overloading sending custom header...</span></b><br />
<b><span style="font-family: Courier New, Courier, monospace;"><br /></span></b>
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjJK6NY61Z-VSk4zNf3NsW66Np3ih7r8BSsns78NFjFyAD0G_iK3oR39TLAL5bquJkzfY4SzQ17U-48KQtU31Awgdk4OCQyeRpjffsLHQS42gQKmMA1dWVnNNfWNkOSwd_jiCMZUHGfL1I/s1600/metodo+3.PNG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><span style="font-family: Courier New, Courier, monospace;"><img border="0" height="290" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjJK6NY61Z-VSk4zNf3NsW66Np3ih7r8BSsns78NFjFyAD0G_iK3oR39TLAL5bquJkzfY4SzQ17U-48KQtU31Awgdk4OCQyeRpjffsLHQS42gQKmMA1dWVnNNfWNkOSwd_jiCMZUHGfL1I/s640/metodo+3.PNG" width="640" /></span></a></div>
<b><span style="font-family: Courier New, Courier, monospace;"><br /></span></b>
<b><span style="font-family: Courier New, Courier, monospace;">Async method run...</span></b><br />
<b><span style="font-family: Courier New, Courier, monospace;"><br /></span></b>
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiQnPjASYRY2wW3oFgrHf5vf3_vtVmlzkdRc0vuHt58yS2vR9RPsP6iMZnqhFPLzRI5MDUytpiTLyq6VG3lP9QWlOPAwpkQ5T7eIcCpDv1_gogxNNlOGbw_QxxkY0HWxkQ2Wq4fxdlY-QI/s1600/metodo+4.PNG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><span style="font-family: Courier New, Courier, monospace;"><img border="0" height="148" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiQnPjASYRY2wW3oFgrHf5vf3_vtVmlzkdRc0vuHt58yS2vR9RPsP6iMZnqhFPLzRI5MDUytpiTLyq6VG3lP9QWlOPAwpkQ5T7eIcCpDv1_gogxNNlOGbw_QxxkY0HWxkQ2Wq4fxdlY-QI/s640/metodo+4.PNG" width="640" /></span></a></div>
<b><span style="font-family: Courier New, Courier, monospace;"><br /></span></b>
<b><span style="font-family: Courier New, Courier, monospace;">Usage!!</span></b><br />
<b><span style="font-family: Courier New, Courier, monospace;"><br /></span></b>
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgeJ5apwbmHNVA9IMM5DzPdmrHJBMtZFI38rUKwZOI17P1_DR9hou4IKhFuvoziBzV7p0_2bAfPPwZ5OAIjlcNtTbY4Kw5zNDWBxiI2V4Xd1hWrG5-y0J15YOudI3VKlZOBPH6bK723NR8/s1600/command.PNG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><span style="font-family: Courier New, Courier, monospace;"><img border="0" height="128" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgeJ5apwbmHNVA9IMM5DzPdmrHJBMtZFI38rUKwZOI17P1_DR9hou4IKhFuvoziBzV7p0_2bAfPPwZ5OAIjlcNtTbY4Kw5zNDWBxiI2V4Xd1hWrG5-y0J15YOudI3VKlZOBPH6bK723NR8/s640/command.PNG" width="640" /></span></a></div>
<b><span style="font-family: Courier New, Courier, monospace;"><br /></span></b>
<span style="font-family: Courier New, Courier, monospace;"><b>...</b>With this implementation the service call is dynamic and independent enabling updates on unchanged in customer service.</span><br />
<span style="font-family: Courier New, Courier, monospace;"><br /></span><span style="background-color: white; color: #666666; line-height: 18.2000007629395px; text-align: start;"><span style="font-family: Courier New, Courier, monospace;">Thanks, Happy coding :)</span></span><br />
<span style="background-color: white; color: #666666; line-height: 18.2000007629395px; text-align: start;"><span style="font-family: Courier New, Courier, monospace;"><br /></span></span></div>
Anonymoushttp://www.blogger.com/profile/11593196735866212585noreply@blogger.com0tag:blogger.com,1999:blog-2614996039040117788.post-59315790149332247182015-07-27T19:32:00.002-07:002015-07-27T19:32:18.174-07:00Using JSON Web Token<span style="font-family: Courier New, Courier, monospace;">( Wikipedia ) <b>JSON Web Token (JWT)</b> is a JSON-based open standard (RFC 7519) for passing claims between parties in web application environment. The tokens are designed to be compact, URL-safe and usable especially in web browser single sign-on (SSO) context. JWT claims can be typically used to pass identity of authenticated users between an identity provider and a service provider, or any other type of claims as required by business processes. The tokens can also be authenticated and encrypted. </span><span style="font-family: 'Courier New', Courier, monospace;">JWT relies on other JSON-based standards: JWS (JSON Web Signature) RFC 7515 and JWE (JSON Web Encryption)</span><br />
<span style="font-family: Courier New, Courier, monospace;"><br /></span>
<span style="font-family: 'Courier New', Courier, monospace;">JWT is a recent open standard that is being driven by the international standards body IETF and has top-level backers from the technology sector (</span><b style="font-family: 'Courier New', Courier, monospace;">for example, Microsoft, Facebook, and Google</b><span style="font-family: 'Courier New', Courier, monospace;">).</span><br />
<span style="font-family: Courier New, Courier, monospace;"><br /></span>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjgFBoCQt9-1WrTF0i9RNcYqQLbrijB_5EoD5tT1OgQ4Uvtd3Cf9F6aOvFPXTq46oUZ1r4aPBckLY7DmdTHBk1iGaXF-yRlVUmhYsycLK7Dag7K6ZlvDWh5wf3S6g8x_rH0S4l_MGgaCFk/s1600/logo-400.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="320" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjgFBoCQt9-1WrTF0i9RNcYqQLbrijB_5EoD5tT1OgQ4Uvtd3Cf9F6aOvFPXTq46oUZ1r4aPBckLY7DmdTHBk1iGaXF-yRlVUmhYsycLK7Dag7K6ZlvDWh5wf3S6g8x_rH0S4l_MGgaCFk/s320/logo-400.png" width="320" /></a></div>
<b style="font-family: 'Courier New', Courier, monospace;"><br /></b>
<b style="font-family: 'Courier New', Courier, monospace;">What is JSON Web Token?</b><br />
<span style="font-family: Courier New, Courier, monospace;"><a href="http://jwt.io/">http://jwt.io/</a></span><br />
<span style="font-family: Courier New, Courier, monospace;"><a href="http://tools.ietf.org/html/draft-jones-json-web-token-10">http://tools.ietf.org/html/draft-jones-json-web-token-10</a></span><br />
<span style="font-family: Courier New, Courier, monospace;"><a href="https://en.wikipedia.org/wiki/Internet_Engineering_Task_Force">https://en.wikipedia.org/wiki/Internet_Engineering_Task_Force</a></span><br />
<span style="font-family: Courier New, Courier, monospace;"><br /></span>
<span style="font-family: Courier New, Courier, monospace;"><b>JWT</b> is simple method send information authentication over a URL or other services transports. Let's not forget JWT does not encrypt the payload, it only signs it so you may want to consider using SSL for all communication between the application requesting authentication and the application granting authentication . You may also want to consider encrypting the JWT token.</span><br />
<div class="separator" style="clear: both; text-align: center;">
</div>
<div style="text-align: center;">
<span style="font-family: Courier New, Courier, monospace;"><br /></span></div>
<span style="font-family: 'Courier New', Courier, monospace;">The example code below demonstrates a fully working in C#:</span><br />
<span style="font-family: 'Courier New', Courier, monospace;"><br /></span>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjNWpP9k033F1Rud46yFIVE5OwbTI_oVr5aifjU1fjrbs0Gpmdj1hl37N9QtumlmhJHI4XGFP4h9FEaCWw0UwWXjkuvEJZQXsrQ5tnHa_PZl2SLaGoL5z5eo_vsCbfBLfgcO8xK8E8MpJU/s1600/nuget.PNG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="121" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjNWpP9k033F1Rud46yFIVE5OwbTI_oVr5aifjU1fjrbs0Gpmdj1hl37N9QtumlmhJHI4XGFP4h9FEaCWw0UwWXjkuvEJZQXsrQ5tnHa_PZl2SLaGoL5z5eo_vsCbfBLfgcO8xK8E8MpJU/s400/nuget.PNG" width="400" /></a></div>
<div class="separator" style="clear: both; text-align: center;">
<br /></div>
<span style="font-family: Courier New, Courier, monospace;">Let's encode!!</span><br />
<span style="font-family: Courier New, Courier, monospace;"><br /></span>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjyp7UBx4ZpwDY8tkIZGwaSVRyCapg46rl0rU4fx3AAwkTWfoaYPm1tk5Jza2jdET0dmYaZudACxcpPWw5nH_5GTiTaZewGqDCvmf8xrg7EMbNhPYP9HaZCXrslXGTfyJCPdZx7hwzGtuw/s1600/code1.PNG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="379" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjyp7UBx4ZpwDY8tkIZGwaSVRyCapg46rl0rU4fx3AAwkTWfoaYPm1tk5Jza2jdET0dmYaZudACxcpPWw5nH_5GTiTaZewGqDCvmf8xrg7EMbNhPYP9HaZCXrslXGTfyJCPdZx7hwzGtuw/s640/code1.PNG" width="640" /></a></div>
<span style="font-family: Courier New, Courier, monospace;"><br /></span>
<span style="font-family: Courier New, Courier, monospace;">JWT really does provide a very simple solution to communicating information across untrusted channels.</span><br />
<span style="font-family: Courier New, Courier, monospace;"><br /></span>
<span style="font-family: Courier New, Courier, monospace;">Don't forget Unit Test...</span><br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhcpX9Qq1rTry2W3MiM7MwFnsi7Dgb5fADClqiKwKGB2f1oN_MrxJL96Le1-QlR-EWSj2T9RT2_2uxmBgzZBW3gZ1b6Eg5VQ3zRk0hz4bOn9I_Y_5QDrR9AxLtePRJfXzDSkhvGbtfKP_0/s1600/code2.PNG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="350" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhcpX9Qq1rTry2W3MiM7MwFnsi7Dgb5fADClqiKwKGB2f1oN_MrxJL96Le1-QlR-EWSj2T9RT2_2uxmBgzZBW3gZ1b6Eg5VQ3zRk0hz4bOn9I_Y_5QDrR9AxLtePRJfXzDSkhvGbtfKP_0/s640/code2.PNG" width="640" /></a></div>
<br />
<span style="font-family: Courier New, Courier, monospace;">I hope, this article has given you sufficient information to start implementing. </span><br />
<span style="font-family: Courier New, Courier, monospace;"><br /></span>
<span style="font-family: 'Courier New', Courier, monospace;">Thanks, Happy coding :)</span><br />
<span style="font-family: Courier New, Courier, monospace;"><br /></span>
<span style="font-family: Courier New, Courier, monospace;"><b>link download:</b></span><br />
<span style="font-family: Courier New, Courier, monospace;"><a href="https://onedrive.live.com/redir?resid=EB97825B1A5209E9%212009">https://onedrive.live.com/redir?resid=EB97825B1A5209E9%212009</a></span>Anonymoushttp://www.blogger.com/profile/11593196735866212585noreply@blogger.com0tag:blogger.com,1999:blog-2614996039040117788.post-31796892302662186772014-12-10T12:02:00.004-08:002014-12-10T12:12:06.362-08:00Upload arquivos usando o AWS SDK for .NET (C#)<span style="font-family: Courier New, Courier, monospace;">É bastante comum em diferentes tipos de projetos a necessidade de fazer upload de algum tipo de arquivo, sendo ele uma imagem ou algum outro. A forma mais fácil ou a mais utilizada seria fazer upload desse arquivo para uma determinada pasta do projeto, e se você estiver utilizando o IIS como servidor de pagina ou mesmo se for APACHE por exemplo de ambas as formas você estaria fazendo teu servidor entregar o conteúdo estático que nesse caso seria o arquivo que foi feito upload. Não vejo nenhum problema nisso quando falamos de poucos arquivos mas se a sua aplicação tiver uma necessidade maior de performance na entrega ou até mesmo a quantidade for bastante grande gerando um tamanho significante no disco do teu servidor você teria que optar por outra coisa.</span><br />
<div>
<span style="font-family: Courier New, Courier, monospace;">Para isso a AMAZON AWS oferece um serviço bastante barato e rápido que pode ser utilizado para diversas outras funcionalidades. Apresentação do serviço no site oficial: <a href="http://aws.amazon.com/pt/s3/" target="_blank">http://aws.amazon.com/pt/s3/</a>. </span><br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgmViegvD283XF1unp6QgIiVi4fsyNwsP7GNKblf1w9eCwIGFSRbb4TmWBxtT53IgAp0XCgeqe76lufj2esGe6TKLuJuKWE3w_djO2ZV7hLFQSpOOMfwhoEWLPCYuP71e3PTQYrANGLc5M/s1600/amazon+4.gif" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgmViegvD283XF1unp6QgIiVi4fsyNwsP7GNKblf1w9eCwIGFSRbb4TmWBxtT53IgAp0XCgeqe76lufj2esGe6TKLuJuKWE3w_djO2ZV7hLFQSpOOMfwhoEWLPCYuP71e3PTQYrANGLc5M/s1600/amazon+4.gif" height="217" width="400" /></a></div>
<span style="font-family: 'Courier New', Courier, monospace;">A intenção desse post é exatamente mostrar como é simples a integração com o serviço "Simple Storage Service" ou como é conhecido AMAZON S3.</span></div>
<div>
<br /></div>
<div>
<span style="font-family: Courier New, Courier, monospace;">Primeiramente eu criei uma classe estática e nela vamos codificar o nosso método de uploadFile. A organização de onde ficaria melhor a classe fica a critério da arquitetura que você está trabalhando.</span></div>
<div>
<span style="font-family: Courier New, Courier, monospace;">Antes de começar a codificar vamos fazer referencia ao SDK da amazon aws, você pode encontrar ele facilmente no Nuget.<a href="https://www.nuget.org/packages/AWSSDK/2.3.12" target="_blank">https://www.nuget.org/packages/AWSSDK/2.3.12</a> ou se você prefere por command.</span></div>
<div>
<span style="font-family: Courier New, Courier, monospace;"><br /></span></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiJpZZuTFWOMIVp60npI_N5KpiCS9Pn5QLRnuuKwJNQi2WzbLQ31O4WXgqlzX2WjtJBXVGK3cb77gol7VPniwoGO8augm5-CVVv_Ohe4Y9ABTSnZxBKlipBcuU2zkkdnuflxcJq_PmT79I/s1600/amazon+1.PNG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiJpZZuTFWOMIVp60npI_N5KpiCS9Pn5QLRnuuKwJNQi2WzbLQ31O4WXgqlzX2WjtJBXVGK3cb77gol7VPniwoGO8augm5-CVVv_Ohe4Y9ABTSnZxBKlipBcuU2zkkdnuflxcJq_PmT79I/s1600/amazon+1.PNG" height="150" width="400" /></a></div>
<div>
<br /></div>
<pre style="background-image: URL(https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhtDkiUO9nySrprZDIjEIEJoxRX3AuY42e5gAii42s0X5LltSQDuFgkK2KCenBuZDe5hzN8gyAvGkO6tfzvpnKnIt6mpyAT-eMdZKd9C5yv2-mFzkCRTQe3LrYOdZrEn3qzd5NfoNdynIUe/s320/codebg.gif); background: #f0f0f0; border: 1px dashed #CCCCCC; color: black; font-family: arial; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;"> public static class UploadAmazon
{
private static IAmazonS3 client;
public static HttpStatusCode UploadFile(Stream file, string type, string nomeImagem)
{
using (client = AWSClientFactory.CreateAmazonS3Client("****key****", "***secret key****"))
{
PutObjectRequest request = new PutObjectRequest();
request.BucketName = "MeusArquivos"; //nome do bucket name
request.CannedACL = S3CannedACL.PublicRead; //permissões
request.Key = "Arquivos/" + nomeImagem; //diretorio e nome do arquivo
request.ContentType = type; //type do arquivo
request.InputStream = file; //Stream do arquivo
return client.PutObject(request).HttpStatusCode;
}
}
}
</code></pre>
<span style="font-family: 'Courier New', Courier, monospace;">Veja que o código é bastante simples =)</span><br />
<span style="font-family: Courier New, Courier, monospace;">Apenas se atentar alguns detalhes, a propriedade "<b>BucketName</b>" eu coloquei fixa porém você poderia fazer uma verificação se esse "BucketName" se ele já não existe na sua storage, ficaria mais ou menos assim:</span><br />
<pre style="background-image: URL(https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhtDkiUO9nySrprZDIjEIEJoxRX3AuY42e5gAii42s0X5LltSQDuFgkK2KCenBuZDe5hzN8gyAvGkO6tfzvpnKnIt6mpyAT-eMdZKd9C5yv2-mFzkCRTQe3LrYOdZrEn3qzd5NfoNdynIUe/s320/codebg.gif); background: #f0f0f0; border: 1px dashed #CCCCCC; color: black; font-family: arial; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;"> private static bool IsCheckBucket(string bucketName)
{
ListBucketsResponse response = client.ListBuckets();
bool found = false;
foreach (S3Bucket bucket in response.Buckets)
{
if (bucket.BucketName == bucketName)
{
found = true;
break;
}
}
return found;
} </code></pre>
<span style="font-family: Courier New, Courier, monospace;"><b>(...) e para criar o BucketName</b></span><br />
<pre style="background-image: URL(https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhtDkiUO9nySrprZDIjEIEJoxRX3AuY42e5gAii42s0X5LltSQDuFgkK2KCenBuZDe5hzN8gyAvGkO6tfzvpnKnIt6mpyAT-eMdZKd9C5yv2-mFzkCRTQe3LrYOdZrEn3qzd5NfoNdynIUe/s320/codebg.gif); background: #f0f0f0; border: 1px dashed #CCCCCC; color: black; font-family: arial; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;"> public void CreateBucket(string bucketName)
{
if (!this.IsCheckBucket(bucketName))
{
client.PutBucket(new PutBucketRequest()
{
BucketName = bucketName,
UseClientRegion = true //Utiliza a mesma região que estiver como padrão no WS.
});
}
}
</code></pre>
<br />
<span style="font-family: Courier New, Courier, monospace;">Outra propriedade importante também seria "<b>CannedACL</b>" que indica o tipo de permissão que o arquivo terá no storage da amazon aws, nesse caso eu coloquei como "<b>S3CannedACL.PublicRead</b></span><span style="font-family: 'Courier New', Courier, monospace;">" que esse arquivo poderá ser visto publicamente.</span><br />
<span style="font-family: 'Courier New', Courier, monospace;">Para concluirmos você deve ter reparado que ao fazer a chamada da classe "</span><span style="font-family: Courier New, Courier, monospace;">AWSClientFactory" você precisa passar a ela a sua chave e também a chave secreta. Essas duas chaves você pode gerar através do painel de controle da Amazon AWS.</span><br />
<span style="font-family: Courier New, Courier, monospace;">Ao acessar o console <a href="https://aws.amazon.com/" target="_blank">https://aws.amazon.com/</a> com o teu login, você vai ver no menu acima na aba escrita com seu nome a opção "<b>Security Credencials</b>".</span><br />
<span style="font-family: Courier New, Courier, monospace;"><br /></span>
<span style="font-family: Courier New, Courier, monospace;">Acesse:</span><br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjJk0UxQbaiXeV-I9JioXAelY-44YBwosDeO5pIkpVqWoGeOTbpIgjY3yq-QdkO6Z-Wo2pue8pILRPZQrmw4EPBgXIkK9_-TMdIiJpgi4BYj76UjTix4RDbCFmAelFXJ4IM-HmJxvBv2TQ/s1600/amazon+3.PNG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjJk0UxQbaiXeV-I9JioXAelY-44YBwosDeO5pIkpVqWoGeOTbpIgjY3yq-QdkO6Z-Wo2pue8pILRPZQrmw4EPBgXIkK9_-TMdIiJpgi4BYj76UjTix4RDbCFmAelFXJ4IM-HmJxvBv2TQ/s1600/amazon+3.PNG" height="136" width="640" /></a></div>
<span style="font-family: Courier New, Courier, monospace;"><br /></span>
<span style="font-family: Courier New, Courier, monospace;">Agora é só gerar a sua key e secret key e inserir na chamada.</span><br />
<span style="font-family: 'Courier New', Courier, monospace;">Se obtiver sucesso no upload você pode acessar o console na opção de serviço S3, você vai perceber que o seu "BucketName" e dentro dele o arquivo enviado, ao clicar sobre o arquivo perceba nas propriedade que Amazon AWS gerou uma url publica de acesso ao seu arquivo que será algo parecido com isso: </span><span style="font-family: Courier New, Courier, monospace;"><u style="font-weight: bold;">https://s3.amazonaws.com/MeusArquivos/Arquivos/nome_arquivo</u></span><br />
<span style="font-family: 'Courier New', Courier, monospace;">Agora é só usufruir da performance</span><span style="font-family: 'Courier New', Courier, monospace;"> que a storage vai te oferecer além disso com um valor muito pequeno.</span><br />
<span style="font-family: Courier New, Courier, monospace;"><br /></span>
<span style="font-family: Courier New, Courier, monospace;">Espero ter ajudado.</span><br />
<span style="font-family: Courier New, Courier, monospace;">Abraço,</span>Anonymoushttp://www.blogger.com/profile/11593196735866212585noreply@blogger.com0tag:blogger.com,1999:blog-2614996039040117788.post-55316946973113501192014-12-08T11:00:00.001-08:002014-12-08T11:09:32.764-08:00MongoDB + ASP.NET Web API 2<div style="text-align: justify;">
<span style="font-family: Courier New, Courier, monospace;">No dia-dia de um desenvolvedor é bem comum a necessidade de criar uma API com pequena ou baixa complexidade, ambientes que possam entregar informações a qualquer dispositivo e plataforma vem se tornando cada vez mais rotineiro.</span></div>
<div style="text-align: justify;">
<span style="font-family: Courier New, Courier, monospace;">Através dessa necessidade que a microsoft criou um Framework bastante fácil para desenvolver serviços HTTP <a href="http://www.asp.net/web-api" target="_blank">http://www.asp.net/web-api</a>. </span><br />
<span style="font-family: Courier New, Courier, monospace;"><br /></span>
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhA3dCjnUxAG9xDSYjk9mqaQqFn2HnTgp5F7KcAUYb-bZXUzC1sxigWvY3QmudlltBii2X0jUjnqJjZfy551tY5zeKH9rHqzkgGrkJEXppzzb_pSMr8h_7bXm8fPUlH3_gZIl3fQZPMHIk/s1600/ASP.Net-Web-API.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhA3dCjnUxAG9xDSYjk9mqaQqFn2HnTgp5F7KcAUYb-bZXUzC1sxigWvY3QmudlltBii2X0jUjnqJjZfy551tY5zeKH9rHqzkgGrkJEXppzzb_pSMr8h_7bXm8fPUlH3_gZIl3fQZPMHIk/s1600/ASP.Net-Web-API.png" height="130" width="320" /></a></div>
<span style="font-family: Courier New, Courier, monospace;"><br /></span>
<br />
<span style="font-family: Courier New, Courier, monospace;"><br /></span>
<span style="font-family: Courier New, Courier, monospace;">A primeira vez que tive contato com Web Api ainda na versão 1 fiquei muito animado porque consegui ver muitos ganhos principalmente em agilidade de desenvolvimento em relação aos serviços RESTful desenvolvidos com WCF até então. </span></div>
<div style="text-align: justify;">
<span style="font-family: Courier New, Courier, monospace;">Para você que não teve a oportunidade de entrar nesse mundo de serviços RESTful te recomendo a começar com Web Api, é bastante fácil e com pouco programado você vai conseguir ver um resultado bastante interessante. Esse tutorial escrito por Mike Wasson <a href="http://www.asp.net/web-api/overview/getting-started-with-aspnet-web-api/tutorial-your-first-web-api" target="_blank">http://www.asp.net/web-api/overview/getting-started-with-aspnet-web-api/tutorial-your-first-web-api</a> no site oficial do Asp Net vai perceber como é simples criar e consumir o teu serviço criado. Reforço a sua atenção no tutorial do Mike em que ele cria um client em Javascript para teste dos serviços, algo também muito utilizado ou talvez o mais utilizado ... fácil não? </span><br />
<span style="font-family: Courier New, Courier, monospace;"><br />
</span><br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi06mFbGk9tGgnmJutOymaKjfhWKgEKxCope1xi37HuPTs1v_vxlkRKakkRytQmNTMdYHrIyIcQpvW9xFFn25dJIZdvskLEFQfcbr5nk5csOFCTSFS6GwoYtR_JBqmvRzleQkJ16XROvUU/s1600/client+javascript.PNG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><span style="font-family: Courier New, Courier, monospace;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi06mFbGk9tGgnmJutOymaKjfhWKgEKxCope1xi37HuPTs1v_vxlkRKakkRytQmNTMdYHrIyIcQpvW9xFFn25dJIZdvskLEFQfcbr5nk5csOFCTSFS6GwoYtR_JBqmvRzleQkJ16XROvUU/s1600/client+javascript.PNG" height="122" width="400" /></span></a></div>
<br /></div>
<span style="font-family: Courier New, Courier, monospace;"><span class="pln" style="background-attachment: initial; background-clip: initial; background-color: transparent; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: 0px; color: black; margin: 0px; outline: 0px; padding: 0px; vertical-align: baseline;">A minha intenção com esse post além de apresentar o Asp Net Web Api é mostrar a você que você pode também acoplar ele a um banco de dados NoSQL e tornar o seu serviço ainda mais rápido, é claro isso vai depender se a tua analise comporta um banco de dados NoSQL.</span></span><br />
<span style="font-family: Courier New, Courier, monospace;"><span class="pln" style="background-attachment: initial; background-clip: initial; background-color: transparent; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: 0px; color: black; font-family: Courier New, Courier, monospace; margin: 0px; outline: 0px; padding: 0px; vertical-align: baseline;"><br /></span>
<span class="pln" style="background-attachment: initial; background-clip: initial; background-color: transparent; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: 0px; color: black; font-family: Courier New, Courier, monospace; margin: 0px; outline: 0px; padding: 0px; vertical-align: baseline;">Sirva-se de um café e vamos codificar (...) Primeiramente iremos precisar criar um projeto Web Api. Eu optei por criar um projeto "Empty". </span></span><br />
<span style="font-family: Courier New, Courier, monospace;"><span class="pln" style="background-attachment: initial; background-clip: initial; background-color: transparent; background-image: initial; background-origin: initial; background-position: initial; background-repeat: initial; background-size: initial; border: 0px; color: black; font-family: Courier New, Courier, monospace; margin: 0px; outline: 0px; padding: 0px; vertical-align: baseline;"><br /></span>
</span><br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgPOl0mBSCnNLZssR4JELs3aF9u6KwcblxzmzZ-amZXGZmr4aHlU838gWZiJ4zzFy1wO92JSkKdjopUIPg1MGeNnYXyhiqtRApmaYYwyvL7V0ZoeEWa5de8Zpp4hFhIdNJsiFV_nBDsepA/s1600/web+api+1.PNG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><span style="font-family: Courier New, Courier, monospace;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgPOl0mBSCnNLZssR4JELs3aF9u6KwcblxzmzZ-amZXGZmr4aHlU838gWZiJ4zzFy1wO92JSkKdjopUIPg1MGeNnYXyhiqtRApmaYYwyvL7V0ZoeEWa5de8Zpp4hFhIdNJsiFV_nBDsepA/s1600/web+api+1.PNG" height="240" width="320" /></span></a></div>
<div class="separator" style="clear: both; text-align: center;">
<span style="font-family: Courier New, Courier, monospace;"><br /></span></div>
<div class="separator" style="clear: both; text-align: justify;">
<span style="font-family: Courier New, Courier, monospace;">Após criar o projeto já também criei um controller chamado "NOTICIA" e também um modelo também chamado "NOTICIA", perceba que me antecipei e já criei uma pasta chamada "MONGODB". A minha solution ficou mais ou menos assim ...</span></div>
<div class="separator" style="clear: both; text-align: justify;">
<span style="font-family: Courier New, Courier, monospace;"><br /></span></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg0ctyuON8J584pT9pM5YFg7c7wjvagQUnDGe-s4aSed2BviyCxUGMi02rs9qfUpSIQfghslIvLVN8abLH5Ytf2jnI4vfsvHE86wNXolObyxw9r3TRbLZ6vrOz6pUbgRVhvcVFecdRLxkU/s1600/web+api+2.PNG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><span style="font-family: Courier New, Courier, monospace;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg0ctyuON8J584pT9pM5YFg7c7wjvagQUnDGe-s4aSed2BviyCxUGMi02rs9qfUpSIQfghslIvLVN8abLH5Ytf2jnI4vfsvHE86wNXolObyxw9r3TRbLZ6vrOz6pUbgRVhvcVFecdRLxkU/s1600/web+api+2.PNG" height="248" width="320" /></span></a></div>
<div class="separator" style="clear: both; text-align: justify;">
<span style="font-family: Courier New, Courier, monospace;">Se você executar o projeto vai ver que o serviço já esta funcionando porém você não implementou nenhum dos métodos no controller vai receber um erro ou se você optou por criar um controller já com as funções de read/write actions vai ter um template de alguns métodos previamente implementado, fica a sua escolha. </span></div>
<div class="separator" style="clear: both; text-align: justify;">
<span style="font-family: Courier New, Courier, monospace;">Com o nosso serviço funcionando vamos agora implementar um pequeno repositório para facilitar a nossa vida ao escrever as nossas consultar no MongoDB.</span></div>
<br />
<pre style="background-image: URL(https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhtDkiUO9nySrprZDIjEIEJoxRX3AuY42e5gAii42s0X5LltSQDuFgkK2KCenBuZDe5hzN8gyAvGkO6tfzvpnKnIt6mpyAT-eMdZKd9C5yv2-mFzkCRTQe3LrYOdZrEn3qzd5NfoNdynIUe/s320/codebg.gif); background: #f0f0f0; border: 1px dashed #CCCCCC; color: black; font-family: arial; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;"> public interface IRepository<TEntity> where TEntity : EntityBase
{
bool Insert(TEntity entity);
List<TEntity> SearchFor(Expression<Func<TEntity, bool>> predicate);
List<TEntity> GetAll();
TEntity GetById(ObjectId id);
} </code></pre>
<pre style="background-image: URL(https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhtDkiUO9nySrprZDIjEIEJoxRX3AuY42e5gAii42s0X5LltSQDuFgkK2KCenBuZDe5hzN8gyAvGkO6tfzvpnKnIt6mpyAT-eMdZKd9C5yv2-mFzkCRTQe3LrYOdZrEn3qzd5NfoNdynIUe/s320/codebg.gif); background: #f0f0f0; border: 1px dashed #CCCCCC; color: black; font-family: arial; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;">
public abstract class EntityBase
{
[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
public string Id { get; set; }
}
</code></pre>
<span style="font-family: Courier New, Courier, monospace;"><br /></span>
<span style="font-family: Courier New, Courier, monospace;">Implementamos uma interface com os métodos que teremos disponíveis no repositório e também uma classe abstract para utilizar em nossos modelos, logo você vai perceber que não será necessário criar um atributo "Id" para nossos modelos sendo que apenas devemos herdar a nossa classe "EntityBase".</span><br />
<span style="font-family: Courier New, Courier, monospace;"><br /></span>
<span style="font-family: Courier New, Courier, monospace;">Exemplo:</span><br />
<pre style="background-image: URL(https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhtDkiUO9nySrprZDIjEIEJoxRX3AuY42e5gAii42s0X5LltSQDuFgkK2KCenBuZDe5hzN8gyAvGkO6tfzvpnKnIt6mpyAT-eMdZKd9C5yv2-mFzkCRTQe3LrYOdZrEn3qzd5NfoNdynIUe/s320/codebg.gif); background: #f0f0f0; border: 1px dashed #CCCCCC; color: black; font-family: arial; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;"> public class Noticia : EntityBase
{
public string Titulo { get; set; }
public string Conteudo { get; set; }
public string Autor { get; set; }
} </code></pre>
<br />
<span style="font-family: Courier New, Courier, monospace;">Não devemos esquecer de baixar o pacote de DLL do drive do MongoDB para C# é bastante simples e pode ser baixado no</span><br />
<span style="font-family: Courier New, Courier, monospace;">nuGet <a href="https://www.nuget.org/packages/mongocsharpdriver/1.9.2" target="_blank">https://www.nuget.org/packages/mongocsharpdriver/1.9.2</a></span><br />
<br />
<pre style="background-image: URL(https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhtDkiUO9nySrprZDIjEIEJoxRX3AuY42e5gAii42s0X5LltSQDuFgkK2KCenBuZDe5hzN8gyAvGkO6tfzvpnKnIt6mpyAT-eMdZKd9C5yv2-mFzkCRTQe3LrYOdZrEn3qzd5NfoNdynIUe/s320/codebg.gif); background: #f0f0f0; border: 1px dashed #CCCCCC; color: black; font-family: arial; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;"> public class MongoDbRepository<TEntity> : IRepository<TEntity> where TEntity : EntityBase
{
private MongoDatabase _Database;
private MongoCollection<TEntity> _Collection;
public MongoDbRepository()
{
GetDatabase();
GetCollection();
}
private void GetDatabase()
{
var client = new MongoClient(GetConnectionString());
var server = client.GetServer();
_Database = server.GetDatabase(GetDatabaseName());
}
private string GetConnectionString()
{
return WebConfigurationManager.AppSettings["MongoDbConnectionString"].Replace("{DB_NAME}", GetDatabaseName());
}
private string GetDatabaseName()
{
return WebConfigurationManager.AppSettings["MongoDbDatabaseName"];
}
private void GetCollection()
{
_Collection = _Database
.GetCollection<TEntity>(typeof(TEntity).Name);
}
public bool Insert(TEntity entity)
{
entity.Id = ObjectId.GenerateNewId().ToString();
return _Collection.Insert(entity).Ok;
}
public List<TEntity> SearchFor(System.Linq.Expressions.Expression<Func<TEntity, bool>> predicate)
{
return _Collection
.AsQueryable<TEntity>()
.Where(predicate.Compile())
.ToList();
}
public List<TEntity> GetAll()
{
return _Collection.FindAllAs<TEntity>().ToList();
}
public TEntity GetById(ObjectId id)
{
return _Collection.FindOneByIdAs<TEntity>(id);
}
} </code></pre>
<span style="font-family: Courier New, Courier, monospace;">Se você já teve oportunidade de trabalhar com repositórios com o EF por exemplo vai perceber alguma semelhança pois utilizamos de expressões linq para acesso aos documentos. Os três métodos privados ficam responsáveis pela configuração do servidor do mongo.</span><br />
<span style="font-family: Courier New, Courier, monospace;">Eu implementei buscando dentro do web.config apenas para uma melhor organização isso não impediria em nada no funcionamento se estivesse diretamente no código a connection do banco.</span><br />
<span style="font-family: Courier New, Courier, monospace;"><br /></span>
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhr4KLdCzW7L2Uxv2MoLDn9CGZlpSetn8cssjScTqUcvNebmhRiFG50sRJs4GlBoUBQWjtzrY75hSHZF99Yt1Ot2a-a3Pk59XjQopqpYR0lizBaxzQnV7bLnuna0J3g2vSkrvt2qVxVCPM/s1600/url+mongo.PNG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhr4KLdCzW7L2Uxv2MoLDn9CGZlpSetn8cssjScTqUcvNebmhRiFG50sRJs4GlBoUBQWjtzrY75hSHZF99Yt1Ot2a-a3Pk59XjQopqpYR0lizBaxzQnV7bLnuna0J3g2vSkrvt2qVxVCPM/s1600/url+mongo.PNG" height="71" width="400" /></a></div>
<div class="separator" style="clear: both; text-align: justify;">
<span style="font-family: Courier New, Courier, monospace;">O servidor do MongoDB poderia estar localmente instalado como escrevi um tutorial a algum tempo falando especificamente sobre essa instalalção no windows. <a href="http://jr-encode.blogspot.com.br/2013/03/instal-mongodb-no-windows-como-servico.html" target="_blank">http://jr-encode.blogspot.com.br/2013/03/instal-mongodb-no-windows-como-servico.html</a>.</span></div>
<div class="separator" style="clear: both; text-align: justify;">
<span style="font-family: Courier New, Courier, monospace;">O processo de instalação é bastante simples mas temos uma outra opção se você não quiser instalar o serviço do mongoDB na sua rede você pode estar utilizando um serviço que inicialmente é gratuito até um certo tamanho de banco e tendo a opção de escalar conforme sua necessidade. É um serviço muito bom pude utilizar em um projeto recentemente e não tive problemas. Você pode estar lendo mais a respeito <a href="https://mongolab.com/" target="_blank">https://mongolab.com/</a>, após criar um login e senha no Mongolab você terá que criar um novo database.</span></div>
<div class="separator" style="clear: both; text-align: justify;">
<span style="font-family: Courier New, Courier, monospace;"><br /></span></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiGTiHodTZzwQBbo8P6EAY2vpXx1b2xuYlLfMIS_v4oJ3ZWCwfNssdXKXmhezsWYrmxSlwnWtlrSrwl_jh402x1jQfT0ZoHiDdtwD1u0Vm0gN6kmWPPDyYBvsZ8EwTdW3gsO5Z2S3O9iug/s1600/mongolab.PNG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiGTiHodTZzwQBbo8P6EAY2vpXx1b2xuYlLfMIS_v4oJ3ZWCwfNssdXKXmhezsWYrmxSlwnWtlrSrwl_jh402x1jQfT0ZoHiDdtwD1u0Vm0gN6kmWPPDyYBvsZ8EwTdW3gsO5Z2S3O9iug/s1600/mongolab.PNG" height="400" width="352" /></a></div>
<div class="separator" style="clear: both; text-align: justify;">
<span style="font-family: Courier New, Courier, monospace;"><br /></span></div>
<div class="separator" style="clear: both; text-align: justify;">
<span style="font-family: Courier New, Courier, monospace;">Recomendo a você a criar um single-node que tem uma opção de até 0.5G gratuito, você terá que informar ao mongolab o nome do seu database a próxima pagina o mongolab irá mostrar sua URL de acesso ao database onde você terá que substituir na config do repositório, depois disso é SUCESSO, você terá um banco NoSQL online tendo a opção de escalar muito dependendo da necessidade e crescimento da sua API.</span></div>
<div class="separator" style="clear: both; text-align: justify;">
<span style="font-family: Courier New, Courier, monospace;">Com o nosso repositório configurado podemos agora codificar os métodos do nosso controller de noticia.</span></div>
<br />
<pre style="background-image: URL(https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhtDkiUO9nySrprZDIjEIEJoxRX3AuY42e5gAii42s0X5LltSQDuFgkK2KCenBuZDe5hzN8gyAvGkO6tfzvpnKnIt6mpyAT-eMdZKd9C5yv2-mFzkCRTQe3LrYOdZrEn3qzd5NfoNdynIUe/s320/codebg.gif); background: #f0f0f0; border: 1px dashed #CCCCCC; color: black; font-family: arial; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;"> public class NoticiaController : ApiController
{
private IRepository<Noticia> _RepNoticia;
public NoticiaController()
{
_RepNoticia = new MongoDbRepository<Noticia>();
}
/// <summary>
/// Retorna todas as noticias.
/// </summary>
/// <returns></returns
[Route("")]
public IEnumerable<Noticia> Get()
{
return _RepNoticia.GetAll();
}
/// <summary>
/// Retorna uma noticia filtrada pelo Id
/// </summary>
/// <param name="id">Id</param>
/// <returns></returns>
[Route("{id}")]
public Noticia Get(ObjectId id)
{
return _RepNoticia.GetById(id);
}
/// <summary>
/// Retorna todas as noticias filtrando por alguma palavra contida no titulo.
/// </summary>
/// <param name="titulo">Titulo</param>
/// <returns></returns>
[Route("titulo/{titulo}")]
public IEnumerable<Noticia> Get(string titulo)
{
return _RepNoticia.SearchFor(f => f.Titulo.Contains(titulo)).ToList();
}
/// <summary>
/// Grava uma noticia
/// </summary>
/// <param name="value"></param>
[Route("")]
public HttpResponseMessage Post(Noticia noticia)
{
try
{
_RepNoticia.Insert(noticia);
return Request.CreateResponse(HttpStatusCode.OK, "Noticia gravada com sucesso");
}
catch (Exception ex)
{
return Request.CreateResponse(HttpStatusCode.InternalServerError, ex.Message);
}
}
}
</code></pre>
<span style="font-family: 'Courier New', Courier, monospace;">As chamadas para o repositório fica de forma limpa e de fácil entendimento, basicamente temos quatro métodos de teste, são eles: Get (retorna todos), Get (retorna filtrado por id), Get (retorna todos por alguma palavra contida titulo), Post (Grava uma noticia). Outro detalhe que possa parecer diferente é a utilização de "RoutePrefix" na anotação do controller. Isso irá mudar a URL de acesso no router que deverá ser acessada agora assim: </span><b style="font-family: 'Courier New', Courier, monospace; text-decoration: underline;">http://localhost/api/public/v1/noticias/ </b><span style="font-family: 'Courier New', Courier, monospace;"> dessa forma você consegue padronizar melhor as chamadas da sua API, acredito que isso é mais uma boa pratica porém se você tiver uma maior quantidade de controller vai perceber que começa a ficar "complicada" a organização da API. Segue um outro interessante tutorial falando sobre "RouterPrefix" também escrito pelo Mike Wasson </span><a href="http://www.asp.net/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2" style="font-family: 'Courier New', Courier, monospace;" target="_blank">http://www.asp.net/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2</a><br />
<br />
<span style="font-family: Courier New, Courier, monospace;">Outra dica interessante que costumo fazer é como geralmente utilizo retorno de formato JSON até porque é bem mais tranquilo para você trabalhar em Javascript por exemplo, removendo o retorno de XML e também formatando o retorno do JSON algo que vai te ajudar bastante na leitura em ambiente de desenvolvimento.</span><br />
<span style="font-family: Courier New, Courier, monospace;"><br /></span>
<span style="font-family: Courier New, Courier, monospace;">Global.asax.cs (Método register)</span><br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhKAJ0awzj_uht8ih_dRX70gEZOtIzNge-vjT6gi7eBX7ioc-mgupBGFqBqv3BvqlL_DDtA2AXgvVhqD-jKU5B3X80s8L1O5veHP7gs4BpxrCjd1g_40NucX0r-p5Z-9we2MUCGPRXt_W4/s1600/REMOVER+XML.PNG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhKAJ0awzj_uht8ih_dRX70gEZOtIzNge-vjT6gi7eBX7ioc-mgupBGFqBqv3BvqlL_DDtA2AXgvVhqD-jKU5B3X80s8L1O5veHP7gs4BpxrCjd1g_40NucX0r-p5Z-9we2MUCGPRXt_W4/s1600/REMOVER+XML.PNG" height="85" width="400" /></a></div>
<div class="separator" style="clear: both; text-align: center;">
<br /></div>
<div class="separator" style="clear: both; text-align: justify;">
<span style="font-family: Courier New, Courier, monospace;">Espero ter ajudado, Fique a vontade para manter contato.</span></div>
<span style="font-family: Courier New, Courier, monospace;">Abraço,</span><br />
<br />Anonymoushttp://www.blogger.com/profile/11593196735866212585noreply@blogger.com0tag:blogger.com,1999:blog-2614996039040117788.post-48346535995463498622013-03-29T10:34:00.001-07:002013-03-29T10:54:35.452-07:00Instalando MongoDB no Windows<div style="text-align: justify;">
<span style="font-family: Courier New, Courier, monospace;">Você que está antenado em novas tendencias já deve ter ouvido falar em NoSQL. Basicamente esse termo é utilizado para definir banco de dados não-relacionais, algo que rompe toda uma historia dos banco relacionais. </span></div>
<div style="text-align: justify;">
<span style="font-family: Courier New, Courier, monospace;">Seu autor Carlo Strozzi<span style="line-height: 19.1875px;"> tem uma frase que defini bem:</span></span></div>
<div style="text-align: justify;">
<span style="font-family: Courier New, Courier, monospace;"><b>"é completamente distinto do modelo relacional e portanto deveria ser mais apropriadamente chamado "NoREL" ou algo que produzisse o mesmo efeito".</b></span></div>
<div style="text-align: justify;">
<span style="font-family: Courier New, Courier, monospace;"><span style="line-height: 19.1875px;">Aqueles que gostam de historia, te recomendo a dar uma navegada por esses sites:</span></span></div>
<div style="text-align: justify;">
<span style="font-family: Courier New, Courier, monospace;"><span style="line-height: 19.1875px;"><a href="http://www.strozzi.it/" target="_blank">http://www.strozzi.it/</a>,</span></span></div>
<div style="text-align: justify;">
<span style="font-family: Courier New, Courier, monospace;"><span style="line-height: 19.1875px;"><a href="http://blog.caelum.com.br/bancos-de-dados-nao-relacionais-e-o-movimento-nosql/" target="_blank">http://blog.caelum.com.br/bancos-de-dados-nao-relacionais-e-o-movimento-nosql/</a>, </span></span></div>
<div style="text-align: justify;">
<span style="font-family: Courier New, Courier, monospace;"><span style="line-height: 19.1875px;"><a href="http://pt.wikipedia.org/wiki/NoSQL" target="_blank">http://pt.wikipedia.org/wiki/NoSQL</a>.</span></span></div>
<div style="text-align: justify;">
<span style="font-family: Courier New, Courier, monospace;"><span style="line-height: 19.1875px;">O foco desse nosso POST é dar inicio a utilização de um banco de dados não-relacional, inicialmente irei mostrar como instalar o banco e configura-lo para ficar como um serviço do windows. </span></span><br />
<span style="font-family: Courier New, Courier, monospace;"><span style="line-height: 19.1875px;">Ao inicial o sistema operacional, juntamente com ele o serviço do nosso banco de dados. </span><span style="line-height: 19.1875px;">Venho estudando e utilizando em alguns projetos o banco "MongoDB". <a href="http://www.mongodb.org/" target="_blank">http://www.mongodb.org/</a>.</span></span><br />
<span style="color: #333333; font-family: Courier New, Courier, monospace;"><span style="line-height: 20px;">MongoDB é uma aplicação de código aberto, de alta performance, sem esquemas, orientado à documentos.</span></span></div>
<div style="text-align: justify;">
<br />
<span style="font-family: Courier New, Courier, monospace;"><span style="line-height: 19.1875px;">Nesse mundo de NoSql ele é um cara bastante conhecido e utilizado por muita gente grande como Twitter, Facebook etc que por sua vez são sistemas que necessitam de alta escalabilidade nas consultas e utilização de compartilhamento de informações entre servidores. </span></span><br />
<span style="font-family: Courier New, Courier, monospace;"><span style="line-height: 19.1875px;">Suas bibliotecas são escritas em C++ e utiliza técnicas avançadas em recorrer totalmente a memoria para leitura dos dados.</span></span></div>
<div class="separator" style="clear: both; text-align: justify;">
<span style="font-family: Courier New, Courier, monospace; margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiB_Z2Da_ihz5GGhzMnmJLgpqcDR9AOi0cPQvHJKmH_xmD_cRBTeRKmsCXlqRhOCckIYu4f3_GU4AGxCGaPMOBtAP08yPHCCsZPWD87fvDsr3maOTqtouIS7LMVdr7mAV39qDDJbo6ReZU/s1600/A.png" height="230" width="400" /></span></div>
<span style="font-family: Courier New, Courier, monospace;"><br /></span>
<br />
<div style="text-align: justify;">
<span style="color: #222222; font-family: 'Courier New', Courier, monospace; line-height: 16px;">Começamos fazendo o download da biblioteca que está disponível no site oficial </span><a href="http://www.mongodb.org/downloads" style="font-family: 'Courier New', Courier, monospace; line-height: 16px;" target="_blank">http://www.mongodb.org/downloads</a><span style="color: #222222; font-family: 'Courier New', Courier, monospace; line-height: 16px;">.</span></div>
<span style="color: #222222; font-family: 'Courier New', Courier, monospace; line-height: 16px; text-align: justify;">Após teremos que criar duas pastas para apontar ao mongo aonde os arquivos do repositório será armazenado.</span><br />
<div style="text-align: justify;">
<span style="color: #222222; font-family: 'Courier New', Courier, monospace; line-height: 16px;"><br /></span></div>
<div style="text-align: justify;">
<span style="background-color: #cccccc; color: #222222; font-family: 'Courier New', Courier, monospace; line-height: 16px;">md data</span></div>
<div style="text-align: justify;">
<span style="color: #222222; font-family: Courier New, Courier, monospace;"><span style="background-color: #cccccc; line-height: 16px;">md data\db</span></span></div>
<div style="text-align: justify;">
<span style="color: #222222; font-family: 'Courier New', Courier, monospace; line-height: 16px;">Depois de criada as pastas, teremos que navegar até a pasta em que baixamos e executar o </span><span style="background-color: #cccccc; color: #222222; font-family: 'Courier New', Courier, monospace; line-height: 16px;">Mongod.exe</span></div>
<div style="text-align: justify;">
<span style="font-family: Courier New, Courier, monospace;"><span style="color: #222222;"><span style="line-height: 16px;"><span style="background-color: #cccccc;"><br /></span></span></span>
</span></div>
<div class="separator" style="clear: both; text-align: justify;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEje0hq47-4LNpOFTtXl2ivqR0qiQxdtTp3Nr00oTJmu6iGX0SjDNzhTxKvIDDR8UHhJ240ZOOQrorwz7ohQpX4HttQPmsKsNEHoqZAXVzkLMnyM8Is_IWDyiIjsQCjmBNKtIpfQDPZTjz8/s1600/2.PNG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><span style="font-family: Courier New, Courier, monospace;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEje0hq47-4LNpOFTtXl2ivqR0qiQxdtTp3Nr00oTJmu6iGX0SjDNzhTxKvIDDR8UHhJ240ZOOQrorwz7ohQpX4HttQPmsKsNEHoqZAXVzkLMnyM8Is_IWDyiIjsQCjmBNKtIpfQDPZTjz8/s1600/2.PNG" height="200" width="400" /></span></a></div>
<br />
<div style="text-align: justify;">
<span style="font-family: 'Courier New', Courier, monospace;">Com a execução realidade com sucesso você poderá testar se o serviço está rodando corretamente. Vá até o seu navegador de preferencia e escreva a seguinte URL </span><span style="background-color: #cccccc; font-family: 'Courier New', Courier, monospace;">http://localhost:27017/</span></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg2oYAZHkRImdX_HP89swbuscSq9ysPFZ__vOCP43AWlYTgVqxe7ImEnLG7of0tRWdlTcDlv3Gbh37UyI23LGpy8cyK0w5QVNeL07GwqOAvGa9hhYv2w4WltensgUYYS_DiAXaKq3qjKDw/s1600/3.PNG" imageanchor="1" style="clear: left; float: left; margin-bottom: 1em; margin-right: 1em; text-align: justify;"><span style="font-family: Courier New, Courier, monospace;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg2oYAZHkRImdX_HP89swbuscSq9ysPFZ__vOCP43AWlYTgVqxe7ImEnLG7of0tRWdlTcDlv3Gbh37UyI23LGpy8cyK0w5QVNeL07GwqOAvGa9hhYv2w4WltensgUYYS_DiAXaKq3qjKDw/s1600/3.PNG" height="30" width="400" /></span></a></div>
<div style="text-align: justify;">
<span style="font-family: Courier New, Courier, monospace;"><br /></span></div>
<div style="text-align: justify;">
<span style="font-family: Courier New, Courier, monospace;"><br />
</span></div>
<div style="text-align: justify;">
<span style="font-family: Courier New, Courier, monospace;"><br /></span>
<span style="font-family: Courier New, Courier, monospace;"><br /></span><br />
<span style="font-family: Courier New, Courier, monospace;">Se você reparar no gerenciador de processos da sua maquina vai ver um processo chamado mongod.exe. </span><span style="font-family: 'Courier New', Courier, monospace;">Muito fácil</span><span style="font-family: Courier New, Courier, monospace;"> não é? isso já seria suficiente para começar a utilização do banco.</span><br />
<span style="font-family: Courier New, Courier, monospace;">Mas como disse inicialmente vamos coloca-lo na inicialização do sistema operacional, para isso execute o seguinte comando:</span></div>
<pre style="color: #222222; font-size: 16px; line-height: 1.2em; margin: 20px; overflow-x: auto; overflow-y: hidden; padding: 10px; text-align: justify;"><span style="background-color: #cccccc; font-family: Courier New, Courier, monospace;">C:\mongodb\bin\mongod.exe --config C:\mongodb\mongod.cfg --install</span></pre>
<div class="separator" style="clear: both; text-align: justify;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhJ3-StKoXS01yeD_GsiFYe3GgxY9L_bjjvZMFmlivWP7Xyh3AkvCiUjF1U5Wv4abI8dxfOo_mC0UG7KhgPKZIMgKQCQVnpDjdmDOfXJfVpfBhN7OdhxOQ8mr9-r0HMSlmkIrR2_qybbUw/s1600/4.PNG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><span style="font-family: Courier New, Courier, monospace;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhJ3-StKoXS01yeD_GsiFYe3GgxY9L_bjjvZMFmlivWP7Xyh3AkvCiUjF1U5Wv4abI8dxfOo_mC0UG7KhgPKZIMgKQCQVnpDjdmDOfXJfVpfBhN7OdhxOQ8mr9-r0HMSlmkIrR2_qybbUw/s1600/4.PNG" height="198" width="400" /></span></a></div>
<div class="separator" style="clear: both; text-align: justify;">
<span style="font-family: Courier New, Courier, monospace;"><br /></span></div>
<div class="separator" style="clear: both; text-align: justify;">
<span style="font-family: Courier New, Courier, monospace;">Fique atento se o arquivo mongod.cfg existe no diretório, caso contrario execute os seguintes comandos para criar o diretório de log.</span></div>
<div class="separator" style="clear: both; text-align: justify;">
<span style="background-color: #cccccc; font-family: Courier New, Courier, monospace;"><br /></span></div>
<div class="separator" style="clear: both; text-align: justify;">
<span style="font-family: Courier New, Courier, monospace;"></span></div>
<div class="separator" style="clear: both; text-align: justify;">
<span style="font-family: Courier New, Courier, monospace;"><span style="background-color: #cccccc;">md C:\mongodb\log</span></span></div>
<div class="separator" style="clear: both; text-align: justify;">
<span style="font-family: Courier New, Courier, monospace;"><span style="background-color: #cccccc;">echo logpath=C:\mongodb\log\mongo.log > C:\mongodb\mongod.cfg</span></span></div>
<div class="separator" style="clear: both; text-align: justify;">
<span style="font-family: Courier New, Courier, monospace;"><span style="background-color: #cccccc;"><br /></span></span></div>
<div class="separator" style="clear: both; text-align: justify;">
<span style="font-family: Courier New, Courier, monospace;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhyOen-_wCteIKrhYbZdX0td-uYq6b0szlLI_U67XfydmV5q_p9Uwc5bdkSn3JFl1SwLunOO8bl_FfwPd-ruqHh7FUrMqppRg4-844j7WTqvn7oRzBJb8jEbiZKbx2oX3zF41_0YEW25Ks/s1600/5.PNG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhyOen-_wCteIKrhYbZdX0td-uYq6b0szlLI_U67XfydmV5q_p9Uwc5bdkSn3JFl1SwLunOO8bl_FfwPd-ruqHh7FUrMqppRg4-844j7WTqvn7oRzBJb8jEbiZKbx2oX3zF41_0YEW25Ks/s1600/5.PNG" height="132" width="400" /></a></span></div>
<div class="separator" style="clear: both; text-align: justify;">
<span style="font-family: Courier New, Courier, monospace;"><span style="background-color: #cccccc;"><br /></span></span></div>
<div class="separator" style="clear: both; text-align: justify;">
<span style="font-family: Courier New, Courier, monospace;">Agora o arquivo mongod.cfg foi gerado, após efetuado o procedimento com sucesso, execute novamente o comando para instalação do serviço.</span></div>
<div class="separator" style="clear: both; text-align: justify;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj8sesvHdrFPABYM87aB30H1tqXgR9EECGBuVcNdqr16DsGSyHOCI4LsVC-TSlkPbzsEkt-8w_vW5InOwcqhoOiZh1-in2RvCA6hgw5klR-2GruVlDbmKvXZnGcZVkOkBXVNNqNhMOOzcE/s1600/6.PNG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><span style="font-family: Courier New, Courier, monospace;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj8sesvHdrFPABYM87aB30H1tqXgR9EECGBuVcNdqr16DsGSyHOCI4LsVC-TSlkPbzsEkt-8w_vW5InOwcqhoOiZh1-in2RvCA6hgw5klR-2GruVlDbmKvXZnGcZVkOkBXVNNqNhMOOzcE/s1600/6.PNG" height="17" width="400" /></span></a></div>
<div class="separator" style="clear: both; text-align: justify;">
<span style="font-family: Courier New, Courier, monospace;">Reinicie o sistema operacional e verá que o serviço será iniciado...</span></div>
<div class="separator" style="clear: both; text-align: justify;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh47MqwzOFqRiC3Dwybl1ONBahiuvfYUomFKTS-FX9aTh-8NxbRQpQssQQcNPKEWRnzdXtBnv5w6EM9ZKuJpGbaOfKiLOc3aqfhtc9oBp1PWZHxSw-tOlFQ2xFx3db5OZ_jLJTw6-XyjfA/s1600/7.PNG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><span style="font-family: Courier New, Courier, monospace;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh47MqwzOFqRiC3Dwybl1ONBahiuvfYUomFKTS-FX9aTh-8NxbRQpQssQQcNPKEWRnzdXtBnv5w6EM9ZKuJpGbaOfKiLOc3aqfhtc9oBp1PWZHxSw-tOlFQ2xFx3db5OZ_jLJTw6-XyjfA/s1600/7.PNG" height="20" width="400" /></span></a></div>
<div class="separator" style="clear: both; text-align: justify;">
<span style="font-family: Courier New, Courier, monospace;"><br /></span></div>
<div class="separator" style="clear: both; text-align: justify;">
</div>
<div class="separator" style="clear: both;">
<span style="font-family: Courier New, Courier, monospace;">Acessando a URL <span style="background-color: #cccccc;">http://localhost:28017/</span> terá um gerenciador bastante simplificado aonde é mostrado algumas atividades do banco.</span></div>
<div class="separator" style="clear: both;">
<span style="font-family: Courier New, Courier, monospace;">Uma outra dica bastante produtiva seria a utilização de um gerenciador com uma interface gráfica um pouco mas amigável.</span></div>
<div class="separator" style="clear: both;">
<span style="font-family: Courier New, Courier, monospace;"><a href="http://robomongo.org/" target="_blank">http://robomongo.org/</a> é uma biblioteca também de código aberto de muito fácil configuração e utilização, nela você terá um ambiente gráfico para gerenciar suas bases no MongoDB.</span></div>
<div class="separator" style="clear: both; text-align: justify;">
<span style="font-family: Courier New, Courier, monospace;"><span style="background-color: white;"><br /></span></span></div>
<div class="separator" style="clear: both; text-align: justify;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjO-z14N8QDODNS3bwQPuYnz_-RT8U_LbFA84ZUFAr04wjkoGjDdW3tt75EDApYCfuHxUcW99D7kzBxh0ej62Xnx7MOEdC18J4wc8G9gfQqEXg9n0kP5IyJSLRPbL_ToCDkph5i4ucqHiY/s1600/8.PNG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><span style="font-family: Courier New, Courier, monospace;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjO-z14N8QDODNS3bwQPuYnz_-RT8U_LbFA84ZUFAr04wjkoGjDdW3tt75EDApYCfuHxUcW99D7kzBxh0ej62Xnx7MOEdC18J4wc8G9gfQqEXg9n0kP5IyJSLRPbL_ToCDkph5i4ucqHiY/s1600/8.PNG" height="200" width="400" /></span></a></div>
<div class="separator" style="clear: both; text-align: justify;">
<br /></div>
<div class="separator" style="clear: both; text-align: justify;">
<span style="font-family: Courier New, Courier, monospace;">Apenas lembrando que testei esse procedimento de instalação nos sistema operacional windows 7 ultimamte 64 bits e windows server 2008 R2 Enterprise.</span></div>
<div class="separator" style="clear: both; text-align: justify;">
<span style="font-family: Courier New, Courier, monospace;"><br /></span></div>
<div class="separator" style="clear: both; text-align: justify;">
<span style="font-family: Courier New, Courier, monospace;">É isso ai! Espero ter ajudado.</span></div>
<div class="separator" style="clear: both; text-align: justify;">
<span style="font-family: Courier New, Courier, monospace;">Abraço =)</span></div>
<div class="separator" style="clear: both; text-align: justify;">
<span style="font-family: Courier New, Courier, monospace;"><br /></span></div>
<div class="separator" style="clear: both; text-align: justify;">
<span style="font-family: Courier New, Courier, monospace; font-size: x-small;"></span></div>
<div class="separator" style="clear: both; text-align: justify;">
<span style="font-family: Courier New, Courier, monospace;"> <i>"O sucesso nasce do querer, da determinação e persistência em se chegar a um objetivo. Mesmo não atingindo o alvo, quem busca e vence obstáculos, no mínimo fará coisas admiráveis."</i></span></div>
<div class="separator" style="clear: both; text-align: justify;">
<span style="font-family: Courier New, Courier, monospace;"><i>José de Alencar</i></span></div>
Anonymoushttp://www.blogger.com/profile/11593196735866212585noreply@blogger.com1tag:blogger.com,1999:blog-2614996039040117788.post-32904000637166150602012-11-17T14:36:00.003-08:002012-11-17T14:50:39.872-08:00JQuery Mobile, Plante Aqui vs Google Maps API<span style="font-family: Courier New, Courier, monospace;">Boa tarde caros "encodes" ...</span><br />
<span style="font-family: Courier New, Courier, monospace;">sábado quente em Londrina pra variar! A um bom tempo sem escrever, prova de certificação bem próxima e o tempo vai ficando um pouco escasso, chega de desculpas baratas "HAHA" e vamos lá (...)</span><br />
<span style="font-family: Courier New, Courier, monospace;">Post de hoje pretendo expor a vocês uma nova API que venho estudando e pude participar de um "Hackathon" com uma galera muito fera, que o intuito era apresentar essa API e suas funcionabilidades. Falando um pouco sobre a API, ela se chama Plante Aqui você pode encontrar mais sobre no <a href="http://www.facebook.com/planteaqui?ref=ts&fref=ts" target="_blank">Plante Aqui no Facebook</a> ou se preferir no site oficial <a href="http://www.planteaqui.org/" target="_blank">http://www.planteaqui.org/</a> lá você vai encontrar sobre a ideia da API e a proposta que a mesma está divulgando que é bastante interessante por sinal.</span><br />
<span style="font-family: Courier New, Courier, monospace;">Aqui vou apresentar algo bastante básico e utilizar o recurso de consultas que a API (Plante Aqui) me fornece.</span><br />
<span style="font-family: Courier New, Courier, monospace;">Após você ter dado uma lida nos links que repassei vamos explicar o nosso programa de exemplo:</span><br />
<span style="font-family: Courier New, Courier, monospace;"><br /></span>
<span style="font-family: Courier New, Courier, monospace;">1 - Desenvolver uma interface mobile com JQuery Mobile.</span><br />
<span style="font-family: Courier New, Courier, monospace;">2 - Repassar os dados consultados a API(Plante Aqui).</span><br />
<span style="font-family: Courier New, Courier, monospace;">3 - Com o retorno de sucesso da API(Plante Aqui) vamos utilizar a API(Google Maps) para mostrar os resultados em tela.</span><br />
<span style="font-family: Courier New, Courier, monospace;"><br /></span>
<span style="font-family: Courier New, Courier, monospace;">Considerando que você leu a ideia central do Plante Aqui a nossa interface cliente basicamente vai receber os dados de latitude e longitude informados pelo usuário que seria as coordenadas em que você quer saber se naquele ponto existe um local adequado para se plantar uma arvore se as coordenadas forem encontradas vamos repassar elas a nosso maps marcando o local.</span><br />
<span style="font-family: Courier New, Courier, monospace;">Chega de papo e vamos codar =)</span><br />
<span style="color: #333333; font-family: Courier New, Courier, monospace;"><span style="line-height: 17px;">Começamos a implementar a parte visual:</span></span><br />
<pre style="background-image: URL(https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhtDkiUO9nySrprZDIjEIEJoxRX3AuY42e5gAii42s0X5LltSQDuFgkK2KCenBuZDe5hzN8gyAvGkO6tfzvpnKnIt6mpyAT-eMdZKd9C5yv2-mFzkCRTQe3LrYOdZrEn3qzd5NfoNdynIUe/s320/codebg.gif); background: #f0f0f0; border: 1px dashed #CCCCCC; color: black; font-family: arial; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;"> <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Google Maps vs Plante Aqui</title>
<link rel="stylesheet" href="css/themes/default/jquery.mobile-1.2.0.css" />
<link rel="stylesheet" href="docs/_assets/css/jqm-docs.css" />
<script src="js/jquery.js"></script>
<script src="docs/_assets/js/jqm-docs.js"></script>
<script src="js/jquery.mobile-1.2.0.js"></script>
</head>
<script type="text/javascript">
</script>
<body>
<div class="ui-body ui-body-a">
<div data-role="fieldcontain">
<label for="latitude">Latitude:</label>
<input type="text" name="latitude" id="latitude" value="" />
</div>
<div data-role="fieldcontain">
<label for="longitude">Longitude:</label>
<input type="text" name="longitude" id="longitude" value="" />
</div>
<button type="button" data-theme="b" id="enviar" name="enviar" onclick="buscarEndereco();">Verificar Disponibilidade
</button>
</div>
<div id="map_canvas" style="width: 100%; height: 500px"></div>
</body>
</html>
</code></pre>
<span style="font-family: 'Courier New', Courier, monospace;">Como pode ver o código é bastante simples com </span><a href="http://jquerymobile.com/" style="font-family: 'Courier New', Courier, monospace;" target="_blank">JQuery Mobile</a><span style="font-family: 'Courier New', Courier, monospace;">.</span><br />
<span style="font-family: Courier New, Courier, monospace;">O próximo passo seria implementar o codigo que será responsável em "desenhar" o mapa.</span><br />
<span style="font-family: Courier New, Courier, monospace;">Não sei se você teve a oportunidade de trabalhar com alguma integração das API do google porém vai ver que é bastante simples de entender e aplicar nos seus programas as inúmeras funcionabilidades que a google apresenta.</span><br />
<span style="font-family: Courier New, Courier, monospace;">Sobre o google maps em questão você vai encontrar a documentação aqui: <a href="https://developers.google.com/maps/documentation/javascript/v2/introduction" target="_blank">https://developers.google.com/maps/documentation/javascript/v2/introduction</a> neste link tem os exemplos de códigos e parametros que você pode utilizar para enriquecer teu programa.</span><br />
<span style="font-family: 'Courier New', Courier, monospace;">Voltando a nosso exemplo implemente essa função.</span><br />
<pre style="background-image: URL(https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhtDkiUO9nySrprZDIjEIEJoxRX3AuY42e5gAii42s0X5LltSQDuFgkK2KCenBuZDe5hzN8gyAvGkO6tfzvpnKnIt6mpyAT-eMdZKd9C5yv2-mFzkCRTQe3LrYOdZrEn3qzd5NfoNdynIUe/s320/codebg.gif); background: #f0f0f0; border: 1px dashed #CCCCCC; color: black; font-family: arial; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;"> var map = null;
var geocoder = null;
function initialize() {
if (GBrowserIsCompatible()) {
map = new GMap2(document.getElementById("map_canvas"));
map.setCenter(new GLatLng(37.4419, -122.1419), 1);
map.setMapType(G_HYBRID_MAP);
map.setUIToDefault();
geocoder = new GClientGeocoder();
}
}
</code></pre>
<br />
<span style="font-family: Courier New, Courier, monospace;">Se você deu uma lida rápida no link que repassei sobre a API do Google Maps creio que ficou bastante fácil entender o meu código a seguir! "hehe" De modo geral eu instancio a classe GMap2() repassando para o construtor da classe o elemento HTML criado na minha pagina que irá receber o canvas do mapa gerado.</span><br />
<span style="font-family: Courier New, Courier, monospace;">O restante do código se trata de configurações propriamente falando do map</span><span style="font-family: arial; font-size: 12px; line-height: 20px;">a</span><span style="font-family: Courier New, Courier, monospace;"><span style="line-height: 20px;">. O método SetMapType(G_HYBRID_MAP); por exemplo defini o tipo de mapa que será apresentando ao inicializar o programa, no meu caso eu escolhi o "SATÉLITE".</span></span><br />
<span style="font-family: Courier New, Courier, monospace;"><span style="line-height: 20px;">O nosso próximo passo seria adicionar a função a seguir no onload da pagina:</span></span><br />
<pre style="background-image: URL(https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhtDkiUO9nySrprZDIjEIEJoxRX3AuY42e5gAii42s0X5LltSQDuFgkK2KCenBuZDe5hzN8gyAvGkO6tfzvpnKnIt6mpyAT-eMdZKd9C5yv2-mFzkCRTQe3LrYOdZrEn3qzd5NfoNdynIUe/s320/codebg.gif); background: #f0f0f0; border: 1px dashed #CCCCCC; color: black; font-family: arial; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;"> <body onload="initialize()" onunload="GUnload()"> </code></pre>
<span style="font-family: Courier New, Courier, monospace;">...e também não podemos esquecer de adicionar a referencia a API do google:</span><br />
<pre style="background-image: URL(https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhtDkiUO9nySrprZDIjEIEJoxRX3AuY42e5gAii42s0X5LltSQDuFgkK2KCenBuZDe5hzN8gyAvGkO6tfzvpnKnIt6mpyAT-eMdZKd9C5yv2-mFzkCRTQe3LrYOdZrEn3qzd5NfoNdynIUe/s320/codebg.gif); background: #f0f0f0; border: 1px dashed #CCCCCC; color: black; font-family: arial; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;"> <script src="http://maps.google.com/maps?file=api&amp;v=2&amp;key="SUA_CHAVE"
type="text/javascript"></script>
</code></pre>
<span style="font-family: Courier New, Courier, monospace;">Perceba que no parametro "KEY" você deverá colocar a sua KEY gerada pela google no momento que você marcou a utilização de alguma API com o teu usuário google é claro.</span><br />
<span style="font-family: Courier New, Courier, monospace;">Mais informações para obter a sua KEY:</span><br />
<span style="font-family: Courier New, Courier, monospace;"><a href="https://developers.google.com/maps/documentation/javascript/tutorial" target="_blank">https://developers.google.com/maps/documentation/javascript/tutorial</a></span><br />
<span style="font-family: Courier New, Courier, monospace;">Fazendo isso você já verá algum resultado (...)</span><br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiILtg5ViMFcmfgLnYq7U7SXxpwOzsUQ5jQg2aqR1ywJX91n3YMgsGqvDagQ9ii8vLyLkexGMqaN9ZGK3UKgfw5WI9NoPBGTYgSBHHXuAPbszSlm9po6ObeFblNoVjxyKFunMTviXHLV58/s1600/1.PNG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiILtg5ViMFcmfgLnYq7U7SXxpwOzsUQ5jQg2aqR1ywJX91n3YMgsGqvDagQ9ii8vLyLkexGMqaN9ZGK3UKgfw5WI9NoPBGTYgSBHHXuAPbszSlm9po6ObeFblNoVjxyKFunMTviXHLV58/s1600/1.PNG" height="226" width="400" /></a></div>
<div class="separator" style="clear: both; text-align: center;">
<br /></div>
<div class="separator" style="clear: both; text-align: left;">
<span style="font-family: Courier New, Courier, monospace;">Vamos agora para a nossa próxima implementação que seria a função de busca das coordenadas informadas.</span></div>
<div class="separator" style="clear: both; text-align: left;">
<span style="font-family: Courier New, Courier, monospace;">No evento onclick="" do button "Verificar Disponibilidade" vamos chamar a seguinte função:</span></div>
<pre style="background-image: URL(https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhtDkiUO9nySrprZDIjEIEJoxRX3AuY42e5gAii42s0X5LltSQDuFgkK2KCenBuZDe5hzN8gyAvGkO6tfzvpnKnIt6mpyAT-eMdZKd9C5yv2-mFzkCRTQe3LrYOdZrEn3qzd5NfoNdynIUe/s320/codebg.gif); background: #f0f0f0; border: 1px dashed #CCCCCC; color: black; font-family: arial; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;"> function buscarEndereco(button){
var iLatitude = $('#latitude').val();
var iLongitude = $('#longitude').val();
if(iLatitude != '' || iLongitude != ''){
$.getJSON('http://www.planteaqui.org/api/position?lat='+iLatitude+'&lon='+iLongitude+'',
function(data) {
// dados retornados do Plante Aqui
point = new GLatLng(data[0].positions.lat,data[0].positions.lon);
marker = new GMarker(point);
map.addOverlay(marker);
}
);
}else{
alert('Informe a Latitude e a Longitude para buscar!');
}
}
</code></pre>
<span style="font-family: Courier New, Courier, monospace;">Antes de explicarmos o nosso código vale ressaltar sobre a API Plante Aqui, pois se você a leu a documentação vai perceber que ela é baseada em REstFull desta forma utilizei a função <b>$.getJSON(url,function() { } );</b> </span><br />
<span style="font-family: Courier New, Courier, monospace;">veja que a requisição é assíncrona e no segundo parâmetro você deve criar a sua função que receberá o retorno que no nosso caso é um JSON, após o retorno instancio a classe </span><br />
<span style="font-family: Courier New, Courier, monospace;"><b>GLatLng(LATITUDE, LONGITUDE);</b> </span><br />
<span style="font-family: Courier New, Courier, monospace;">repassando as coordenadas encontradas pela API Plante Aqui o retorno da função será guardada em uma VAR que será também repassada a classe <b>GMarker();</b> que receberá as coordenadas retornando um ponto a ser marcado que por final será adicionado ao objeto principal do mapa. =)</span><br />
<span style="font-family: Courier New, Courier, monospace;">Tranquilo né?</span><br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgerLbrH9HT6MdhydhHdub4SocUKNV_UhKfjYfBjTD4wNOG9DGD9mNfvVnYEt41EnqBTHHCADXbDLjOWvWD61_yRD6gB_Pc4qlOgXmZERPwoQ-ra5QS-PllGNMI_hUNMXtqQf0FXPMpdto/s1600/2.PNG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgerLbrH9HT6MdhydhHdub4SocUKNV_UhKfjYfBjTD4wNOG9DGD9mNfvVnYEt41EnqBTHHCADXbDLjOWvWD61_yRD6gB_Pc4qlOgXmZERPwoQ-ra5QS-PllGNMI_hUNMXtqQf0FXPMpdto/s1600/2.PNG" height="225" width="400" /></a></div>
<span style="font-family: Courier New, Courier, monospace;">Pensando em ficar funcional para o usuário que estará fazendo a consulta não fico muito legal pois saber a latitude e longitude exata de um local é um pouquinho complicado "HAHA" porém este é o nosso primeiro exemplo utilizando API Plante Aqui, A ideia é evoluir e o próximo post que está praticamente pronto será implementado algumas alterações para corrigir isso. =)</span><br />
<span style="font-family: Courier New, Courier, monospace;">A nível acadêmico alcançamos o nosso objetivo que seria mostrar como consumir uma API em RestFull e também a integração com o maps do google.</span><br />
<span style="font-family: Courier New, Courier, monospace;">Fica o reforço da dica para você dar uma melhor olhada na API Plante Aqui veja que a documentação explica exatamente como "sugerir um local para se plantar" e outros métodos vale dizer também que a API está em constante alterações e novas melhorias vem ai.</span><br />
<span style="font-family: Courier New, Courier, monospace;">Ficamos por aqui, com o agradecimento em especifico ao pessoal do Plante Aqui que abriu a oportunidade e a iniciativa.</span><br />
<span style="font-family: Courier New, Courier, monospace;"><br /></span>
<span style="font-family: Courier New, Courier, monospace;"><a href="http://code.google.com/p/jr-encode/downloads/list" target="_blank">Download do projeto completo</a></span><br />
<span style="font-family: Courier New, Courier, monospace;">Até a próxima. :)</span><br />
<span style="font-family: Courier New, Courier, monospace;"><br /></span>Anonymoushttp://www.blogger.com/profile/11593196735866212585noreply@blogger.com0tag:blogger.com,1999:blog-2614996039040117788.post-35794569729900487162012-10-26T19:39:00.003-07:002012-10-28T18:47:17.722-07:00MVC Helpers vs ExtJS 3.4 Sencha<span style="color: #333333;"><span style="font-family: Courier New, Courier, monospace; line-height: 20px;">Eai Caros "Encodes" (...)</span></span><br />
<span style="color: #333333;"><span style="font-family: Courier New, Courier, monospace; line-height: 20px;">Sexta-feira de muita chuva em Londrina é totalmente inspirador para um Post novo hehe, hoje vo tenta mostra a vocês a ideia de utilização de helpers no MVC 3.</span></span><br />
<span style="color: #333333; font-family: Courier New, Courier, monospace;"><span style="line-height: 20px;">Iniciando podemos começar falando um pouco do "RAZOR". Esse é o novo motor de visões de paginas adotado pela microsoft, esse novo "cara" segue o mesmo modelo de arquivos</span><span style="line-height: 20px;"> (.ASPX/.ASCX/.MASTER) que já estamos acostumados no WEB FORM.</span></span><br />
<span style="font-family: Courier New, Courier, monospace;"><span style="color: #333333;"><span style="line-height: 20px;">Para uma mais refinada explicação vou utilizar uma definição feita em um ótimo blog que costumo visitar. (<a href="http://weblogs.asp.net/scottgu/" target="_blank">ScottGu's Blog</a>) </span></span></span><br />
<blockquote class="tr_bq">
<span style="font-family: Courier New, Courier, monospace;"><b>Compacto, Expressivo, e Fluente</b>: o
Razor minimiza o número de caracteres e teclas digitadas necessárias em um
arquivo, e permite um fluxo de trabalho de codificação rápido e fluente. Ao
contrário das sintaxes de outros modelos, você não precisa interromper sua
codificação para explicitamente indicar blocos do servidor dentro do código
HTML. O analisador é inteligente o suficiente para inferir isso a partir do seu
código. Isto permite uma sintaxe muito compacta e expressiva, que é limpa,
rápida e divertida para digitar.</span></blockquote>
<blockquote class="tr_bq">
<span style="font-family: Courier New, Courier, monospace;"><b>Fácil para Aprender:</b> o
Razor é fácil de aprender e te permite ser produtivo rapidamente com um mínimo
de conceitos. Você usa todas as suas habilidades existentes de linguagens de
programação e HTML.</span></blockquote>
<blockquote class="tr_bq">
<span style="font-family: Courier New, Courier, monospace;"><b>Não é uma nova linguagem:</b> Nós
conscientemente optamos por não criar uma nova linguagem imperativa com o
Razor. Em vez disso, queríamos permitir que os desenvolvedores utilizassem seus
atuais conhecimentos de linguagens de programação C#/VB (ou outras) com o
Razor, entregando uma sintaxe de marcação para modelagem que permite um fluxo
de trabalho de construção de código HTML bem legal com a sua linguagem de
preferência.</span></blockquote>
<blockquote class="tr_bq">
<span style="font-family: Courier New, Courier, monospace;"><b>Funciona com qualquer Editor de Texto:</b> o Razor não necessita de uma ferramenta específica e te
permite ser produtivo em qualquer editor de texto velho e simples (notepad
funciona muito bem).</span></blockquote>
<blockquote class="tr_bq">
<span style="font-family: Courier New, Courier, monospace;"><b>Tem ótimo suporte à Intellisense:</b> o
Razor foi projetado para não necessitar de uma ferramenta específica ou editor
de código, mas ainda assim ele terá um excelente suporte para intellisense
dentro do Visual Studio.</span></blockquote>
<blockquote class="tr_bq">
<span style="font-family: Courier New, Courier, monospace;"><b>Unidade Testável:</b> A
nova implementação deste motor de visões suportará a capacidade de testar
visões de maneira unitária (sem a necessidade de um controlador ou de um
servidor web, e pode ser hospedado em qualquer projeto de teste unitário - não
há necessidade de um app-domain [domínio de aplicação] especial).</span></blockquote>
<span style="font-family: Courier New, Courier, monospace;">
Após entendermos algumas definições do Razor podemos partir para uma outra ideia que seria de criar o nosso próprio ajudante para criação de layouts.</span><br />
<span style="font-family: Courier New, Courier, monospace;">O que vou mostrar a seguir seria basicamente utilizar o recurso das chamadas Razor em uma pagina HTML seguido de alguns parâmetros dinâmicos e gerando através do ExtJs (O que é ExtJs?) É um framework JavaScript de ricos recursos para desenvolvimento de layouts, ficando extremamente conhecido no Brasil, sendo agora de propriedade da SENCHA (<a href="http://www.sencha.com/" target="_blank">http://www.sencha.com/</a>) ele vem sendo atualizado constantemente a comunidade é ativa e nem preciso elogiar também a documentação !</span><br />
<span style="font-family: Courier New, Courier, monospace;">Se você não conhece e tiver algum interesse em estudar mais ...</span><br />
<span style="font-family: Courier New, Courier, monospace;"><br />
<a href="http://docs.sencha.com/ext-js/3-4/#!/api" target="_blank">Docs - Versão 3.4 utilizada neste Post</a></span><br />
<a href="http://docs.sencha.com/ext-js/4-1/" target="_blank"><span style="font-family: Courier New, Courier, monospace;">Docs - Versão 4.1 (ATUAL)</span></a><br />
<span style="font-family: Courier New, Courier, monospace;"><br />
Continuando (...) o que o ExtJs tem haver com o Razor? hehe na verdade como disse no começo vou agregar esse dois recursos para um ganho significativo na produtividade para a criação de uma Grid. Se você tem uma noção mais voltada para arquitetura pode estar pensando "Abstrair o que já está abstraído?" realmente um termo que me perguntei varias vezes até começar a trabalhar em algo do tipo, porém a PRODUTIVIDADE vs PADRONIZAÇÃO falou mais alto. Na verdade isso seria papo para uma longa discução mas ao final do POST seja você capaz de tirar suas próprias conclusões! Chega de "BLA BLA" e para manter o costume sirva-se de um café e vamos codar ...</span><br />
<span style="font-family: Courier New, Courier, monospace;">
Primeiramente, criei um projeto PADRÃO utilizando um template já pronto do VS2010 e também uma pasta "Helpers".</span><br />
<span style="font-family: Courier New, Courier, monospace;"><br />
</span><br />
<div class="separator" style="clear: both; text-align: center;">
<span style="font-family: Courier New, Courier, monospace; margin-left: 1em; margin-right: 1em;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjpsI1Z4EZk3Lc71akFt84ZCPz4O3ULrd-hOoJL99waHSmJ8JPxS3D7QG_QoXEjGDFbgTjHBOuvY9SRP1U7fUQlAk7nr9s70cG5B6xyoCnhpTbXlo_dq5TJgkWBirdnK4hcSDT6PVlGjK8/s1600/helper_1.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjpsI1Z4EZk3Lc71akFt84ZCPz4O3ULrd-hOoJL99waHSmJ8JPxS3D7QG_QoXEjGDFbgTjHBOuvY9SRP1U7fUQlAk7nr9s70cG5B6xyoCnhpTbXlo_dq5TJgkWBirdnK4hcSDT6PVlGjK8/s1600/helper_1.png" /></a></span></div>
<span style="font-family: Courier New, Courier, monospace;">
Na pasta Helpers adiciona um classe chamada "HelperGrid.cs" essa classe irá receber e processar as chamadas vinda da pagina feita pelo Razor.</span><br />
<span style="font-family: Courier New, Courier, monospace;">Vamos implementar a classe HelperGrid.cs, resumidamente nela eu implementei uma logica simples, aonde coloquei toda a ideia de parâmetros que uma Grid poderia receber dinamicamente sendo mais simplificado ainda, utilizei da minha imaginação e adicionei alguns métodos aonde enxerguei que a minha Grid poderia ser dinâmica. Segue o código:</span><br />
<pre style="background-color: #f0f0f0; border: 1px dashed rgb(204, 204, 204); color: black; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><span style="font-family: Courier New, Courier, monospace;"><code style="color: black; word-wrap: normal;"> namespace MvcApplication1.Helpers
{
public static class HelperGrid
{
public static ExtGrid ExtGrid(this HtmlHelper helper, string id)
{
return new ExtGrid(helper, id);
}
}
public class ExtGrid
{
private HtmlHelper helper;
private string id;
private string url;
private string pkTabela;
private string tituloGrid;
private List<ColunasGrid> listaColunasGrid = new List<ColunasGrid>();
private string elementoRoot;
private int pageSizeGrid;
public ExtGrid(HtmlHelper helper, string id)
{
this.helper = helper;
this.id = id;
}
/// <summary>
///
/// </summary>
/// <param name="url"></param>
/// <param name="pkTabela"></param>
/// <returns></returns>
public ExtGrid SetDataStore(string url, string pkTabela)
{
this.url = url;
this.pkTabela = pkTabela;
return this;
}
/// <summary>
///
/// </summary>
/// <param name="root"></param>
/// <returns></returns>
public ExtGrid SetElementRoot(string root)
{
this.elementoRoot = root;
return this;
}
/// <summary>
///
/// </summary>
/// <param name="pageSize"></param>
/// <returns></returns>
public ExtGrid SetPageSize(int pageSize = 20)
{
this.pageSizeGrid = pageSize;
return this;
}
/// <summary>
///
/// </summary>
/// <param name="Name"></param>
/// <param name="Header"></param>
/// <param name="Tamanho"></param>
/// <param name="Visivel"></param>
/// <param name="Xtype"></param>
/// <returns></returns>
public ExtGrid Columns(string Name, string Header, int Tamanho, bool Visivel = true, string Xtype = null)
{
ColunasGrid colunasGrid = new ColunasGrid(Name, Header, Tamanho, Visivel, Xtype);
this.listaColunasGrid.Add(colunasGrid);
return this;
}
/// <summary>
///
/// </summary>
/// <param name="titulo"></param>
/// <returns></returns>
public ExtGrid SetTitulo(string titulo = null)
{
this.tituloGrid = titulo;
return this;
}
/// <summary>
///
/// </summary>
public void Render()
{
GridXml gridXmlAtributos = new GridXml()
{
url = this.url,
pkTabela = this.pkTabela,
tituloGrid = this.tituloGrid,
elementoRoot = this.elementoRoot,
pageSize = this.pageSizeGrid
};
foreach (ColunasGrid column in this.listaColunasGrid)
{
GridColumnXml layoutColumnGrid = new GridColumnXml()
{
name = column.name,
header = column.header,
tamanho = column.tamanho,
visible = column.visivel,
xtype = column.xtype
};
gridXmlAtributos.columns.Add(layoutColumnGrid);
}
string xml;
try
{
xml = HelperUtil.Serialize<GridXml>(gridXmlAtributos);
}
catch (Exception ex)
{
throw new Exception("Erro ao serializar o XML" + ex.Message);
}
helper.ViewContext.Writer.Write("<div id=\"" + this.id + "\"");
helper.ViewContext.Writer.Write(" data-isGrid=\"true\"");
helper.ViewContext.Writer.WriteLine(">");
helper.ViewContext.Writer.WriteLine("<script type=\"text/xml\" id=\"" + this.id + "grid_xml\">");
helper.ViewContext.Writer.WriteLine(xml);
helper.ViewContext.Writer.WriteLine("</script>");
helper.ViewContext.Writer.WriteLine("</div>");
}
}
public class ColunasGrid
{
public string name { get; set; }
public string header { get; set; }
public int tamanho { get; set; }
public bool visivel { get; set; }
public string xtype { get; set; }
public ColunasGrid(string name, string header, int tamanho, bool visivel, string xtype)
{
this.name = name;
this.header = header;
this.tamanho = tamanho;
this.visivel = visivel;
this.xtype = xtype;
}
}
/// <summary>
///
/// </summary>
[XmlType(TypeName = "gridLayout")]
public class GridXml
{
public string url;
public string pkTabela;
public string tituloGrid;
public string elementoRoot;
public int pageSize;
public string modeFilter;
public int charFiltro;
public List<GridColumnXml> columns;
public GridXml()
{
this.columns = new List<GridColumnXml>();
}
public readonly static XmlSerializer Serializer = new XmlSerializer(typeof(GridColumnXml));
}
/// <summary>
///
/// </summary>
[XmlType(TypeName = "column")]
public class GridColumnXml
{
[XmlAttribute]
public string name;
[XmlAttribute]
public string header;
[XmlAttribute]
public int tamanho;
[XmlAttribute]
public bool visible;
[XmlAttribute]
public string xtype;
}
}
</code>
</span></pre>
<span style="font-family: Courier New, Courier, monospace;"><br />
Vale colocar algumas observações na parte do código:</span><br />
<pre style="background-color: #f0f0f0; background-position: initial initial; background-repeat: initial initial; border: 1px dashed rgb(204, 204, 204); color: black; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;"><span style="font-family: Courier New, Courier, monospace;"> helper.ViewContext.Writer.Write("<div id=\"" + this.id + "\"");
helper.ViewContext.Writer.Write(" data-isGrid=\"true\"");
helper.ViewContext.Writer.WriteLine(">");
helper.ViewContext.Writer.WriteLine("<script type=\"text/xml\" id=\"" + this.id + "grid_xml\">");
helper.ViewContext.Writer.WriteLine(xml);
helper.ViewContext.Writer.WriteLine("</script>");
helper.ViewContext.Writer.WriteLine("</div>");
</span></code></pre>
<span style="font-family: Courier New, Courier, monospace;"><br />
Esse é o trecho que podemos dizer que é mais importante nessa logica, pois através do ViewContext que é disponibilizado pelo "helper" que seria basicamente todo conteúdo da pagina colocamos um pacote XML serializado que como você pode perceber no restante do código anterior é a nossa hierarquia de classes. Porque um pacote XML contido dentro de um <script> </script> ? Isso é devido a renderização da pagina pois se escrevermos simplesmente o texto do XML serializado o browser irá tentar "fazer alguma coisa" com a string repassada prejudicando o nosso objetivo que como vamos ver adiante é capturar esse pacote via JavaScript (...)</span><br />
<span style="font-family: Courier New, Courier, monospace;">AHH, já ia esquecendo implemente uma outra classe chamada "HelperUtil.cs" nela coloquei o codigo responsável por serializar qualquer objeto repassado <T>, segue o codigo:</span><br />
<pre style="background-color: #f0f0f0; background-position: initial initial; background-repeat: initial initial; border: 1px dashed rgb(204, 204, 204); color: black; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;"><span style="font-family: Courier New, Courier, monospace;"> public static class HelperUtil
{
public static string Serialize<T>(T value)
{
if (value == null)
{
return null;
}
XmlSerializer serializer = new XmlSerializer(typeof(T));
System.Xml.XmlWriterSettings settings = new System.Xml.XmlWriterSettings();
settings.Encoding = new System.Text.UnicodeEncoding(false, false);
settings.Indent = false;
settings.OmitXmlDeclaration = false;
using (StringWriter textWriter = new StringWriter())
{
using (System.Xml.XmlWriter xmlWriter = System.Xml.XmlWriter.Create(textWriter, settings))
{
serializer.Serialize(xmlWriter, value);
}
return textWriter.ToString();
}
}
}
</span></code></pre>
<span style="font-family: Courier New, Courier, monospace;"><br />
Ao chamar o metodo Render(); do nosso helper o pacote XML será escrito na pagina que foi feita a chamada, nesta VIEW o código é bastante reduzido pois ai que está a "graça" de tudo hehe nela será contida apenas os parâmetros requisitados para compor a nossa Grid e como estamos utilizando MVC a Url.Content do nosso controlador aonde a busca dos dados será feita.</span><br />
<span style="font-family: Courier New, Courier, monospace;"><br />
Index.cshtml</span><br />
<pre style="background-color: #f0f0f0; border: 1px dashed rgb(204, 204, 204); height: auto; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="word-wrap: normal;"><span style="font-family: Courier New, Courier, monospace;"><span style="line-height: 20px;"> @using MvcApplication1.Helpers
@{
Html.ExtGrid("DIV_GRID_CONSULTA_PESSOA").SetDataStore(@Url.Content("~/Teste/GetAll"), "</span><span style="line-height: 20px;">idPessoa</span><span style="line-height: 20px;">"). </span><span style="line-height: 20px;">
</span><span style="line-height: 20px;"> SetTitulo("Consultar Pessoas").
SetElementRoot("Pessoa").
SetPageSize(20).
Columns("idPessoa", "Pessoa", 50, true, "Int").
Columns("nmPessoa", "Nome", 820, true, "String").
Render();
}
</span></span></code></pre>
<span style="font-family: Courier New, Courier, monospace;"><br />
ATENÇÃO: não se esqueça de adicionar o <b>@using</b> do seu helper pois é extremamente valido, sem ele você não terá acesso aos métodos disponibilizados no helper.</span><br />
<span style="font-family: Courier New, Courier, monospace;">Teria uma outra maneira de implementar essa referencia diretamente no Web.config mas optei por fazer na VIEW para uma melhor visualização conceitual e também expressar a importância pois sem a referencia você não terá acesso a sua classe ajudante.</span><br />
<span style="font-family: Courier New, Courier, monospace;"><br /></span>
<span style="font-family: Courier New, Courier, monospace;">Seguindo a nossa chamada que foi feita a partir da nossa VIEW o pacote XML foi gerado como retorno na pagina, agora iremos montar no JavaScript como iria ficar a nossa Grid. Antes de "codarmos" o JS teremos que adicionar em nosso projeto a pasta contendo o Source da estrutura do ExtJs, enfatizando que disse no começo utilizei a versão 3.4, aproveitando também criamos uma outra pasta chamada </span><br />
<span style="font-family: Courier New, Courier, monospace;">"ext-js-helpers" para colocarmos o nosso JS que será responsável pela criação da Grid.</span><br />
<span style="font-family: Courier New, Courier, monospace;">Agora o escopo do nosso projeto ficaria mais ou menos assim (...)</span><br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj6UZn_UrB2cc64QbCJpGDlLThCs5GbW1bTDnQDtubeICBFizv1QZPt_3F_U_EVB1HSA4kh-tJ2IEORHtOzzAOX1wIjGgVrdxGIw-Y4xqKMOUMWyQwBgtOxwV_Rqlcuz6_J4wXPhzBzlD0/s1600/helper_2.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><span style="font-family: Courier New, Courier, monospace;"><img border="0" height="400" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj6UZn_UrB2cc64QbCJpGDlLThCs5GbW1bTDnQDtubeICBFizv1QZPt_3F_U_EVB1HSA4kh-tJ2IEORHtOzzAOX1wIjGgVrdxGIw-Y4xqKMOUMWyQwBgtOxwV_Rqlcuz6_J4wXPhzBzlD0/s1600/helper_2.png" width="210" /></span></a></div>
<span style="font-family: Courier New, Courier, monospace;"><br /></span>
<span style="font-family: Courier New, Courier, monospace;">Vamos implementar o nosso JS ...</span><br />
<pre style="background-color: #f0f0f0; background-position: initial initial; background-repeat: initial initial; border: 1px dashed rgb(204, 204, 204); color: black; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;"><span style="font-family: Courier New, Courier, monospace;"> jQuery(document).ready(function () {
var grids = jQuery("div[data-isGrid=\'true']");
grids.each(function (i, obj) {
var grid = new Grid(i, obj);
});
});
function Grid(index, rootDiv) {
var $this = this;
var id = $(rootDiv).attr('id');
var id_grid_panel = 'GRID_'+id;
// Vamos pegar o nosso XML...
var atributosGrid = $($("#" + id + "grid_xml").html());
// aqui vamos pegar os atributos do nosso xml
var url = $(atributosGrid).find('url').text();
var pkTabela = $(atributosGrid).find('pkTabela').text();
var tituloGrid = $(atributosGrid).find('tituloGrid').text();
var root = $(atributosGrid).find('elementoRoot').text();
var pageSize = parseInt($(atributosGrid).find('pageSize').text());
var columnsModel = [];
var columnsField = [];
$(atributosGrid).find('columns column').each(function (i, obj) {
columnsModel.push({
id: $(obj).attr("name"),
header: $(obj).attr("header"),
dataIndex: $(obj).attr("name"),
width: parseInt($(obj).attr("tamanho")),
sortable: true
});
columnsField.push($(obj).attr("name"));
});
// criamos um JsonStore...
var StoreGrid = new Ext.data.JsonStore({
url: url,
root: root,
totalProperty: 'total',
idProperty: pkTabela,
fields: columnsField
});
StoreGrid.load({ params: { start: 0, limit: pageSize } });
var grid = new Ext.grid.GridPanel({
id: id_grid_panel,
width: 900,
height: 395,
title: tituloGrid,
store: StoreGrid,
viewConfig: { emptyText: 'Nenhum registro encontrado', deferEmptyText: false },
stripeRows: true,
// grid columns
columns: columnsModel,
bbar: new Ext.PagingToolbar({
pageSize: pageSize,
store: StoreGrid,
displayInfo: true,
displayMsg: 'Exibindo Tópicos {0} - {1} of {2}',
emptyMsg: "Nenhum tópico para mostrar"
})
});
grid.render(id);
}
</span></code></pre>
<span style="font-family: Courier New, Courier, monospace;"><br /></span>
<span style="font-family: Courier New, Courier, monospace;">Veja que não tem segredo !</span><br />
<span style="font-family: Courier New, Courier, monospace;">O código é basicamente implementado a partir do ExtJs para gerar a instancia do objeto Ext.grid.GridPanel e as propriedades vindas do pacote XML sendo capturado utilizando a bilbioteca do JQuery e abusando do comando Push() para montar as propriedades de Object esperado pelo ExtJs dinamicamente.</span><br />
<span style="font-family: Courier New, Courier, monospace;">Após a correta implmentação não vamos esquecer de adicionar os scripts a nossa pagina ...</span><br />
<span style="font-family: Courier New, Courier, monospace;"><br /></span>
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj8zl5a6l_zfkqLMZohmPFG53jpWjSIUGFyFhLBOA_-xo7Vhm0gxosumuvRL6qxtSUK3JuWRuz58kMxkvfGCwUfnVFs59YMjg09kf_SiBc2cZvnWK8wf4QAoXuxHv20aXFDMCgJv75LUss/s1600/helper_4.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><span style="font-family: Courier New, Courier, monospace;"><img border="0" height="57" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj8zl5a6l_zfkqLMZohmPFG53jpWjSIUGFyFhLBOA_-xo7Vhm0gxosumuvRL6qxtSUK3JuWRuz58kMxkvfGCwUfnVFs59YMjg09kf_SiBc2cZvnWK8wf4QAoXuxHv20aXFDMCgJv75LUss/s1600/helper_4.png" width="400" /></span></a></div>
<span style="font-family: Courier New, Courier, monospace;"><br /></span>
<span style="font-family: Courier New, Courier, monospace;">Com isso feito o resultado da nossa Grid seria mais ou menos isso !</span><br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj3x15_V7XJHgzSYyzw7I2c5q7VcCRSuIKkrkvyGPBbGgIbT4N5-zQZ6McwueIsNz96ZECJ6u6CfqsMW8ekGN4As9GusK9-FW-q6FfUADO9j0OmqadH471k54moekQ0zJIkingFTk71__I/s1600/helper_3.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><span style="font-family: Courier New, Courier, monospace;"><img border="0" height="182" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj3x15_V7XJHgzSYyzw7I2c5q7VcCRSuIKkrkvyGPBbGgIbT4N5-zQZ6McwueIsNz96ZECJ6u6CfqsMW8ekGN4As9GusK9-FW-q6FfUADO9j0OmqadH471k54moekQ0zJIkingFTk71__I/s1600/helper_3.png" width="400" /></span></a></div>
<span style="font-family: Courier New, Courier, monospace;"><br /></span>
<span style="font-family: Courier New, Courier, monospace;">Os dados gerados não são dados vindo de uma base "quente" e sim dados aleatórios (de um Model) serializados no método que informamos no @Url.Content.</span><br />
<span style="font-family: Courier New, Courier, monospace;">Perceba a requisição feita através do firebug no Firefox</span><br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg6tTCZ-4MObhFrWrtEMAPdvQUtC8tLPoOMW1KbYL_Byv8TFyIxmWZrQ2Cpf6xCmtxwOq1NEbrYSD_GnPvvMErTul5CNeCN8VugmrB_pALctYtR51NWN8CnH_VECvkvrdyBpMhafCvpm5g/s1600/helper_5.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><span style="font-family: Courier New, Courier, monospace;"><img border="0" height="91" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg6tTCZ-4MObhFrWrtEMAPdvQUtC8tLPoOMW1KbYL_Byv8TFyIxmWZrQ2Cpf6xCmtxwOq1NEbrYSD_GnPvvMErTul5CNeCN8VugmrB_pALctYtR51NWN8CnH_VECvkvrdyBpMhafCvpm5g/s1600/helper_5.png" width="400" /></span></a></div>
<div class="separator" style="clear: both; text-align: center;">
<span style="font-family: Courier New, Courier, monospace;"><br /></span></div>
<div class="separator" style="clear: both; text-align: left;">
<span style="font-family: Courier New, Courier, monospace;">Algo bastante importante para chamarmos atenção seria os metodos <b>SetElementRoot()</b> passado na VIEW que corresponde ao elemento PAI do JSON de retorno e também é claro os campos que como pode perceber o objeto que utilizei tinha muito mais propriedades do que mostrei na Grid porém exibi apenas o campo idPessoa e nmPessoa do mesmo, a ideia é exatamente essa deixar intuitivo para o desenvolvedor que string NAME repassada ao Helper corresponde ao nome da propriedade do objeto serializado.</span></div>
<div class="separator" style="clear: both; text-align: left;">
<span style="font-family: Courier New, Courier, monospace;"><br /></span></div>
<div class="separator" style="clear: both; text-align: left;">
<span style="font-family: Courier New, Courier, monospace;">É isso galera, espero que isso tenha sido útil e aqueles que lerem absorvam a ideia que quis repassar dessa junção de Helper e ExtJs. </span></div>
<div class="separator" style="clear: both; text-align: left;">
<span style="font-family: Courier New, Courier, monospace;">OBS: vale ressaltar novamente a quantidade de código na VIEW para a criação do mesmo, deixando seu projeto mais limpo e padronizado.</span></div>
<div class="separator" style="clear: both; text-align: left;">
<span style="font-family: Courier New, Courier, monospace;"><br /></span></div>
<div class="separator" style="clear: both; text-align: left;">
<span style="font-family: Courier New, Courier, monospace;">Abraço. =))</span></div>
<blockquote class="tr_bq">
<span style="font-family: Courier New, Courier, monospace;"><b><i>Assim que tenho visto que não há coisa melhor do que alegrar-se o homem nas suas obras, porque essa é a sua porção; pois quem o fará voltar para ver o que será depois dele?</i></b></span></blockquote>
<blockquote class="tr_bq">
<b><i>Eclesiastes 3:22 </i></b></blockquote>
<div class="MsoNoSpacing">
<o:p></o:p></div>
Anonymoushttp://www.blogger.com/profile/11593196735866212585noreply@blogger.com0tag:blogger.com,1999:blog-2614996039040117788.post-86415990298598578242012-10-18T16:04:00.002-07:002012-10-19T04:42:10.036-07:00ASP.NET MVC AreasEai Caros "Encodes" (...)<br />
Estava a pensar nesses dias sobre um novo assunto para compartilhar com vocês e veio a mente um problema que tive algum tempo atrás em uma arquitetura web que estou trabalhando e resolvi compartilhar pois fiz varias pesquisas achei bons tutorias sobre o assunto porém a maioria deles em inglês, não é algo muito complicado porém se você nunca necessitou desse tipo de arquitetura e está disposto a implementar algo parecido vai perceber que fica um pouco chato no começo e muito simples e organizado de se trabalhar no passar do tempo do projeto.<br />
Falando do "problema" necessariamente, quando você está trabalhando em um padrão de projeto em dotnet mais especificamente MVC 3 que é o meu caso, você possui um padrão que o próprio visual studio cria para você ... seria mais ou menos assim:<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgn_C78ytGCXzJgQCuFedMGjzamE8C66T0thxpgC-j8WouS0ZOzlZUmM2NO5-ST3rnE9RpUPDUxafLDmap9nwl-d2QR3PhcZtKquNYCRHQe2zcP_GG8u-IBZejYKvDHa3C2Ctq7kBSGTOs/s1600/mvc_padrao.PNG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="345" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgn_C78ytGCXzJgQCuFedMGjzamE8C66T0thxpgC-j8WouS0ZOzlZUmM2NO5-ST3rnE9RpUPDUxafLDmap9nwl-d2QR3PhcZtKquNYCRHQe2zcP_GG8u-IBZejYKvDHa3C2Ctq7kBSGTOs/s400/mvc_padrao.PNG" width="400" /></a></div>
(OBS: apenas um parentes como você pode ver eu estou utilizando a versão 2012 do VS e apenas para nível de aprendizado e percepção de mudanças criei um projeto MVC4 mas para o assunto que estamos abordando não vai mudar nada praticamente na implementação)<br />
Voltando (...)<br />
<br />
Como pode ver existe o padrão de pastas CONTROLLERS, MODELS, VIEWS e o Global.asax este por sua vez é de extrema importância num projeto MVC pois ele é responsável pela manipulação de eventos e do ciclo de vida da aplicação. Basicamente ele contém uma tabela de rotas que é criada ao iniciar o aplicativo, mais detalhes sobre você pode dar uma lida no site oficial:<br />
<a href="http://www.asp.net/mvc/tutorials/older-versions/controllers-and-routing/asp-net-mvc-routing-overview-cs" target="_blank">http://www.asp.net/mvc/tutorials/older-versions/controllers-and-routing/asp-net-mvc-routing-overview-cs</a><br />
até ai estava tudo certo até que comecei a perceber que no projeto em que estou locado iria ter um problema de organização dessas pastas pois não iria ter apenas um conceito de regra dentro da hierarquia do projeto, deixando isso mais claro simulei apenas para nível conceitual um diagrama demonstrando esse possível ambiente:<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhAfzDbAhNQRYuShvBZSeDq4cp_chRM4_MWUE-A8GACsd0-KDBmHGsg_-VmNE4Yi_CstCWbfdwvg4KAUIHZT7Bdj5yuTNLPexOWu1qbxrbZ0M6mhZk0UcThuAauYyxRQ14pcrymqziTFO0/s1600/cenario.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="195" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhAfzDbAhNQRYuShvBZSeDq4cp_chRM4_MWUE-A8GACsd0-KDBmHGsg_-VmNE4Yi_CstCWbfdwvg4KAUIHZT7Bdj5yuTNLPexOWu1qbxrbZ0M6mhZk0UcThuAauYyxRQ14pcrymqziTFO0/s400/cenario.png" width="400" /></a></div>
Seria mais ou menos essa a ideia, como você pode ver tenho um site principal aonde o acesso seria publico sendo mais detalhista seria acessado por qualquer usuário sem nenhuma autenticação, porém os outros módulos seria de acesso especifico apenas para usuários credenciados e também devemos considerar que seria desenvolvido por uma equipe diferente. Foi nessa ideia que partir a pesquisar e verifiquei que o dotnet tem algo chamado de AREA. É dessa forma que ele representa os subdomínios da sua aplicação, com isso você poderia tranquilamente simular esse ambiente que colocamos a seguir tendo nele uma arquitetura de pastas na mesma visão do MVC porém dividido por áreas ficando assim muito mais organizado e limpo o desenvolvimento (...)<br />
Pra você que curti uma vídeo aula:<br />
<a href="http://www.asp.net/mvc/videos/mvc-2/how-do-i/aspnet-mvc-2-areas" target="_blank">http://www.asp.net/mvc/videos/mvc-2/how-do-i/aspnet-mvc-2-areas</a><br />
<br />
Chega de "historinha" hehe, para não perder o costume, sirva-se de um belo café e vamos codar, irei mostras as alterações que implementei com base nesse diagrama e também a tela principal com alguns ActionLink fazendo o roteamento para as outras áreas.<br />
Inicialmente esta seria a arquitetura já criada:<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgnr_1t2KoT3c7hPgMvDkemy-rdWDASrYHxwvGmXYnv0Cl0uSLcas_ZiNNjGjAkxbxcAZ36jsnMBdIg3MjG3DaroLMG0EL8q-GD8n49jxZawujv8PAGITR0mxQlIH-apbL_k8BrWwb68Rw/s1600/menu.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="400" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgnr_1t2KoT3c7hPgMvDkemy-rdWDASrYHxwvGmXYnv0Cl0uSLcas_ZiNNjGjAkxbxcAZ36jsnMBdIg3MjG3DaroLMG0EL8q-GD8n49jxZawujv8PAGITR0mxQlIH-apbL_k8BrWwb68Rw/s400/menu.png" width="211" /></a></div>
<br />
Perceba que o visual studio já criou pra você classes de "Registros" separadamente. Isso quer dizer que quando o Global.asax for registrar a aplicação verá que necessita também de registrar as áreas separadamente (...)<br />
Global.asax:<br />
<br />
<pre style="background-image: URL(https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhtDkiUO9nySrprZDIjEIEJoxRX3AuY42e5gAii42s0X5LltSQDuFgkK2KCenBuZDe5hzN8gyAvGkO6tfzvpnKnIt6mpyAT-eMdZKd9C5yv2-mFzkCRTQe3LrYOdZrEn3qzd5NfoNdynIUe/s320/codebg.gif); background: #f0f0f0; border: 1px dashed #CCCCCC; color: black; font-family: arial; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;"> // Note: For instructions on enabling IIS6 or IIS7 classic mode,
// visit http://go.microsoft.com/?LinkId=9394801
public class MvcApplication : System.Web.HttpApplication
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.IgnoreRoute("{*favicon}", new { favicon = @"(.*/)?favicon.ico(/.*)?" });
}
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
}
}
</code></pre>
<br />
<div id="noIframeDiv218aa0ac-d1f2-449d-a05e-9e334452f33d" style="display: block; margin: 0px;">
<pre></pre>
</div>
As classes "PosVendaAreaRegistration.cs", "LojaAreaRegistration.cs", "FinanceiroAreaRegistration.cs" foram criadas automaticamente pelo VS quando criei a AREA.<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj3-x7xjvkCQhA7UTITlz5JYApYNVM52i7R4-9ux9qYMI0EpY_v3_v2iD2XvFdXsa6YY0EB1MvAvmsybT6cjA_vrH6J6iQUKvVTSfeXp5yLnqv1T_zYhyphenhyphenp0S_-93kVjtJ0J8Srny1RCOXQ/s1600/add-area.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="167" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj3-x7xjvkCQhA7UTITlz5JYApYNVM52i7R4-9ux9qYMI0EpY_v3_v2iD2XvFdXsa6YY0EB1MvAvmsybT6cjA_vrH6J6iQUKvVTSfeXp5yLnqv1T_zYhyphenhyphenp0S_-93kVjtJ0J8Srny1RCOXQ/s320/add-area.png" width="320" /></a></div>
<br />
Apenas na classe <b>"PrincipalAreaRegistration.cs"</b> fiz uma pequena alteração dizendo quem seria a pagina "ROOT" do projeto basicamente seria a pagina que será chamada inicialmente ao abrir a aplicação.
<br />
<br />
<pre style="background-image: URL(https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhtDkiUO9nySrprZDIjEIEJoxRX3AuY42e5gAii42s0X5LltSQDuFgkK2KCenBuZDe5hzN8gyAvGkO6tfzvpnKnIt6mpyAT-eMdZKd9C5yv2-mFzkCRTQe3LrYOdZrEn3qzd5NfoNdynIUe/s320/codebg.gif); background: #f0f0f0; border: 1px dashed #CCCCCC; color: black; font-family: arial; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;"> public class PrincipalAreaRegistration : AreaRegistration
{
public override string AreaName
{
get
{
return "Principal";
}
}
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute("Root", "", new { controller = "Publico", action = "Index", id = UrlParameter.Optional });
context.MapRoute(
"Principal_default",
"Principal/{controller}/{action}/{id}",
new { action = "Index", id = UrlParameter.Optional }
);
}
}
</code></pre>
<br />
O trecho de codigo "context.MapRoute()" mapea o root da pagina que por sua vez aponta para o controller "Publico" e a View "Index" do projeto, ao executar a aplicação o resultado seria esse:<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj0mZNEFb1tqu3l6EGHKvFlBuJqEgc5DFi5U1gqM153MQcN_yCpGsgAv0RA2d-N3pF6mUgafYAT1hpn3ueNRzKzIdPfmm8sKJAF7gk4gvJntcz1rNsR0yrc_7D4-P_JxkxaU01wDywdMmo/s1600/publico.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="115" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj0mZNEFb1tqu3l6EGHKvFlBuJqEgc5DFi5U1gqM153MQcN_yCpGsgAv0RA2d-N3pF6mUgafYAT1hpn3ueNRzKzIdPfmm8sKJAF7gk4gvJntcz1rNsR0yrc_7D4-P_JxkxaU01wDywdMmo/s400/publico.png" width="400" /></a></div>
Como pode ver eu já implementei os links que irão chamar os outros módulos, perceba que ao clicar em cada um deles o roteamento é feito para a sua respectiva área chamando o "CONTROLLER" indicado no ActionLink, veja o fonte da Index:<br />
<br />
<pre style="background-image: URL(https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhtDkiUO9nySrprZDIjEIEJoxRX3AuY42e5gAii42s0X5LltSQDuFgkK2KCenBuZDe5hzN8gyAvGkO6tfzvpnKnIt6mpyAT-eMdZKd9C5yv2-mFzkCRTQe3LrYOdZrEn3qzd5NfoNdynIUe/s320/codebg.gif); background: #f0f0f0; border: 1px dashed #CCCCCC; color: black; font-family: arial; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;"> @{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<div style="text-align:center">
<h2>Domínio Público</h2>
@Html.ActionLink("Area - Financeira", "Index", "Home", new { area = "Financeiro" }, null)
<br />
@Html.ActionLink("Area - Loja de Produtos", "Index", "Home", new { area = "Loja" }, null)
<br />
@Html.ActionLink("Area - Pós Venda", "Index", "Home", new { area = "PosVenda" }, null)
</div>
</body>
</html>
</code></pre>
<br />
Sem mistérios ! =))<br />
Uma visão bastante interessante desse tipo de arquitetura seria o compartilhamento de _layouts e informações entres os "SITES" a grosso modo podemos ter uma percepção que temos vários ambientes de site dentro de apenas um, facilitando a manutenção e futuras melhorias no mesmo.<br />
É isso ...<br />
Espero ter ajudado.<br />
Um abraço!Anonymoushttp://www.blogger.com/profile/11593196735866212585noreply@blogger.com0tag:blogger.com,1999:blog-2614996039040117788.post-6523332266945857422012-10-15T18:20:00.000-07:002012-10-15T21:06:04.296-07:00HTML5 - Web SQL Database<span style="font-family: inherit;">Eai, Caros "Encodes" ... Meu primeiro post =)</span><br />
<div>
<span style="font-family: inherit;">Decidi compartilhar com vocês uma tecnologia que pude estudar a algum tempo atrás e implementar alguns pequenos projetos.</span></div>
<div>
<span style="font-family: inherit;">Este recurso de "BANCO DE DADOS" no browser é um recurso de persistência diretamente no cliente.</span></div>
<div>
<span style="font-family: inherit;">Para aqueles acostumados ao desenvolvimento web de alguns anos atrás pode achar que esse recurso é totalmente impossível da parte conceitual. </span></div>
<div>
<span style="font-family: inherit;">Porém com os ricos recursos que o HTML5 vem trazendo isso é totalmente aceitável até porque se você tem um bom conceito de "desenvolvedor back-end" vai estar acostumado a utilizar SQL e feliz como um "PORCO NA LAMA" hehe então ...</span></div>
<div>
<span style="font-family: inherit;">Aqui neste breve exemplo vamos abordar três métodos:</span></div>
<div>
<br />
1-<b> openDatabase</b><br />
<b>2- transaction</b><br />
<b>3- executeSql</b><br />
<br />
Porém Antes de implementa-los vamos aplicar um layout simples apenas para dar um lado mais "usuário" para o exemplo, vou utilizar uma biblioteca (JQuery Mobile) rica, simples, funcional...enfim vai te poupar de muita coisa na parte gráfica, a parte ruim é que alguém poderá te chamar de "Designer" HAHAHA chega de papo sirva-se de um café e vamos codar :)<br />
<span style="font-family: inherit;"><br />
Primeiramente não se esqueça de fazer as referencias necessárias para o funcionamento do JQuery Mobile.</span><br />
<pre style="background-color: #f0f0f0; background-position: initial initial; background-repeat: initial initial; border: 1px dashed rgb(204, 204, 204); color: black; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;"><span style="font-family: inherit;"> <link rel="stylesheet" href="css/themes/default/jquery.mobile-1.2.0.css" />
<script src="js/jquery.js"></script>
<script src="js/jquery.mobile-1.2.0.js"></script>
</span></code></pre>
<span style="font-family: inherit;"><br />
</span><br />
<span style="font-family: inherit;">Feito isso vamos codificar a parte do layout (...)</span></div>
<span style="font-family: inherit;"><br />
</span><br />
<pre style="background-color: #f0f0f0; background-position: initial initial; background-repeat: initial initial; border: 1px dashed rgb(204, 204, 204); color: black; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;"><span style="font-family: inherit;"> <body>
<div class="ui-body ui-body-a">
<div data-role="fieldcontain">
<label for="status">Status:</label>
<select name="status" id="status" data-role="slider">
<option value="on">Ativa</option>
<option value="off">Inativa</option>
</select>
</div>
<div data-role="fieldcontain">
<label for="name">Nome:</label>
<input type="text" name="name" id="name" value="" />
</div>
<div data-role="fieldcontain">
<label for="sexo" class="select">Sexo:</label>
<select name="sexo" id="sexo">
<option value="Selecione">Selecione</option>
<option value="Masculino">Masculino</option>
<option value="Feminino">Feminino</option>
</select>
</div>
<button type="button" data-theme="b" id="gravar" name="gravar" onclick="GravarDados()">Gravar</button>
</div>
</body>
</span></code></pre>
<span style="font-family: inherit;"><br />
Desta forma já podemos verificar o resultado inicial do nosso layout.</span><br />
<span style="font-family: inherit;"><br />
</span><br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh9YjKOW1LDVoOaHeJyz6LCMqO3hxbeIL_OjanZ5ztTxn3B-fwyifW2fjYcGLZf4yaYCR1BXMB179IRP32eQuRjPZeETYqbpsFNEMatTHYOAZwNxbPRRtZahaQvfhnKW1xiLkh-CE6xq74/s1600/jquery_1.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><span style="font-family: inherit;"><img border="0" height="75" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh9YjKOW1LDVoOaHeJyz6LCMqO3hxbeIL_OjanZ5ztTxn3B-fwyifW2fjYcGLZf4yaYCR1BXMB179IRP32eQuRjPZeETYqbpsFNEMatTHYOAZwNxbPRRtZahaQvfhnKW1xiLkh-CE6xq74/s400/jquery_1.png" width="400" /></span></a></div>
<span style="font-family: inherit;"><br />
"bunitão né?" rs, repare que o JQuery Mobile já trata todos os recursos necessários para o funcionamento ideal para um dispositivo móvel.</span><br />
<span style="font-family: inherit;">Continuando, como você pode ver fizemos uma chamada de uma função Javascript "GravarDados()" ao clicar no botão "GRAVAR" porém ela não foi implementada e se por acaso você fizer o teste verá que o resultado será um "Erro" por falta de implementação da mesma, sendo assim vamos codifica-la ...</span><br />
<span style="font-family: inherit;"><br />
</span><br />
<pre style="background-color: #f0f0f0; background-position: initial initial; background-repeat: initial initial; border: 1px dashed rgb(204, 204, 204); color: black; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;"><span style="font-family: inherit;"> var GravarDados = function(){
if (!window.openDatabase) {
alert('Not Supported -> Please try with a WebKit Browser');
}else{
try{
var db = openDatabase('bancoWebBrowser_1', '1.0', 'meu primeiro web database', 2 * 1024 * 1024);
}catch(e) {
alert('Erro !'+e);
}
}
}
</span></code></pre>
<span style="font-family: inherit;"><br />
Como o objetivo do tutorial é mostrar de forma "simplificada" pode notar que adotei um padrão de código simples, nada impede destas implementações ser feita utilizando recursos mais avançados de técnicas de orientação objetos e etc (...)</span><br />
<span style="line-height: 24px;">Algo bastante importante em citar na primeira verificação " if (!window.openDatabase) { "que é bastante necessária pois o webSql Database não foi implementado por todos os browser. =/</span><br />
<span style="line-height: 24px;">Os navegadores que dão suporte até o momento são: </span><br />
<span style="line-height: 24px;">(Safari, SafariMobile and Chrome) and Opera 10.50 (ATOW alpha on Mac) </span><br />
<span style="line-height: 24px;">As empresas responsáveis por alguns browsers como o Firefox alega que a não implementação seria por falta de padronização do SQL, lembrando que o padrão adotado seria do SQLLite.Devemos lembrar também que as especificações sobre web SQL Database não estão mais sendo mantida pela W3C.</span><br />
<br />
<blockquote class="tr_bq">
<span style="background-color: black; color: white; font-family: inherit; font-weight: 900; text-align: center;">Beware. This specification is no longer in active maintenance and the Web Applications Working Group does not intend to maintain it further.</span></blockquote>
<span style="font-family: inherit; line-height: 24px;">Se quiser saber mais sobre o assunto verifique na documentação oficial. <a href="http://www.w3.org/TR/webdatabase/" target="_blank">http://www.w3.org/TR/webdatabase/</a></span><br />
<span style="font-family: inherit;"><span style="line-height: 24px;"><br /></span>
<span style="line-height: 24px;">Voltando ao que interessa (...)</span></span><br />
<span style="font-family: inherit; line-height: 24px;">O código abaixo efetua a criação do nosso banco de dados.</span><br />
<span style="font-family: inherit; line-height: 24px;">1 - Database Name</span><br />
<span style="font-family: inherit; line-height: 24px;">2 - Version Number</span><br />
<span style="font-family: inherit; line-height: 24px;">3 - Text Description</span><br />
<span style="font-family: inherit; line-height: 24px;">4 - Estimated size of database</span><br />
<span style="font-family: inherit;"><br /></span>
<span style="font-family: inherit; line-height: 24px;">- Nada de muito complexo até o momento! =)</span><br />
<span style="font-family: inherit;"><br /></span>
<br />
<pre style="background-color: #f0f0f0; background-position: initial initial; background-repeat: initial initial; border: 1px dashed rgb(204, 204, 204); color: black; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;"><span style="font-family: inherit;"> db.transaction(function (tx) {
tx.executeSql('CREATE TABLE IF NOT EXISTS pessoa (id INTEGER PRIMARY KEY AUTOINCREMENT, status text, nome text, sexo text)');
var status = $('#status').val();
var nome = $('#name').val();
var sexo = $('#sexo').val();
tx.executeSql('INSERT INTO pessoa (status,nome,sexo) VALUES (?,?,?)', [status,nome,sexo]);
tx.executeSql('SELECT id,status,nome,sexo FROM pessoa', [], function (tx, results) {
var len = results.rows.length, i;
for (i = 0; i < len; i++) {
console.log('Chave: ' +results.rows.item(i).id + ' Nome: '+ results.rows.item(i).nome+ ' Sexo: '+results.rows.item(i).sexo+ ' Status Cadastro: '+ results.rows.item(i).status);
}
});
// Limpa campos ...
$('#status').val('');
$('#name').val('');
$('#sexo').val('');
});
</span></code></pre>
<span style="font-family: inherit;"><br /></span>
<span style="font-family: inherit;">- Note que os comando adotados para a criação da tabela "pessoa" possui uma sintaxe em que qualquer desenvolvedor back-end está acostumado a utilizar no seu dia-dia, após efetuarmos um script de INSERT também padrão pegando os campos da tela com o auxilio do JQuery.</span><br />
<span style="font-family: inherit;"><br /></span>
<br />
<pre style="background-image: URL(https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhtDkiUO9nySrprZDIjEIEJoxRX3AuY42e5gAii42s0X5LltSQDuFgkK2KCenBuZDe5hzN8gyAvGkO6tfzvpnKnIt6mpyAT-eMdZKd9C5yv2-mFzkCRTQe3LrYOdZrEn3qzd5NfoNdynIUe/s320/codebg.gif); background: #f0f0f0; border: 1px dashed #CCCCCC; color: black; font-family: arial; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;"> var nome = $('#name').val();
</code></pre>
<span style="font-family: inherit;"><br /></span>
<span style="font-family: inherit;">...em seguida efetuamos uma consulta para verificarmos todos os dados gravados na nossa base sendo eles mostrado no "Console" do navegador. (Nada impede que você implemente uma interface para a melhor mostragem dos dados.)</span>
<br />
<pre style="background-image: URL(https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhtDkiUO9nySrprZDIjEIEJoxRX3AuY42e5gAii42s0X5LltSQDuFgkK2KCenBuZDe5hzN8gyAvGkO6tfzvpnKnIt6mpyAT-eMdZKd9C5yv2-mFzkCRTQe3LrYOdZrEn3qzd5NfoNdynIUe/s320/codebg.gif); background: #f0f0f0; border: 1px dashed #CCCCCC; color: black; font-family: arial; font-size: 12px; height: auto; line-height: 20px; overflow: auto; padding: 0px; text-align: left; width: 99%;"><code style="color: black; word-wrap: normal;"> tx.executeSql('SELECT id,status,nome,sexo FROM pessoa', [], function (tx, results) {
var len = results.rows.length, i;
for (i = 0; i < len; i++) {
console.log('Chave: ' +results.rows.item(i).id + ' Nome: '+ results.rows.item(i).nome+ ' Sexo: '+results.rows.item(i).sexo+ ' Status Cadastro: '+ results.rows.item(i).status);
}
});
</code></pre>
<br />
<span style="font-family: inherit;">É interessante efetuarmos um parentes aqui e enfatizar a importância da utilização de uma ferramenta de DEBUG para implementação de códigos Javascript's pois ele é o seu único Guia como sabemos o Javascript é interpretado pelo motor do browser isso dificulta um pouco a leitura dos erros. Eu costumo utilizar o Chrome que já possui um console nativo porém o Firefox existe o Firebug um plugin excelente de terceiro que inclusive existe para varias outras versões de navegadores.</span><br />
<span style="font-family: inherit;">Site Oficial: <a href="http://getfirebug.com/" target="_blank">http://getfirebug.com/</a></span><br />
<span style="font-family: inherit;"><br /></span>
<span style="font-family: inherit;">O resultado da implementação acima seria essa:</span><br />
<span style="font-family: inherit;"><br /></span>
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhCp_03llaM4q6ZTN2SDrwtaUmr3oj4_516CkgCOpnzgUtO2n4r7N6n_vZUQbXCulCspsd-5QMs8VhEjW6UHMFylS0ON0T34DG-AaecP063EK3jzWJAbRbUKHAhYYyQ5tK3KN4XID3Ujuc/s1600/jquery_2.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><span style="font-family: inherit;"><img border="0" height="215" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhCp_03llaM4q6ZTN2SDrwtaUmr3oj4_516CkgCOpnzgUtO2n4r7N6n_vZUQbXCulCspsd-5QMs8VhEjW6UHMFylS0ON0T34DG-AaecP063EK3jzWJAbRbUKHAhYYyQ5tK3KN4XID3Ujuc/s400/jquery_2.png" width="400" /></span></a></div>
<span style="font-family: inherit;"><br /></span>
<span style="font-family: inherit;">O resultado do "SELECT * " no console, ficaria assim (...)</span><br />
<span style="font-family: inherit;"><br /></span>
<br />
<div class="separator" style="clear: both; text-align: center;">
<span style="font-family: inherit; margin-left: 1em; margin-right: 1em;"><img border="0" height="151" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEibjp728UgngekbVZXepbT5prJa_NNUSpigP3QPZQ8QLD03MySPu9auz3RIfIeiXmqGDzzzd4WNHXUpOiu4oxY2KR0rm8nG17a9_JPP59g4H6P2OZseZgcVxgejWEWdZdGJeOM9bkitBis/s400/jquery_3.png" width="400" /></span></div>
<div class="separator" style="clear: both; text-align: center;">
<span style="font-family: inherit;"><br /></span></div>
<div class="separator" style="clear: both; text-align: left;">
<span style="font-family: inherit;"><br /></span></div>
<div class="separator" style="clear: both; text-align: left;">
<span style="font-family: inherit;">Isso é tudo que você precisa para começar com Web SQL Database.</span></div>
<div class="separator" style="clear: both; text-align: left;">
<span style="font-family: inherit;"><br /></span></div>
<div class="separator" style="clear: both; text-align: left;">
<span style="font-family: inherit;">Você já deve ter percebido mas vale constar a ideia de software que colocamos a seguir é um conceito que vem surgindo novo, principalmente no mundo móvel que seria de um software web porém com funcionabilidades locais não descartando a possibilidade de uma integração com algum webservice ou sincronia desses dados (...) enfim fica a ideia !</span></div>
<div class="separator" style="clear: both; text-align: left;">
<span style="font-family: inherit;"><br /></span></div>
<div class="separator" style="clear: both; text-align: left;">
<span style="font-family: inherit;">Missão dada é missão cumprida ! hehe</span></div>
<div class="separator" style="clear: both; text-align: left;">
<span style="font-family: inherit;">LOGO estarei disponibilizando para download o fontes dos exemplos realizados aqui.</span></div>
<div class="separator" style="clear: both; text-align: left;">
<span style="font-family: inherit;"><br /></span></div>
<div class="separator" style="clear: both; text-align: left;">
<span style="font-family: inherit;">Até a próxima =)</span></div>
<div class="separator" style="clear: both; text-align: left;">
<span style="font-family: inherit;"><br /></span></div>
<div class="separator" style="clear: both; text-align: left;">
<span style="font-family: inherit;">Links Utilizados no Post:</span></div>
<div class="separator" style="clear: both; text-align: left;">
<a href="http://jquerymobile.com/" target="_blank"><span style="font-family: inherit;">http://jquerymobile.com/</span></a></div>
<div class="separator" style="clear: both; text-align: left;">
<a href="http://www.w3.org/TR/webdatabase/" target="_blank"><span style="font-family: inherit;">http://www.w3.org/TR/webdatabase/</span></a></div>
Anonymoushttp://www.blogger.com/profile/11593196735866212585noreply@blogger.com1