Keep in touch

you can keep in touch with my all blogs and sites by install this Toolbar...
http://rworldtoolbar.ourtoolbar.com/

Saturday, March 6, 2010

Get IP Address of Visitor's Machine

Dim ipaddress As String
ipaddress = Request.ServerVariables("HTTP_X_FORWARDED_FOR")
If ipaddress = "" Or ipaddress Is Nothing Then
ipaddress = Request.ServerVariables("REMOTE_ADDR")
End If

When users use any proxies or routers the REMOTE_ADDR returns the IP Address of router or proxy and not the client user’s machine. So first we need to check HTTP_X_FORWARDED_FOR.

Confirm Before Page Close

Try using the confirm method on the onUnLoad event:

if (confirm("Are you sure you want to leave) == true)
{ return true; }
else
{ return false; }

Export A File and Delete it from Server

Private Sub DownloadFile()
Response.ContentType = ContentType
Response.AppendHeader("Content-Disposition", _
"attachment; filename=myFile.txt")
Response.WriteFile(Server.MapPath("~/uploads/myFile.txt"))
Response.Flush()
System.IO.File.Delete(Server.MapPath("~/uploads/myFile.txt"))
Response.End()
End Sub

URL Rewritting: Hide Web Page Extentsion

write this code in ur Global.asax

Private Sub Application_BeginRequest(ByVal sender As Object, ByVal e As EventArgs)
Dim fullOrigionalpath As String = Request.Url.ToString()
If Not fullOrigionalpath.EndsWith(".aspx") Then
Context.RewritePath(fullOrigionalpath.Substring(fullOrigionalpath.IndexOf("/", 9)) & ".aspx")
End If
End Sub

Check if Url Exists or not in ASP.NET

Public Shared Function IsValidUrl(ByVal Url As String) As Boolean
Dim sStream As Stream
Dim URLReq As HttpWebRequest
Dim URLRes As HttpWebResponse
Try
URLReq = WebRequest.Create(Url)
URLRes = URLReq.GetResponse()
sStream = URLRes.GetResponseStream()
Dim reader As String = New StreamReader(sStream).ReadToEnd()
Return True
Catch ex As Exception
‘Url not valid
Return False
End Try
End Function

Convert A Number To Month Name and Month Name to Number in ASP.NET

For Converting A Number To Month Name Use:

dim MyMonthNumber as integer = 7
MonthName(MyMonthNumber)

or

Format(New Date(2009, MyMonthNumber, 1), "MMMMM")

-------------------------------------------------------------------------

For Converting A Number To Month Name Use:

dim MyMonthName as String = "July"
CDate("01-" & MyMonthName & "-2009").Month

Get Country Name by Client IP

Add WebService Reference of

http://www.webservicex.net/geoipservice.asmx?wsdl

Here is the code:

Dim objWebServiceX As New webservicex.GeoIPService
Dim countryName As String = objWebServiceX.GetGeoIP(Request.ServerVariables("REMOTE_ADDR")).CountryName
Response.Write(countryName & "
")

Write To A File on Server in ASP.NET

Public Shared Function SaveTextToFile(ByVal strData As String, ByVal fname As String) As Boolean
Try
Dim fs As New FileStream(fname, FileMode.Create, FileAccess.Write)
Dim s As New StreamWriter(fs)
s.BaseStream.Seek(0, SeekOrigin.End)
s.WriteLine(strData)
s.Close()
Return True
Catch ex As Exception
' your exception handler here
End Try
Return False
End Function

VB.NET: Read Registry Value

Imports Microsoft.Win32

dim MyValue as string
MyValue = RegValue(RegistryHive.LocalMachine, "SOFTWARE\Microsoft\Internet Explorer", "Version")

Public Function RegValue(ByVal Hive As RegistryHive, ByVal Key As String, ByVal ValueName As String, Optional ByRef ErrInfo As String = "") As String
Dim objParent As RegistryKey
Dim objSubkey As RegistryKey
Dim sAns As String
Select Case Hive
Case RegistryHive.ClassesRoot
objParent = Registry.ClassesRoot
Case RegistryHive.CurrentConfig
objParent = Registry.CurrentConfig
Case RegistryHive.CurrentUser
objParent = Registry.CurrentUser
Case RegistryHive.DynData
objParent = Registry.DynData
Case RegistryHive.LocalMachine
objParent = Registry.LocalMachine
Case RegistryHive.PerformanceData
objParent = Registry.PerformanceData
Case RegistryHive.Users
objParent = Registry.Users
End Select
Try
objSubkey = objParent.OpenSubKey(Key)
'if can't be found, object is not initialized
If Not objSubkey Is Nothing Then
sAns = (objSubkey.GetValue(ValueName))
End If
Catch ex As Exception
sAns = "Error"
ErrInfo = ex.Message
Finally
If ErrInfo = "" And sAns = "" Then
sAns = "No value found for requested registry key"
End If
End Try
Return sAns
End Function

ASP.NET: Force Page to Use secure connection HTTPS

Sometimes we want to provide secure channel over an insecure network. e.g. for payment transactions. In that case we need HTTPS connection

Assume that your page is as follows: http://www.mydomain.com/mypage.aspx

Just add following code inside Load Event Handler!

If Not Request.IsSecureConnection Then
Response.Redirect("https://www.mydomain.com/mypage.aspx ")
End If

ASP.NET: Binding DataList with Images in a Directory

<%@ Page Language="C#" %>
<%@ Import Namespace="System.IO" %>
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">




Pic Album






' style="width:200px" Runat="server" />


<%# Eval("Name") %>





ASP.NET: Programatically Change Page Headers (Title, Stylesheets, Meta)

Private Sub Page_Load()
' Change the title
Page.Header.Title = "My Content Page Title"

' Change the background color
Dim myStyle As New Style()
myStyle.BackColor = System.Drawing.Color.Red
Page.Header.StyleSheet.CreateStyleRule(myStyle, Nothing, "html")

' Create Meta Description
Dim metaDesc As New HtmlMeta()
metaDesc.Name = "DESCRIPTION"
metaDesc.Content = "Content Page Meta Description"

' Create Meta Keywords
Dim metaKeywords As New HtmlMeta()
metaKeywords.Name = "KEYWORDS"
metaKeywords.Content = "Content Page Meta Keywords"

' Add Meta controls to HtmlHead
Dim head As HtmlHead = DirectCast(Page.Header, HtmlHead)
head.Controls.Add(metaDesc)
head.Controls.Add(metaKeywords)
End Sub

This can also be used to override MasterPage setting :)

VB.NET: Write/Create an Excel File

Dim OutputArray(200, 200) As String
Dim strFileName As String = "MyExl.xls"

'set ur OutputArray here

Dim excel As New Microsoft.Office.Interop.Excel.ApplicationClass
Dim wBook As Microsoft.Office.Interop.Excel.Workbook
Dim wSheet As Microsoft.Office.Interop.Excel.Worksheet

wBook = excel.Workbooks.Add()
Try
wSheet = wBook.ActiveSheet()
Dim Range As Microsoft.Office.Interop.Excel.Range = wSheet.Range("A1", wSheet.Cells(200, 200))
Range.Value2 = OutputArray
wBook.SaveAs(strFileName)
Catch ex As Exception
msgbox("Some Error Occured !!!")
Finally
wBook.Close()
excel.Quit()
excel = Nothing
End Try

ASP.NET: GridView with Scrollbar

1. Define Your GridView as






2. Create a style as


3. Add Following code at RowDataBound Event of GridView
Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
If e.Row.RowType = DataControlRowType.DataRow Then
If e.Row.RowIndex = 0 Then
e.Row.Style.Add("height", "40px")
End If
End If
End Sub


-------------------------------------------------------------------------------------------------------
Alternativelyyou can simply do this tooo



Oracle: New String Aggregation Techniques

The LISTAGG analytic function was introduced in Oracle 11g Release 2

SELECT deptno, LISTAGG(ename, ',') WITHIN GROUP (ORDER BY ename) AS employees
FROM emp
GROUP BY deptno;

DEPTNO EMPLOYEES
---------- --------------------------------------------------
10 CLARK,KING,MILLER
20 ADAMS,FORD,JONES,SCOTT,SMITH
30 ALLEN,BLAKE,JAMES,MARTIN,TURNER,WARD




If you are not running 11g Release 2

SELECT deptno, wm_concat(ename) AS employees
FROM emp
GROUP BY deptno;

DEPTNO EMPLOYEES
---------- --------------------------------------------------
10 CLARK,KING,MILLER
20 SMITH,FORD,ADAMS,SCOTT,JONES
30 ALLEN,BLAKE,MARTIN,TURNER,JAMES,WARD




Check it out here: http://www.oracle-base.com:80/articles/misc/StringAggregationTechniques.php

ASP.NET: Get Client IP Address

Private Function GetIPs() As StringCollection
Dim localIP = New StringCollection()
Dim localHostName = Dns.GetHostName()
Dim hostEntry = Dns.GetHostEntry(localHostName)
For Each ipAddr As IPAddress In hostEntry.AddressList
localIP.Add(ipAddr.ToString())
Next
GetIPs = localIP
End Function

Tuesday, February 3, 2009

How to: Send Data Using the WebRequest Class

For C#,
=======
using System;
using System.IO;
using System.Net;
using System.Text;

namespace Examples.System.Net
{
public class WebRequestPostExample
{
public static void Main ()
{
// Create a request using a URL that can receive a post.
WebRequest request = WebRequest.Create ("http://www.rushiraval.co.cc);
// Set the Method property of the request to POST.
request.Method = "POST";
// Create POST data and convert it to a byte array.
string postData = "This is a test that posts this string to a Web server.";
byte[] byteArray = Encoding.UTF8.GetBytes (postData);
// Set the ContentType property of the WebRequest.
request.ContentType = "application/x-www-form-urlencoded";
// Set the ContentLength property of the WebRequest.
request.ContentLength = byteArray.Length;
// Get the request stream.
Stream dataStream = request.GetRequestStream ();
// Write the data to the request stream.
dataStream.Write (byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close ();
// Get the response.
WebResponse response = request.GetResponse ();
// Display the status.
Console.WriteLine (((HttpWebResponse)response).StatusDescription);
// Get the stream containing content returned by the server.
dataStream = response.GetResponseStream ();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader (dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd ();
// Display the content.
Console.WriteLine (responseFromServer);
// Clean up the streams.
reader.Close ();
dataStream.Close ();
response.Close ();
}
}

------------------------------------------------------------------------------------

For VB,
==========
Imports System
Imports System.IO
Imports System.Net
Imports System.Text
Namespace Examples.System.Net
Public Class WebRequestPostExample

Public Shared Sub Main()
' Create a request using a URL that can receive a post.
Dim request As WebRequest = WebRequest.Create("http://www.rushiraval.co.cc ")
' Set the Method property of the request to POST.
request.Method = "POST"
' Create POST data and convert it to a byte array.
Dim postData As String = "This is a test that posts this string to a Web server."
Dim byteArray As Byte() = Encoding.UTF8.GetBytes(postData)
' Set the ContentType property of the WebRequest.
request.ContentType = "application/x-www-form-urlencoded"
' Set the ContentLength property of the WebRequest.
request.ContentLength = byteArray.Length
' Get the request stream.
Dim dataStream As Stream = request.GetRequestStream()
' Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length)
' Close the Stream object.
dataStream.Close()
' Get the response.
Dim response As WebResponse = request.GetResponse()
' Display the status.
Console.WriteLine(CType(response, HttpWebResponse).StatusDescription)
' Get the stream containing content returned by the server.
dataStream = response.GetResponseStream()
' Open the stream using a StreamReader for easy access.
Dim reader As New StreamReader(dataStream)
' Read the content.
Dim responseFromServer As String = reader.ReadToEnd()
' Display the content.
Console.WriteLine(responseFromServer)
' Clean up the streams.
reader.Close()
dataStream.Close()
response.Close()

End Sub
End Class
End Namespace

}

for detailed, read more

Thursday, October 23, 2008

Javascript validation for input limited text into textbox or textarea in ASP.NET

Javascript validation for input limited text into textbox or textarea
On design page source::
----------------------------



On b/h code source page:
protected void Page_Load(object sender, EventArgs e)
{
txtLocation.Attributes.Add("onkeypress", "return LocationLength()");
txtLocation.Attributes.Add("onkeyup", "return LocationLength()");
}

Happy Coding..!!

Saturday, October 18, 2008

Get And Set The System Date And Time using c#

Have you want to get your current system date and time as well as set the system date and time using c# code.
here it is, C# code snippet that uses unmanaged code to retrieve the current date and time of the Windows operating system, and also sets it to the specified values.

  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Windows.Forms;
  6. using System.Runtime.InteropServices;
  7. namespace Sample
  8. {
  9. public partial class Form1 : Form
  10. {
  11. public Form1()
  12. {
  13. InitializeComponent();
  14. }
  15. public struct SystemTime
  16. {
  17. public ushort Year;
  18. public ushort Month;
  19. public ushort DayOfWeek;
  20. public ushort Day;
  21. public ushort Hour;
  22. public ushort Minute;
  23. public ushort Second;
  24. public ushort Millisecond;
  25. };
  26. [DllImport("kernel32.dll", EntryPoint = "GetSystemTime", SetLastError = true)]
  27. public extern static void Win32GetSystemTime(ref SystemTime sysTime);
  28. [DllImport("kernel32.dll", EntryPoint = "SetSystemTime", SetLastError = true)]
  29. public extern static bool Win32SetSystemTime(ref SystemTime sysTime);
  30. private void button1_Click(object sender, EventArgs e)
  31. {
  32. // Set system date and time
  33. SystemTime updatedTime = new SystemTime();
  34. updatedTime.Year = (ushort)2008;
  35. updatedTime.Month = (ushort)4;
  36. updatedTime.Day = (ushort)23;
  37. // UTC time; it will be modified according to the regional settings of the target computer so the actual hour might differ
  38. updatedTime.Hour = (ushort)10;
  39. updatedTime.Minute = (ushort)0;
  40. updatedTime.Second = (ushort)0;
  41. // Call the unmanaged function that sets the new date and time instantly
  42. Win32SetSystemTime(ref updatedTime);
  43. // Retrieve the current system date and time
  44. SystemTime currTime = new SystemTime();
  45. Win32GetSystemTime(ref currTime);
  46. // You can now use the struct to retrieve the date and time
  47. MessageBox.Show("It's " + currTime.Hour + " o'clock. Do you know where your C# code is?");
  48. }
  49. }
  50. }
Happy Coding..!!

Delete All Temporary Internet Files Of Internet Explorer

  1. using System.IO;
  2. public static void Main()
  3. {
  4. ClearFolder(new DirectoryInfo(Environment.GetFolderPath(Environment.SpecialFolder.InternetCache))); // Execute ClearFolder() on the IE's cache folder
  5. }
  6. void ClearFolder(DirectoryInfo diPath)
  7. {
  8. foreach (FileInfo fiCurrFile in diPath.GetFiles())
  9. {
  10. fiCurrFile.Delete();
  11. }
  12. foreach (DirectoryInfo diSubFolder in diPath.GetDirectories())
  13. {
  14. ClearFolder(diSubFolder); // Call recursively for all subfolders
  15. }
  16. }
Happy Coding..!!