Oracle full text search with ASP.NET

First you need oracle full text search to be installed.

Then you have to create index on some field in table, this field can be any type: text, number or even file. Oracle text search supports pdf, doc,… and some other file types.

for example we have a table MyTable with following structure

Id number
title nvarchar(50)
attachment blob

field attachment contains files in format pdf, txt, doc…

if you try to search text ‘find me’ on column attachment, you will get error message, because this column is not indexed,

Select tbl.id, tbl.title, tbl.attachment from MyTable tbl
Where contains (tbl.attachment, ‘find me’);

After you create index, you can search in this fields. To create index run the following statement

Create index my_index_name_attachment_idx on MyTable(attachment) INDEXTYPE IS CTXSYS.CONTEXT PARAMETERS ('SYNC ( ON COMMIT)')

And now you can select data from table and the oracle full text search works.

How to call WCF services from JavaScript jQuery and ASP.NET AJAX

First we have to create a webapplication and add to it Ajax enabled WCF service.

Change default DoWork method to accept parameter

        [OperationContract]
        public string DoWork(string userName)
        {
            // Add your operation implementation here
            return "Hello " + userName;
        }

First add on the page input text control and two buttons.

        <input type="text" name="txtName" id="txtName" />
        <input type="button" value="jQuery call" onclick="cityClickJQuery();" />
        <input type="button" value="ASP.NET AJAX Call" onclick="cityClick();" />

First we will call this method with jQuery. So reference jQuery library and add this javascript function for calling WCF service

        function cityClickJQuery()
        {
            $.ajax({
                type: "POST",
                url: "http://localhost:65424/CityService.svc/DoWork",
                data: '{"userName":"'+$get("txtName").value+'"}',
                processData:false,
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function(data)
                {
                    alert(data.d);
                }
            });
        }

It’s very easy, you have to pass url with method, parameter (value from textbox) specify data type and callback function.

Now you can run webapplication, put some text in input box and press button “jQuery call”

image

 

Calling WCF service with Microsoft Ajax is much more easy. You do not to provide most of the properties like jQuery call.

        function cityClick()
        {
            CityService.DoWork($get("txtName").value, onSuccess);
        }

        function onSuccess(data)
        {
            if (data)
                alert(data);
        }

After pressing button, you will have the same result.

image

 

All source code can bi found below. I did not change web.config, so you can use default data generated by VisualStudio.

ASPX page:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs"
    Inherits="WebApplication1._Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>

    <script src="jquery-1.3.2.js" type="text/javascript"></script>
    <script src="jquery-1.3.2-vsdoc.js" type="text/javascript"></script>

    <script type="text/javascript">
        function cityClickJQuery()
        {
            $.ajax({
                type: "POST",
                url: "http://localhost:65424/CityService.svc/DoWork",
                data: '{"userName":"'+$get("txtName").value+'"}',
                processData:false,
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function(data)
                {
                    alert(data.d);
                }
            });
        }
        function cityClick()
        {
            CityService.DoWork($get("txtName").value, onSuccess);
        }

        function onSuccess(data)
        {
            if (data)
                alert(data);
        }
    </script>

</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ScriptManager runat="server">
            <Services>
                <asp:ServiceReference Path="~/CityService.svc" />
            </Services>
        </asp:ScriptManager>

        <div style="background-color:#eee;">

        <input type="text" name="txtName" id="txtName" />
        <input type="button" value="jQuery call" onclick="cityClickJQuery();" />
        <input type="button" value="ASP.NET AJAX Call" onclick="cityClick();" />
        </div>

    </div>
    </form>
</body>
</html>

 

C# code:

namespace WebApplication1
{
    using System.ServiceModel;
    using System.ServiceModel.Activation;

    [ServiceContract(Namespace = "")]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class CityService
    {
        // Add [WebGet] attribute to use HTTP GET
        [OperationContract]
        public string DoWork(string userName)
        {
            // Add your operation implementation here
            return "Hello " + userName;
        }

        // Add more operations here and mark them with [OperationContract]
    }
}

Referencing JavaScript files from MasterPage

To avoid problems with pathes you can you “~” at the start of your ulr. But this works only for controls with runat=”server” attribute. You can add this attribute to head tag.

