window.open method

Posted by Venkat | Labels: , ,

Window.open method in asp.net - this is used in javascript to open a page on new window.
through this you can hide the menubar ,set the width and hieght of the popupwindow,status,toolbar,resizable etc., for this you can either set the value is 0 | 1 or yes | no

Example

window.open('http://msdn.microsoft.com', '', '');");

Suppose if you want to do on code behind check this code :

Here i have mentioned widht , height of the window ,top and left , menubar,toolbar,
location, resizable, scrollbars
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append("<script language="javascript">");
sb.Append("window.open('popuop.aspx', 'CustomPopUp',");
sb.Append("'width=1020, height=750, left=0, top=0, menubar=no, toolbar=no, resizable=no, status=no, location=no, scrollbars=yes');<");
sb.Append("/script>");
Type t = this.GetType();
if (!Page.ClientScript.IsStartupScriptRegistered(t, "PopupScript"))
{
     Page.ClientScript.RegisterStartupScript(t, "PopupScript", sb.ToString());
 }


If you want to open a new window through in-line code try this.

   <img border="0" id="img_PopUp" onclick="window.open('../PopUp.aspx','custompopop','width=250,height=300,toolbar=no,menubar=no,statusbar=no,resizable=no,scrollbars=no,location=no, directories=no,copyhistory=no,left=250,top=250')" />
                                runat="server" src="../Images/Newwindow.png" style="width: 35px" />

Reference:


http://dotnetslackers.com/articles/aspnet/JavaScript_with_ASP_NET_2_0_Pages_Part1.aspx

Arithmetic Captcha

Posted by Venkat | Labels: , ,

In this post i am going to show how to work with Arithmetic CAPTCHA. Generally we used , Alpha or alphaNumeric Captcha on most of the site but some site like  ASP.SNIPPETS it shows ARITHMETIC CAPTCHA like 18 + 12 = ? so user have to give correct value then only it proceeds.

Here I am getting help from this site

http://www.knowlegezone.com/documents/80/Simple-ASPNET-CAPTCHA-Tutorial/

Which was in VB.NET so I would like to Written in C#, here I have been posted , On the Above link they used normal ASPX image to Generate the Image ie: 18 + 12 = .

So i written the code on Generic Handler File to improve the site performance.
By default Handler file does not Read or write the value to Session so we have to use like this

using System.Web.SessionState;

public class Captcha : IHttpHandler, IRequiresSessionState


suppose if we are going to read the Session value on HTTP Handler file

using System.Web.SessionState;
public class Captcha : IHttpHandler, IReadOnlySessionState

This is the full code for Captcha.ashx file

<%@ WebHandler Language="C#" Class="Captcha" %>
using System;
using System.Web;
using System.Drawing;
using System.Web.SessionState;
public class Captcha : IHttpHandler, IRequiresSessionState
{
   
    public void ProcessRequest (HttpContext context) {
        //context.Response.ContentType = "text/plain";
        //context.Response.Write("Hello World");
        Random num1 = new Random();
        Random num2 = new Random();
        int numQ1 = 0;
        int numQ2 = 0;
        string QString = null;
        numQ1 = num1.Next(10, 15);
        numQ2 = num1.Next(17, 31);
        QString = numQ1.ToString() + " + " + numQ2.ToString() + " = ";
        int tAnswer = numQ1 + numQ2;
        context.Session["answer"] = tAnswer .ToString ();
        Bitmap bitmap = new Bitmap(85, 25);
        Graphics Grfx = Graphics.FromImage(bitmap);
        Font font = new Font("Arial", 18, FontStyle.Bold, GraphicsUnit.Pixel);
        Rectangle Rect = new Rectangle(0, 0, 100, 25);
        Grfx.FillRectangle(Brushes.Snow, Rect);
        Grfx.DrawRectangle(Pens.White, Rect);
        // Border
        Grfx.DrawString(QString, font, Brushes.Black, 0, 0);
        context.Response.ContentType = "Image/jpeg";
        bitmap.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
        bitmap.Dispose();
        Grfx.Dispose();
    }
    public bool IsReusable {
        get {
            return false;
        }
    }
}

Here is the code if you are going to write it on Captcha.aspx page

Explanation was given on Comment itself. Write the below code on Page_Load Event

