Tuesday, September 20, 2011

Reading and Writing CLOB column in oracle by asp.net


Imports Oracle.DataAccess.Client
Imports Oracle.DataAccess.Types

Public Sub ReadLOBData()
Dim con As New OracleConnection(connectionstring)
con.Open()
Dim sql As String = "Select Mft_Text from Tab_Manifestation where Mft_Id=2"
Dim cmd As OracleCommand = New OracleCommand(sql, con)
Dim dr As OracleDataReader = cmd.ExecuteReader()
dr.Read()
Dim blob As OracleClob = dr.GetOracleClob(0)
txtManifest.Text = blob.Value
blob.Close()
dr.Close()
con.Close()
End Sub

Public Sub WriteLOBData()
Dim connection As New OracleConnection(connectionstring)
connection.Open()

Dim strSQL As String = "INSERT INTO TestCLOB (ID,CLOBTEXTFIELD) VALUES (1,:TEXT_DATA) "
'Dim strsql As String = "UPDATE TestCLOB SET CLOBTEXTFIELD=:TEXTDATA where testid=1"
Dim paramData As New OracleParameter
paramData.Direction = ParameterDirection.Input
paramData.OracleDbType = OracleDbType.Clob
paramData.ParameterName = "TEXT_DATA"
paramData.Value = txtInput.Text

Dim cmd As New OracleCommand
cmd.Connection = connection
cmd.Parameters.Add(paramData)
cmd.CommandText = strSQL
cmd.ExecuteNonQuery()

paramData = Nothing
cmd = Nothing
connection.Close()
End Sub

Monday, March 7, 2011

Parent Child Relation Query in Oracle

This query brings the records where record is related with parent
records

select parent
from relation
start with child='d2'
connect by prior parent = child;

Thursday, March 18, 2010

Keeping Session Live all the time in Asp.net

In Master Page of Page Load Event Call the Function

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load AddKeepAlive()
End Sub
Private Sub AddKeepAlive() Dim int_MilliSecondsTimeOut As Integer = 2 * 60 * 1000 '2 minutes 'Math.Max((this.Session.Timeout * 60000) - 30000, 5000); Dim path As String = VirtualPathUtility.ToAbsolute("~/KeepAlive.aspx")
Dim str_Script As String = ("<script>(function(){var r=0,w=window;if (w.setInterval)w.setInterval(function() {r ;var img=new Image(1,1);img.src='" & path & "?count=' r;},") int_MilliSecondsTimeOut.ToString() & ");})();</script>" Page.ClientScript.RegisterStartupScript(GetType(Page), UniqueID & "Reconnect", str_Script) End Sub


Create a Page say as KeepAlive.aspx
Add this in the Page

<%@ OutputCache Location="None" VaryByParam="None" %><?xml version="1.0" encoding="utf-8"?>
<%=now %>

Monday, February 22, 2010

To Fire OnBlur Event of Textbox on Sever Side

I will show in this post a simple method to fire onBlur Event of a textbox in server side, this can be used to check the value in textbox with the database, like to validate the data if already exist

put a server side button in the page and hide the button with div having style display none so that it is not triggered by clicking event
In page load
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim eventhandler As String = Me.ClientScript.GetPostBackEventReference(Me.btnLoad, "")
Me.TextName.Attributes.Add("onblur", eventhandler)

End Sub


Write your process in the button click event
Protected Sub btnLoad_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnLoad.Click
‘Put your Own Code’
End Sub

Thursday, February 18, 2010

Enter Key in Asp.net

One of the common requests in ASP.NET is to submit a form when visitor hits an Enter key. That could be a case if, for example you want to make Login Screen. It is expected that user just hit enter when he insert a user name and password instead to of forcing him to use a mouse to click login button. If you want to make search function on your web site, it is frequently required to give a possibility to hit enter after you insert a search terms instead of mouse click on a Search button.

When you don’t want to submit a form with Enter key?

Rarely, you will need to disable an Enter key and avoid submitting form. If you want to prevent it completely, you need to use OnKeyDown handler on <body> tag of your page. The JavaScript code should be:


if (window.event.keyCode == 13)
{
event.returnValue=false;
event.cancel = true;
}



How to make a default button in ASP.NET
Method1:

TextBox1.Attributes.Add("onkeydown", "if(event.which event.keyCode){if ((event.which == 13) (event.keyCode == 13)) {document.getElementById('"+Button1.UniqueID+"').click();return false;}} else {return true}; ");

Method2:

<form defaultbutton="button1" runat="server">
<asp:textbox id="textbox1" runat="server"/>
<asp:textbox id="textbox2" runat="server"/>
<asp:button id="button1" text="Button1" runat="server"/>

