Friday, January 30, 2009

Oracle function to return Comma separated values as Table

This oracle function expects varchar as input parameter and returns a table.




Input (String)a,bc,de,fg,hi
Output (Table)



Since output is to expected to be a table, it does not mean to create a temporary table to store the comma separated values.
Oracle provides an option to define a type as user required, some thing like user type.
In similar to programming language as we have int, float, string which are predefined data types, oracle too has such predefined types like varchar, number, char, etc…
In programming language we can define user defined type like classes defined by user,
Also in similar fashion we can create user defined types in oracle using Type clause.
Syntax:-
CREATE OR REPLACE TYPE [TYPE NAME] AS [TYPE];
Ex :-
CREATE OR REPLACE TYPE SampleType AS OBJECT (
A VARCHAR2(100),
B VARCHAR2(100),
C NUMBER
)

In our case to return a table from oracle function, we should create a object of Type table.
Since table constitutes of columns to append rows, so first we should define an object which holds those columns and next an another object of type table for the above object which holds the columns.
That is,



1)
--An object type that holds the values that are comma separated or
--since a table has to hold the comma separated values, so we
--need a single column of varchar datatype
CREATE OR REPLACE TYPE ValueType AS OBJECT (
Val VARCHAR2(100)
)
2)
--We need to create a table that holds the values of the comma separated values,
--such that this table type is table of the above object type (ValueType).
CREATE OR REPLACE TYPE ValueType_Tbl AS TABLE OF ValueType




3) Oracle function.
Please copy and paste this function into toad or an editors to understand comments against each line.
--argStr is the input string that has to splitted based upon delimeter
--delimeter is input string which has to be considered to split,
--such for this comma seperated values delimeter is ","
CREATE OR REPLACE FUNCTION Csv(argStr IN VARCHAR,delimeter IN VARCHAR)
--Return type mean to say that the table type defined as expaind above,
--rows that are to piped in while executing this function should
--be inserted or pipelined into ValueType_Tbl.
--such that this function returns this pipelined table (ValueType_Tbl)
RETURN ValueType_Tbl PIPELINED IS
tmpStr VARCHAR2(2000);
tmpSubStr VARCHAR2(100);
--Declaring a varaible of the new row type in table (ValueType_Tbl) indirectly
--since ValueType_Tbl is table of ValueType
out_rec ValueType := ValueType(NULL);
--ValueType(null) mean that it is default value
BEGIN
--taking the input string into another variable
tmpStr:=argStr;
--chekcing the length of the given input string
WHILE(LENGTH(tmpStr)>0 AND tmpStr IS NOT NULL)
LOOP
--taking first par of substring from the string till delimeter occurs (,)
tmpSubStr:=SUBSTR(tmpStr,1,INSTR(tmpStr,delimeter)-1);
--chekcing if there is no other part of string then asking to pipe line this row
-- and exit the loop
IF(tmpSubStr IS NULL)THEN
out_rec.Val:=tmpStr;
PIPE ROW(out_rec);
EXIT;
END IF;
--Assigning the sub string value to the record and pipe linening into the considered table type
out_rec.Val:=tmpSubStr;
PIPE ROW(out_rec);
--Taking the other of string after removing the sub string
tmpStr:=SUBSTR(tmpStr,INSTR(tmpStr,delimeter)+1);
END LOOP;
RETURN ;
END;
/






Output:-
Query that has to be executed to run this oracle function
SELECT * FROM TABLE(Csv('1,bc,de,fg',','))
We can observe that this function which returns, we are trying to type cast the pipelined rows to a table, such that we can have the result set in table format


Thursday, January 29, 2009

Registration form in three tire architecture.