<head runat="server">

It works fine for css links

<link href="~/styles/style.css"
rel="stylesheet" type="text/css" />

But if you will try to add this attribte to scritp tag you will have compiler error

<script type=”text/javascript”
src=”~/scripts/myScript.js” runat=server/>

But there are another solution, use ResolveUrl method

<script src="<%=ResolveUrl("~/Scripts/jquery-1.3.2.js") %>"
type="text/javascript"></script>

But somtimes this method trow error

The Controls collection cannot be modified because the control contains code blocks (i.e. <% … %>).

It’s because of “=” in “<%=”. But it can be resolved very easy using “#” databinding expression.

<script src="<%#ResolveUrl("~/Scripts/jquery-1.3.2.js") %>" type="text/javascript"></script> 

But do not forget to bind this url in pageLoad event

protected override void OnLoad(System.EventArgs e)
{
    base.OnLoad(e);
    Page.Header.DataBind();
} 

Resharper 4.5.1 was released

Jetbrains just released Resharper 4.5.1 Maintenance build, which can be downloaded here.
There are a lot of bugs was fixed in this build. You can seed release notes here.

It’s a free upgrade to all licensed users of 4.x version.

Migrate to new version Nhibernate 2.1.0 with Oracle database

A couple of days ago new version of Nhibernate was released. You can download new version here

And if you migrate to this version and using Oracle database,
You will get this exception

Could not load type NHibernate.Dialect.OracleDialect. Possible cause: no assembly name specified

The reason is, you need specify not OracleDialect, but Oracle8iDialect, Oracle9iDialect, Oracle10gDialect, or OracleLiteDialect instead.
For example for oracle 10.x version you have to change dialect line in your hibernate.cfg.xml to this line

<property name="dialect">NHibernate.Dialect.Oracle10gDialect</property>

Building charts with Dundas Charts and SqlDataSource

Dundas has a very good Chart controls which I am using now in my project. And if you are familiar with Microsoft Charts you can easy start using Dundas charts, because Microsoft Charts based on Dundas charts.

Chart controls support SqlDataSource, and all than you need is Bind SqlDataSource to Dundas charts and tell charts what fields to use from DataSource.

<asp:SqlDataSource runat="server" ProviderName="System.Data.OracleClient" SelectCommand="select AxisX, AxisY from chart_values"

    ID="SqlData"></asp:SqlDataSource>
<DCWC:Chart ID="Chart1" runat="server" DataSourceID="SqlData"
    Width="1000px" Height="600px">
    <Legends>
        <DCWC:Legend TitleFont="Microsoft Sans Serif, 8pt, style=Bold"
            BackColor="Transparent" EquallySpacedItems="True" Font="Trebuchet MS, 8pt, style=Bold"
            AutoFitText="False" Name="Default">
        </DCWC:Legend>
    </Legends>
    <Series>
        <DCWC:Series ValueMemberX="AxisX" ValueMembersY="AxisY">
        </DCWC:Series>
    </Series>
    <ChartAreas>
        <DCWC:ChartArea Name="Default">
            <AxisX LineColor="Blue">
            </AxisX>
            <AxisY LineColor="Red">
            </AxisY>
            <Area3DStyle Enable3D="True" />
        </DCWC:ChartArea>
    </ChartAreas>
</DCWC:Chart>

clip_image001

Experts-exchange forum, how to use it for free?

I believe all developers know this forum http://www.experts-exchange.com. Usually you can see it in the first position in Google while looking for information about programming.

But This forum is not free, and you have to pay $12.95 Monthly to access this forum. So most of the people who don’t want to pay usually skip this forum in Google search result.

But you can read this forum for free!!!
All than you need, is scroll down to the end of the page. And at the bottom you will see all the answers.

For example you can go to this page
Scroll down to the bottom of the page and see answers for free.

Global.asax file events for Application and Session

Global.asax file comes in ASP.NET from ASP language. This file contains events for Application and Session, and global.asax must be in the root directory of .net web application.

Below is the list of events in global.asax file you can call.

Application events in global.asax:

Application_Start:
This event used to set up an application environment and called only when the application starts first time.

