Tuesday, July 29, 2014

Javascript and Jquery


Add JQUERY and CSS Header

<script src="Scripts/jquery-2.0.3.min.js"></script>
<script src="Scripts/jquery-ui-1.10.3.min.js"></script>
<script src="Scripts/configSetting.js"></script>
<link href="Content/themes/base/jquery-ui.css" rel="stylesheet" />

Way to find Javascript Class : $(".Config")

2 way to find Javascript ID :
  1. $("a[id*=InsertLink]")
  2. $("#InsertLink")
INPUT
Button | checkbox | hidden | image | radio | DateTime | Textbox
a
Link
SELECT
DropDown


JQUERY METHOD AND CODE


Click trigger
( can use this in following as an object)
$("INPUT[id*=SelectCheck]").click(function () { }

Change trigger
$("INPUT[id*=radStatus]").change(function () {
Check Box set True (attr – before JQuery 1.6 / prop – after JQuery 1.6)
$("INPUT[id*=SelectCheck]").prop("checked"true);

Set (true|false to set disabled | enabled)
$("INPUT[id*= txtname]").removeAttr("disabled");
$("INPUT[id*=txtname]").attr("disabled"true);
Dropdown Select Index
$("SELECT[id*=ddlCountry]")[0].selectedIndex = 0;
Find and get Value
var app = $(this).find(INPUT [type=hidden][id*=App]').val();
Get value
Get Checkbox / radio value 
$(this).val();
$("INPUT[id*=rbEffective]:checked").val();
Set Value
$(this).val("Inactive");

hide / show
$('#countryFieldSet').hide();   / .show();
Link URL
location.href = Country.aspx';
Get  Table Column
var getNameCol = $("TABLE[id*=gvPeople] tr").find('th:nth-child(2)').text();

DropDown or Text Change
$("INPUT[id*=txtName],SELECT[id*=ddlGender]").change(function () {
Parse Float (sometimes + is for string, u need to convert to numeric 1st)
var price = parseFloat($("INPUT[id*=txtPrice]").val()); | parseint
Change Image
$('#Image1').attr('src', x);
Modal Popup
$('#myModal').modal('show');

Function with Param
function modalup(x, y) { }

onclick='modalup("<%# Eval("ImageURL","studentImage/{0}") %>","<%# Eval("Age")%>");'>
Date Format
<script src="scripts/jquery.dateFormat-1.0.js"></script>
$.format.date(new Date, 'dd/M/yy hh:mm:ss'));

Pass self and target to function ($this must at onclick)
<input type="checkbox" name="search_rule" onclick="ControlList($(this),'ListTransMatchedRule')" />

function ControlList(checkbox, list) {
    if (checkbox.is(':checked')) {
       $("#" + list).attr("disabled", true);
       $("#" + list)[0].selectedIndex = -1;
    }
    else {
       $("#" + list).attr("disabled", false);
    }
}
Foreach Tr with specific Class
$("Table[id=tblCust] tr[class='content']").each(function (tr)
Get Attribute (Id, name, rowspan)
$(this).attr('id');
Split string
var rowArray = rowID.split("_");
Hide & Show
$(this).hide(); | show();
Hide Checking
if (tdDataType.is(':hidden'))
Insert | add td to tr (this is TR)
tdData.prependTo($(this)); | tdData.appendTo($(this));
Find (like) start from  | eq(0) is first item
$("Table[id=tblCust]").find("tr[id^='" + prow + "']").eq(0);


















Monday, July 28, 2014

SQL Filteration

There are 2 method to form a filteration SQL Statment with valueable or nullable parameter.The [Country] is must filter object and [City] is an optional filter object:


METHOD 1 
  1. All the Paramater is always added [Con]

const string SQL_STATEMENT =
                "SELECT COUNT(1) FROM [dbo].[Customer] " +
                "Where [Country]= @Country{0}";

string filter = (city != “”) ? " AND [City]=@City" : String.Empty;
          
Database db = DatabaseFactory.CreateDatabase(BULKSETTINGS_CONNECTIONNAME);
              
using (DbCommand cmd = db.GetSqlStringCommand(String.Format(SQL_STATEMENT, filter)))
{
db.AddInParameter(cmd, "@City ", DbType.String, city);
db.AddInParameter(cmd, "@Country ", DbType.String, country);
    result = Convert.ToInt32(db.ExecuteScalar(cmd));

}



METHOD 2 
  1. Only Filter onject have to add param
  2. need to form SQL Statment 1st and change it by cmd.CommandText

const string SQL_STATEMENT =
                "SELECT COUNT(1) FROM [dbo].[Customer] " +
                "{0}";

Database db = DatabaseFactory.CreateDatabase(CONNECTION_NAME);
using (DbCommand cmd = db.GetSqlStringCommand(SQL_STATEMENT))
{
   string filter = string.Empty;

   db.AddInParameter(cmd, "@Country", DbType.AnsiString, country);
   filter += "[Country]=@Country ";
   if (!string.IsNullOrWhiteSpace(prefix))
   {
      db.AddInParameter(cmd, "@City ", DbType.AnsiString, city);
      filter += “AND [City]=@City ";
   }

   if (!string.IsNullOrWhiteSpace(filter))
        filter = "WHERE " + base.FormatFilterStatement(filter);

cmd.CommandText = string.Format(SQL_STATEMENT, filter);



SUPPORT METHOD

To Remve AND OR word in 1st word of  filteration sql statment

protected string FormatFilterStatement(string filter)
{
   return Regex.Replace(filter, "^(AND|OR)", string.Empty);
}

Tuesday, July 22, 2014

Object List Reference Not Equal

Not Equal - Although is not equal , but when update it still will reference

List
<Person> personList1 = new List<Person>(upc.personList2.ToList());

Not Equal and Not Reference

List<Person> person = upc.personList2.Select(x => new Person
{
     Name = x.Name,
     Address = x.Address,
     Phone = phone,
}).ToList();

Thursday, July 3, 2014

EMAIL LINK TO OTHER PAGE

1) FORM THE URL

This method is to get the current URL
1) http://localhost:64591/
2) http://sit/test/

public string GetWebAppRoot()
{
  if (HttpContext.Current.Request.ApplicationPath == "/")
    return "http://" + HttpContext.Current.Request.Url.Authority;
  else
    return "http://" + HttpContext.Current.Request.Url.Authority +            HttpContext.Current.Request.ApplicationPath;
}

string URL = GetWebAppRoot() + "/URL.aspx?";

2) CREATE ENCRYPTION CLASS

public class QueryStringEncryption
{
    private byte[] key = { };
    private byte[] IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xab, 0xcd, 0xef };
     
    public string Decrypt(string stringToDecrypt)
    {
        byte[] inputByteArray = new byte[stringToDecrypt.Length + 1];
        try
        {
           key = System.Text.Encoding.UTF8.GetBytes("mkadm11n");
           DESCryptoServiceProvider des = new DESCryptoServiceProvider();
           inputByteArray = Convert.FromBase64String(stringToDecrypt);
           MemoryStream ms = new MemoryStream();
           CryptoStream cs = new CryptoStream(ms,
           des.CreateDecryptor(key, IV), CryptoStreamMode.Write);
           cs.Write(inputByteArray, 0, inputByteArray.Length);
           cs.FlushFinalBlock();
           System.Text.Encoding encoding = System.Text.Encoding.UTF8;
           return encoding.GetString(ms.ToArray());
         }
         catch (Exception e)
         {
                return e.Message;
         }
     }

     public string Encrypt(string stringToEncrypt)
     {
        try
        {
           key = System.Text.Encoding.UTF8.GetBytes("mkadm11n");
           DESCryptoServiceProvider des = new DESCryptoServiceProvider();
           byte[] inputByteArray = Encoding.UTF8.GetBytes(stringToEncrypt);
           MemoryStream ms = new MemoryStream();
           CryptoStream cs = new CryptoStream(ms,
           des.CreateEncryptor(key, IV), CryptoStreamMode.Write);
           cs.Write(inputByteArray, 0, inputByteArray.Length);
           cs.FlushFinalBlock();
           return Convert.ToBase64String(ms.ToArray());
        }
        catch (Exception e)
        {
                return e.Message;
        }
 }

2)  ENCRYPT INPUT PARAM

1)URLEncode param 1st, because special word like ?,= will have error
2)Encypt it to protect the URL, not let user to see the info

QueryStringEncryption queryStringEncrption = new QueryStringEncryption();

string queryString = string.Format("UserID={0}&NewPassword={1}&SentDate={2}", user.UserID, HttpUtility.UrlEncode(user.Password), HttpUtility.UrlEncode((DateTime.Now).ToString()));
string encyptedQS = queryStringEncrption.Encrypt(queryString);

URL = URL + encyptedQS;
content = content + "Please Click this <a href=\"" + URL + "\">link </a>";

3)  URL PAGE LOAD

1)Get Raw URL
2)Decrypt and URLDecode

queryString = Request.RawUrl;
queryString = queryString.Substring(queryString.IndexOf('?') + 1);

queryString = queryStringEncrption.Decrypt(queryString);

string[] arrMsgs = queryString.Split('&');
string[] arrValue;
                      
arrValue = arrMsgs[0].Split('='); //Get Name

long userID = Convert.ToInt64(HttpUtility.UrlDecode(arrValue[1].ToString()));