Rails 3.1 beta on Ubuntu

As i have written before, i use Ubuntu for my rails development, and have been using it as my main OS last 10 months. I have been trying all the rails 3.1 beta hype and encountered a problem running 3.1 apps on my machine.

The main problem is with CoffeScript and its compiling into “real” JavaScript. So here is an easy way to enable your machine for rails 3.1. You have to install Node.js on your machine( i have tried all other Javascript runtimes with no luck). All the instructions for other platforms are listed on the project’s GitHub page, i will include only the ubuntu procedure here.


sudo apt-get install python-software-properties

sudo add-apt-repository ppa:jerome-etienne/neoip

sudo apt-get update

sudo apt-get install nodejs

And that is all, hope i have made your life easier at least a bit.

Moving to WordPress

I just moved my blog from DasBlog to WordPress. The main reason for this was the expiration of my Win hosting account, and me phasing  my development to opensource.

I used DasBlog to BlogML converter for the conversion of posts, you have to download the whole folder and then point the tool at it.

After that, I installed BlogML Importer plugin for WordPress, and used that in the import script. I’m very happy that the process worked like a charm.

Now that everything works again, I can dedicate myself to my new love, Ruby and Rails development.

Installing Rails 3 in Ubuntu 10.04

As i am exploring different languages and platforms for web development, i have encountered(a few months ago) ruby on rails. I has impressed me so much that i wanted to create a virtual development environment for it. For the base i choose Ubuntu 10.04 LTS which is a great distribution for *nix beginners. We will install everything we need for a slick and updateable ruby on rails development machine.

I will just copy/paste the script i have made, notice that git version may change.

#Install git

#   1.  First we install the dependent packages, thus you wont have to install #   the packages yourself.

sudo aptitude build-dep git-core

#   2. Download latest stable GIT release from here

wget http://kernel.org/pub/software/scm/git/git-1.7.2.tar.gz

#   3. Extract the archive and change to the extracted directory

tar xvzf git-1.7.2.tar.gz
cd git-1.7.2/

#   4. Run the following

./configure && make
sudo make install

#5. Check installation and clean up

git --version
cd ../;rm -r git-1.7.2 git-1.7.2.tar.gz

#install curl
sudo apt-get install curl

#install rvm