Application_Init:
This method occurs after Application_Start and is used for initializing your code.

Application_Disposed:
This event occurs before destroying an instance of an application.

Application_Error:
This event is used to handle all unhandled exceptions in the application. It’s the best place to put your error tracking mechanism.

Application_End:
Like classic ASP method it used to clean up variables and memory while application ends.

Application_BeginRequest:
This event occurs when a client makes a request to any pages of the application. It can be useful for example to open connection to database for all request.

Application_EndRequest:
This is the last request to the page.

Application_PreRequestHandlerExecute:
This event occurs before ASP.Net begins executing a handler such as a page or a web service. At this point, the session state is available.

Application_PostRequestHandlerExecute:
This method occurs when the ASP.Net handler finishes execution.

Application_PreSendRequestHeaders:
This event occurs just before ASP.Net sends HTTP Headers to the client. You can use it if you want to modify a header

Application_PreSendRequestContent:
This event occurs just before sending content to the client.

Application_AcquireRequestState:
This event occurs when ASP.Net acquires the current state (eg. Session state) associated with the current request.

Application_ReleaseRequestState:
This event occurs after ASP.NET finishes executing all request handlers and causes state modules to save the current state data.

Application_AuthenticateRequest:
This event occurs when the identity of the current user has been established as valid by the security module .

Application_AuthorizeRequest:
This event occurs when the user has been authorized to access the resources of the security module .

Session events in global.asax:

Session_Start:
As with classic ASP, this event is triggered when any new user accesses the web site.

Session_End:
As with classic ASP, this event is triggered when a user’s session times out or ends. The default session timeout is 20 min.

Oracle and SqlDataSource two way data binding

Often you have to create a simple pages for your website, for example admin pages which allow you edit tables through web. When working with Ms Sql server it’s a very easy task which you can solve with SqlDataSource and DataGrid. But using Oracle it’s difficult to make your page work without exceptions and you have to know some tricks for using Oracle with SqlDataSource.

To develop webpage you can start with user interface. Put SqlDataSource and DataGrid on the page, and add css class if needed.

Than you need to add settings to SqlDataSource to select data from database using SelectCommand. And now you can have data inside of DataGrid.

clip_image001

To make Grid editable you have to define UpdateCommand which in this case contains the name of stored procedure which I am using to update table:

CREATE OR REPLACE PACKAGE HEATMAP.orm_web_support
AS
   PROCEDURE update_stream_lookup (
      stream_id_     public_stream_lookup.stream_id%TYPE,
      stream_name_   public_stream_lookup.stream_name%TYPE,
      is_visible_    public_stream_lookup.is_visible%TYPE
   );
END orm_web_support;
/ 

CREATE OR REPLACE PACKAGE BODY HEATMAP.orm_web_support
AS
   PROCEDURE update_stream_lookup (
      stream_id_     public_stream_lookup.stream_id%TYPE,
      stream_name_   public_stream_lookup.stream_name%TYPE,
      is_visible_    public_stream_lookup.is_visible%TYPE
   )
   AS
   BEGIN
      UPDATE public_stream_lookup
         SET stream_name = stream_name_,
             is_visible = is_visible_,
             last_modified_date = SYSDATE
       WHERE stream_id = stream_id_;
   END;
END orm_web_support;
/ 

It’s a simple Sql to update table, but I was not able to make page work without stored procedure.

You need to provide parameters for UpdateCommand inside of SqlDataSource:


<UpdateParameters>
    <asp:Parameter Name="STREAM_ID" Type="Int32" />
    <asp:Parameter Name="STREAM_NAME" Type="String" />
    <asp:Parameter Name="IS_VISIBLE" Type="String" />
</UpdateParameters> 

Now if you try to run application you will get Exception:

PLS-00306: wrong number or types of arguments in call to ‘UPDATE_STREAM_LOOKUP’

To make UpdateCommand work in OnUpdating event for DataSource you have to initialize parameters if you need, or add some parameters, usually it’s username who make changes or something like this. The number and the names of parameters must be the same as in Oracle stored procedure, so you have to add underscore at the and of the parameters.

