Saturday, February 1, 2014

Custom C# Attributes

I got quizzed about this in an interview recently.  Embarrassment is a great instructor

Filters and attributes are ways of creating re-usable bits of code that you can use with attributes to methods in your controllers.  You can also apply the annotation to the whole controller to apply the code logic to ALL of the methods in the controller class.

Here is the simplest implementation of custom attributes that I came up with.  Put this in one of your controllers, or set up another class file for all of your attributes.

public class CustomActionAttribute : FilterAttribute, IActionFilter { 
   void IActionFilter.OnActionExecuted(ActionExecutedContext context) {                   context.Controller.ViewBag.OnActionExecutedViewBag =                                          "IActionFilter.OnActionExecuted filter called"; } 
   void IActionFilter.OnActionExecuting(ActionExecutingContext context) {                 context.Controller.ViewBag.OnActionExecutingViewBag =                                          "IActionFilter.OnActionExecuting filter called"; } 
 }
As long as you add the IActionFilter attribute, visual studio error will give you enough information to build the methods.  i.e.  you must implement OnActionExecuted and OnActionExecuting.  Errors are thrown if the parameters are missing as well.

Add the annotation to a controller class (or to the whole controller):
[CustomAction]
 public ActionResult Index()
 { return View(); }


This code in your view should convince you that the code executed:
@ViewBag.OnActionExecutingViewBag 
@ViewBag.OnActionExecutedViewBag

If you want to add parameters [CustomAction(Message="Description for attribute")], just add properties to your class:

public class CustomActionAttribute : FilterAttribute, IActionFilter { 
     public string Message { get; set; } 