bash < <( curl http://rvm.beginrescueend.com/releases/rvm-install-head )

#Then add this line as the last line in your .bashrc:

if [[ -s "$HOME/.rvm/scripts/rvm" ]]  ; then source "$HOME/.rvm/scripts/rvm" ; fi

#install rvm dependencies

sudo apt-get install bison build-essential zlib1g zlib1g-dev libssl-dev     libreadline5-dev libreadline6-dev libxml2-dev git-core subversion         autoconf

#install ruby
rvm update
rvm install 1.9.2
rvm 1.9.2 --default
#test ruby version
ruby -v
# install rails 3.0.4
gem install rails

gem update --system
gem update

This is for a single user installation, like you would have at your home/work computer, for a server installation, you should install rvm as superuser so it will install rvm into /user/local/rvm

EDIT: There is an easier way to do this, as described on: Rails Ready

It is an automated script that does all of this for you

Moving oracle tables with lob columns to another tablespace

I have encountered a problem with oracle database that it does not reuse lob data. So, if you have 5000 rows of some lob data, and you delete them from the table, then insert the same 5000 rows, you will have 10000 rows of consumed space. That could be done easily with shrinking the table but the default tablespace segment space management (SSM) on oracle 10g is manual, so it does not allow row movement and table shrinking.

First, you create a tablespace with ASSM, that is automatic segment space management:

CREATE TABLESPACE NEW_TABLESPACE DATAFILE
'/home/oracle/product/10.2.0/db_1/dbs/new_tablespace.dbf' SIZE 16109M AUTOEXTEND ON NEXT
1000M MAXSIZE UNLIMITED
LOGGING
ONLINE
PERMANENT
EXTENT MANAGEMENT LOCAL AUTOALLOCATE
BLOCKSIZE 8K
SEGMENT SPACE MANAGEMENT AUTO
FLASHBACK ON;

Now we can proceed with table movement and after that lob_segment movement. There are some steps we should follow:

  1. Move table
  2. Rebuild indexes (and move them to the new tablespace if you wish so)
  3. Move the lob segment
  4. Enable row movement
  5. Shrink the table and lob segment

Here is the sql needed, of course, you will need to change and/or add indexes that reside on the current table.

--moving the table to the new tablespace
alter table table_name move tablespace new_tablespace;

--rebuilding the index(es) and moving them to the new tablespace
alter index index_name rebuild tablespace new_tablespace;

--moving the lobsegment(s) to the new tablespace
alter table table_name move lob (lob_column) store as
(tablespace new_tablespace);

--shrinking the table and lobsegment
alter table table_name enable row movement;
alter table table_name shrink space cascade;
alter table table_name modify lob (lob_column) (shrink space);

Table and the lob segment will shrink during migration, but just in case you need further space shrinkage i have included the scripts needed.

Datediff function in Oracle

As i am working on Oracle database at my day job, i have found something that is by default on sqlserver but not in oracle. That is the datediff function that given the input of two dates and an identifier like day, month or year returns integer with the requested number.

So to cut the long story short, i have written my own datediff function for oracle use. You can request more return types in the comments, and i will be glad to add them. Here is the code:

create or replace function datediff(v_type VARCHAR2, date_from DATE, date_to DATE) return integer as
v_diff INTEGER;
begin
v_diff :=
  case upper(v_type)
    when 'MONTH' then
      months_between(date_to, date_from)
    when 'DAY' then
      date_to - date_from
    when 'YEAR' then
      trunc(months_between(date_to, date_from)/12)
    when 'HH' then
    (date_to - date_from) * 24
    when 'MM' then
    (date_to - date_from) * 24 * 60
    when 'SS' then
    (date_to - date_from) * 24 * 60 * 60
  end;
return abs(v_diff);
end;

As you can see, the type parameters are: MONTH for difference in months, DAY for difference in days and YEAR for difference in years respectively.

I hope oracle will see the light and include this function in any of the future releases.

UPDATE: As my friend LILkillaBEE has mentioned that he could be in a need of hour/minute/second difference, i have added that too, so, this should be the final implementation.

New parameters are HH for hour, MM for minute and SS for seconds difference.

Sending an SMS message using .NET CF on Win Mobile

My best man asked me a few months ago to create him an app that would allow him to send a predefined sms to a predefined number on a click of a button using his Win Mobile phone. I thought about it and decided to write this application for him.

First thing that we need to do is to create a Smart Device project, and choose device application from the next page. In my solution i have one form called Sender and a Program.cs file, this is only the basics so we will not need anything more.

As you can see from the previous picture, the user interface is very intuitive and plain. We have two textboxes and a button that sends the SMS. This part of the application is completely working and can be used to send SMS from your Win Mobile phone.

For sending the SMS message we need only the code below, and of course the call from the Send button

using Microsoft.WindowsMobile.PocketOutlook;
public static void SendSms(string recipientNumber, string messageText)
{
try
{
var sms = new SmsMessage()
{
Body = messageText
};
sms.To.Add(new Recipient(recipientNumber));
sms.Send();
MessageBox.Show("Message sent!");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

To fire up the sending from a command line(that was the original idea if you remember, he wanted to be able to send it on a click of a button) we need to handle some command line arguments. My idea was to call the program the same way we have called the method that send the message first the recipient number, and then the message. calling the program without arguments would open the form, any other number of arguments will show a message with the correct way of doing it.

[MTAThread]
static void Main(string[] args)
{
switch (args.Length)
{
case 0:
Application.Run(new Sender());
break;
case 2:
Sender.SendSms(args[0],args[1]);
break;
default:
MessageBox.Show("Wrong number of arguments entered. Correct order is RecipientNumber \"SmsText in quotes\"");
break;
}
}

We can also do a regular expression check depending on the numbers we allow the user to send the SMS to, if we want to limit the user in any way, because i know my only user, i believe i can trust him 🙂

Next thing you need is to set up a shortcut that calls the application using the parameters and bind the shortcut to a button on your device. Quick way to pay tram fare when the conductor enters the tram and you just forgot to buy the ticket that day.

Allow only one instance of MDI child in your VB.NET MDI application

I have encountered a problem in class today, we needed our Contact Manager application only to run one instance of every MDI child form, so the user will not be able to start unlimited(more than 1) number of Contacts form, or any of the settings forms. I have binged the solution and found a piece of code that allows something like that, but as i am teaching VB.NET here, i had to rewrite it from C# to VB.NET. The original C# Code provided by Roy Osherove is HERE
Here is the VB.NET code i have rewritten from Roy’s version:

Imports System
Imports System.Windows.Forms
Imports System.Collections.Specialized
Public Class MdiFormLoader
    Private m_InitializedForms As HybridDictionary = New HybridDictionary()
    Public Sub LoadFormType(ByVal formType As Type, ByVal mdiParentForm As Form)
        If (IsAlreadyLoaded(formType)) Then
            Return
        End If
        FlagAsLoaded(formType)
        Dim frm As Form = Activator.CreateInstance(formType)
        frm.MdiParent = mdiParentForm
        AddHandler frm.Closed, New EventHandler(AddressOf FormClosed)
        frm.Show()
    End Sub
    Private Sub FlagAsLoaded(ByVal formType As Type)
        m_InitializedForms(formType.Name) = True
    End Sub
    Private Sub FlagAsNotLoaded(ByVal formType As Type)
        m_InitializedForms(formType.Name) = False
    End Sub
    Private Function IsAlreadyLoaded(ByVal formType As Type) As Boolean
        Return If(m_InitializedForms(formType.Name), m_InitializedForms(formType.Name) = True)
    End Function
    Private Sub FormClosed(ByVal sender As Object, ByVal e As EventArgs)
        Dim closingForm As Form = sender
        RemoveHandler closingForm.Closed, New EventHandler(AddressOf FormClosed)
        FlagAsNotLoaded(sender.GetType())
    End Sub
End Class

You can call your form by using these 2 lines:

Dim _formLoader As New MdiFormLoader()
_formLoader.LoadFormType(GetType(ContactsMain), Me)

Creating ASP.NET MVC application against Oracle database pt. 1

This is a first in a series of posts, as i will try to build ASP.NET MVC application against Oracle XE database, but this example can be used for any Oracle database greater than 9i.

I will try to use Oracle ODAC.net the latest version that i can get from the Oracle Site.

With a little help from LILkillaBEE i created generic helpers that return IEnumerable<T> on which i can use LINQ and play with it.

First thing first, as i am creating a Contact manager application part by part, the first functionality i want to implement is getting the data from the Oracle XE database and working with it in MVC way. So i have created the table with personal data only in it.

CREATE TABLE  PEOPLE
   (
    PERSON_ID NUMBER NOT NULL ENABLE,
    NAME VARCHAR2(100) NOT NULL  ENABLE,
    SURNAME VARCHAR2(100) NOT NULL ENABLE,
    ADDRESS_LINE1  VARCHAR2(100) NOT  NULL ENABLE,
    ADDRESS_LINE2 VARCHAR2(100),
    ZIP_CODE  VARCHAR2(100) NOT  NULL ENABLE,
    CITY VARCHAR2(100) NOT NULL  ENABLE,
    COUNTRY VARCHAR2(100) NOT NULL ENABLE,
     CONSTRAINT PEOPLE_PK PRIMARY KEY  (PERSON_ID) ENABLE
   );

CREATE OR REPLACE TRIGGER  BI_PEOPLE
  before insert on PEOPLE
  for  each row
begin
    select PEOPLE_SEQ.nextval into  :NEW.PERSON_ID from  dual;
end;

ALTER TRIGGER  BI_PEOPLE ENABLE;

After this, i have created the Person class in my project

public class Person
{
    public virtual int PersonID { get; set; }
    public virtual string FirstName { get; set; }
    public virtual string LastName { get; set; }
    public virtual string AddressLine1 { get; set; }
    public virtual string AddressLine2 { get; set; }
    public virtual string ZipCode { get; set; }
    public virtual string City { get; set; }
    public virtual string Country { get; set; }
}

And an interface that i will implement later in my repository

interface IPersonInterface
{
    IEnumerable&lt;Person&gt; GetAll();
    Person GetById(int id);
    void Add(Person person);
    void Delete(int id);
}

EDIT: After considering to finish this tutorial i finally gave up because there is no easy way of doing this and i kept hitting the wall a few times.

How to get directory contents in C#

I am creating a backup application and have to get the list of files in some directory here is the simple way to do it. If you only need contents of one directory you can use this code, i output it to System.Console just as an example, you can catch everything in string[] or whatever collection you prefer for your application. You only need using System.IO for this example:

static void GetDirContents(string sDir)
       {
           try
            {
        foreach (string d in Directory.GetDirectories(sDir))
             {
                DirectoryInfo dirInfo = new DirectoryInfo(d);
                  Console.WriteLine("[DIR] " + dirInfo.Name);
                  foreach (string f in Directory.GetFiles(d))
                    {
                         FileInfo fInfo = new FileInfo(f);
                     Console.WriteLine("\t" + fInfo.Name);
                    }
              }
         }
             catch (Exception sex)
              {
                 Console.WriteLine(sex.Message);
             }
         }

If you are in need to do this recursively for all sub directories you just call the void after file writing for loop

static void GetDirContents(string sDir)
         {
             try
            {
                 foreach (string d in Directory.GetDirectories(sDir))
               {
                   DirectoryInfo dirInfo = new DirectoryInfo(d);
                     Console.WriteLine("[DIR] " + dirInfo.Name);
                     foreach (string f in Directory.GetFiles(d))
                 {
                    FileInfo fInfo = new FileInfo(f);
                    Console.WriteLine("\t" + fInfo.Name);
                   }
                    GetDirContents(d);
                }
           }
           catch (Exception sex)
          {
              Console.WriteLine(sex.Message);
          }
         }

See you soon with next example.