<asp:panel defaultbutton="button2" runat="server">
<asp:textbox id="textbox3" runat="server"/>
<asp:button id="button2" runat="server"/>
</asp:panel>
</form>

Sunday, February 7, 2010

Replace any Character in Text File in Vb.net

Sub Main()
Dim Fs As FileStream = New FileStream("c:\Edit1.TXT",FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite)
Dim sw As New StreamWriter(Fs)
Dim sr As New StreamReader(Fs)
Dim str As String
str = sr.ReadToEnd()
str = str.Replace(vbCrLf, "^")
Fs.Position = 0
Fs.SetLength(str.Length)
sw.Write(str)
sw.Flush()
sw.Close()
Fs.Close()
End Sub

Happy Coding!

Sunday, January 17, 2010

SFTP Client OpenSource and DLL

You can find opensource code to for SecureFTP Server in the below said link
where the dlls can be used in .Net to access files in SecureFTP Server

http://www.tamirgal.com/blog/page/SharpSSH.aspx

Thanks to Tamir Gal

Note: In the wrapper class the rm function has to be called for remove file function in the source code and compile

Tuesday, January 12, 2010

Error Log in Text File in Asp.Net 2.0

Simple vb.net code function used to log error in text file which rises in our application

Imports Microsoft.VisualBasic
Imports System.IO
Imports System.Globalization

Public Class ErrorHandler

Public Shared Sub WriteError(ByVal errorMessage As String)
Try
Dim path As String = "~/Error/" & DateTime.Today.ToString("dd-mm-yy") & ".txt"
If (Not File.Exists(System.Web.HttpContext.Current.Server.MapPath(path))) Then
File.Create(System.Web.HttpContext.Current.Server.MapPath(path)).Close()
End If
Using w As StreamWriter = File.AppendText(System.Web.HttpContext.Current.Server.MapPath(path))
w.WriteLine(Constants.vbCrLf & "Log Entry : ")
w.WriteLine("{0}", DateTime.Now.ToString(CultureInfo.InvariantCulture))
Dim err As String = "Error in: " & System.Web.HttpContext.Current.Request.Url.ToString() & ". Error Message:" & errorMessage
w.WriteLine(err)
w.WriteLine("__________________________")
w.Flush()
w.Close()
End Using
Catch ex As Exception

End Try

End Sub
End Class



This Code should be written in App_Code Folder of Web Application

This function can be called in all Exception Catches
Try
'Your Code Goes Here’
Catch ex as Exception
ErrorHandler.WriteError(ex.Innerexception)
End Try



To Err is Human

Monday, December 21, 2009

Disable button by checking validators and invoke server side event

Scenario: - Check whether any validator is triggered. If triggered then don't postback and don't disable the button. If all validators are valid then disable the button and call the server side event.

Solution:-
To solve this scenario , I found out one simple solution using javascript


<script type="text/javascript" language="javascript">
function fnValidate(obj)
{
for(var i=0; i<Page_Validators.length; i++)
{
ValidatorEnable(Page_Validators[i]);

if (Page_Validators[i].isvalid)
{
obj.disabled=true;
}
else
{
obj.disabled=false;
break;
}
}

if (obj.disabled==true)
{
<%=Page.GetPostBackEventReference(btnSubmit)%> }

}

</script>


Call this javascript function in button's OnClientClick property as follows.


<asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClientClick="fnValidate(this);" CausesValidation="true" OnClick="btnSubmit_Click"/>

Tuesday, December 1, 2009

Enum to Datatable Function Using Vb.net

In this post I have given simple vb.net snippet to convert Enumeration data to datatable, so that we can use the enumeration datas as master table or lookup table


Shared Function EnumToDataTable(ByVal typEnum As Type) As DataTable
Dim ddlTypnames() As String = [Enum].GetNames(typEnum)
Dim arrddlTypVals As Array = [Enum].GetValues(typEnum)

Dim dt As New DataTable
Dim dr As DataRow

dt.Columns.Add(New DataColumn("values", GetType(Int32)))
dt.Columns.Add(New DataColumn("names", GetType(String)))
Dim i2 As Integer
For i2 = 0 To ddlTypnames.Length() - 1
dr = dt.NewRow()

dr(0) = CInt(arrddlTypVals(i2))
dr(1) = ddlTypnames(i2)

dt.Rows.Add(dr)
Next i2

Return dt
End Function

Using this function

Dim dt As DataTable
dt = EnumToDataTable(GetType(EnumSample))


Happy Coding!

Sunday, November 22, 2009

To Disable Button on Submit Using JavaScript

Simple Javascript Snippet to disable button on submitting to server,
this script has to be placed in the page where the button has to be disabled.
Paste the script below the script manager
This function used to disable the button when the server side button is
clicked and after all other validations.

