Friday, October 23, 2015

Generate Random Strings Using ASP/VBScript


Generate Random Strings Using ASP/VBScript

This is a simple yet highly customizable function that allows you to generate random strings using VBScript that you can use in your ASP/VBScript applications. The random strings can be used for various purposes, including:

  • Login Systems
    • Random password for new registrations
    • Random password for users requesting password reset
  • Referral Codes
  • Promotional Codes
  • Primary Keys for tables where using integers as primary keys is not desirable

It generates an 8 character long random string that contains 1 digit:

<%
function RandomString()

    Randomize()

    dim CharacterSetArray
    CharacterSetArray = Array(_
        Array(7, "abcdefghijklmnopqrstuvwxyz"), _
        Array(1, "0123456789") _
    )

    dim i
    dim j
    dim Count
    dim Chars
    dim Index
    dim Temp

    for i = 0 to UBound(CharacterSetArray)

        Count = CharacterSetArray(i)(0)
        Chars = CharacterSetArray(i)(1)

        for j = 1 to Count

            Index = Int(Rnd() * Len(Chars)) + 1
            Temp = Temp & Mid(Chars, Index, 1)

        next

    next

    dim TempCopy

    do until Len(Temp) = 0

        Index = Int(Rnd() * Len(Temp)) + 1
        TempCopy = TempCopy & Mid(Temp, Index, 1)
        Temp = Mid(Temp, 1, Index - 1) & Mid(Temp, Index + 1)

    loop

    RandomString = TempCopy

end function
%>
Sample Output
jogwafs2
uuwigi6r
cj3gpdbn
7ifmzdhq
yvceae4x
qm8dxhik
4kyhyevr
evk9hmcb

For better readability and ease of customization, I have split the CharacterSetArray definition on to multiple lines. This code relies on VBScript Arrays and the following functions:

  • Randomize()
  • Rnd()
  • Int()
  • Len()
  • Mid()

Customization

With minor changes to the CharacterSetArray, you can customize the length and characters of the generated strings.

Complex password that contains 1 digit and 1 symbol
<%
function RandomString()

    Randomize()

    dim CharacterSetArray
    CharacterSetArray = Array(_
        Array(6, "abcdefghijklmnopqrstuvwxyz"), _
        Array(1, "0123456789"), _
        Array(1, "!@#$+-*&?:") _
    )

    dim i
    dim j
    dim Count
    dim Chars
    dim Index
    dim Temp

    for i = 0 to UBound(CharacterSetArray)

        Count = CharacterSetArray(i)(0)
        Chars = CharacterSetArray(i)(1)

        for j = 1 to Count

            Index = Int(Rnd() * Len(Chars)) + 1
            Temp = Temp & Mid(Chars, Index, 1)

        next

    next

    dim TempCopy

    do until Len(Temp) = 0

        Index = Int(Rnd() * Len(Temp)) + 1
        TempCopy = TempCopy & Mid(Temp, Index, 1)
        Temp = Mid(Temp, 1, Index - 1) & Mid(Temp, Index + 1)

    loop

    RandomString = TempCopy

end function
%>
Sample Output
zb5&bxjr
pd$8lrlu
yljmoq:5
$xsaxc6r
sf!n3mho
tpg+t4pr
@zykc1pb
ln3ep-vk

Even more complex password that contains 1 upper-case character, 1 digit and 1 symbol

<%
function RandomString()

    Randomize()

    dim CharacterSetArray
    CharacterSetArray = Array(_
        Array(5, "abcdefghijklmnopqrstuvwxyz"), _
        Array(1, "ABCDEFGHIJKLMNOPQRSTUVWXYZ"), _
        Array(1, "0123456789"), _
        Array(1, "!@#$+-*&?:") _
    )

    dim i
    dim j
    dim Count
    dim Chars
    dim Index
    dim Temp

    for i = 0 to UBound(CharacterSetArray)

        Count = CharacterSetArray(i)(0)
        Chars = CharacterSetArray(i)(1)

        for j = 1 to Count

            Index = Int(Rnd() * Len(Chars)) + 1
            Temp = Temp & Mid(Chars, Index, 1)

        next

    next

    dim TempCopy

    do until Len(Temp) = 0

        Index = Int(Rnd() * Len(Temp)) + 1
        TempCopy = TempCopy & Mid(Temp, Index, 1)
        Temp = Mid(Temp, 1, Index - 1) & Mid(Temp, Index + 1)

    loop

    RandomString = TempCopy

end function
%>
Sample Output
cg9hm$Yy
Mmp&j1kp
kipww7H+
?oVjny9b
Qjq5lgi-
sd:7Elnp
*kaxgl4Z
xqjc5jN!

Referral code containing mix of digits and upper-case characters