This 3 tier architecture or layers are categorised such that they communicate to each other to perform tasks.
These 3 layers are said to be as
1) Presentation Layer (User Interface form).
2) Business Layer (Layer where business plans can be validated or Media between user to application core data base.
3) Data Layer (Layer which is very specific to access database and does not interact with user directly but send/receive information from User through Business Layer.





We can find 3 blocks in this diagram that states that there is inter block communication to handle requests and response from user.

Example:-
I would like to create a windows form named “3Tier –Demo”.
Presentation Layer
So this comes under first layer (from user prospective) or User Interface.




Business Layer
I would like to add new project saying “class library” to this solution saying “BusinessLayer”.
Rename the default created “Class1.cs” to “Form.cs”.




Data Layer
Similar fashion as above I would like to add one more class library as new project for this solution saying “DataLayer”.
Rename the default created “Class1.cs” to “Form.cs”.




So now there are three layers available to our application (3Tier-Demo).



Step 1
First I would to start coding from Data layer, i.e; to start writing sql querues that perform sql transactions with the database like select, Insert, Update, Delete etc…

using System;
using System.Collections.Generic;
using System.Text;

namespace DataLayer
{
public class Form
{
//Connection string set to this which is read and set from app.config file or any other
//hardcoded variable
public string ConnectionString;
public void InsertData(string argName, int argAge, string argOccupation, string argPlace)
{
//Write code to open orcale/sql connection, insert query to be performed, etc...
}
public void ReadData(string argName,out int argAge,out string argOccupation,out string argPlace)
{
argAge = 0;
argOccupation = String.Empty;
argPlace = String.Empty;
//Write code to open orcale/sql connection, select query to read user
//details based upon given username (argName)
//Assign readed age,location,place to the given out parameters. }

}
}


Now build data layer, add this as reference to business layer.
Since business layer has to interact with data layer to handle user requests or response.




Step 2
Now I would like to start coding in business layer (Form.cs).

using System;
using System.Collections.Generic;
using System.Text;
using DataLayer;
namespace BusinessLayer
{
public class Form
{
//Connection string set to this which is read and set from app.config file or any other
//hardcoded variable
public string ConnectionString;
public void InsertData(string argName, int argAge, string argOccupation, string argPlace)
{
DataLayer.Form objForm = new DataLayer.Form();
objForm.ConnectionString = ConnectionString;
objForm.InsertData(argName, argAge, argOccupation, argPlace);
}
public void ReadData(string argName, out int argAge, out string argOccupation, out string argPlace)
{
argAge = 0;
argOccupation = String.Empty;
argPlace = String.Empty;
DataLayer.Form objForm = new DataLayer.Form();
objForm.ConnectionString = ConnectionString;
objForm.ReadData(argName,out argAge, out argOccupation, out argPlace);
}
}
}


Similarly, add this business layer as reference to presentation layer (3Tier-Demo).



Step 3
I would like to start coding in Presentation Layer or 3Tier-Demo, in the windows form accessing the business layers form class to get or send data from or to database through data layer.









Now after building the application, it is fine.
Things left and to be written or updated
1) Write sql queries for specific actions like Insert or select or update to specific table.
2) Mention connection string for appropriate database.
3) Call these “Insertdata” and “Getdata” functions in Presentation layer where ever needed or required.
There are some instants where we introduce one more layer saying
"Common Layer" that holds the data transfered from/to between these 3 layers



Wednesday, January 28, 2009

How to send HTML content in Mail?

We can find many mails that we are in loop among friends like sending birthday wishes, festival, advertisements, captions, scenaries, etc…
I would like to share my code that could help to send such kind of mails very easily.
I have created a windows form which asks for to/Form mail ID, From Mail ID’s password, Mail subject, Body.



