Showing posts with label How-To. Show all posts
Showing posts with label How-To. Show all posts

Saturday, June 25, 2011

My site's style, how-to

Someone asked how I accomplish the styling on my blog. Without further ado, head to Alex Gorbatchev's syntax highlighter

Since I'm using the <pre /> method, I have to HTML-encode my code before I post it in my blog, for that I created the following ASP.NET MVC utility:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace HtmlEncoder.Controllers
{
    
    [ValidateInput(false)]
    public class HomeController : Controller
    {
        public ActionResult Index(string Encode = "")
        {
            ViewData["Encode"] = Encode;
            return View();
        }

    }
}

Note the use of ValidateInput(false), if you don't put that attribute, ASP.NET MVC will be in paranoid mode, anytime it encounters tags from user input, it will refuse to continue doing anything to prevent cross-site scripting.

And this will be your code in view:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<dynamic>"   %>



<% using(var c = Html.BeginForm()) { %>

    Paste your code here:
    
    <p><%: Html.TextArea("Encode", new { cols = 120, rows = 12 }) %></p>
        
    <p><input type="submit" value="Encode"/></p>



    Copy the following HTML-encoded code:


    <% string s = Html.Encode(Request["Encode"]); %>
    <p><%: Html.TextArea("Output", s, new { cols = 120, rows = 12 } ) %></p>


<% } %>

I wrote that code(using WebForm tags) prior to Razor support in ASP.NET MVC, and that's the only currently supported in ASP.NET MVC on Mono, I'm on Mac OS X now.

For console-like output, example:

Example

I'm using the following css style:
<style type='text/css'>
.console {
background-color: black;
color: #00FF00;
font-family: courier;
}</style>

And to use full-screen content on blogger, disable the content-outer class in your blog's content, the easiest way to do it is to change the <div class='content-outer'> to <div class='x_content-outer'>

Lastly, if you don't want to include the namespace when copying code or you just want to paste the only relevant code to your blog(good also for pasting code to stackoverflow), use block highlighting, if you are in Visual Studio, hold Alt then start highlighting the indented code of your class; on MonoDevelop on Mac, hold the command button, unfortunately this doesn't work well, it can only highlight up to the last column only, and unfortunately, most of the last line of the code you are copying is a single character only, i.e. the curly bracket }

Thursday, December 23, 2010

Date functions

Michael-Buens-MacBook:~ Michael$ cal 2010
                             2010

      January               February               March
Su Mo Tu We Th Fr Sa  Su Mo Tu We Th Fr Sa  Su Mo Tu We Th Fr Sa
                1  2      1  2  3  4  5  6      1  2  3  4  5  6
 3  4  5  6  7  8  9   7  8  9 10 11 12 13   7  8  9 10 11 12 13
10 11 12 13 14 15 16  14 15 16 17 18 19 20  14 15 16 17 18 19 20
17 18 19 20 21 22 23  21 22 23 24 25 26 27  21 22 23 24 25 26 27
24 25 26 27 28 29 30  28                    28 29 30 31
31                                          
       April                  May                   June
Su Mo Tu We Th Fr Sa  Su Mo Tu We Th Fr Sa  Su Mo Tu We Th Fr Sa
             1  2  3                     1         1  2  3  4  5
 4  5  6  7  8  9 10   2  3  4  5  6  7  8   6  7  8  9 10 11 12
11 12 13 14 15 16 17   9 10 11 12 13 14 15  13 14 15 16 17 18 19
18 19 20 21 22 23 24  16 17 18 19 20 21 22  20 21 22 23 24 25 26
25 26 27 28 29 30     23 24 25 26 27 28 29  27 28 29 30
                      30 31                 
        July                 August              September
Su Mo Tu We Th Fr Sa  Su Mo Tu We Th Fr Sa  Su Mo Tu We Th Fr Sa
             1  2  3   1  2  3  4  5  6  7            1  2  3  4
 4  5  6  7  8  9 10   8  9 10 11 12 13 14   5  6  7  8  9 10 11
11 12 13 14 15 16 17  15 16 17 18 19 20 21  12 13 14 15 16 17 18
18 19 20 21 22 23 24  22 23 24 25 26 27 28  19 20 21 22 23 24 25
25 26 27 28 29 30 31  29 30 31              26 27 28 29 30
                                            
      October               November              December
Su Mo Tu We Th Fr Sa  Su Mo Tu We Th Fr Sa  Su Mo Tu We Th Fr Sa
                1  2      1  2  3  4  5  6            1  2  3  4
 3  4  5  6  7  8  9   7  8  9 10 11 12 13   5  6  7  8  9 10 11