<script language="javascript" type="text/javascript">
//Set function to execute when the event occurs

..Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(BeginRequestHandler);
//The function which will disable the button

function BeginRequestHandler(sender, args)
{
document.getElementById("$lt%=btnSave.ClientId %>").disabled=true;
//Insert here the script that needs to be executed
//before the request is sended to the server
}

</script>


Add This in WebConfig File

<httphandlers>

<add validate="false" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" path="ScriptResource.axd" verb="GET,HEAD">
</httphandlers>
<httpmodules>
<add type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" name="ScriptModule">
</httpmodules>

Tuesday, November 3, 2009

To Read Line By Line of Text File in VB.net 2.0

In this Post I have shown the simple code snippet for reading a text file line by line.

Dim strFileName As String = String.Empty
Dim fs As FileStream = Nothing
Dim m_streamReader As StreamReader = Nothing
Dim strCompany As String = String.Empty

fs = New FileStream(strFilePath, FileMode.Open, FileAccess.Read)
m_streamReader = New StreamReader(fs)
m_streamReader.BaseStream.Seek(0, SeekOrigin.Begin)

Do
strContent = m_streamReader.ReadLine()

Loop While (Not m_streamReader.EndOfStream)

Thursday, October 8, 2009

Simple Delay Function Using VB.Net

Simple Delay Function Using VB.Net

Private Sub Delay(ByVal ms As Integer)
Dim time As Integer = Environment.TickCount
Do While (True)
If Environment.TickCount - time >= ms Then
Exit Do
End If
Loop
End Sub

Happy Coding!

Sunday, September 27, 2009

To Write and Save a Text File in Asp.Net 2.0

In this post I will show u the simple code snippet to write and save a text file in specific folder in asp.net using vb code


Public Sub WriteTextandSaveFile()

Dim fs As FileStream = Nothing
Dim sw As StreamWriter = Nothing

Try
fs = New FileStream("D:\Sample\Sample1.txt", FileMode.Create, FileAccess.Write)
sw = New StreamWriter(fs)
sw.WriteLine("This is Sample text")

Catch ex As Exception

Finally
sw.Close()
fs.Close()
sw.Dispose()
fs.Dispose()
End Try


End Sub


never regret anything, if it was good, its wonderful, if it was bad, its experience!

Wednesday, September 16, 2009

Simple File Watcher Program using Vb.Net 2.0

I will show you how to watch file’s activities in a folder and log it, say if a text file is created, changed, deleted etc in specific folder that will be logged in separated text file

First Create a Folder of your own name in your specified path,

In D drive create a folder WatchFolder so the path would be D:\WatchFolder
In D drive create another folder Logs and inside the Log Folder Create Log.txt so the path would be like this D:\Logs\Log.txt

Now create a Project

File-> New Project -> WindowsApplication1 - OK!

In the left side toolbox pan drag and drop FileSystemWatcher control to the Form

Create Two Buttons Button1 and Button 2 in the Form

Change the Text of Button1 as Start Watch and Change the Text of Button2 as Stop Watch

And Write the Code as Follows



Imports System.IO

Public Class Form1

Private Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
FileSystemWatcher1.Path = "D:/WatchFolder"
MsgBox("Started Watching Folder")
End Sub

Private Sub Button2_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button2.Click
FileSystemWatcher1.Dispose()
MsgBox("Stopped Watching Folder")
End Sub

Private Sub FileSystemWatcher1_Changed(ByVal sender As Object, ByVal e As System.IO.FileSystemEventArgs) Handles FileSystemWatcher1.Changed
WriteLog(e.Name + " Changed")
End Sub

Private Sub FileSystemWatcher1_Created(ByVal sender As Object, ByVal e As System.IO.FileSystemEventArgs) Handles FileSystemWatcher1.Created
WriteLog(e.Name + " Created")
End Sub

Private Sub FileSystemWatcher1_Deleted(ByVal sender As Object, ByVal e As System.IO.FileSystemEventArgs) Handles FileSystemWatcher1.Deleted
WriteLog(e.Name + " Deleted")
End Sub

Private Sub WriteLog(ByVal strMsg As String)
Dim fs As FileStream = New FileStream("D:\WatchFolder\Logs\Log.txt", FileMode.Append, FileAccess.Write)
Dim m_streamWriter As StreamWriter = New StreamWriter(fs)
m_streamWriter.BaseStream.Seek(0, SeekOrigin.End)
m_streamWriter.WriteLine(Now.ToString() & " ::==> " & strMsg & Constants.vbLf)
m_streamWriter.Flush()

fs.Close()

fs.Dispose()
End Sub


End Class