     void IActionFilter.OnActionExecuted(ActionExecutedContext context) 
       { if (!string.IsNullOrEmpty(Message))                                                context.Controller.ViewBag.OnActionExecutedViewBag = Message; 
         else 
           context.Controller.ViewBag.OnActionExecutedViewBag =                                    "IActionFilter.OnActionExecuted filter called 2"; }


You can use the following types of filters, similarly to the way we implemented the Action filter:
  • Authorization filter
  • Action filter
  • Result filter
  • Exception filter

Tuesday, January 7, 2014

font-face

Thank goodness we can use any fonts we want on the web now.  Here is the easiest way I have found to get the font you want for your website and how to make sure all browsers can use it.  Font Squirrel makes it super easy:
  1.   Download your font on Font Squirrel or another site, it can be any of the following file formats:  *.eot, *.woff, *.ttf, *.svg.  Make sure the license enables you to use this font!
  2. Navigate to Font-Squirrels Web Font Generator and add fonts with the 'add fonts' button.  
  3. After you have uploaded the fonts for your site, choose the 'optimal' radio button, and click 'Download your kit'.
  4. The generator not only gives you all the file types you need to be cross browser compatible, but it also gives you an HTML and CSS file that gives a perfect example of how to use it.
  5. Place ALL of the font files in a fonts directory.
  6. Grab the @font-face rule from the CSS file and use it in your own CSS file for your project.  Keep in mind that the url path is relative to your CSS file, so modify the path as appropriate.  Here is the CSS for reference:
    @font-face { font-family: 'ralewaybold'; src: url('fonts/raleway-bold-webfont.eot'); src: url('fonts/raleway-bold-webfont.eot?#iefix') format('embedded-opentype'), url('fonts/raleway-bold-webfont.woff') format('woff'), url('fonts/raleway-bold-webfont.ttf') format('truetype'), url('fonts/raleway-bold-webfont.svg#ralewaybold') format('svg'); font-weight: normal; font-style: normal; }
  7. Use the font face now.  I set it in my body tag, making it the default font for the site:  body { font-family: ralewaybold, Verdana, Helvetica, Sans-Serif;
  8. Enjoy your non-standard font!

CSS Reset

Every new site needs a CSS reset to tame those nasty standards-ignoring browsers.  Here it is before I forget and for good reference.  This CSS was largely taken from this site, but modified slightly:

html, body, div, span, object, iframe,h1, h2, h3, h4, h5, h6, p, blockquote, pre,abbr, address, cite, code,del, dfn, em, img, ins, kbd, q, samp,small, strong, sub, sup, var,b, i,dl, dt, dd, ol, ul, li,fieldset, form, label, legend,table, caption, tbody, tfoot, thead, tr, th, td,article, aside, canvas, details, figcaption, figure, footer, header, hgroup, menu, nav, section, summary,time, mark, audio, video { margin:0; padding:0; border:0; outline:0; font-size:100%; vertical-align:baseline; background:transparent; } body { line-height: 1; } article,aside,details,figcaption,figure,footer,header,hgroup,menu,nav,section { display:block; } nav ul { list-style:none;} blockquote, q { quotes:none;} blockquote:before, blockquote:after, q:before, q:after { content:''; content:none; } a { margin:0; padding:0; font-size:100%; vertical-align:baseline; background:transparent;} table { border-collapse:collapse; border-spacing:0; } hr { display:block; height:1px; border:0; border-top:1px solid #cccccc; margin:1em 0; padding:0; } input, select { vertical-align:middle; }

Wednesday, December 18, 2013

SCSS, SASS, Sassy CSS, Compass, CSS Awesomeness

I had a chance to experiment with Sassy CSS recently.  As usual, here are the notes so I don't forget what my tinkering uncovered.

Compass is the best tool I found to work with SCSS.  Install instructions can be found here:  http://compass-style.org/install/.  For installation, install Ruby, and then run the following commands:  > gem update --system and then > gem install compass.

Ignore the instructions under "Tell us about your project and we'll help you get it set up:".  Open up a command prompt with administrator privs, change directory to your project directory (this can be an existing solution or a new solution).  Run compass create <project name>.

This will create some default directories and files for css, sass and create a config.rb file.  Edit config.rb to see where compass thinks folders are located.  The settings are pretty straight forward.  Here is the setup that I am initially happy with:

# in config.rb:
http_path = "/"
css_dir = "css"
sass_dir = "sass"
images_dir = "images"
javascripts_dir = "scripts"
line_comments = false
environment = :development
output_style = :expanded

Change the config file to match the directory names of your project.  After this is set up, run >compass watch from the command line in the root of your project.  If you change the configuration (or want Compass to stop, ctrl-c at the command prompt and Y to "stop the batch".  >compass watch again to use your new config settings.

I removed the default scss and css files that were created during compass create <project name> and created a style.scss file in the sass directory.  You don't need to add style.css, Compass will create this for you.  If you do create it, Compass will update it.

After this is set up, it's time to start coding!  Edit style.scss, save the changes and then view css/style.css.  It should be automatically updated.  Pretty rad.

This article wasn't intended to dig into the language of scss, there are plenty of tutorials out there.  Along my journey, I also found this page that was useful to test scss:  http://sassmeister.com/

I am excited to start learning SCSS and incorporate it into my projects.  It's going to make things a lot easier.  If you haven't started using it yet, this is another handy dandy tool that will help speed your development up:  http://livereload.com/.  It basically detects changes in CSS and refreshes your browser for you.

Heaven.

Wednesday, November 13, 2013

favicon

Time to revisit the favicon for websites.  I always forget how to do this one..

The first part is pretty easy.  Upload your starting image to http://www.favicon.cc/?.  Pretty self explanatory.
The next step is putting it in the head of your html files.  Here is the link statement:  <link rel='shortcut icon' type='image/x-icon' href='/favicon.ico' />  Place the favicon.ico in the root directory of your site.

If your favorite favicon won't update, change the href to force it with href='/favicon.ico?v=2'.  Your browser won't know what hit it.

Forgotten more than I remember

Ok, finally had enough of the thought "damn, I did that once, but I can't remember how".  Stay posted for random web development tasks and whatever else in life I care to document to make it easier the next time..