// Getting Random number
        Random num1 = new Random();
        Random num2 = new Random();

        int numQ1 = 0;
        int numQ2 = 0;
        string QString = null;

        // here we get the random number for the first and second numer - ie: shows the number in between the range.
        numQ1 = num1.Next(10, 15);
        numQ2 = num1.Next(17, 31);

        //Total answer has been  stored it on String and assign to the Session["number"]
        QString = numQ1.ToString() + " + " + numQ2.ToString() + " = ";
        Session["answer"] = numQ1 + numQ2;

        // Here we create  Bitmap width - 85 and height - 25
        Bitmap bitmap = new Bitmap(85, 25);
        Graphics Grfx = Graphics.FromImage(bitmap);

        // Setting the font name, size etc for the text that we have to write it on the image
        Font font = new Font("Arial", 18, FontStyle.Bold, GraphicsUnit.Pixel);

        // Here we specify  a Rectangle object of x , y co-ordinate , with width and height 
        Rectangle Rect = new Rectangle(0, 0, 100, 25);

        //Fill the color to the Rectangle
        Grfx.FillRectangle(Brushes.Snow  ,Rect);

        // Now Using Pen Object Drawing a rectangle
        Grfx.DrawRectangle(Pens.White, Rect);

        // Border - here drawing the string of the num1 and num 2, font size , type etc, font color , and x and y co-ordinate
        Grfx.DrawString(QString, font, Brushes.Black   , 0, 0);
        // Specify the Content type of the image - here i am using JPEG
        Response.ContentType = "Image/jpeg";

        // Save the image and show it on page using response object
        bitmap.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);

        //Dispose the object and release the resources
        bitmap.Dispose();
        Grfx.Dispose();

Google Custom Search

Posted by Venkat | Labels: , ,

Google Custome Search

Google provider Custom search - that can be integrated to our own site - to searh a text,keywords
inside our site.

This is the link go Through and add to your site.

http://code.google.com/apis/customsearch/docs/ui.html

Fetch DB to Xml then bind to Asp.net Server control

Posted by Venkat | Labels: , ,

Today I am going to see how to bind or get the Data from the DB to XML file. so XML is also a
Datasource to store the data or content and you can get the data from xml file easily,it also
improves server performance. ie: instead of creating connection and request the DB to fetch the data
, Getting the Data , Closing Connection. so this operation occurs multiple times or as per
user needs.

Now what i am doing here is , first get the Table Data From DB to the XML file.
first i had created one xml file called Test.xml - to place the Employee Tables Data.

Then OnButton_Click Event i have written the code to bind the data to XML file.

Ex: i am getting the Employee Table from DB bind to the XML file.

Here is the Code :

Include Namespace

using System.IO;
using System.Data.SqlClient;


protected void Button1_Click(object sender, EventArgs e)
    {
        SqlCommand command = new SqlCommand();
        command.CommandText = "Select * from Employees";
        command.CommandType = CommandType.Text;
        command.Connection = con;
        SqlDataAdapter da = new SqlDataAdapter(command);
        DataSet ds = new DataSet();
        da.Fill(ds, "Emp");
       
        // Get a StreamWriter object
        StreamWriter xmlDoc = new StreamWriter(Server.MapPath("~/Test.xml"), false);

        // Apply the WriteXml method to write an XML document
        ds.WriteXml(xmlDoc, XmlWriteMode .WriteSchema );
        xmlDoc.Close();

       
    }
After that - i am going to bind the all the employeename and empid to the Dropdownlist.

Here is the Code : so we get the emp details on the XML file , we have to retrieve the data
from the XML file using Dataset because - Dataset has two method ReadXML and WriteXML ie: able
to read or write the data from the XML.

so after read the data from XML to Dataset, now we have all the emp details on the Dataset ds,
. just bind as its to the Dropdownlist datasource.


 DataSet ds = new DataSet();

 ds.ReadXml(Server.MapPath("~/Testdo.xml"));

DropDownlist1.DataSource = ds;
DropDownlist1.DataTextField = "empname";
DropDownlist1.DataValueField = "empid";
DropDownlist1.DataBind();
suppose i want to filter the employees whose salary is greater than 20000

write like this

dt = ds.Tables[0];
  DataRow[] dr ;
        dr = dt.Select("salary >= '20000'");

 DataTable fDt = new DataTable();
        fDt.Columns.Add("empName");
        fDt.Columns.Add("empId");

 foreach (DataRow dr1 in dr)
        {
            DataRow newrow = fDt.NewRow(); 
            newrow[0] = dr1[0];  // here you have to give correct index for the empid or empname field name
            newrow[1] = dr1[1];
           

            fDt.Rows.Add(newrow);
        }