<%
function RandomString()

    Randomize()

    dim CharacterSetArray
    CharacterSetArray = Array(_
        Array(4, "ABCDEFGHIJKLMNOPQRSTUVWXYZ"), _
        Array(4, "0123456789") _
    )

    dim i
    dim j
    dim Count
    dim Chars
    dim Index
    dim Temp

    for i = 0 to UBound(CharacterSetArray)

        Count = CharacterSetArray(i)(0)
        Chars = CharacterSetArray(i)(1)

        for j = 1 to Count

            Index = Int(Rnd() * Len(Chars)) + 1
            Temp = Temp & Mid(Chars, Index, 1)

        next

    next

    dim TempCopy

    do until Len(Temp) = 0

        Index = Int(Rnd() * Len(Temp)) + 1
        TempCopy = TempCopy & Mid(Temp, Index, 1)
        Temp = Mid(Temp, 1, Index - 1) & Mid(Temp, Index + 1)

    loop

    RandomString = TempCopy

end function
%>
Sample Output
9HL284CB
OTH357O8
DY6W32J0
4KI134MJ
QP190HE9
KDU35A67
PY03F3S2
3EBV871R

Monday, August 3, 2015

Page Life Cycle of Master Page with Content Page

Generally one question is faced by very developer what is asp.net page life cycle every body know very well like sequence of asp.net page event like

  1. Page_init
  2. Page_load
  3. Page_render
  4. Page_unload

It is fine for standalone pages but if a page have master page then what the page life cycle? confuse!!!

Below is the sequence of event of page events which contain master page with chronological order.


  1. Master page (Page_Init) event
  2. Content page (Page_Init) event
  3. Content page (Page_Load) event
  4. Master page (Page_Load) event
  5. Content page (Page_Prerender) event
  6. Master page (Page_Prerender) event
  7. Content page (Page_Prerendercomplete) event
  8. Master page (Page_Prerendercomplete) event


Remember one thing page life cycle of page contain master page all event fire like first master page event then content page event but in case of page load event first content page load event fire then master page event fire.

Thursday, April 2, 2015

HowTo: Convert a string to proper case in a label expression

Summary

Instructions provided describe how to use a label expression to convert a string that is upper case, lower case or mixed case to proper case. For example, if a string that is in the following formats:

"hello world"
"HELLO WORLD"
"hELLO wORLD"
"Hello World"

The following label expression will convert the string to: "Hello World".

For information on how to do the equivalent steps in the ArcMap field calculator, see the link in the Related Information section below.


Procedure