Why do you need to add underscore? The thing is, in UpdateParameter you need to have the same names as in stored procedure, but you can’t change parameter names inside of your SqlDataSource, because they will not be initialized, so you have to change names inside of OnUpdating event. And the easiest way is use underscore for new parameter names.

protected void SqlStreams_OnUpdating(object sender, SqlDataSourceCommandEventArgs e)
{
    foreach (DbParameter param in e.Command.Parameters)
    {
        param.ParameterName = param.ParameterName + "_";
    }
} 

And now you can change data in table

clip_image001[5]

If not all the columns in the table should be editable, for example Id, you have use asp:TemplateField instead of BoundField and Bind method instead of Eval. Why you have to use Bind, read here

To delete line from table you have to make the more simple steps as for edit. You need to define DeleteCommand which is simple sql statement. DeleteParameters in this case is not defined, so you have to create new parameter in your c# code and add it to command in OnDeleting event:

protected void SqlStreams_OnDeleting(object sender, SqlDataSourceCommandEventArgs e)
{
    int appId;
    if (Int32.TryParse(deleteKey, out appId))
    {
        OracleParameter parameter = new OracleParameter("STREAM_ID", appId);
        e.Command.Parameters.Add(parameter);
    }
} 

But before you need to know id of the row to delete. And you can save it in OnRowDeleting event for DataGrid:

protected void Grid_OnRowDeleting(object sender, GridViewDeleteEventArgs e)
{
    GridView grid = sender as GridView;
    if (null != grid)
    {
        deleteKey = e.Values["STREAM_ID"].ToString();
    }
} 

And now it should work, and you will be able to edit rows inside of DataGrid and delete rows from DataGrid.

Below is source code for both .aspx and .cs pages:


<%@ Page Title="" Language="C#" MasterPageFile="~/DevKitV5Content.master"
    AutoEventWireup="true" CodeFile="PublicStreamsLookup.aspx.cs"
    Inherits="PublicStreamsLookup" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1"
    runat="Server">
    <asp:SqlDataSource ID="SqlStreams" runat="server" SelectCommand="select STREAM_ID, stream_name, is_visible, last_modified_date from public_stream_lookup order by stream_id desc"
        DeleteCommand="delete from public_stream_lookup where stream_Id = :Id"
        UpdateCommand="heatmap.orm_web_support.update_Stream_lookup"
        UpdateCommandType="StoredProcedure" ProviderName="System.Data.OracleClient"
        OnUpdating="SqlStreams_OnUpdating" OnDeleting="SqlStreams_OnDeleting">
        <UpdateParameters>
            <asp:Parameter Name="STREAM_ID" Type="Int32" />
            <asp:Parameter Name="STREAM_NAME" Type="String" />
            <asp:Parameter Name="IS_VISIBLE" Type="String" />
        </UpdateParameters>
        <DeleteParameters>
            <asp:Parameter Name="STREAM_ID" Type="Int32" />
        </DeleteParameters>
    </asp:SqlDataSource>
    <div>
        <asp:Label runat="server" ForeColor="Red" ID="LblError"></asp:Label>
        <table class="dataGrid">
            <tr>
                <th>
                    Stream name
                </th>
                <th>
                    Visible
                </th>
            </tr>
            <tr>
                <td>
                    <asp:TextBox ID="TxtStreamName" runat="server" CssClass="selectable"></asp:TextBox>
                </td>
                <td>
                    <asp:DropDownList ID="LstVisible" runat="server">
                        <asp:ListItem Text="Yes" Value="Y"></asp:ListItem>
                        <asp:ListItem Text="No" Value="N"></asp:ListItem>
                    </asp:DropDownList>
                </td>
            </tr>
        </table>
        <asp:Button ID="Button1" runat="server" Text="Add" Style="float: right;"
            CssClass="buttonclass" OnClick="AddButton_OnClick" />
    </div>
    <asp:GridView runat="server" DataSourceID="SqlStreams" AutoGenerateEditButton="true"
        CssClass="dataGrid" GridLines="None" ID="GridStreams" AutoGenerateDeleteButton="true"
        OnRowDeleting="Grid_OnRowDeleting" AutoGenerateColumns="false">
        <AlternatingRowStyle CssClass="odd" />
        <Columns>
            <asp:TemplateField HeaderText="Id">
                <ItemTemplate>
                    <asp:Label runat="server" ID="lblId" Text='<%#Bind("STREAM_ID") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:BoundField HeaderText="Stream name" DataField="stream_name" />
            <asp:BoundField HeaderText="Visible" DataField="is_visible" />
            <asp:TemplateField HeaderText="Last modified date">
                <ItemTemplate>
                    <asp:Label runat="server" ID="lblDate" Text='<%#Eval("last_modified_date", "{0:dd/MM/yyyy}") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>