dropdownlist2.DataSource = fDt;
DropDownlist1.DataTextField = "empname";
DropDownlist1.DataValueField = "empid";
DropDownlist1.DataBind();

Creation Tooltip

Posted by Venkat | Labels: , ,

Good Friday to all.

Now i am going to show how to create  a Tooltip using Javascript there are many scripts,JQuery available to make the work easy and even we can design the tooltip stylish manner.

But finally i have worked with this sample , it shows tooltip , when u click on the Textbox - you can give your own font color, backcolor.

Here is the link Check it

http://lixlpixel.org/javascript-tooltips/

And its a dynamic tool tip..

http://blog.devarchive.net/2008/04/advanced-tooltip-control-aspnet-ajax.html

Here is the Screenshot

How to Create Nifty Round corner

Posted by Venkat | Labels: , ,

I have situation Create a Roundcorner for the table or div or panel ...
So in Ajax there is a built-in-control - RoundCornerExtender is available , but i have used that but i was not showing the round corner sometimes properly.

so i found this Nifty round corner was the good one, no image needed for the Round Corner.

Its full javascript., you can apply the round corner to div,panel,table etc..

Here is the Sample code

First you have to add Javascript on your page. You can get the javascript here ie: niftycube.js and niftycorner.css.

http://www.html.it/articoli/nifty/index.html

http://www.html.it/articoli/niftycube/index.html

You have to write code like this

if you use id use (#) , if you are going to use it for class user (.)


<script type="text/javascript">
window.onload=function(){
Nifty("div#box","big");
Nifty("Panel#" + '<%= contactUs_Panel.ClientID %>',"transparent");
Nifty("Panel.setround","big");
Nifty("Panel#" + '<%= callback_Panel.ClientID %>',"transparent");
Nifty("table.setround","big");

//Nifty("PopupControlExtender","big");
}
</script>


Validate Indian Mobile Number

Posted by Venkat | Labels: ,

Hi , Now i am going to discuss about how to validate a Indian Mobile Number.

First the Mobile Number field should not be null so for that - Add RequiredFieldValidator.

It should not accept any Aplhabets , or any special characters for this you have to write RegularExpression Validator to Accept only Numbers
EX:

Regex \d+


Atlast i have to check whether user entered Number is 10 digit or not and also it should be valid Mobile Number
Regex ^[9][0-9]{9}$


This Regex which first digit should be 9 then followed by 9 digits and totally it accept only 10 digits.

Paypal Code - Validate Credit Card & CreditCard Payment through Website Payments Pro method

Posted by Venkat | Labels: , , ,

How to Validate the CreditCard in asp.net ??

To validate the CreditCard first you have to check the Card Type then followed by
the no.of digits..etc.. on that Specific Card type. here i am using Luhn Algorithm to validate.

So you have place these algorithm on Separate Class file ie: Create

CardValidator.cs on the App_Code Folder and paste the below code.

using System;

public enum CardType
{
    MasterCard, BankCard, Visa, AmericanExpress, Discover, DinersClub, JCB
};

public sealed class CardValidator
{
    private CardValidator() { } // static only

    public static bool Validate(CardType cardType, string cardNumber)
   {
      byte[] number = new byte[16]; // number to validate

      // Remove non-digits
      int len = 0;
      for(int i = 0; i < cardNumber.Length; i++)
      {
         if(char.IsDigit(cardNumber, i))
         {
            if(len == 16) return false; // number has too many digits
            number[len++] = byte.Parse(cardNumber[i].ToString ());
         }
      }

      // Validate based on card type, first if tests length, second tests prefix
      switch(cardType)
      {
         case CardType.MasterCard:
            if(len != 16)
               return false;
            if(number[0] != 5 || number[1] == 0 || number[1] > 5)
               return false;
            break;

         case CardType.BankCard:
            if(len != 16)
               return false;
            if(number[0] != 5 || number[1] != 6 || number[2] > 1)
               return false;
            break;

         case CardType.Visa:
            if(len != 16 && len != 13)
               return false;
            if(number[0] != 4)
               return false;
            break;

         case CardType.AmericanExpress:
            if(len != 15)
               return false;
            if(number[0] != 3 || (number[1] != 4 && number[1] != 7))
               return false;
            break;

         case CardType.Discover:
            if(len != 16)
               return false;
            if(number[0] != 6 || number[1] != 0 || number[2] != 1 || number[3] != 

1)
               return false;
            break;

         case CardType.DinersClub:
            if(len != 14)
               return false;
            if(number[0] != 3 || (number[1] != 0 && number[1] != 6 && number[1] 

!= 8)
               || number[1] == 0 && number[2] > 5)
               return false;
            break;

         case CardType.JCB:
            if(len != 16 && len != 15)
               return false;
            if(number[0] != 3 || number[1] != 5)
               return false;
            break;
        
      }

      // Use Luhn Algorithm to validate
      int sum = 0;
      for(int i = len - 1; i >= 0; i--)
      {
         if(i % 2 == len % 2)
         {
            int n = number[i] * 2;
            sum += (n / 10) + (n % 10);
         }
         else
            sum += number[i];
      }
      return (sum % 10 == 0);
   }
}

I have the task of payment method through paypal pro using Credit Card.i was

googled a lot with paypal site , fourms and came with the sample code.

The PayPal Name-Value Pair API (NVP API) enables you to leverage thefunctionality of the PayPal API by simply sending an HTTP request to PayPal and specifying request parameters using name-value pairs. The NVP API is a lightweight alternative to the PayPal SOAP API and provides access to the same set of functionality as the SOAP API.

Ref: https://www.paypal.com/IntegrationCenter/ic_nvp.html

Here i am usin NVP API for payment through CreditCard using website Payment Pro

Method , we can also use SOAP API for this we need to do

1)setExpressionCheckout

