Tuesday, April 21, 2009

How to add Image in the DataGridView or ListView Column, VB.NET

How to add Image in the DataGridView or ListView Column, VB.NET
 
Some time you have to display different images in the datagrid view based on column value. The simplest and fast performing way to achive this with datagridview, you add one Image column in the datatable and bind this datatable into the datagridview.
For ListView Control, you add one Image column listview item and add this item into into the listview control
 
NameSpace
Imports System.Text
Imports System.IO
 
Source Code
 
'Display Image column in the first column in the datagridview
Private Function BindDataGrid() As Integer
 
Dim rowCount As Integer
Dim dsCustomer As New DataSet
'Get related data from database
dsCustomer = GetAllCustomerData()
 
Try
 
Dim custTable As DataTable = dsCustomer.Tables(0)
Dim col As DataColumn
col = New DataColumn("Image", GetType(System.Drawing.Image))
custTable.Columns.Add(col)
col.SetOrdinal(0) 'This line will add image column in '0' place
 
'ImageList1 is ImageList control defined in the design time and add desired image (Design time) in the Imagelist Control,
For rowCount = 0 To custTable.Rows.Count - 1
If custTable.Rows(rowCount)("Dept").ToString() = "Finance" Then
   custTable.Rows(rowCount)("Image") = ImageList1.Images("ImageName1")
ElseIf custTable.Rows(rowCount)("Dept").ToString() = "Sales" Then
   custTable.Rows(rowCount)("Image") = ImageList1.Images("ImageName2")
Else
   custTable.Rows(rowCount)("Image") = ImageList1.Images("ImageName3")
End If
Next
 
   DataGridView1.DataSource = custTable
   DataGridView1.Columns(0).Width = "20"
 
   Return custTable.Rows.Count
 
Catch ex As Exception
    Throw ex
End Try
 
End Function
 
Note:  Another way to add Image in the ImageList Object at runtime
         ImageList.Images.Add(Bitmap.FromFile("../Icons/Image1.ico"))
 
'Display Image column in the first column in the listview control
Private Function BindListView() As Integer
 
Dim rowCount As Integer
Dim dsCustomer As New DataSet
'Get related data from database
dsCustomer = GetAllCustomerData()
 
Try
 
'Clear all the previous data if any, to overcome from binding duplicate data
ListView1.Clear()
' Set the view to show details. This is for to display all the rows and columns
ListView1.View = View.Details
 
'Design time add desired image in the Imagelist Control, ImageList1 is ImageList control defined in the design time
ListView1.SmallImageList = ImageList1
 
'Add columns,
ListView1.Columns.Add("Cust_Name", -2, HorizontalAlignment.Left)
ListView1.Columns.Add("Cust_Address", -2, HorizontalAlignment.Right)
 
Dim item As New ListViewItem
Dim custTable As DataTable = dsCustomer.Tables(0)
 
For rowCount = 0 To custTable.Rows.Count - 1
If custTable.Rows(rowCount)("Dept").ToString() = "Finance" Then
    item = New ListViewItem(custTable.Rows(rowCount)(0).ToString(), 0) 'Image1
ElseIf custTable.Rows(rowCount)("Dept").ToString() = "Sales" Then
    item = New ListViewItem(custTable.Rows(rowCount)(0).ToString(), 1) 'Image2
Else 'Other Dept
     item = New ListViewItem(custTable.Rows(rowCount)(0).ToString(), 2) 'Image3
End If
 
     item.SubItems.Add(custTable.Rows(rowCount)(0).ToString())
     item.SubItems.Add(custTable.Rows(rowCount)(1).ToString())
      ListView1.Items.Add(item)
Next
 
Return custTable.Rows.Count
 
Catch ex As Exception
     Throw ex ' Handle Exception here
End Try
 
End Function
 
Note:   'Another way to add Image in the custTable Row at runtime
           custTable.Rows(rowCount)("Image") = New System.Drawing.Bitmap ("../Icons/Image1.ico")

Friday, April 17, 2009

ListView Control De-select it selected value when click on other controls in .NET