In this body is an html file which you can browse. So that the content of the browsed html file is considered as body. So, the mail is sent saying that its content is html.
I am using Google mail server which helps me to send mails globally.
Code:-

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Web.Mail;
namespace SendMail
{
public partial class frmSendMail : Form
{
string strTitle = "Send Mail";
public frmSendMail()
{
InitializeComponent();
}
private void btnBrowse_Click(object sender, EventArgs e)
{
opnFldlg.ShowDialog();
lblPath.Text = opnFldlg.FileName;
}

private void btnSend_Click(object sender, EventArgs e)
{
try
{
if (txtPassword.Text.Trim().Length == 0 || txtToMailID.Text.Trim().Length == 0 || txtFromMail.Text.Trim().Length == 0 || txtSubject.Text.Trim().Length == 0 || lblPath.Text.Trim().Length == 0)
throw new Exception("Please enter detals");
btnSend.Text = "Sending...";
MessageBox.Show(SendMail(txtFromMail.Text.Trim(), txtPassword.Text.Trim(), txtToMailID.Text.Trim(), File.ReadAllText(lblPath.Text.Trim()), txtSubject.Text.Trim()), strTitle, MessageBoxButtons.OK, MessageBoxIcon.Information); }
catch (Exception exp)
{
MessageBox.Show(exp.Message, strTitle, MessageBoxButtons.OK, MessageBoxIcon.Information);
}
finally
{
btnSend.Text = "Send";
}
}
private string SendMail(string strFromMailID, string strPswd,string strToMailID, string strBody, string strSubject)
{
try
{
SmtpMail.SmtpServer = "smtp.gmail.com";
MailMessage message = new MailMessage();
message.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate", "1");
message.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendusername", strFromMailID);
message.Fields.Add("http://schemas.microsoft.com/cdo/configuration/sendpassword", strPswd);
message.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpserverport", "465");
message.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpusessl", "true");
message.From = strFromMailID;
message.To = strToMailID;
message.BodyFormat = MailFormat.Html;
message.Subject = strSubject;
message.Body = strBody;
SmtpMail.Send(message);
return "Mail sent successfully to " + strToMailID;
}
catch (Exception exp)
{
throw exp;
}
}
}
}


Say suppose I would like to wish my friend for his birthday with a greeting card.
I found a greeting card through google at http://www.4to40.com/images/egreetings/Birthday/Happy_Birthday_Wishes-Birthday-148_big.gif.




Now I will prepare a html page that includes this image and few lines with my comments in it.
Now I can browse this html page as body through my windows forms and send it to my friend.
My HTML page using this image url

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title></title>
</head>
<body>
<table><tr><td>
Hi Friend......
</td></tr>
<tr><td>
<img src="http://www.4to40.com/images/egreetings/Birthday/Happy_Birthday_Wishes-Birthday-148_big.gif" width='50%' /> </td></tr>
<tr><td>
Cheers,
</td></tr>
<tr><td>
Srinivas
</td></tr></table>
</body>
</html>

Html Page output :-




I saved this html file as “wishes.htm”.
Now I am filling the form with the details to send this html content as mail.




When I click on send,







Now I wish to open my 2 gmails (vsssrinivas85 and surya.srinivas85) to check this mail in outbox and in box respectively.



Vsssrinivas85 - Outbox






surya.srinivas85- Inbox



Tuesday, January 27, 2009

How to debug JavaScript in .NET?

Latest Microsoft visual studio 2008 is providing an option to debug javascript.
In earlier versions of Microsoft visual studio 2003 or 2005, we need to externally place debug option in javascript code.

Example:-
<!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>
<title>Demo1</title>
<script type="text/javascript" language="javascript">
function clk1(obj)
{
debugger
alert(obj.value);
}
</script>


</head>
<body>
<input type="button" value="Hi" onclick="clk1(this);" />

</body>
</html>

In above html content, we can find “debugger” in javascript function.
At the moment when this clk1 () function is called and control is at debugger line, we get an option in browser to choose the debugging editor.
Output:-
As soon as I click on the button, which is calling the javascript function that I am wishing to debug.



Now I am selecting to choose new instance of visual studio 2005 or I can even continue in same visual studio editor where I am writing my source code.

It highlights the line where debugger is placed.



From now debugging is same as how we do in code behind page. i.e;
F10 key to goto next line and donot go into the child function
F11key to got next line and also into the child function
Cntrl + Alt + Q for quick watch of an object.
F5 to continue to next debugger, if next debugger not found continue execution.
Etc…

We get plus sign over there after placing near to the object, which I can expand and investigate in detail for each attribute, text etc…




Note:-
When you try to debug, we should also check whether browser supports to debug javascript.
For this
If it is Internet explorer then
1) Go to “Tools”.
2) “Internet Options” – “Advanced” tab.
3) Uncheck the check box which is saying “Disable script debugging”.




How to refer elements in an html file in another html file?