</asp:Content> 
using System;
using System.Data.Common;
using System.Data.OracleClient;
using System.Web.UI.WebControls;
using ORM_MS.DAL;
using ORM_MS.Framwork;
public partial class PublicStreamsLookup : PageBase
{
    private string deleteKey;
    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);
        SqlStreams.ConnectionString = Settings.HeatmapConnectionString;
        SqlStreams.DataBind();
    }
    protected void Page_Load(object sender, EventArgs e)
    {
    }
    protected void SqlStreams_OnUpdating(object sender, SqlDataSourceCommandEventArgs e)
    {
        foreach (DbParameter param in e.Command.Parameters)
        {
            param.ParameterName = param.ParameterName + "_";
        }
    } 

    protected void SqlStreams_OnDeleting(object sender, SqlDataSourceCommandEventArgs e)
    {
        int appId;
        if (Int32.TryParse(deleteKey, out appId))
        {
            OracleParameter parameter = new OracleParameter("STREAM_ID", appId);
            e.Command.Parameters.Add(parameter);
        }
    }
    protected void Grid_OnRowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        GridView grid = sender as GridView;
        if (null != grid)
        {
            deleteKey = e.Values["STREAM_ID"].ToString();
        }
    }
    protected void AddButton_OnClick(object sender, EventArgs e)
    {
        try
        {
            new DbMaintanenceDao().AddInStreams(TxtStreamName.Text,
                                                LstVisible.SelectedValue);
            GridStreams.DataBind();
        }
        catch (Exception ex)
        {
            LblError.Text = "It was an error while adding value. Error id = " + Logger.LogException(ex);
            ;
        }
    }
} 

Eval vs Bind for ASP.NET

When you start working with ASP.NET sometimes it’s difficult to understand what is the difference between Eval and Bind for data binding controls in ASP.NET.

If you just need to display data on the screen from DataSource it’s enough to use Eval. It’s something like read-only method from DataSource.

But if you need to edit data inside of Grid you have to use Bind method. Because it provides two way binding you can read data from DataSource and you can write data back.

Usually you have to use this methods if you need to quickly develop some WebPages and display and edit data from one table or simple view.

If you try to edit some row in Data Grid and want to make some changes in code behind class in OnUdpdating event, data with Eval method will not be available instead of Bind method.

<asp:GridView ID="GridView1" runat="server" CssClass="dataGrid"
   DataSourceID="SqlDataSource1" AllowPaging="True" AutoGenerateColumns="false"
  OnRowDeleting="grid_onRowDeleting" OnRowUpdating="GridView1_OnRowUpdating"
    AutoGenerateEditButton="true" AutoGenerateDeleteButton="true"
  PageSize="20" GridLines="None" Width="99%">
   <AlternatingRowStyle CssClass="odd" />
   <Columns>

       <asp:TemplateField HeaderText="App Id">
           <ItemTemplate>
               <asp:Label ID="lbl" runat="server" Text='<%#Bind("APP_ID") %>'></asp:Label>
           </ItemTemplate>
       </asp:TemplateField>

      <asp:TemplateField HeaderText="App name">
           <ItemTemplate>
               <%#Eval("APPLICATION_NAME")%>
           </ItemTemplate>
       </asp:TemplateField>
   </Columns>
</asp:GridView>
protected void GridView1_OnRowUpdating(object sender, GridViewUpdateEventArgs e)
{
   // if APP_ID in the grid bind with Eval method, it will be exception below
   // But if you use Bind instead of Eval it will be ok.
   rowToUpdate = e.NewValues["APP_ID"];
}
Technorati Tags: ,