theKindOfMe

January 31, 2010

Notes on setting up devise (authentication solution for rails)

Filed under: Uncategorized — Tags: , , — yasi8h @ 4:38 pm

From Devise’s project page:

Devise is a flexible authentication solution for Rails based on Warden. It:

  • Is Rack based;
  • Is a complete MVC solution based on Rails engines;
  • Allows you to have multiple roles (or models/scopes) signed in at the same time;
  • Is based on a modularity concept: use just what you really need.

I was playing around with devise trying to get it set-up in my app, came through some configuration errors on my part, thought of noting them down for future reference.

NoMethodErrors and NameErrors

  • if you are getting NoMethodErrors for methods such as user_signed_in?, current_user, user_session, admin_signed_in? in your ActiveViews, check your routes.rb file for correct “map.devise_for :”  statements. If you have users and a admin in your system and Users and Admin models in your models. You should have something like this:
    map.devise_for :users, :admin
    
  • If you are getting NameErrors like “undefined local variable or method `edit_user_path' for #….” (could be for new_admin_session_path…etc anything to do with session path) Then check whether you have mapped your controllers correctly on your routes.rb. If you are having a UsersController and a AdminController your routes.rb can have some lines like:
    map.resource :user
    map.resources :admins
    

January 29, 2010

Gmail Attachment Downloader Script

Filed under: Uncategorized — Tags: , — yasi8h @ 1:54 am

<rant>I wanted to download all the attachments from all the emails in my account, that have a label x on them. With all the cool libs around this should be a piece of cake. But… After a lot of googling, and spending hours installing different versions of the ruby runtimes (found out about RVM in the process, this is very useful), and going through old gems that spits out so many errors when they are run on 1.9 runtimes… etc, came up with this one, that among other things, just work!. One thing that i am again reminded is that its not easy coming back to ruby development when you don’t have a good working environment set up. Installing (it’s more about knowing what dependencies you need for different gems i guess) every thing that is required on Ubuntu is not that simple either.</rant>

How to Run

  • Edit the script to reflect your account and other settings.
  • Install the nesseary gems (gem install tmail)

Things you should know about

  • This was tested on ruby 1.8.7 (2009-06-12 patchlevel 174)
  • You need tmail -> gem install tmail
  • Your Gmail account should be IMAP enabled (more info).
  • The script will first go through all the mails with some label applied on them. And it will download the attachments on these mails one by one. After it have processed one email, it will put on another label on it, to signify that this message’s attachments have been downloaded. So you could continue this script from where it stopped, if the script crashes out in the middle of the process.
  • I first tried doing this using ruby-gmail gem, but for some reason it fails to detect the attachments. But this may be fixed when you are reading this post. So if you want a more simpler script with more gmail oriented functionalities have a look at that project.
  • Whatever you do, do not violate Gmail’s ToS.

Issues

  • This process emails one by one, it is not multi threaded. And it will take sometime. So be patient and let it do its job.
  • When a certain email is processed and its attachments are downloaded the script will attach a label to it. This might/might not remove the existing labels from that email. If it does not remove them, you will need to do so manually, if and when you are starting the script to resume its work from where it stopped last time.
  • The script doesn’t know about (gmail) threads, it processes individual emails.

I am giving up, its too hard to post source code on wordpress, get it from git hub

#! /usr/bin/ruby
#This script is baised on http://snippets.dzone.com/posts/show/7530

username = "username@gmail.com"
password = "pa$sword"
look_in_folder = "gmail_label_of_the_messages_whose_attachments_you_want_downloaded"
move_downloaded_mails_to_folder = "gmail_label_to_be_applied_for_processed_emails"
save_to_folder = "/path/to/folder/where/attachments/will/be/saved"

require 'net/imap'
require 'rubygems'
require 'tmail'

# This is a convenience monkey patch
class Net::IMAP
 def uid_move(uid, mailbox)
 uid_copy(uid, mailbox)
 uid_store(uid, "+FLAGS", [:Deleted])
 end
end

puts 'Starting...'
imap = Net::IMAP.new('imap.gmail.com', '993', true)

puts "Logging in as #{username} ..."

imap.login(username, password)
imap.select(look_in_folder)
mails = imap.uid_search(["NOT", "DELETED"])

puts "Found #{mails.count} mail(s) in folder '#{look_in_folder}'"

puts "\nFetching the next email (this might take some time depending on the size of the message/attachment..."
mails.each do |uid|
 # save_attachment
 mail = TMail::Mail.parse( imap.uid_fetch(uid, 'RFC822').first.attr['RFC822'] )
 puts "Processing '#{mail.subject}'"
 if ! mail.attachments.blank?
 puts "Detected #{mail.attachments.count} attachment(s)"
 mail.attachments.each {|attachment|
 puts "Saving attachment to '#{attachment.original_filename}'..."
 File.open(save_to_folder + attachment.original_filename,"w+") { |local_file|
 local_file << attachment.gets(nil)
 }
 }

 end

 # archive mail to mailbox
 puts "Moving '#{mail.subject}' to folder '#{move_downloaded_mails_to_folder}'"
 imap.uid_move(uid, move_downloaded_mails_to_folder)
end

imap.expunge
puts "Logging out..."
imap.logout

References

January 22, 2010

Thoughts about HP 2133 Mini-Note

Filed under: Uncategorized — Tags: , , — yasi8h @ 4:24 pm

On My Bed, Looking Smart 🙂

Slim and Looking Good

More Pictures on flickr

My dad got a HP 2133 Mini-Note as a gift (!!!, seriously, its me who should have got a gift like this 😛 ). He don’t really use it and i am the only one to spend some time with it. This is the first ever net book that i got my hands on. I expected a lot more from a netbook than what i got from 2133. I think this is due to the fact that the model i got was some  what a economic edition, it had Linux and thats good. But i think HP made my model as a low end one so needless to say it degraded the net book’s performance. Why do everybody have to us Linux users less RAM anyways?!#!!. It didn’t have a SSD, the cpu is a via and its not as powerful (i don’t want it to be as fast as my desktop cpu or even come close to it. but its still too slow for doing some web browsing and playing some music. it lags at times…etc) as i want it to be. And the battery don’t last that long. Plus it gets really hot!.

Any how now this model is suspended and is replaced by the newer 2140.

Following specs were obtained from the HP’s web site (http://h40059.www4.hp.com/hp2133/).

Specifications
Model number KX872AA (This is what i got) FF009AA
Operating system installed SUSE Linux Enterprise Desktop Genuine Windows Vista® Business
Processor Via C7-M (1.2G) Via C7-M (1.2G)
Memory 1024MB DDR RAM 2048MB DDR RAM
Network Support 56K Modem, 802.11b/g,Bluetooth 56K Modem, 802.11a/b/g,Bluetooth
Disk 120GB HDD 120GB HDD
Battery 3-Cell LiIon Battery 6-Cell LiIon Battery
Warranty 1 year 1 year
OS Linux VB OFC07 Ready

Simple breakdown of pros and cons as i see it.

Pros

  • Looks nice
  • Solid build
  • OK Keyboard
  • Small size
  • Came with Suse Linux pre installed! (i uninstalled it and installed Ubuntu straight away ;))
  • No Drivers-Missing problems with Linux. Almost (dynamic CPU frequency setting was not working on stock Ubuntu. I am sure this contributed to the cons about low battery life and too much heat) everything works with a default Ubuntu installation.

Cons

  • Processor is too slow
  • Didn’t come with a SSD
  • Gets really hot
  • Battery life is too short for a netbook
  • Heavier than it looks 🙂

I am sure i can make this useful in many ways, but its not the ideal net book i had in mind.

January 18, 2010

Thoughts about Grado SR60i Headphones

Filed under: Uncategorized — Tags: , , — yasi8h @ 12:10 pm

Grado SR60i Headphones

Got a Classic Look eh? 🙂

More Pictures on flickr

There was a chance for me to get some thing brought down from Amazon, so i brought a set of headphones (and a sound card). I am nothing close to an audiophile so whatever i say about this set of headphones is coming from an ordinary geek.

Pros

  • Overall grate sound quality.
  • Lows, Mids and Highs all sounds good.
  • I hear more sounds (ie: i hear some instrument playing in the background which i have never heard before, in a familiar song.) than i used to hear though my speakers.
  • Music sounds better through my headphones, when comparing with my 5.1 surround sound system (Creative Impress).
  • The build quality is pretty good. I hope this will last for some time.
  • Connectors are good, i hear no noise.

Cons

  • It is not comfortable to wear. My ears starts paining after a while.
  • This is ‘open air’, so others around you can hear what you are listening to. Can be a nuisance sometimes.
  • Bit heavy and have a 80s look (may be this should be a pro? 🙂 ).
  • For movies and games i would rather turn to my speakers (not really a con i guess…).

I am happy about my investment.

January 15, 2010

Bopath Ella Falls

Filed under: Uncategorized — Tags: , , — yasi8h @ 8:53 am

14th Jan is a public holiday in Sri Lanka. On that day me and a couple of my work buddies went on a trip, to Bopath Ella Falls (http://en.wikipedia.org/wiki/Bopath_Ella_Falls). It was grate. We climbed to the very top of the falls. It was not easy, walking barefoot on a small trail covered with jungle like terrine. However it was fun :). Some pics follows…

Bopath Ella Falls

Looking down from the top

In the top

More Pictures on flickr

🙂

January 4, 2010

Validation Frameworks for .net Compact Framework

Filed under: Uncategorized — Tags: , — yasi8h @ 6:52 am

If you google the title of this post you would not find any satisfying results. I tried it and i didn’t (.net validation framework intends to support the .net compact framework. But this is still in the todo list) came across any validation framework that officially supports .net CF. But most of .net validation frameworks out there or at least certain parts of the frameworks can be used in a .net cf project. I had to do some research on this topic recently so i am writing down my finding here. Please note that this post is by no means perfect. I might have missed some validation frameworks intentionally or accidentally. I was interested in a framework that would provide a basic validation framework and some ‘bindings’/helpers for windows forms and asp.net MVC. I needed a framework that can be used in a web/desktop and a mobile application. Any framework that was heavily coupled with any one of the platforms was ignored (as it will be difficult to use them in the other platforms).

Validation Frameworks ‘Assessed’

.net Validation Framework

  • The main ValidationFramework.dll assembly works with .netcf 3.5
  • validation rules can be specified as attributes, runtime code and xml configuration. so for whatever validation you need to do, you can use a exsisting rule or you can write a new one.
    • Attributes
      • As you would expect you can specify attributes that specify one or more rules to be applied on a given field, property or (method) parameter.
    • Runtime Code
      • You could write some code to specify what rules needs to be applied to what members. This code can be invoked at the runtime. This code will use types given in ValidationFramework.Reflection namespace to get the relavant members of a given type through reflection. After which you can add validation rules to those members.
    • XML
      • Validation definitions can be defined using XML configuration. The mapping document is designed to be readable and hand-editable.
        • <?xml version=”1.0″ encoding=”utf-8″ ?> <validationMapping xmlns=”urn:validationFramework-validationDefinition-1.5″> <class typeName=”ValidationSample.Person, ValidationSample”><property name=”Name”> <rule typeName=”RequiredStringRule” initialValue=”aaaa”/> </property> <property name=”Age”> <rule typeName=”RangeRule” minimum=”18″ maximum=”80″errorMessage=”Age is invalid” /> </property> <method name=”SetTheAge”> <overloadType typeName=”System.Int32″/> <parameter name=”age”> <rule typeName=”RangeRule” minimum=”18″ maximum=”80″ errorMessage=”Age is invalid” /> </parameter> </method> </class> </validationMapping>
  • Actual validating of a object is done one of the two ways noted bellow.
    • Inside validation
      • This is when the class is aware of validation and does the validation her self. this can be done by inheriting this class from one of the provided base classes and using the inherited methods (such as NotifyValidateChange method, which validate and then do a NotifyChange as in INotifyPropertyChange interface implementations).
      • Another way of doing this is by using a FieldValidationManager or a PropertyValidationManager internally within the class.
    • Outside validation
      • When outside validation is done the class whose objects are validated doesn’t know about the validation process and does not invoke it. someone can externally use a FieldValidationManager or a PropertyValidationManager to do the validation.
  • Validation Rules can be grouped using RuleSets
  • All the Validate methods in *ValidationManagers and Validation related base classes return a ValidationResult.
  • If you decide to write your biznuess classes inheriting from a provided base class that implements IDataErrorInfoProvider interface you can use windows forms controls like ErrorProvider to display errors in windows forms projects.
  • The framework also provides types to help you implement validation in WPF and Web projects.
  • Although the framework have some documentation including the on site wiki, QuickStart projects, FAQ and a help file with documantaion for all the types and there members in the framework. There is a lack of a getting started guide.

Validation Application Block

  • Has better documentation when compared to .net Validation Framework.
  • Just as the .net Validation Framework, Validation Application Block (from here onwards reffered to as VAB) has three ways to specify validation rules or validators.
    • Attributes
    • Runtime Code
    • XML
  • “can be integrated with ASP.NET, Windows Forms, and Windows Communications Foundation (WCF).”
  • Depends on
    • Core library functionality: Microsoft.Practices.EnterpriseLibrary.Common.dll
    • The ObjectBuilder subsystem: Microsoft.Practices.ObjectBuilder.dll
  • When editing the XML configuration for the validation block you can use the provided enterprice library configuration editor(s). This configuration file can contain validation details for types.
  • Validation Rules can be grouped using RuleSets.
  • Validation is done in a manner similler to .net validation framework (or the other way around). ValidationResults class is used to send out validation results…etc
  • Has “Self Validation”. Which basically lets a class mark it self as self validatable and then when the class is validated a specified (by the class it self) method (inside the class) will be run. This method would receive a ValidatinResults type instance which should be modified with the appopriate results.
  • Self Validation and ‘normal’ validation (other validators provided by the framework) can be used together.
  • Validation of a object is done like:
    • Customer customer = new Customer(); ValidationResults results = Validation.Validate<Customer>(customer, customerRuleSetCombo.Text);
    • Or
    • Customer customer = new Customer(); Validator<Customer> validator = ValidationFactory.CreateValidator<Customer>(customerRuleSetCombo.Text); ValidationResults results = validator.Validate(customer);
  • Provides integration support for Win Forms. The main point of integration is ValidationProvider class. It is an Extender (http://msdn.microsoft.com/en-us/library/system.componentmodel.iextenderprovider.aspx) control that adds properties (at design time) to controls. So if you have a form for adding a new customer you can have a ValidationProvider component in it. And set each control on the form to use the ValidationProvider (using the extended properties on them). You can also set a property (via the SourcePropertyName extented property) name to which the value in the respective control should set to.
    • ValidationProvider class effectively lets you validate values for a given business class’s properties without actually having to have an instance of it at the time of validation.However ValidationProvider is not supported on netcf, due to the unavailability of IExtenderProvider interface.

EViL

  • Works with netcf
  • Validation rules can be specified with attributes
  • Business objects can inherit from a provided base class to get the IsValid method (which is used to validate an instance) or use EvilValidator class to do the validation.
  • Don’t have any integration helpers

Fluent Validation

  • Works with netcf
  • Can write validation rules using the builder pattern
    • RuleFor(customer => customer.Postcode).Must(BeAValidPostcode).WithMessage(“Please specify a valid postcode”);
  • Provide ASP.net MVC framework integration (although as of the time of writing the provided integration is minimal).

NHibernate Validator

  • NHibernate.Validator.dll Works with .netcf
  • Validation rules can be declared using attributes, the builder pattern (ex:- Define(x => x.Name).NotNullableAndNotEmpty();) and XML.
  • Written validators can support applying constrains to the NHibernate meta model. Hence you can use your validation rules to generate an database schema with relevant constrains.
  • “NHibernate Validator is not limited to only be used with NHibernate”.
  • “NHibernate Validator integrates with NHibernate in a native way”
  • Provides integration with
    • WinForms – through NHibernate.Validator.Binding
    • NHibernate
  • Validation is done in a similar way to validation application block.
  • framework can be configured using xml or programaticaly (fluent/builder pattern).

Spring.NET Validation Framework

  • Validation rules can be specified by XML and programmatically.
  • Have WinForms support with Spring.NET RichClient
  • RichClient provides some custom controls, which are not usable in netcf (ie: the custom controls are based on .net system.windows.forms controls).

Personally i think the Validation Application Block is the best bet. It has good documentation, features and ‘support’. But i would never know for sure. Got to use it and experience it for my self.

Create a free website or blog at WordPress.com.