We are sure that elements or html components like textbox, checkbox, div, table, label, span, etc.. are accessible through JavaScript by saying “document.getElementById”.
Example:-
I am creating an html page with name Demo1.html
I have an html component as
<div id=”div1”></div>
We could say
document.getElementById(‘div1’) which returns div1 object.
Demo1 Html file:-
<!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>
<title>Demo1</title>
<script type="text/javascript" language="javascript">
function clk()
{
alert(document.getElementById('div1'));
}
</script>
</head>
<body>
<div id="div1"></div>
<input type="button" value="div" onclick="clk();" />
</body>
</html>

Output:-



Now I am creating an another html page say Demo2.html, with content same as Demo1 i.e;
<!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>
<title>Demo2</title>
<script type="text/javascript" language="javascript">
function clk()
{
alert(document.getElementById('div1'));
}
</script>
</head>
<body>
<div id="div1"></div>
<input type="button" value="div" onclick="clk();" />
</body>
</html>
Now I want access div tag whose id is “div1” available in Demo2.html from Demo1.html.
In such case, I would like place “iframe” object in Demo1.htm whose src is Demo2.html
Demo1.html:-
<!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>
<title>Demo1</title>
<script type="text/javascript" language="javascript">
function clk1()
{
alert(document.getElementById('div1'));
}
function clk2()
{
alert(dm2.document.getElementById('div1'));
}


</script>
</head>
<body>
<div id="div1"></div>
<input type="button" value="Demo1-div" onclick="clk1();" />
<br/><input type="button" value="Demo2-div" onclick="clk2();" />

<iframe src="demo2.htm" id="dm2"></iframe>


</body>
</html>
Output:-
Clicking on ="Demo2-div" button



If required we can hide the iframe, so that user cannot view that Demo1.html is including Demo2.html.
Demo1.html:-
<!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>
<title>Demo1</title>
<script type="text/javascript" language="javascript">
function clk1()
{
alert(document.getElementById('div1'));
}
function clk2()
{
alert(dm2.document.getElementById('div1');
}


</script>
</head>
<body>
<div id="div1"></div>
<input type="button" value="Demo1-div" onclick="clk1();" />
<br/>
<input type="button" value="Demo2-div" onclick="clk2();" />

<iframe src="demo2.htm" id="dm2" style="display:none"></iframe>


</body>
</html>

Output:-
Clicking on ="Demo2-div" button


How to Import and Export Database dump file in Oracle.

After installing oracle, we can find imp.exe and exp.exe files in bin folder.
These exe files could help for importing and exporting database dump.

This database dump file consists of tables (with or without data), database objects (Stored procedures, Views, Triggers, Constraints, Indexes, Sequences, etc…).

While exporting or importing, we have an option whether to consider table data or not.
So situations, like where we are just in need of only schema it helps to export or import without data. We also have an option for importing or exporting selected tables, i.e; we can mention a list of tables which we require to export or import.

So these exp and imp exe files have input parameters which are set depending upon need.
To know the parameters of imp, say in command prompt as
Imp help=y




Similarly for exp say,
Exp help=y



We can find imp and exp files almost expect the same kind of parameters.

Example:-
If I have a database whose connection string is
Demo/abcd@MyDB
(User name: Demo
Password: abcd
Schema: MyDB)
If I need to export I can go to command prompt and say “exp”, then it asks me for username where I have to give Demo/abcd@MyDB.
After that it asks for the file path where dump has to be exported, Export table data or not.




or I can say
exp Demo/abcd@MyDB file=[dumpfile export path] rows=(Y or N) log=[log file path]
This directly connects to the database and exports the database objects to the specific dump file path mentioned. We can find a log file at given Log file path, to just verify if there are any errors while exporting.
If we want only selected tables to be exported we can say
exp Demo/abcd@MyDB file=[dumpfile export path] rows=(Y or N) log=[log file path] tables=(table1, table2, tables3, …tablen)

Also for importing a database dump file, I should say imp in command prompt.
Say, if I am willing to import a database dump file to Demo\abcd@MyDemo,
Then I should give username as Demo\abcd@MyDemo, wheimp.exe prompts for.
Then it asks for the database dump file where it is to export.
We can either give the path or drag and drop the dump file.




or
I can say
Imp Demo\abcd@MyDemo file=[import databse dump file path] log=[log file path] rows=Y tables=(table1, table2.. tablen).
So import and export process seems to be almost same.

Sunday, January 25, 2009

Request is not available in this context - Resolution

I have a web application (ASP.NET) using IIS 6.0 in my machine.
I have prepared a web application set up of this web site.

Then I have copied and installed this web application set up in my friend’s machine which is having IIS 7.0.
I felt that after installing this web set up in that machine, it works fine.

Set up runnned well and I found the web folder created in the core folder (c:\Inetpub\wwwroot\).

But after browsing the web application for login page, it is giving a strange error saying”Request is not available in this context”.





I am having global.asax file for this web site in which under “Applcation_start” event I am using “HttpContext.Current.Request” function to read some xml file available in the root directory.
While surfing through google, I found that in IIS 7.0, we cannot use this request object in application start event.
As of now to make my web application to be worked, I found a temporary solution.
Step 1:
I opened Inetmgr (Internet Information Service manager(IIS)).
Under my machine name tab,I have selected “Applcation pools” and said “Set Applicaition pool defaults..”.




I have changed “Managed pipeline mode” value from “Integrated” to “Classic”.





There after doing this, when I have tried to browse my web application. It worked fine.




How to make an assembly as shared or global assembly.

Private assemblies can be made as shared assembly by placing them in shared assembly folder (c:\windows\assembly).

Please refer Private and Global assembles in Prog.Findings for difference between global and private assemblies.


But it is not simple step to just copy and paste in assembly folder.
There are certain steps that are to be followed for doing so.

Step 1: Prepare private assembly which you are willing to make it as global or shared.
I am creating a class library named “MsgBox”, in which I have created a class file named “Msg.cs”.
This functionality is to display a message box with the text sent as parameter.
So once if this dll is shared globally among applications, the same function can be used to display message box at all instants.
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
namespace MsgBox
{
public class Msg
{
public void DisplayMessage(string argMessage)
{
MessageBox.Show(argMessage);
}
}
}

After building the project solution, I can find a dll file created inside the bin folder which is said to be as the private assembly.
I wish to make this as global assembly and use the same dll file in other application when and there required.




Step 2: This dll has to be strongly named before placing this into the global assembly folder (c:\windows\assembly).
Strongly naming is a necessary step, else if we try to drag and drop the private assembly into c:\windows\assembly folder with out strongly naming it,
It says “Failure adding assembly to the cache: Attempt to install an assembly without a strong name”.



To strongly name the private assembly:
Step i) Open .NET command prompt and set the prompt path to the private assembly’s folder path.
Type
sn –k [filename as your wish].snk
Example: - sn –k mykey.snk





