RSS

Generate a Random Password or Verification String

How to Generate a Random Password or Verification String

- In some cases we need to generate the random string using the some of the input from the user. This post simply explains about the generating the Random Verification string.

- To generate the random verification string we need to give the input for how many characters we need a output, input Letter (e.g., User Name) and the number for mixing to the string.

- Use the following Random generator code class library we can create the verification codes.

''' <summary>
''' GENERATES A RANDOM STRING OF LETTERS AND NUMBERS. LETTERS CAN BE RANDOMLY
'CAPITAL OR SMALL.
''' </summary>
''' <returns type="String">RETURNS THE RANDOMLY GENERATED KEY</returns>

Public Function Generate() As String
Dim i_key As Integer
Dim Random1 As Single
Dim arrIndex As Int16
Dim sb As New StringBuilder
Dim RandomLetter As String

' CONVERT LettersArray & NumbersArray TO CHARACTR ARRAYS
LettersArray = Key_Letters.ToCharArray
NumbersArray = Key_Numbers.ToCharArray

For i_key = 1 To Key_Chars
Randomize()
Random1 = Rnd()
arrIndex = -1
' IF THE VALUE IS AN EVEN NUMBER WE GENERATE A LETTER, OTHERWISE WE
' GENERATE A NUMBER
' THE NUMBER '111' WAS RANDOMLY CHOSEN. ANY NUMBER WILL DO, WE JUST NEED
' TO BRING THE VALUE ABOVE '0'

If (CType(Random1 * 111, Integer)) Mod 2 = 0 Then
' GENERATE A RANDOM LOCATION IN THE LETTERS CHARACTER ARRAY
Do While arrIndex < 0
arrIndex = Convert.ToInt16(LettersArray.GetUpperBound(0) * Random1)
Loop
RandomLetter = LettersArray(arrIndex)
' CREATE ANOTHER RANDOM NUMBER. IF IT IS ODD, WE CAPITALIZE THE
' LETTER
If (CType(arrIndex * Random1 * 99, Integer)) Mod 2 <> 0 Then
RandomLetter = LettersArray(arrIndex).ToString
RandomLetter = RandomLetter.ToUpper
End If
sb.Append(RandomLetter)
Else
' GENERATE A RANDOM LOCATION IN THE NUMBERS CHARACTER ARRAY
Do While arrIndex < 0
arrIndex = Convert.ToInt16(NumbersArray.GetUpperBound(0) * Random1)
Loop
sb.Append(NumbersArray(arrIndex))
End If
Next
Return sb.ToString
End Function


- To add the Reference of the dll to another project (Window or Web) and create teh object for the class RandomKeyGenerator and call the method Generate().
E.g.
protected void Button1_Click(object sender, EventArgs e)
{
RandomKeyGenerator Rnd = new RandomKeyGenerator();
Rnd.KeyChars = 5;
Rnd.KeyLetters = "Siva";
Rnd.KeyNumbers = "12345";
Response.Write(Rnd.Generate());
}

To use the namespace using RandomKey;

-> To download Random Verification String Generator Click Here

read comments Read User's Comments

Working With Session in Asp.Net (Vb.Net Code behind)

Working With Session

- How to Check the Session expires in the main page, the redirect to the default page or login page.
- In Default.aspx page To add a label with the text “Your Name” , Text Box and Button Control with text “Go”



- To set the Session for the Name which you gave, use the following code

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
If (Trim(TextBox1.Text) <> "") Then
Session("UserName") = UCase(Trim(TextBox1.Text))
Response.Redirect("Mainpage.aspx")
Else
Response.Write("User Name Required!")
End If
End Sub

To check session expires and the other pages redirect to default page
- We can check using the Query String from the other pages to the Default Page in the Page load event.

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If (Not IsPostBack) Then
If (Request.QueryString("session") = "expired") Then
Response.Write("Your Session has Expired")
End If
End If
End Sub