2) DoExpressionCheckout

3) GetExpressionCheckout.

Either we can use API or through Code. I am Registering on Sandbox.paypal to check the code. we have to create the Buyer , seller Account to check the amount has been transferred or not , so it will automatically create the creditcard no, cardtype for the test account, we have to use this to check the Amount Transfer
or not. While testing , the amount was not deducted on the buyer account but it will credited on Seller account  as this is sanbox test, this is not an issue ,while you upload it on live , it will work smoothly.As i was tested with Sandbox - so you can check it on live.

One of the main advantage of this method is , it will not redirect the user to paypal site,instead the process has been doing on background from the same site after successfull transaction it will give the Transactionid ,
act etc.. so you can store this thing on DB.


While page Designing make sure you have these Fields

1) Card Type

2) Textbox for CreditCard Number

3) Expire Date  / Expire Month

4) Pay button / Cancel button

paybutton_Click
try
        {
              bool validateCard = false;
              if (ddlCCType.SelectedValue.ToString() == "Visa")
              {
                  validateCard = CardValidator.Validate( CardType.Visa , 

txtCCNumber.Text);
              }
              else if (ddlCCType.SelectedValue.ToString() == "MasterCard")
              {
                  validateCard = CardValidator.Validate(CardType.MasterCard , 

txtCCNumber.Text);
              }
              else if (ddlCCType.SelectedValue.ToString() == "AMEX")
              {
                  validateCard = CardValidator.Validate(CardType.AmericanExpress, 

txtCCNumber.Text);
              }

            if (validateCard != false)
            {
                  string ipaddress;

                ipaddress = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

                if (ipaddress == "" || ipaddress == null)
                {
                    ipaddress = Request.ServerVariables["REMOTE_ADDR"];

                }
        Session["ipAddress"] = ipaddress;

         //API Credentials (3-token)

            string strUsername = "troy2._1261822640_biz_api1.gmail.com";

            string strPassword = "1261822646";

            string strSignature = 

"An5ns1Kso7MWUdW4ErQKJJJ4qi4-A60C4mgCoX2-L9FhwhF2rfGtRPeI";

            string strCredentials = "USER=" + strUsername + "&PWD=" + strPassword 

+ "&SIGNATURE=" + strSignature;
        
            // For Sandbox testing use this API 
            string strNVPSandboxServer = "https://api-3t.sandbox.paypal.com/nvp";

            // Fpr Live Server use this API
            string strNVPLiveServer = "https://api-3t.paypal.com/nvp";

            string strAPIVersion = "2.3";

// here i am assigning the credit card type cardno,expiry date/month to
 //the session variable and pass it here 

                       string strNVP = strCredentials + 

"&METHOD=DoDirectPayment&CREDITCARDTYPE=" + Session["cardType"].ToString() + 

"&ACCT=" + Session["cardNo"].ToString() + "&EXPDATE=" + 

Session["expiryDate"].ToString() + "&CVV2=808&AMT=" + Amount_Label.Text + 

"&FIRSTNAME=" + FirstName_Label.Text + "&LASTNAME=" + LastName_Label.Text + 

"&IPADDRESS=" + Session["ipAddress"].ToString() + "&STREET=" + address1 + "+" + 

address2 + "&CITY=" + city + "&STATE=" + state + "&COUNTRY=" + country + "&ZIP=" 

+ zip + "&COUNTRYCODE=US&PAYMENTACTION=Sale&VERSION=" + strAPIVersion;

  //Create web request and web response objects, make sure you using the correct 

server (sandbox/live)

            HttpWebRequest wrWebRequest = 

(HttpWebRequest)WebRequest.Create(strNVPSandboxServer);

            ////Set WebRequest Properties
            wrWebRequest.Method = "POST";

            //// write the form values into the request message
            StreamWriter requestWriter = new 

StreamWriter(wrWebRequest.GetRequestStream());

            requestWriter.Write(strNVP);
            requestWriter.Close();

            //// Get the response.
            HttpWebResponse hwrWebResponse = 

(HttpWebResponse)wrWebRequest.GetResponse();

            StreamReader responseReader = new 

StreamReader(wrWebRequest.GetResponse().GetResponseStream());

            //// and read the response
            string responseData = responseReader.ReadToEnd();

            responseReader.Close();
            Response.Write(Server.UrlDecode(responseData));
               
            }
            else
            {
                validateCard_Label.Text = "Please check your card number...";
            }
            
            
          
        }
        catch (Exception ex)
        {
            throw ex;
        } 