ListView Control De-select it selected value when click on other controls in .NET

Following example tested with VB.NET Window Form, .NET Framework 2.0 and IE 6.0

Problem:

  1. Load listview control
  2. Select some rows from listview
  3. Now select some other controls in the form
  4. All listview selected rows are de-selected

Solution:

Select your listview control on lost focus of listview event


Private Sub ListView1_LostFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles ListView1.LostFocus

ListView1.Select()

End Sub


Note:
Here the simple way to select/Unselect listview control programatically

'Select Items from ListView Control
ListView1.Items(0).Selected = True

ListView1.Select()

'Un-Select Items from ListView Control
ListView1.Items(0).Selected = False
ListView1.Select()

Thursday, April 09, 2009

Confirm Popup message box with “Yes/No” button instead of “Ok/Cancel”

Confirm Popup message box with "Yes/No" button instead of "Ok/Cancel" In the javascript you have 'Confirm' function to popup message box and this message box comes with "Ok" and "Cancel" button but sometime you might have a requirement to display "Yes" and "No" button popup message box instead of "ok" and "Cancel". To achive this we have lots of work around. One of that is go and overrite window confirm function with vbscript. So you are still using JavaScript and Confirm function to display popup message box with "Yes" and "No" button and this fucntion will return "True" or "False" based on which button clicked. Copy and past following code in your aspx page before <Body> tag. This will give you popup message box on page load


<script language=javascript>

/*@cc_on @*/
/*@if (@_win32 && @_jscript_version>=5)
function window.confirm(str)
{
execScript('n = msgbox("'+str+'","4132")', "vbscript");
return(n == 6);
}
@end @*/
var r = confirm("Do you think you can do it?");
alert(r);


</script>


If you want this popup message box on click of button then call this fucntion on button click like below.


<asp:Button runat="server" Text="Button" OnClientClick="confirm('Do you think you can do it?')" ></asp:Button>


Message box WITH JavaScript Message box WITHOUT JavaScript

Friday, March 27, 2009

Error: ORA-30683: failure establishing connection to debugger

Error: ORA-30683: failure establishing connection to debugger or

ORA-06512: at "SYS.DBMS_DEBUG_JDWP"

In Oracle SQL Developer Tool


If you are getting following error while debug your stored procedure then you can try following steps


  1. In the Oracle SQL Developer Tool
  2. Go to "Tool" Menu
  3. Go to "Preferences"
  4. Go to "Debugger"
  5. Check "Prompt for Debugger Host for Database Debugging" check box
  6. Click "OK"
  7. Now whenever you will be debug it will prompt
  8. "Debugger Host for Database Debugging" dialog box
  9. Type you local system IP Address
  10. Click "OK"

Thursday, March 12, 2009

Execute Oracle Stored Procedure/Query FROM SQL Server

Execute Oracle Stored Procedure/Query FROM SQL Server


Most of the time your project requirement to work with two databases, In
some scenarios you want to execute one database stored procedure from
another database. Here I am giving the example to execute Oracle stored
procedure from SQL server database.
To achieve this first you have to set up link from SQL server to Oracle


How to link Oracle Database from SQL server


http://blogs.techrepublic.com.com/datacenter/?p=133

http://support.microsoft.com/kb/280106

http://msdn.microsoft.com/en-us/library/aa259589(SQL.80).aspx


To execute an Oracle Stored Procedure from SQL Server you can try
the following: You can make a sample package named Project_Package
with the procedure named TestProcedure:


Package Header:


PROCEDURE TestProcedure
(
I_Parameter1 IN NUMBER,
I_Parameter2 IN NUMBER,
O_Parameter1 OUT NUMBER,
O_Parameter2 OUT NUMBER
);


Package Body:


PROCEDURE TestProcedure
(
I_Parameter1 IN NUMBER,
I_Parameter2 IN NUMBER,
O_Parameter1 OUT NUMBER,
O_Parameter2 OUT NUMBER
) AS
BEGIN
O_Parameter1 := I_Parameter1 + 1;
O_Parameter2 := I_Parameter2 + 1;
END TestProcedure;