10 11 12 13 14 15 16  14 15 16 17 18 19 20  12 13 14 15 16 17 18
17 18 19 20 21 22 23  21 22 23 24 25 26 27  19 20 21 22 23 24 25
24 25 26 27 28 29 30  28 29 30              26 27 28 29 30 31
31                                          


Months' first Mondays...
#
    base_date    | month_first_monday 
-----------------+--------------------
 Jan 01 2010 Fri | Jan 04 2010 Mon
 Feb 01 2010 Mon | Feb 01 2010 Mon
 Mar 01 2010 Mon | Mar 01 2010 Mon
 Apr 01 2010 Thu | Apr 05 2010 Mon
 May 01 2010 Sat | May 03 2010 Mon
 Jun 01 2010 Tue | Jun 07 2010 Mon
 Jul 01 2010 Thu | Jul 05 2010 Mon
 Aug 01 2010 Sun | Aug 02 2010 Mon
 Sep 01 2010 Wed | Sep 06 2010 Mon
 Oct 01 2010 Fri | Oct 04 2010 Mon
 Nov 01 2010 Mon | Nov 01 2010 Mon
 Dec 01 2010 Wed | Dec 06 2010 Mon
(12 rows)

...query (month_beginning_dow):

select to_char(z.d, 'Mon dd yyyy Dy') as base_date, 

    to_char( month_beginning_dow(extract(year from z.d)::int, 
        extract(month from z.d)::int, 1), 'Mon dd yyyy Dy') 
            as month_first_monday
from
(
     select 'Jan 1 2010'::date + (interval '1' month * x.n) as d
     from generate_series(0,11) as x(n)
) as z

Months' last Sundays...
#
    base_date    | month_last_date | month_last_sunday 
-----------------+-----------------+-------------------
 Jan 01 2010 Fri | Jan 31 2010 Sun | Jan 31 2010 Sun
 Feb 01 2010 Mon | Feb 28 2010 Sun | Feb 28 2010 Sun
 Mar 01 2010 Mon | Mar 31 2010 Wed | Mar 28 2010 Sun
 Apr 01 2010 Thu | Apr 30 2010 Fri | Apr 25 2010 Sun
 May 01 2010 Sat | May 31 2010 Mon | May 30 2010 Sun
 Jun 01 2010 Tue | Jun 30 2010 Wed | Jun 27 2010 Sun
 Jul 01 2010 Thu | Jul 31 2010 Sat | Jul 25 2010 Sun
 Aug 01 2010 Sun | Aug 31 2010 Tue | Aug 29 2010 Sun
 Sep 01 2010 Wed | Sep 30 2010 Thu | Sep 26 2010 Sun
 Oct 01 2010 Fri | Oct 31 2010 Sun | Oct 31 2010 Sun
 Nov 01 2010 Mon | Nov 30 2010 Tue | Nov 28 2010 Sun
 Dec 01 2010 Wed | Dec 31 2010 Fri | Dec 26 2010 Sun
(12 rows)

...query:
select to_char(z.d, 'Mon dd yyyy Dy') as base_date,
to_char(month_last_date(extract(year from z.d)::int, 
    extract(month from z.d)::int), 'Mon dd yyyy Dy') 
        as month_last_date,
to_char( month_ending_dow(extract(year from z.d)::int, 
    extract(month from z.d)::int, 0), 'Mon dd yyyy Dy') 
        as month_last_sunday       
from
(
     select 'Jan 1 2010'::date + (interval '1' month * x.n) as d
     from generate_series(0,11) as x(n)
) as z

Date library:
CREATE FUNCTION month_last_date(_year integer, _month integer)
  RETURNS date AS
$$
 select (($1 || '-' || $2 || '-1')::date + interval '1' month)::date - 1;
$$
  LANGUAGE sql immutable;



-- this function and the next function, has nice symmetry to each other
CREATE FUNCTION date_next_dow(_base_date date, _dow integer)
  RETURNS date AS
$$
 select
  case when extract(dow from $1) <= $2 then
   $1 + ($2 - (extract(dow from $1)::int))
  else
   $1 + ($2 - (extract(dow from $1)::int)) + 7
  end 
$$
  LANGUAGE sql immutable;


CREATE FUNCTION date_previous_dow(_base_date date, _dow integer)
  RETURNS date AS