Test Results Were Extremely Gratifying, We're surprised the stupid thing works.

Thursday, August 13, 2009

Master Detail Group Report Using Crystal Report XI



Report generation Plays a Major Role in Application Project, So I will show you how create a simple report using Crystal Report XI


Say Table A --> Describes the student Details


Table A
Student Id (Primary Key)
Student Name
Student Class




Say Table B --> Describes the Student Fees Paid Details


Table B
Paid Id (Primary Key)
Student Id (Foreign Key)
Paid Amount
Paid Date

Table B will have multiple Entries for Single Entry of Table A


I will Explain Step by Step Method to display in the Crystal Report XI


Step 1: Open Crystal Report XI
Step 2: File-> New-> Standard Report
Step 3: Create New Connection-> OLE DB (ADO) -> Microsoft OLE DB Provider for Oracle
I have mentioned for Oracle Provider, you can select your own data source
Step 4: Service: Server Name; UserId: Username; Password: Password of the server
Step 5: Select the Two Tables from Left Side Pan of Available Data source and Move to Right Side
Step 6: Click Next
Step 7: You will see two tables in the Report Creation Wizard, Now Select the Primary Key of Table A and Drag to Table B’s Foreign Key
Step 8: Select the Line/Link of the two tables and Right Click it Select Link Option
Step 9: Select the Radio Button of Left Outer Join and Press Ok button
Step 10: Click Finish Button
Step 11: Select from Menu Insert-> Group Select the Primary Key of Table A and Select Ascending Order and Press Ok Button
Now you can see Detail Section below Group Section
Step 12: Now place the Table A Details in Group Header Section and Place the Table B Details in Details Section



If you preview, you can see the Table B Details of Every Record of Table A
And you can filter by record selection formula.



Happy To Share!




Monday, August 10, 2009

To Select All Checkboxes in Grid View Using JavaScript

In this I have given simple tip to select all the check boxes in the template field of a gridview
Using JavaScript,

Place the JavaScript where the gridview you have to bind

JavaScript in the Page

<script type="text/javascript" language="javascript">
function fncheckAll()
{
var eleChk=event.srcElement;
var eleTbody=eleChk.parentNode.parentNode.parentNode;
var i=1;
for(i=1;i<eleTbody.children.length;i++)
eleTbody.children[i].children[2].children[0].checked=eleChk.checked;
}
</script>


Grid View

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" >
<Columns>
<asp:BoundField DataField="CustomerName" HeaderText="Name" />
<asp:BoundField DataField="CustomerAge" HeaderText="Age" />
<asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox ID="chkSelectAll" runat="server" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkId" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>


Code Behind

Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
If e.Row.RowType = DataControlRowType.Header Then
CType(e.Row.Cells(2).FindControl("chkSelectAll"), CheckBox).Attributes.Add("onclick", "fncheckAll()")
End If
End Sub

Close Project Coordination -We know who to blame.

Sunday, August 9, 2009

Validating a Textbox in Grid View Using JavaScript

In this post I will show you how to validate a textbox placed in template field of grid view
Say for eg, we have grid view listing Currency and Exchange rate
Where the exchange is in textbox field where you the user can change it
Now we will validate for the currency

If the Currency Code is USD then the exchange rate should not be less that of 3.665

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" >
<Columns>
<asp:BoundField DataField="Currency" HeaderText="Currency" />
<asp:TemplateField HeaderText="Exchg Rate" >
<ItemTemplate>
<asp:TextBox ID="txtExchgRate" runat="server" ></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>



Code Behind

Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound

If e.Row.RowType = DataControlRowType.DataRow Then

If e.Row.Cells(0).Text = "USD" Then
CType(e.Row.Cells(1).FindControl("txtExchgRate"), TextBox).Attributes.Add("onblur", "fnValUSDExchg(this)")
End If

End If

End Sub


JavaScript Function

<script language="javascript" type="text/javascript">

function fnValUSDExchg(txtbox)
{
if (txtbox.value<=3.665)
txtbox.value=3.665;
}
</script>

Low Maintenance - Impossible to fix if broken.

To Create an Corresponding Button Event by Hitting on Enter key

I will show you simple tip how to create an event by hitting on enter key after writing some text in corresponding textbox without conflicts in other events
Say if you have two textboxes and corresponding buttons, in which you write text to textbox of the two, corresponding button event should fire when enter key is hit


<asp:Panel ID="Panel1" runat="server" DefaultButton="Button1">
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</asp:Panel>
<asp:Panel ID="Panel2" runat="server" DefaultButton="Button2">
<asp:Button ID="Button2" runat="server" Text="Button" OnClick="Button2_Click" Style="height: 26px" />
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
</asp:Panel>




Savings are achieved when the power switch is off