In the ArcMap field calculator, use the VBA expression StrConv to convert a string to proper case. However, the default label expression parser VBScript does not have this method. The following label expression works around this VB Script limitation:

  1. Open the Label Expression dialog box.
  2. Click the Advanced button.
  3. Use the following code when converting only one field. Remember to change the name of the field [MyFieldName] to match the field name in the two locations below where it is referenced. 
    Function FindLabel ([MyFieldName])
      FindLabel = PCase([MyFieldName])
    End Function

    Function PCase(strInput)
      Dim iPosition
      Dim iSpace
      Dim strOutput
      iPosition = 1
      Do While InStr(iPosition, strInput, " ", 1) <> 0
        iSpace = InStr(iPosition, strInput, " ", 1)
        strOutput = strOutput & UCase(Mid(strInput, iPosition, 1))
        strOutput = strOutput & LCase(Mid(strInput, iPosition + 1, iSpace - iPosition))
        iPosition = iSpace + 1
      Loop
      strOutput = strOutput & UCase(Mid(strInput, iPosition, 1))
      strOutput = strOutput & LCase(Mid(strInput, iPosition + 1))
      PCase = strOutput
    End Function
       4. Use the following code when converting many fields at once. Remember to change the field names in the code below. Add more fields if required.

      Function FindLabel ([MyFieldName1], [MyFieldName2], [MyFieldName3])
        FindLabel = PCase([MyFieldName1] & " " & [MyFieldName2] & " " & [MyFieldName3])
      End Function
      
      Function PCase(strInput)
        Dim iPosition
        Dim iSpace
        Dim strOutput
        iPosition = 1
        Do While InStr(iPosition, strInput, " ", 1) <> 0
          iSpace = InStr(iPosition, strInput, " ", 1)
          strOutput = strOutput & UCase(Mid(strInput, iPosition, 1))
          strOutput = strOutput & LCase(Mid(strInput, iPosition + 1, iSpace - iPosition))
          iPosition = iSpace + 1
        Loop
        strOutput = strOutput & UCase(Mid(strInput, iPosition, 1))
        strOutput = strOutput & LCase(Mid(strInput, iPosition + 1))
        PCase = strOutput
      End Function

      Wednesday, February 18, 2015

      Multiple Checkbox Select/Deselect Using JQuery

      Almost all the user interfaces that I have created had this functionality of selecting multiple items from a list to process them or delete them. Although its very very easy to implement this functionality in Javascript, using jQuery for this is real fun. I will show you a simple implementation of adding multiple checkbox select and deselect functionality to any webpage. We will have a table with some data in it and checkbox in each row. There will be a select all checkbox in the header of the table. If user select/deselect the selectall checkbox, all the checkbox in table will get selected or deselected accordingly. Now one more thing we would like here to add is, suppose user select all the checkbox one by one then the selectall checkbox should be automatically gets selected. And if user click selectall first and then unchecks any of the checkbox, then the selectall also should be unchecked automatically.


      Add File


       <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>


      Stylish Multiple Checkbox Select/Deselect Using JQuery

      Almost all the user interfaces that I have created had this functionality of selecting multiple items from a list to process them or delete them. Although its very very easy to implement this functionality in Javascript, using jQuery for this is real fun. I will show you a simple implementation of adding multiple checkbox select and deselect functionality to any webpage. We will have a table with some data in it and checkbox in each row. There will be a select all checkbox in the header of the table. If user select/deselect the selectall checkbox, all the checkbox in table will get selected or deselected accordingly. Now one more thing we would like here to add is, suppose user select all the checkbox one by one then the selectall checkbox should be automatically gets selected. And if user click selectall first and then unchecks any of the checkbox, then the selectall also should be unchecked automatically.


      Files to Add



       <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
      <script src="http://fronteed.com/iCheck/icheck.js"></script>
      <link href="http://fronteed.com/iCheck/skins/square/green.css" rel="stylesheet">
           

      CODE:




      refer for more detail: http://fronteed.com/iCheck/


      Monday, January 12, 2015

      Check Special Character in File folder name using regular expression


      In Javascript:

      function checkFolderName(str) {
          strreg = /^[\w\-]+$/
          var strregx = new RegExp(strreg);
          if (strregx.test(str)) {
              //alert("OK")
              return false
          }
          else {
              //alert("Not OK")
              return true
          }
      }

      function checkFileName(str) {
          var name = str.substr(0, str.lastIndexOf('.'));
          var ext = str.substr(str.lastIndexOf('.') + 1);
          ext = ext.toLowerCase();
          //alert(name);
          //alert(ext);
          strreg = /^(?!.*  )(?!.*__)(?!.*--)[\w -]+$/    //Check alphanumeric with underscore and Hyphan and two consecutive spaces,underscore,hyphen
          //strreg = /^[a-zA-Z0-9_\-]+$/          //Check alphanumeric with underscore and Hyphen
          var strregx = new RegExp(strreg);
          if ((strregx.test(name)) && (ext != "asp") && (ext != "aspx") && (ext != "dll") && (ext != "cmd") && (ext != "bat") && (ext != "exe")) {
              //alert("OK")
              return false
          }
          else {
              //alert("Not OK")
              return true
          }
      }
      //-->

      How To use function:

      if(checkFolderName(document.getElementById("abc").value))
      {
          alert("Please don't use special char in Foldername.")
      }

      if(checkFileName(document.getElementById("abc").value))
      {
          alert("Please don't use special char in File Name.")
      }

      </SCRIPT>

      In VBScript
      <%

      function checkFoldername(Foldername)
          dim RegularExpressionObject: Set RegularExpressionObject = New RegExp
          dim matches: matches=""
          RegularExpressionObject.Pattern = "^[\w\-]+$"
          matches = RegularExpressionObject.Test(Foldername)
          checkFoldername = matches
          set RegularExpressionObject = nothing
      end function
      function checkFilename(Filename)
          arrFname = split(Filename,".")
          strExtNum = ubound(arrFname)
          strExt = lcase(arrFname(strExtNum))
       
          for i = 0 to ubound(arrFname)-1
              if strfilename = "" then
                  strfilename = arrFname(i)
              else
                  strfilename = strfilename&"."&arrFname(i)
              end if
          next
          strOK = false
          dim RegularExpressionObject: Set RegularExpressionObject = New RegExp
          dim matches: matches=""
          'RegularExpressionObject.Pattern = "^[\w\-]+$"
          RegularExpressionObject.Pattern = "^(?!.*  )(?!.*__)(?!.*--)[\w -]+$"
          matches = RegularExpressionObject.Test(strfilename)
          if matches and strExt<>"asp"  and strExt<>"aspx" and strExt<>"dll" and strExt<>"cmd" and strExt<>"bat" and strExt<>"exe" then
              strOK = true
          else
              strOK = false
          end if
          checkFilename = strOK
          set RegularExpressionObject = nothing
      end function

      function checkUploadFilename(Filename)
          arrFnameS = split(Filename,"\")
          strfnameNum = ubound(arrFnameS)
          arrFname = split(arrFnameS(strfnameNum),".")
          strExtNum = ubound(arrFname)
          strExt = lcase(arrFname(strExtNum))
       
          for i = 0 to ubound(arrFname)-1
              if strfilename = "" then
                  strfilename = arrFname(i)
              else
                  strfilename = strfilename&"."&arrFname(i)
              end if
          next
          strOK = false
          dim RegularExpressionObject: Set RegularExpressionObject = New RegExp
          dim matches: matches=""
          'RegularExpressionObject.Pattern = "^[\w\-]+$"
          RegularExpressionObject.Pattern = "^(?!.*  )(?!.*__)(?!.*--)[\w -]+$"
          matches = RegularExpressionObject.Test(strfilename)
          if matches and strExt<>"asp"  and strExt<>"aspx" and strExt<>"dll" and strExt<>"cmd" and strExt<>"bat" and strExt<>"exe" then
              strOK = false
          else
              strOK = true
          end if
          checkUploadFilename = strOK
          set RegularExpressionObject = nothing
      end function

      %>


      Thursday, January 8, 2015

      Textbox autocomplete using jquery in asp .net

      In this asp net tutorial we will learn how to use Jquery Autocomplete. Jquery Autocomplete is a very useful plugin which allows users to quickly search and select from list of values when they type into texbox control.
      Whenever user starts typing in Autocomplete enabled textbox he will see a list of suggestions based on the characters he has typed in the textbox. After getting the desired result user can select required value from the autocomplete list which will displayed in the textbox.
         
      You can provide static values in the form of array or you can also bind Jquery Autocomplete with database. In this tutorial we will bind our Jquery Autocomplete plugin with database. I will use northwind database for the demonstration purpose you can choose your own database. 

      Lets get started with sample application: 
      Step1: Create a new asp .net website.
      Step2: Create a default.aspx page and create a textbox control in it.

      <asp:textbox runat="server" id="txtAutoComplete" cssclass="autosuggest"></asp:textbox>

      Step3:  Add neccessary Jquery and Css files. Here I am using CDN(Content Delivery Network) for Jquery and CSS files. You can use CDN or you can download files from Jquery website to your project. Put this code between “Head” tag.


      <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
      <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/themes/base/jquery-ui.css" rel="stylesheet" type="text/css">
      <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/jquery-ui.min.js"></script>
      
      
      Step4: Write a method to get list of employees from database and return to Jquery Autocomplete. For this example I am using WebMethod to get and return list of employees from Northwind database.
      Add Connection String:
      <connectionstrings>      <add name="myConnection" connectionstring="Data Source=Sqlservername;user id=sa;password=yourpassword;Initial Catalog=Northwind"></add>  </connectionstrings>
      Add following namespaces:

      using System.Web.Services;
      using System.Data.SqlClient;
      using System.Configuration;
      Create Following method in Default.aspx.cs page:

      [WebMethod]
          public static List<string> getCustomerNames(string prefixText)
          {
              List<string> customers = new List<string>();
              using (SqlConnection conn = new SqlConnection())
              {
                  conn.ConnectionString = ConfigurationManager.ConnectionStrings["myConnection"].ConnectionString;
                  using (SqlCommand cmd = new SqlCommand())
                  {
                      cmd.CommandText = "select contactName As Name  from Customers where " +
                      "contactName like @SearchText + '%'";
                      cmd.Parameters.AddWithValue("@SearchText", prefixText);
                      cmd.Connection = conn;
                      conn.Open();
                      using (SqlDataReader dr = cmd.ExecuteReader())
                      {
                          while (dr.Read())
                          {
                              customers.Add(dr["Name"].ToString());
                          }
                      }
                      conn.Close();
                  }
              }
              return customers;
          }</string></string></string>
      Step5:  Call Webmethod using Jquery and bind values for Jquery Autocomplete.Put this code between your page’s head tag.
      <script type="text/javascript">
             $(document).ready(function () {
                 SearchText();
             });
             function SearchText() {
                 $(".autosuggest").autocomplete({
                     source: function (request, response) {
                         $.ajax({
                             type: "POST",
                             contentType: "application/json; charset=utf-8",
                             url: "Default.aspx/getCustomerNames",
                             data: "{'prefixText':'" + document.getElementById('txtAutoComplete').value + "'}",
                             dataType: "json",
                             success: function (data) {
                                 response(data.d);
                             },
                             error: function (result) {
                                 alert("Error");
                             }
                         });
                     }
                 });
             }
         </script>