Then we create a SQL Server Stored Procedure to Wrapp the Oracle

Store Procedure Invocation, the T-SQL inside the procedure for this

sample is the following:


DECLARE
@l_i_parameter1 INTEGER
DECLARE
@l_i_parameter2 INTEGER
DECLARE @l_o_parameter1 INTEGER
DECLARE
@l_o_parameter2 INTEGER

SET
@l_i_parameter1 = 5
SET @l_i_parameter2 = 10
SET @l_o_parameter1 = 0
SET @l_o_parameter2 = 0

EXECUTE
( 'begin Project_Package.TestProcedure(?,?,?,?); end;',
@l_i_parameter1, @l_i_parameter2, @l_o_parameter1
OUTPUT, @l_o_parameter2 OUTPUT) AT DBLINK_NAME;

SELECT
@l_o_parameter1, @l_o_parameter2

I Hope this sample illustrate the concept. Also I want to mention that
this sample only works with simple output parameters, if you are trying
to query for result sets I recommend trying the OPENQUERY statement
instead.

OR

EXEC mySchema.myPackage.myProcedure@myRemoteDB( 'someParameter' );

Using OPENQUERY
If exists (select * from master..sysservers where
srvname = '
OracleDemo')
     exec sp_dropserver 'OracleDemo'
go
exec sp_addlinkedserver @server = N'OracleDemo',
    @srvproduct = N'',
    @provider = N'SQLOLEDB', 
    @datasrc = @@servername
go
select * into #Ta from OPENQUERY(OracleDemo,
'exec yourSproc')
select * from #Ta
drop table #Ta
go 
USING SP_EXECUTEESQL
DECLARE @rc INT
DECLARE @v_sql NVARCHAR(4000)
DECLARE @vc_servername VARCHAR(100)

DECLARE c_myservers CURSOR
FOR SELECT
servername
FROM listservers
WHERE active=1
FOR READ ONLY
OPEN c_myservers
FETCH NEXT FROM c_myservers INTO @vc_servername
WHILE (@@FETCHSTATUS = 0 )

BEGIN

SET @v_sql = N'SELECT name, id FROM ['+@vc_servername +
'].dbname.joe.titles'

EXEC @rc = sp_executesql @v_sql
-- if @rc <> 0
--- etc...

FETCH NEXT FROM c_myservers INTO @vc_servername

END
CLOSE c_myservers
DEALLOCATE c_myservers

COMPARISION

Rather your choice is between:

SELECT @sql = 'SELECT .... FROM ' + @server + 'catalog.schema.tbl'

and

SELECT @sql = 'SELECT ... FROM OPENQUERY(' + @server + ', ' +
'''SELECT ... FROM catalog.schema.tbl'')'

That is, accessing the table in four-part notation, or running a
pass-through query.

Thursday, March 05, 2009

How to send Array as an input parameter to Oracle SP using VB.NET

How to send Array as an input parameter to Oracle SP using .NET

Most of the project require to send huge parameter to oracle stored procedure that will be append in IN Clause in the SQL query. Basically you can send dynamically created inclause from the .NET code to oracle stored procedure.

There are multiple way to do this, you can send Array to SP and inside array, you can create concatated string and pass it to your SQL statement. BUT here if your inclause is going to be huge more then 4000 char then this approach wouldn't work, and string concatenation may hit the performance.

To over come with above two issues following approach will be the better approach, From the Array you can insert datainto the temp table and then fetch the data from temp table and create your complete SQL statement with inclause.

Please follow the steps given below for Demo  

Following solution tested with

  1. Visual Studio 2005 with VB.NET
  2. Oracle 10g
  3. Microsoft Enterprise Library 3.0

It should work with higher and couple of lower version too.

Oracle 10g CODE

1)  Create one global type (string_table) as table type (this will be your temparory table)

CREATE OR REPLACE TYPE string_table AS TABLE OF varchar2(100)

2) Create one global package (GLOBAL_PACKAGE) to declare array Type for SP           

          CREATE OR REPLACE PACKAGE GLOBAL_PACKAGE AS

              TYPE REF_CUR IS REF CURSOR;

              TYPE CHARARRAY IS TABLE OF VARCHAR2(50) INDEX BY BINARY_INTEGER;

END GLOBAL_PACKAGE;

33) 3) Create one stored procedure (Data_Fetch)that will take input paremeter as Array and Out parameter as Ref Cursor.

CREATE OR REPLACE PROCEDURE Data_Fetch

     (

prmInClause           IN      Global_package.Chararray,

         prmOUTCursor          OUT     Global_package.REF_CUR

     )

  IS

  BEGIN

  Declare

tempTable  string_table := string_table(NULL);

  BEGIN

          FOR i IN 1..prmInClause.count LOOP

tempTable(i) := prminclause(i);   

tempTable.extend;

END LOOP;

 

   Open prmOUTCursor for

SELECT * FROM Employee where id in (select column_value from table(tempTable)); 

  END Data_Fetch;    

  END;

VB.NET Code

Give the reference to Microsoft Enterprosies Library, if you are using otherwise use simple Oracle command or other object.

Include NameSpace

Imports Microsoft.Practices.EnterpriseLibrary.Data

Imports Oracle.DataAccess.Client

Methods

''' <summary>