$$
 select
  case when $2 <= extract(dow from $1) then
   $1 + ($2 - (extract(dow from $1)::int))
  else
   $1 + ($2 - (extract(dow from $1)::int)) - 7
  end;
$$
  LANGUAGE sql immutable;  



CREATE FUNCTION month_beginning_dow(_year integer, _month integer, _dow integer)
  RETURNS date AS
$$
 select date_next_dow( ($1 || '-' || $2 || '-1')::date, $3);
  
$$
  LANGUAGE sql immutable;


CREATE FUNCTION month_ending_dow(_year integer, _month integer, _dow integer)
  RETURNS date AS
$$
 select date_previous_dow( month_last_date( $1, $2 ), $3);
$$
  LANGUAGE sql immutable;




Other usage, next Friday...

#
    base_date    |   next_friday   
-----------------+-----------------
 Nov 05 2010 Fri | Nov 05 2010 Fri
 Nov 06 2010 Sat | Nov 12 2010 Fri
 Nov 07 2010 Sun | Nov 12 2010 Fri
 Nov 08 2010 Mon | Nov 12 2010 Fri
 Nov 09 2010 Tue | Nov 12 2010 Fri
 Nov 10 2010 Wed | Nov 12 2010 Fri
 Nov 11 2010 Thu | Nov 12 2010 Fri
 Nov 12 2010 Fri | Nov 12 2010 Fri
 Nov 13 2010 Sat | Nov 19 2010 Fri
 Nov 14 2010 Sun | Nov 19 2010 Fri
 Nov 15 2010 Mon | Nov 19 2010 Fri
 Nov 16 2010 Tue | Nov 19 2010 Fri
 Nov 17 2010 Wed | Nov 19 2010 Fri
 Nov 18 2010 Thu | Nov 19 2010 Fri
 Nov 19 2010 Fri | Nov 19 2010 Fri
 Nov 20 2010 Sat | Nov 26 2010 Fri
 Nov 21 2010 Sun | Nov 26 2010 Fri
 Nov 22 2010 Mon | Nov 26 2010 Fri
(18 rows)

..., query:

select to_char(z.d, 'Mon dd yyyy Dy') as base_date, 
       to_char( date_next_dow(z.d, 5), 'Mon dd yyyy Dy') as next_friday
from
(
     select 'Nov 5 2010'::date + x.n as d
     from generate_series(0,17) as x(n)
) as z

Previous Saturday...
#
    base_date    |  previous_saturday  
-----------------+-------------------
 Nov 05 2010 Fri | Oct 30 2010 Sat
 Nov 06 2010 Sat | Nov 06 2010 Sat
 Nov 07 2010 Sun | Nov 06 2010 Sat
 Nov 08 2010 Mon | Nov 06 2010 Sat
 Nov 09 2010 Tue | Nov 06 2010 Sat
 Nov 10 2010 Wed | Nov 06 2010 Sat
 Nov 11 2010 Thu | Nov 06 2010 Sat
 Nov 12 2010 Fri | Nov 06 2010 Sat
 Nov 13 2010 Sat | Nov 13 2010 Sat
 Nov 14 2010 Sun | Nov 13 2010 Sat
 Nov 15 2010 Mon | Nov 13 2010 Sat
 Nov 16 2010 Tue | Nov 13 2010 Sat
 Nov 17 2010 Wed | Nov 13 2010 Sat
 Nov 18 2010 Thu | Nov 13 2010 Sat
 Nov 19 2010 Fri | Nov 13 2010 Sat
 Nov 20 2010 Sat | Nov 20 2010 Sat
 Nov 21 2010 Sun | Nov 20 2010 Sat
 Nov 22 2010 Mon | Nov 20 2010 Sat
(18 rows)

...query:

select to_char(z.d, 'Mon dd yyyy Dy') as base_date, 
       to_char( date_previous_dow(z.d, 6), 'Mon dd yyyy Dy') 
           as previous_saturday
from
(
     select 'Nov 5 2010'::date + x.n as d
     from generate_series(0,17) as x(n)
) as z


Happy new year folks!

Related to: Finding previous day of the week

Saturday, December 11, 2010

Rule #1 and Rule #2

Simple guide to deciphering query's rows relationship.

How can one know that B is one-to-one to A, or if B is many-to-one to A?

SELECT *
FROM A
JOIN B ON B.FieldNameHere = A.FieldNameHere

Two simple rules:

  1. If the first table's primary key don't appear on second table's join condition, the second table is one-to-one to first table.
  2. If the first table's primary key appear on second table's join condition, the second table is many-to-one to first table.