Finally , once your Transaction is success you will get the output ie:TransactionID with ack

EX: Output

ACK=Success&TIMESTAMP=date/timeOfResponse
&CORRELATIONID=debuggingToken&VERSION=2.300000&BUILD=buildNumber
&TOKEN=EC-3DJ78083ES565113B&EMAIL=abcdef@anyemail.com
&PAYERID=95HR9CM6D56Q2&PAYERSTATUS=verified
&FIRSTNAME=John&LASTNAME=Smith...&AMT=15&TRANSACTIONID=24527936A38716

Invalid postback or callback argument.

Posted by Venkat | Labels:

I came across the post on Forums ie:

Invalid postback or callback argument.  Event validation is enabled using in configuration or <%@ Page EnableEventValidation="true" %> in a page.  For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them.  If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation

To Solve this issue Make sure that you are using IsPostback on the Page_Load() event of that page.


 page_Load() event
If (!IsPostBack)
{
// bind the data
}

Check whether Querystring is available or not.

Posted by Venkat | Labels: ,

Now , i am going to explain how to check Whether the Querystring is present or available or not.

For ex: I am passing id as a querystring to the page2.aspx from page1.aspx.

So on Page1.aspx


Button1_Clickevent() Response.Redirect("page2.aspx?id=1",false); Then on Page2.aspx Page2_Loadevent() If(!IsPostback) {        If(!String.ISNullOrEmpty(Request.QueryString["id"]))         {               // get the value of Querstring id , if id is not null or empty         }        else if(!String.ISNullOrEmpty(Request.QueryString["name"]))         {              // get the value of name querystring if name is not null or empty         } }   When you run the above code - ie: on Page2.aspx you can get the id Querystring value. this works fine.   
Suppose if you pass some other querystring name ex: name from the Page1.aspx the above code gives
ie: Button2_Clickevent()
         Response.Redirect("page2.aspx?name=Dotnet",false);
Error : Object Reference Exception. 

Because it first check the  if condition so in the first condition it contains id so the querystring id will not present so it leads to the Null reference exception.


to avoid this exception you have to check like this.

Page2_Loadevent()
If(!IsPostback) {   if(Request.QueryString["id"] != null)     {        If(!String.ISNullOrEmpty(Request.QueryString["id"]))         {               // get the value of Querstring id , if id is not null or empty         }   } if ((Request.QueryString["name"] != null)   {         if(!String.ISNullOrEmpty(Request.QueryString["name"]))         {              // get the value of name querystring if name is not null or empty         } }  }
          This if(Request.QueryString["id"] != null)  - checks if id is a QueryString variable.

  If(!String.ISNullOrEmpty(Request.QueryString["id"]))  - Check if the id is empty or not

     

PayOffers.in