'''  This function will send String Array to the database stored procedure

'''  to create huge Inclause for sql query 

''' </summary>

Private Function ReturnDataSet() As DataSet

 'Define database connection string in the app.config and write the name below

Dim connectDB As Database = DatabaseFactory.CreateDatabase("DATABASE")

Dim ds As DataSet

Dim command As DbCommand

command = connectDB.GetStoredProcCommand("SP_NAME")

Dim objParam As OracleParameter() = New OracleParameter(1) {}

Dim arrInClause() As String = {"345345DSGFDG345", "SAFDS456546J"}

 'Input parameter in stored procedure type as table of varchar2(50)

objParam(0) = New OracleParameter("prmInClause", OracleDbType.Varchar2)

objParam(0).Direction = System.Data.ParameterDirection.Input

objParam(0).CollectionType = OracleCollectionType.PLSQLAssociativeArray

objParam(0).Value = arrInClause

 'Output parameter in stored procedure type as Ref Cursor

objParam(1) = New OracleParameter("prmCustomerOptions", OracleDbType.RefCursor)

objParam(1).Direction = System.Data.ParameterDirection.Output

objParam(1).CollectionType = OracleCollectionType.None

command.Parameters.AddRange(objParam)

ds = connectDB.ExecuteDataSet(command)

Return ds

End Function 

C# Code 

Include NameSpace

using Microsoft.Practices.EnterpriseLibrary.Data

using Oracle.DataAccess.Client

Method

 /// <summary>

/// This function will send String Array to the database stored procedure

/// to create huge Inclause for sql query

/// </summary>

private DataSet ReturnDataSet()

    //Define database connection string in the app.config and write the name below

    Database connectDB = DatabaseFactory.CreateDatabase("DATABASE");

    DataSet ds = default(DataSet);

    DbCommand command = default(DbCommand);

    command = connectDB.GetStoredProcCommand("SP_NAME");

    OracleParameter[] objParam = new OracleParameter[2];

    string[] arrInClause = { "345345DSGFDG345", "SAFDS456546J" };

     //Input parameter in stored procedure type as table of varchar2(50)

    objParam(0) = new OracleParameter("prmInClause", OracleDbType.Varchar2);

    objParam(0).Direction = System.Data.ParameterDirection.Input;

   objParam(0).CollectionType = OracleCollectionType.PLSQLAssociativeArray;

    objParam(0).Value = arrInClause;

     //Output parameter in stored procedure type as Ref Cursor

     objParam(1) = new OracleParameter("prmCustomerOptions",       OracleDbType.RefCursor);

    objParam(1).Direction = System.Data.ParameterDirection.Output;

    objParam(1).CollectionType = OracleCollectionType.None;

    command.Parameters.AddRange(objParam);

    ds = connectDB.ExecuteDataSet(command);

   return ds;

 }