Step ii) You can identify the key file generated in the private assembly folder and with the name given (mykey.snk).







Step iii)
Open the “AssemblyInfo.cs” file under properties folder in the class library.
Mention the path of the generated key file as
[assembly: AssemblyKeyFile([key file path])]
In my example

[assembly: AssemblyKeyFile("C:/Users/srinivas/My personals/Testing/MsgBox/MsgBox/bin/Release/mykey.snk")]






Now build the solution, the dll file which has been created after building the solution is the assembly which is strongly named.
So now this assembly can be globally shared.
Step 3: Now this strongly named private assembly can be globally shared by either dragging and dropping the dll into assembly folder (c:\windows\assembly) or
By registering the private assembly using .NET Command prompt.
I am using .NET command prompt to do so.
Type:
Gacutil –I [dll file path]








Now you can find this private assembly as global assembly in “c:\windows\assembly folder.








Step 5: we should copy and paste this private assembly inside frame work folder, such that we can view this dll that can be added through “Add Reference” dialog in .NET solutions.
Framework folder is at
C:\Windows\Microsoft.NET\Framework\v2.0.50727, inside which we can find many dll files that we use while building .NET applications.
System.Data.dll
System.Design.dll,
Etc..
Simillarly we shall copy and paste our private assembly into this folder.





Step 6:Now I would like to build a new .NET application in a separate solution and in a separate folder, entirely
I am creating a “Demo1” application, in which I have created a windows form saying “MyApp”.

When I click on this add references, I can find that private assembly which has been globally shared in “c:\windows\assembly folder.






I am using this MsgBox.dll file whose functionality is to display a message box.
Windows form :







Output: