Thursday, March 14, 2013

Object Relational Database Features Implemented with Oracle

Oracle is a modern and feature-full database that supports many features of an object relational database system. Oracle supports type definition, type inheritance, collection type, member function, nested table, association and aggregation relationships. In this article, I have implemented all features other than association and aggregation relationships.

1. Database Structure
I have considered a database for a simple ecommerce site. The database will consist of different type of products having a bunch of attributes inherited from Products table whereas each table will have some other attributes of its own. So here I have a product object and a Clothes table that inherits the product object. Each clothe is available in multiple sizes. Further, each clothe tuple is available in multiple colors represented by a collection array in this example. For simplicity, I have included only one such table that inherits from products table where there could be other tables like Jewellery, Bags, Cosmetics and so on. Further, each product has multiple categories which is implemented by a nested category table. In our example, we charger 10% extra on the price of each product. Hence I have used a member function that returns 10% extra of the price.

2. Object Relational Structure
Product is an object, not the table, from which another object or type ClotheType is inherited. Product also contains a nested table Category so that each product row contains a reference to an instance of the table Category. Finally we create a table Clothes of the type ClotheType. ClotheType consists of two attributes: clothesize and clothecolor where clothesize is another Type and clothecolor is a collection array.

The object oriented concept of function has been included in ClotheType object which we call member function in Oracle.

3. DDL Script for the Database Objects

Create a type CategoryType
Create or replace type CategoryType as object(
categoryid int,
categoryname varchar2(50)
) not final

Create a table of CategoryType
Create or replace type ProductCategory as Table of CategoryType

Create an inheritable (specified by "not final" construct) object Product
Create or replace type Product as object(
productid int,
productname varchar2(100),
price number(7,2)
) not final

Create type ProductSize
Create or replace type ProductSize as object(
sizecode varchar2(20),
sizevalue varchar2(20)
)

Create collection array for colors
create or replace type ColorArray as varray(20) of varchar2(20)

Create a type ClotheType that inherits from Product
Create or replace type ClotheType under Products(
clothesize productsize,
clothecolor colorarray,
clothecategory productcategory,
member function total_price return number
)

--define the body for the member function total_price
create or replace type body ClotheType as
 member function  total_price return number is
 begin
                 return (price + price * 0.1);  
 end;
end;

Finally create a table of the type ClotheType
create or replace table Clothes of clothetype
nested table clothecategory store as prod_cat

4. Inserting rows into the Clothes table
Now we insert rows into the Clothes table.
  
   insert into clothes
   values(3,'V-neck tshirts with full sleeve',250,
   productsize('M','Medium'),
   colorarray('White','Blue','Black'),
          productcategory(categorytype('1','T-Shirts'),
                     categorytype('2','Men''s Wears')
   )
      );
   
   insert into clothes
   values(2,'Round-neck tshirts',450,
   productsize('L','Large'),colorarray('Red','Black','Green'),
          productcategory(categorytype('1','T-Shirts'),
                     categorytype('2','Men''s Wears')
      )
      );
     
   insert into clothes
   values(1,'Both side design tshirts',600,
   productsize('S','Small'),colorarray('Red','Blue','Black'),
             productcategory(categorytype('1','T-Shirts'),
                     categorytype('2','Men''s Wears')
      )
      );    
5. Querying the table Clothes
a. Normal query to select the columns productid, productname, pirce and productsize's columns sizecode and sizevalue

select c.productid,c.productname,c.price,
 c.clothesize.sizecode,c.clothesize.sizevalue
from clothes c

select from a table in object relational database Oracle


b. Querying the categories in a product from the nested table clothecategory

select c.productid,c.productname,p.categoryid,p.categoryname
 from clothes c,table(c.clothecategory) p
where c.productid=1;

select c.productid,c.productname,p.categoryid,p.categoryname
 from clothes c,table(c.clothecategory) p
where c.productid=2;

select from nested table in object relational database Oracle


c. Querying the colors associated with a product

select c.productid, c.productname,p.*
 from clothes c, table(c.clothecolor) p
where c.productid=2;

select from collection array in object relational database Oracle


d. Querying the total price by calling the member function total_price

select p.productid, p.productname,p.price,p.total_price() "Total Price"
 from clothes p;

select using member function in object relational database Oracle


6.Conclusion
we realized and implemented a bunch of object relational features of Oracle database. Some of the features we worked with were type inheritance, type as a column, datatype collection and nested table, as well as member function. We developed DDL script to create such objects and performed select queries. All in all, we got the good glimspe of object oriented programming in Oralce database.

Tuesday, February 19, 2013

Add clickable rows in csharp DataTable and bind to asp.net gridview

Responding to a good demand from a lot of readers, I have now presented a way to create DataTable programmatically where rows accept html and hence they can be made clickable. Complementing to my previous post on creating DataTable programmatically in asp.net, this tips will bind DataTable to an asp.net GridView where one of the columns in each row contains clickable html anchor.

Below is the code snippet in C#.

protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            //get data from programmatically created DataTable and bind to GridView
            gvTable.DataSource = CreateTable();
            gvTable.DataBind();
        }
    }


//Create DataTable programmatically
    //In this example, there are three columns
    //namely ID, WebsiteName and URL
    private DataTable CreateTable()
    {
        //create datatable
        DataTable table = new DataTable("Websites");
        
        //add columns to the table
        table.Columns.Add("ID", typeof(int));
        table.Columns.Add("WebsiteName", typeof(string));
        table.Columns.Add("URL", typeof(string));
        //add as many rows as you want
        AddNewRow(1, "dotnetspidor", "http://dotnetspidor.blogspot.com", table);
        AddNewRow(1, "asp.net", "http://asp.net", table);
        AddNewRow(1, "codeplex", "http://codeplex.com", table);
        return table;
    }


//Add new row to a table
    private void AddNewRow(int id,string website, string url,DataTable table)
    {
        DataRow row = table.NewRow();
        row["ID"] = id;
        row["WebsiteName"] = website;
        //get url from GetURL method
        string link = GetURL(website, url);
        row["URL"] = HttpUtility.HtmlDecode(link);
        table.Rows.Add(row);
    }


//create html anchor from website name and it's url
    private string GetURL(string website, string url)
    { 
        return "<a href=\""+url+"\">"+website+"</a>";
    }

Here goes the design code for the GridView. Please note the property HtmlEncode="false" in the third BoundField. This prevents the GridView from rendering encoded html so we retain the html code from our DataTable column.

    <asp:gridview autogeneratecolumns="false" id="gvTable" runat="server" width="500px">  
<columns>
<asp:boundfield datafield="ID" headertext="ID">
<asp:boundfield datafield="WebsiteName" headertext="Website">
<asp:boundfield datafield="URL" headertext="URL" htmlencode="false">
</asp:boundfield></asp:boundfield></asp:boundfield></columns>
</asp:gridview>

The output looks like below.
Fig: Output of programmatically generated DataTable in a gridview - with clickable row
Happy Programming!!
Shout it

Saturday, February 9, 2013

Strip html tags and extract subset of string from text using regular expression in c-sharp

Today I am presenting a quick tips on how to strip html from text using regular expression (with Regex class) in C#. In a scenario like presenting a blurb or summary of certain characters we may need to remove html tags from a html string (of news details, article details etc.). I have following function in my Helper library for the very problem.


    /// 
    /// Strip out html tags from text
    /// 
    /// Source string
    /// 
    public static string StripTagsFromHtml(string source)
    {
        return Regex.Replace(source, "<.*?>", string.Empty);
    }


To extract a number of characters from the source string, we can extend the function as following.

    /// 
    /// Strip out html tags from text and return extract from it
    /// 
    /// Source string
    /// Number of characters to extract
    /// 
    public static string StripTagsFromHtml(string source, int characterCount)
    {
        string stripped = Regex.Replace(source, "<.*?>", string.Empty);
        if (stripped.Length <= characterCount)
            return stripped;
        else
            return stripped.Substring(0, characterCount);
    }

Happy programming!

Shout it

Saturday, January 19, 2013

Learning Java - I am using Eclipse IDE

For a long time, I have remained asp.net web application developer. But as you prepare to bear the role of an academician also, how could you stick to only one programming framework or programming language? Yes, that has come to my life also. And I have growing appetite for learning more programming languages.

JAVA undoubtedly brought about revolutions in so many fields. Oracle proudly declares that millions of devices run with JAVA. The academic world loves C, C++ and JAVA equally for the ongoing researches in so may fields of science and engineering.

To get my hands dirty with the first few programs in JAVA, I downloaded eclipse - the most popular Integrated Development Environment (IDE) for JAVA. I hope to come up with some samples soon.

For now, to elaborate "why java?", an excerpt from java site:

Java is a programming language and computing platform first released by Sun Microsystems in 1995. It is the underlying technology that powers state-of-the-art programs including utilities, games, and business applications. Java runs on more than 850 million personal computers worldwide, and on billions of devices worldwide, including mobile and TV devices. 

Happy programming!

Friday, May 18, 2012

Read hidden field value in asp.net from jquery

Often we are confused about how to read values set in asp.net HiddenField from jquery and use the values in the web form. Many-a-times we see the threads over the asp.net forums about the difficulties associated with reading asp.net HiddenField values. I have tried to give easy and fast way to read values and set values of hidden filed in asp.net using jquery.
You may first download the latest jquery file from jquery.com.
asp.net webform - design page
<body>
    <form id=\"form1\" runat=\"server\">
    <div>
    <asp:HiddenField ID=\"HiddenField1\" runat=\"server\" />
    <asp:Label ID=\"lblSiteName\" runat=\"server\"></asp:Label>
    </div>
    </form>
    <script type=\"text/javascript\" src=\"js/jquery-1.3.2.min.js\"></script>
    <script type=\"text/javascript\">
        $(function () {
            //reading hidden field value
            var mySite = $(\'#HiddenField1\').val();
            //displaying the value in an asp.net Label control
            $(\'#lblSiteName\').html(\'My site is: \' + mySite);
            //setting value of HiddenField control
            $(\'#HiddenField1\').val(\'New site is: http://asp.net\')
        });
    </script>
</body>
asp.net webform - code page (in c#)
protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            HiddenField1.Value = "http://dotnetspidor.blogspot.com";
        }
    }
Known issue
If you have put the asp.net HiddenField control below the script tags, you may end up reading 'undefined' values. To solve the issue, I recommend putting the hidden fields at the top of the page just below the form tag.
Further, if you are using asp.net Master Page, please make changes in the jquery codes respectively. In such case, I  recommend the following syntax:
var mySite=$('[id$=HiddenField1]').val();
The system $= means the value that end with HiddenField1. This works since you usually see the id HiddenFiled1 used with master page rendered as ctl00_ContentPlaceholder1_HiddenField1.

Happy programming!!
Shout it

Popular Posts

Recent Articles