Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Take.io Essentials

1,426 views

Published on

Description of Take.io Essentials library in simple steps.

Published in: Technology
  • Be the first to comment

  • Be the first to like this

Take.io Essentials

  1. 1. TakeIoEssentials<br />Guilherme BalenaVersiani <guibv@take.io><br />
  2. 2. TakeIo.Web<br />
  3. 3. Builton top ofASP.NET MVC 3<br />
  4. 4. publicclassEchoController : RestfulController<br />{<br /> [Get("echo/{thingToEcho}")]<br />publicActionResultReply(stringthingToEcho)<br /> {<br /> return Item(new Echo { ... });<br /> }<br />}<br />Sinatra-likeRESTfulRoutes<br />Define applicationroutes in thecontrollers, not in Global.asax.cs<br />
  5. 5. Support OPTIONS and HEAD methods<br />Derive fromRestfulController, notfromController<br />publicclassEchoController : RestfulController<br />{<br /> [Get("echo/{thingToEcho}")]<br />publicActionResultReply(stringthingToEcho)<br /> {<br /> return Item(new Echo { ... });<br /> }<br />}<br />
  6. 6. Syntax-sugar for returningitems<br />Callthefunction Item().<br />publicclassEchoController : RestfulController<br />{<br /> [Get("echo/{thingToEcho}")]<br />publicActionResultReply(stringthingToEcho)<br /> {<br /> return Item(new Echo { ... });<br /> }<br />}<br />
  7. 7. Syntax-sugar for collections too<br />CallthefunctionCollection().<br />publicclassEchoController : RestfulController<br />{<br /> [Get("list/{from}/{to}")]<br /> public ActionResult List(string from, string to)<br />{<br /> var list = new List<int>();<br /> for (var i = int.Parse(from); i <= int.Parse(to); i++)<br />list.Add(i);<br /> return Collection(list.Count, list, list.Count, int.Parse(from));<br /> }<br />}<br />
  8. 8. Syntax-sugar for resourcecreation<br />CallthefunctionCreated().<br />publicclassContactsController: RestfulController<br />{<br /> [Post("contacts/{ownerId}")]<br /> public ActionResult Create(string ownerId, Contact contact)<br />{<br />Db.CreateContact(ownerId, contact);<br />varcurrentUrl = HttpContext.Request.Url;<br />varuri = new Uri(currentUrl, contact.ContactId.ToString());<br /> return Created(uri);<br /> }<br />}<br />
  9. 9. Syntax-sugar for resourceremoval<br />CallthefunctionDeleted().<br />publicclassContactsController: RestfulController<br />{<br /> [Delete("contacts/{ownerId}/{contactid}")]<br /> public ActionResult Delete(string ownerId, long contactId)<br />{<br />Db.DeleteContact(ownerId, contactId);<br /> return Deleted();<br /> }<br />}<br />
  10. 10. A single ASP.NET appcontainsmultiple modules<br />CallthefunctionMapRouteTable() in Application_Start().<br />publicclassMvcApplication : HttpApplication<br />{<br />protectedvoidApplication_Start()<br /> {<br />RouteTable.Routes.MapRouteTable();<br /> }<br />}<br />
  11. 11. A single ASP.NET appcontainsmultiple modules<br />Use theconfigsectionrouteTable.<br /><configuration><br /> <configSections><br /> <sectionname="routeTable" type="TakeIo.Web.RouteTableSection, TakeIo.Web" /><br /> </configSections><br /> ...<br /> <routeTable><br /> <routes><br /> <addname="RouteName" path="SomePrefix" assembly="TakeIo.Example" /><br /> </routes><br /> </routeTable><br /> ...<br /></configuration><br />
  12. 12. User-friendlyexceptionhandlers<br />Implement a IExceptionHandler interface<br /> public class NotImplementedExceptionHandler : IExceptionHandler<br />{<br /> public Type Type { get { return typeof(NotImplementedException); } }<br />public void HandleException(ExceptionContextexceptionContext,ViewDataDictionaryviewData)<br />{<br />exceptionContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;<br />exceptionContext.HttpContext.Response.StatusDescription= "Feature not implemented";<br />viewData.Add("PageTitle", "This feature wasn't implemented yet");<br />viewData.Add("WhatHappened", "Unfortunately, you called a feature that wasn't implemented by our team yet.");<br />viewData.Add("HowThisAffectYou", "You won't be able to use this feature, and retry won't help you.");<br />viewData.Add("WhatYouCanDo", "You can contact our team to put more efforts to provide this feature for you.");<br /> }<br />}<br />
  13. 13. User-friendlyexceptionhandlers<br />Maptheexceptionhandler in Global.asax.<br />publicclassMvcApplication : HttpApplication<br />{<br />protectedvoidApplication_Start()<br /> {<br />ExceptionHandlers.Handlers.Add(new NotImplementedExceptionHandler());<br /> }<br />}<br />
  14. 14. User-friendlyexceptionhandlers<br />User-friendlyinformation<br />MachineInformation<br />Stack Trace<br />
  15. 15. “Fancy” exceptionhandlers<br /> public class FancyArgumentExceptionHandler: IExceptionHandler<br />{<br /> public Type Type { get { return typeof(ArgumentException); } }<br />public void HandleException(ExceptionContextexceptionContext,ViewDataDictionaryviewData)<br />{<br />exceptionContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest;<br />exceptionContext.HttpContext.Response.StatusDescription= "Invalid arguments";<br />exceptionContext.Result = new ViewResult<br />{<br />MasterName= string.Empty,<br />ViewName= "~/Views/Error.cshtml",<br />ViewData= viewData,<br />TempData= exceptionContext.Controller.TempData<br /> };<br />exceptionContext.ExceptionHandled = true;<br /> }<br />}<br />
  16. 16. RequestsProfiling Module<br />AddWebProfilerModuletoyourconfig file.<br /><configuration><br /> ...<br /> <system.webServer><br /> <modules><br /> <addname="WebProfilerModule" type="TakeIo.Web.WebProfilerModule, TakeIo.Web" /><br /> </modules><br /> </configSections><br /> ...<br /></configuration><br />
  17. 17. RequestsProfiling Module<br />Afterconfiguring log4net, youwillhave:<br />...<br />[00:31:02,783] [2516] [DEBUG] [TakeIo.Web.WebProfilerModule]:[(null)]<br />Timing for 'http://domain.com/my/url?parameter=value' was 578ms<br />...<br />
  18. 18. “Safe” callsto Common Service Locator<br />Providecomprehensiveexceptionswhileaccessing CSL.<br />try{ var instance = SafeServiceLocator.GetInstance<IMyInterface>();}catch (Exceptionex){Console.WriteLine(ex.Message);}<br />Comes fromS#arp<br />Will show:<br />ServiceLocator has not been initialized; I was trying to retrieve 'IMyInterface‘.<br />The needed dependency of type IMyInterfacecould not be located with the ServiceLocator. You'll need to register it with the Common Service Locator (CSL) via your IoC's CSL adapter.<br />Or:<br />
  19. 19. Flexibleaccesstologgingfacility<br />Use staticclassLogger:<br />Logger.Debug("Thisismy debug message");Logger.DebugFormat("Thisismy debugmessage: {0}, {1}, {2}", arg1, arg2, arg3);Logger.Info("Thisismyinfomessage");Logger.InfoFormat("Thisismyinfomessage: {0}, {1}, {2}", arg1, arg2, arg3);Logger.Warn("Thisismywarningmessage");Logger.WarnFormat("Thisismywarningmessage: {0}, {1}, {2}", arg1, arg2, arg3); Logger.Error("Thisismyerrormessage");Logger.ErrorFormat("Thisismyerrormessage: {0}, {1}, {2}", arg1, arg2, arg3);Logger.Fatal("Thisismyfatal message");Logger.FatalFormat("Thisismyfatal message: {0}, {1}, {2}", arg1, arg2, arg3);<br />
  20. 20. Flexibleaccesstologgingfacility<br />For complex log messages, prefertocheckenablingflags<br />if (Logger.IsDebugEnabled){ // very // long, // complexand // performance exhaustive // log routine}<br />
  21. 21. Flexibleaccesstologgingfacility<br />YoucansubstitutetheloggerfacilitybyimplementingtheILogger interface<br />More info:http://docs.castleproject.org/Windsor.Windsor-Tutorial-Part-Five-Adding-logging-support.ashx<br />
  22. 22. Design byContract<br />usingTakeIo.Web;Check.Require(x > 0, "x must be positive.", new ArgumentException("Invalid argument.", "x"));<br />More info:<br />http://www.codeproject.com/KB/cs/designbycontract.aspx<br />
  23. 23. ModelBinder for array data in Query String<br />
  24. 24. Usefulfeatures:<br />New RazorViewEngine<br />SessionlessControllerSupport<br />Dependency Resolver (IoC, Castle Windsor)<br />New HelperMethods<br />Use of ASP.NET MVC 3<br />
  25. 25. Cache ofItemsandCollections<br />Each Item orCollectionreturned includes “ETag” header andhonours “If-None-Match” header in requests. Thisreducesthroughput for cachingandproxiedclients.<br />Supportof OPTIONS and HEAD methods<br />OPTIONS and HEAD requestsproduces a reasonable response for allcontrolleractions.<br />TakeIo.Essentialssupports<br />
  26. 26. Support for legacy browsers:<br />Allcontrollerssupportsalternative PUT and DELETE requests:<br />Use POST as therequestmethodandencapsulatethe PUT and DELETE methods in “_method” attribute in Query String (not in POST content!);<br />Use the “X-HTTP-Method-Override” header extension.<br />TakeIo.Essentialssupports<br />

×