How one knows which field is the primary key?
They are easy to remember, there are only two(or three) variations of them, namely: Id, EntityId, Entity_Id; other variations are not encouraged.


Rule #1 If the first table's primary key don't appear on second table's join condition, the second table is one-to-one to first table. The second table will always return one row at most to first table. There's only one birth country to a person. Example:

SELECT * 
FROM Person
JOIN Country ON Country.CountryId = Person.BirthCountryId

Rule #2 If the first table's primary key appear on second table's join condition, the second table is many-to-one to first table. The second table will return zero or more rows to first table. Example:

SELECT * 
FROM Person
JOIN Bid ON Bid.PersonId = Person.PersonId


Would this technique still work on reverse query? Yeah it would, check this:

SELECT * 
FROM Bid
JOIN Person ON Person.PersonId = Bid.PersonId 

The first table's primary key don't appear on second table's join condition; so, second table is one-to-one to first table. One given bid always belong to one person only.


How about this?

SELECT * 
FROM Country
JOIN Person ON Person.BirthCountryId = Country.CountryId

The first table's primary key appears on second table's join condition, falls under rule #2, it means the second table is many-to-one to first table. There could be zero or more persons that was born on that country.

It would also.

Apparently there's some exceptions to this two rules, check this: http://www.ienablemuch.com/2010/12/exceptions-to-rule-1-and-rule-2-one-to.html

Thursday, November 18, 2010

Simple sample for loading parent child records on NHibernate

Object-Relational:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate.Cfg;
using System.Reflection;
using NHibernate;
using System.Threading;

namespace TestTwoTable
{
    class Program
    {
        static void Main(string[] args)
        {
                                
            if(1 == 1)
            {
                IList<Phone> phones = PhoneList();
    
    
                foreach(Phone p in phones)
                {                                        
                    Console.WriteLine("Phone {0}", p.PhoneNumber);
                    
                    
                    // Try to comment/uncomment Console.WriteLines so you can 
                    // verify that NHibernate indeed lazy loads related parent record,
                    // check your RDBMS log query(s) timestamps to verify that.
                    // 
                    // When using Postgresql on Linux, the log file is in /opt/Postgresql/9.0/data/pg_log
                    // On Mac it is in /Library/PostgreSQL/9.0/data/pg_log
                    // On Windows it is in C:\Program Files (x86)\PostgreSQL\9.0\data\pg_log                                    
                    Console.WriteLine("Owned by {0}", p.Kontact.ContactName);

                    
                    // With lazy loading, the p.Kontact's Phones will not be queried unnecessarily.
                    // The p.Kontact's Phones will only be queried from database when you access it.
                    // Try to comment/uncomment the following code and see that effect in your RDBMS log file.                    .
                    /*
                    foreach(Phone p in p.Kontact.Phones)
                    {
                        Console.WriteLine("Contact's phone {0}", p.PhoneNumber);
                    }*/
                    
                }                                
            }
            
            Console.WriteLine("*****");
            
            if(1 == 1)
            {
                IList<Contact> contacts = ContactList();
    
                foreach(Contact c in contacts)
                {                    
                    Console.WriteLine("\nContact {0}'s Phone(s): ", c.ContactName);                    
                    
                    // With lazy loading, the c's Phones will not be queried unnecessarily.
                    // The c's Phones will only be queried from database when you access it.
                    // Try to comment/uncomment the following code and see that effect in your RDBMS log file                    .
                    foreach(Phone p in c.Phones)
                    {
                        Console.WriteLine("Phone {0}", p.PhoneNumber);
                    }
                    
                    
                }
            }
            
            
        }

        static ISession OpenSession()
        {
            var c = new Configuration();
            c.AddAssembly(Assembly.GetCallingAssembly());
            ISessionFactory f = c.BuildSessionFactory();
            return f.OpenSession();
        }

        static IList<Phone> PhoneList()
        {
            ISession session = OpenSession();
        
            IQuery query = session.CreateQuery("from Phone p where p.Kontact.ContactName = :_contact_name");
            query.SetParameter("_contact_name", "lennon");
            
            IList<Phone> contacts = query.List<Phone>();

            return contacts;

        
        }
        
        static IList<Contact> ContactList()
        {
            ISession session = OpenSession();

            IQuery query = session.CreateQuery("from Contact");
            
            IList<Contact> contacts = query.List<Contact>();
            
            return contacts;
        }
 
    }