To Validate the Session in other page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As 
System.EventArgs) Handles Me.Load
If (Not IsPostBack) Then
If (Session.Item("UserName") <> Nothing) Then
Label1.Text = "Welcome Dear " &
Session.Item("UserName").ToString()
ElseIf (Session.IsNewSession = True) Then
Response.Redirect("Default.aspx?Session=expired")
Else
Response.Redirect("Default.aspx?Session=Empty")
End If
End If
' Response.Write("Session Time out:-" &
' *Session.Timeout.ToString())
End Sub

- To Make the Session Expiry the Session.Abandon() Method is used. This Will act like Logout.

- To Set the Session Timeout duration using the web config file’s SessionState Tag.
E.g.
<sessionState mode="InProc" timeout="10">
</sessionState>

- To Use this we can set the State to Handling the Session. Normally in a small Web Application we can use the InProc mode. Other Session Modes are StateServer,SQLServer,Off,Custom.

- The Default Session Timeout Time span is 20 minutes. We can Set the Session time out maximum of 1 year i.e, 525,601 minutes.

To Set the Session Expiry in Local IIS

- If we are using the Local IIS as web server we can set the Session expiry time through the Application Pool of the IIS.

read comments Read User's Comments

How to Get the COM Port List

>> We can get the COM port list available in the local system using the Name space System.Management.

>> The Serial port class's GetPortNames() method is used to get the COM Ports alone.
Eg.

String[] COMS =System.IO.Ports.SerialPort.GetPortNames();

>> We need to list the all the Ports available in the Local System then the ManagementObjectSearcher Class used.
Eg.

ManagementObjectSearcher ObjUsbSearcher = new ManagementObjectSearcher("Select * from WIN32_SerialPort");

>> The bellow code is Navigate through the ObjUsbSearcher
foreach(ManagementObject Port1 in ObjUsbSearcher.Get())
{
listBox1.Items.Add((String)Port1.GetPropertyValue("Name"));

}

read comments Read User's Comments

Simple Example for event handling in C#

To place a singe button(Button1),textbox(txtViewer) in the Form and create teh new user defind method called OnClick() and wireup the event using the bellow code part

//The Default Form1() initializer Method
public Form1()
{
InitializeComponent();
button1.Click += new EventHandler(OnClick);// Onclick Based
this.Resize+=new EventHandler(this.ResizeForm); //While Form is Resized
}

// User defind method wireupped with Button1 Click
public void OnClick(object sender, EventArgs e)
{
this.txtViewer.Text = "This is test for Event";
}

//User defind method wired with form resize
private void ResizeForm(object sender, EventArgs e)
{
MessageBox.Show("Oops! Form Resized");
}

read comments Read User's Comments

To Retrieve the Sheet Names From the Excel Book

To Use the bellow Method we can get the Sheets Names in the List Box(i.e, lstSheetName) availble in the Form.

public string GetExcelSheetName(String xlsName)
{
OleDbConnection ObjCon = null;
DataTable ObjTable = null;
String ConStr = String.Empty;

try
{
ConStr = "Provider=Microsoft.Jet.Oledb.4.0;Data source=" + XlsFileName;
ConStr += ";Extended Properties=Excel 8.0;";
ObjCon = new OleDbConnection(ConStr);
ObjCon.Open();
ObjTable = ObjCon.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if (ObjTable != null)
{
String[] Sheets = new String[ObjTable.Rows.Count];
int i = 0;
foreach (DataRow dr in ObjTable.Rows)
{
Sheets[i] = dr["TABLE_NAME"].ToString();
i++;
}
// This List box Used to List Sheet Names in Given Excel File
lstSheetName.Items.AddRange(Sheets);
bflg = true;
return "Sheet Name Retrieved Successfuly.";
}
else
{
bflg =false;
return "Excel Database is Empty!.";
}
}
catch (Exception ex)
{
bflg = false;
return ex.Message;
}
}

read comments Read User's Comments