    public class Contact
    {
        public virtual int ContactId { get; set; }
        public virtual string ContactName { get; set; }
        
        public virtual IList<Phone> Phones { get; set; }
        

    }

    public class Phone
    {        
        public virtual Contact Kontact { get; set; }
        public virtual int PhoneId { set; get; }
        public virtual string PhoneNumber { get; set; }
    }


}


Mapping:

<?xml version="1.0" encoding="utf-8" ?>

<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" auto-import="true" assembly="TestTwoTable" namespace="TestTwoTable">

  <class name="Contact" table="contact">
    <id name="ContactId" column="contact_id">
      <generator class="sequence">
        <param name="sequence">contact_contact_id_seq</param>
      </generator>
    </id>

    <property name="ContactName" column="contact_name"/>
    
    <bag name="Phones" inverse="true">
        <key column="contact_id"/>
        <one-to-many class="Phone"/>
    </bag>

  </class>

  <class name="Phone" table="phone">
    <id name="PhoneId" column="phone_id">
      <generator class="sequence">
        <param name="sequence">phone_phone_id_seq</param>
      </generator>
    </id>

    <property name="PhoneNumber" column="phone_number"/>
    
    <many-to-one name="Kontact" column="contact_id" class="Contact" not-null="true"/>
    
  </class>
  
</hibernate-mapping>

The Database:

CREATE TABLE contact
(
  contact_id serial NOT NULL,
  contact_name text NOT NULL,
  CONSTRAINT contact_pkey PRIMARY KEY (contact_id)
);

CREATE TABLE phone
(
  contact_id integer NOT NULL,
  phone_id serial NOT NULL,
  phone_number text NOT NULL,
  CONSTRAINT phone_pkey PRIMARY KEY (phone_id),
  CONSTRAINT fk_phone__contact FOREIGN KEY (contact_id)
      REFERENCES contact (contact_id)
);


insert into contact(contact_name) values('lennon'),('mccartney');
insert into phone(contact_id, phone_number) values(1,'number nine'),(1,'number 10'),(2,'you know my name, look up the number');


Output:
Phone number nine
Owned by lennon
Phone number 10
Owned by lennon
*****

Contact lennon's Phone(s): 
Phone number nine
Phone number 10

Contact mccartney's Phone(s): 
Phone you know my name, look up the number

Monday, October 25, 2010

ASP.NET on Mac OS X Snow Leopard at one fell swoop using mod_mono

Enable Apache first by ticking the checkbox for Web Sharing(System Preferences > Sharing > Web Sharing)




Type 127.0.0.1 in browser's address bar, then it should show:




Install gettext first: https://gist.github.com/1647940


Install Mono, get it at: http://www.go-mono.com/mono-downloads/download.html

Verify on Terminal if you have installed Mono...

mono -V

...should show this:
Mono JIT compiler version 2.10.9 (tarball Mon May  7 20:25:51 EDT 2012)
Copyright (C) 2002-2011 Novell, Inc, Xamarin, Inc and Contributors. www.mono-project.com
 TLS:           normal
 SIGSEGV:       normal
 Notification:  kqueue
 Architecture:  x86
 Disabled:      none
 Misc:          debugger softdebug 
 LLVM:          yes(2.9svn-mono)
 GC:            Included Boehm (with typed GC)


Paste this in your terminal(the next swoop will still have the effect of sudo(i.e. no need to re-enter password)) :
sudo mv /Library/WebServer/Documents/index.html.en /Library/WebServer/Documents/x_index.html.en

And this(so that makes it two swoop ;-)) :
mkdir ~/swoop
cd ~/swoop
sudo ln -s /Library/Frameworks/Mono.framework/Commands/pkg-config /usr/bin/pkg-config
curl -O http://origin-download.mono-project.com/sources/mono/mono-2.10.9.tar.bz2
tar xzf mono-2.10.9.tar.bz2
cd mono-2.10.9
./configure
make 
sudo make install
sudo sh -c "echo '\n\nInclude /etc/apache2/mod_mono.conf' >> /etc/apache2/httpd.conf"
echo "<center><img src='PoweredByMacOSXLarge.gif'><br><% int a = 7 * 6;%><%=a%> <%=new System.Random().Next()%></center>" > /Library/WebServer/Documents/index.aspx 
sudo /usr/sbin/apachectl restart
echo 'Done'


Then refresh the 127.0.0.1 in your browser, you shall be able to see the the answer to life, the universe and everything




This is the how-to video ...