Asp.net

Advanced ASP.NET File Manager:IZWebFileManager

IZWebFileManager is featured File Manager control for ASP.NET 2. It is compatible with most-used browsers like MS Internet Explorer and Firefox.

FileManager

Some Features

  • Copying, moving, renaming, deletion of files and folders
  • Ability to work (copy, move, delete) with several files at once
  • File upload
  • Drag & Drop;
  • Right-click context menu
  • Common keyboard shortcuts supported
  • & more
Asp.net

ASP.NET AJAX callbacks to Web Methods in ASPX pages

In my previous post we have seen basic steps to create AJAX-Enabled WCF Service in web application.
Now in this post, We will see how to implement AJAX web methods.

Why Web Method?? Some times, we need functionality that are logically dedicated to specific ASPX page, in such situation we can use web methods.

How to create:

Step 1: Implementing Web Method

Write WebMethod as below into your code file (.aspx.cs)

[System.Web.Services.WebMethod]
    public static List GetStudents(int schoolID)
    {
        //TODO: Write your logic to get student list 
    }

Step 2: Add ScriptManager into page

Set EnablePageMethods property of ScriptManager to true as,


 

Step 3: Calling WebMethod from javascript

Call the web method through the PageMethods as below,

function GetStudents(schoolID) {
            PageMethods.GetStudents(schoolID, OnSucceeded, OnFailed);           
        }

        function OnSucceeded(result) {
            //TODO: Write logic to display the result from  JSON results to HTML           
        }

        function OnFailed(error) {
            // Alert user to the error.
            alert(error.get_message());
        }
Asp.net

AJAX-Enabled WCF Service

In this post we will see how to create an AJAX-enabled Windows Communication Foundation (WCF) service and an ASP.NET client that accesses the service.

How to create

Step 1: Right-click the WebSite in the Solution Explorer window and select Add, then New Item, and then AJAX-enabled WCF Service.

Step 2: Give the Namespace for ServiceContractAttribute as,
Here I have given Namespace as DemoServices ,

[ServiceContract(Namespace = "DemoServices")]

Step 3: Implementing methods

Add [OperationContract] attribute to each of the service methods/operations.
As,

 [OperationContract]
        public string GetName(int studentID)
        {
           //TODO: Implement method which return name of student
            return "Amol";
        }

Step 4: Configure ScriptManager to access the service

Now to access service we need to add service reference in the aspx page where we want to access service,


Step 5: Calling service methods from java script To call service we need to create an object of Service class and then call service methods as,

function GetStudent(id) {
            var service = new DemoServices.MyService();
            service.GetName(id, onSuccess, OnFailed);
            return false;
        }

While calling service, we have passed two parameters (onSuccess and OnFailed) which is nothing but java scripts functions.
onSuccess function is called when service execute successfully, OnFailed function is called when exception occurred in service method.

Step 6: Results and Error handling

function onSuccess(result) {
            //TODO: Write logic to display the result
            alert(result);

        }

 function OnFailed(error) {
            // Alert user to the error.
            alert(error.get_message());
        }
Asp.net, C#, Tools

NGChart : .net class to generate google charts

NGChart is .NET class library to work with Google Chart API. Which provides simple classes and methods to generate google charts.

Example

BarChart chart = new BarChart(BarsType.Grouped, BarsDirection.Vertical,
         new ChartSize(420, 125),
         new ChartData(new int[][]
           {
              new int[] { 20, 1, 25, 26, 51 },
              new int[] { 7, 12, 60, 57, 4 }
            }) );

chart.Colors = new ChartColors(new Color[] { Color.DodgerBlue, Color.YellowGreen });
chart.Legend = new ChartLegend(new string[] {"Winter", "Summer"});

//chart.ToString() is return google chart image URL
 imgChart.ImageUrl = chart.ToString();

NGChart will generate an URL (Google API) for above code like this:

http://chart.apis.google.com/chart?cht=bvg&chs=420×125&chd=s:UBZaz,HM85E&chco=1E90FF,9ACD32&chdl=Winter|Summer

And above API i.e. URL will display following chart,

bar

Asp.net, Tools

Google Chart API: Generate dynamic charts

Google has provided API to create charts. Google Chart API lets you to generator dynamically chart.

Example:

Following pie chart is generated using API,

http://chart.apis.google.com/chart?cht=p3&chd=s:Uf9a&chs=250×100&chl=January|February|March|April

Google chart

Google Chart API provides following chart types,

Asp.net, JQuery

Reactivate jQuery plugins after Asynchronous request

While playing with jQuery plugins, I observed that some jQuery plugins are not working in asp.net ajax update panel after Asynchronous request.

As most of the jQuery plugins calls there functions on page onload method, So we need to recall plugin functions after an asynchronous postback is finished.

In my previous post Ajax Events I have given basic idea of handling various asp.net Ajax events including endRequest event which raised after an asynchronous postback is finished and control has been returned to the browser.

We can use endRequest event to recall jQuery plugin’s function.

Example

Here I have used vtip tooltip plugin.

Add following script into your page,

<script language="javascript" type="text/javascript">
 function pageLoad() {
 var prm = Sys.WebForms.PageRequestManager.getInstance();
 prm.add_endRequest(EndRequest);
 }

 function EndRequest(sender, args) {
 // call JTool Tip function..
 jQuery(document).ready(function($) { vtip(); })
 }

 </script>
Ajax, Asp.net

Asp.net Ajax Events

ASP.NET AJAX framework provides various page events that are raised during processing ajax requests.

Following table shows details of Events,

Event Name Description
beginRequest Event Raised before processing of an asynchronous postback starts and the postback request is sent to the server.
endRequest Event Raised after an asynchronous postback is finished and control has been returned to the browser.
initializeRequest Event Raised during the initialization of the asynchronous postback.
pageLoaded Event Raised after all content on the page is refreshed as the result of either a synchronous or an asynchronous postback.
pageLoading Event Raised after the response from the server to an asynchronous postback is received but before any content on the page is updated.

Uses

  • beginRequest: can be used to call custom script to set a request header or to start an animation that notifies the user that the postback is being processed.
  • endRequest: can be used to provide a notification to users or to log errors.
  • initializeRequest: can be used to cancel a postback.
  • pageLoaded/ pageLoading: can be used to provide a custom transition effect for updated content.

How To Use

  • Register beginRequest event syntax,
Sys.WebForms.PageRequestManager.instance.add_beginRequest (beginRequestHandler)
  • Remove beginRequest event syntax,
Sys.WebForms.PageRequestManager.instance.remove_beginRequest (beginRequestHandler)

Example

Add following script into your page,


function pageLoad() {
var prm = Sys.WebForms.PageRequestManager.getInstance();
 
prm.add_initializeRequest(InitializeRequest);
prm.add_endRequest(EndRequest);
prm.add_beginRequest(beginRequestHandler);
prm.add_pageLoaded(pageLoaded);
}
 
function InitializeRequest(sender, args) {
//TODO: write InitializeRequest code here
}
 
function BeginRequestHandler(sender, args) {
//TODO: write BeginRequestHandler code here
}
 
function EndRequest(sender, args) {
//TODO: write EndRequest code here
}
 
function pageLoaded(sender, args) {
 //TODO: write pageLoaded code here
}
 

Asp.net

Pass Individual Items to PayPal

In my previous post PayPal Integration with IPN I have wrote about basic PayPal integration using websites payment method by passing the Aggregate Cart Amount to PayPal.

PayPal has also provides facility to pass multiple items to PayPal with individual item details like name, amount, quantity, shipping cost etc. PayPal will then show all item details on payment details page as shown as follows,

paypalcart

How

Step 1. Set the “cmd” variable to “_cart”

<input type="hidden" name="cmd" value="_cart">

Step 2. Add a new variable called “upload”

<input type="hidden" name="upload" value="1">

Step 3. Add item details

<!-- item 1 -->
<input type="hidden" name="item_name_1" value="T-shirt" />

<input type="hidden" name="amount_1" value="25" />
<input type="hidden" name="shipping_1" value="5" />
<input type="hidden" name="quantity_1" value="5" />
<!-- item 2 -->
<input type="hidden" name="item_name_2" value="Shirt" />
<input type="hidden" name="amount_2" value="120" />
<input type="hidden" name="shipping_2" value="30" />
<input type="hidden" name="quantity_2" value="50" />

Table shows details of variables used above,

Name Value
item_name_x (Required for item #x) Name of item #x in the cart. Must be alpha-numeric, with a 127 character limit
item_number_x Optional pass-through variable associated with item #x in the cart. Must be alpha-numeric, with a 127 character limit
amount_x (Required for item #x) Price of the item #x
quantity_x Quantity of item #x
shipping_x The cost of shipping the first piece (quantity of 1) of item #x
shipping2_x The cost of shipping each additional piece (quantity of 2 or above) of item #x

Below is final source page,

<form id="PayPal" name="PayPal" method="post" target="_top" action="https://www.PayPal.com/cgi-bin/webscr">

<input type="hidden" name="cmd" value="_cart" />
<input type="hidden" name="upload" value="1" />
<!-- item 1 -->
<input type="hidden" name="item_name_1" value="T-shirt" />
<input type="hidden" name="amount_1" value="25" />
<input type="hidden" name="shipping_1" value="5" />
<input type="hidden" name="quantity_1" value="5" />
<!-- item 2 -->
<input type="hidden" name="item_name_2" value="Shirt" />

<input type="hidden" name="amount_2" value="120" />
<input type="hidden" name="shipping_2" value="30" />
<input type="hidden" name="quantity_2" value="50" />

<input type="hidden" name="business" value="email@companyname.com" />
<input type="hidden" name="currency_code" value="USD" />
</form>
Asp.net, C#

PayPal Integration with IPN

Most of the e-Commerce and commercial sites are using PayPal for payments. PayPal
provides various payments methods for e-commerce and commercial
websites like Express checkout, Website Payments , email payments,
Virtual Terminals etc .

Here, I have focused on only website payments (Demo),

paypal

How

Step 1. Creating request page

Here is simple request page, which sends values to PayPal like business email , item details, amount

<form action="https://www.PayPal.com/cgi-bin/webscr"  method="post">
<input type="hidden" name="cmd"  value="_xclick">
<input type="hidden" name="business"  value="you@youremail.com">
<input type="hidden" name="item_name"  value="Item Name">

<input type="hidden" name="currency_code"  value="USD">
<input type="hidden" name="amount"  value="10.00">
<input type="hidden" name="notify_url" value="http://yourwebsite/IPNProcess.aspx" />
<input type="hidden" name="return" value="http://yourwebsite/ThankYou.aspx" />
<input type="hidden" name="cancel_return" value="http://yourwebsite/Cancel.aspx" />
<input type="submit"  value="submit"  >
</form>

HTML Variables

  • business: PayPal ID or an email address of merchant.
  • item_name: Name of item
  • currency_code :The currency of prices. The default is USD.
  • amount : total amount of item
  • notify_url : The URL to which PayPal posts information about the transaction, in the form of Instant Payment Notification messages.
  • return : The URL to which the payer’s browser is redirected after completing the payment
  • cancel_return : A URL to which the payer’s browser is redirected if payment is cancelled

Information of all hidden fields and its details are available here and here

Step 2. Validate purchase confirmation using IPN

When buyer clicks on Pay Now button from PayPal order detail form, a encrypted notification is sent to Merchant’s Website for confirmation.

Instant Payment Notification (IPN) is PayPal’s interface for
handling real-time purchase confirmation and server-to-server
communications. IPN delivers immediate notification and confirmation of
PayPal payments you receive and provides status and additional data on pending, cancelled, or failed transactions.

IPNOverview

PayPal sends various information with notification (see Table 1), we can use
Request.Form[“”] to receive values of parameters as follows,

string PaymentStatus = HttpContext.Current.Request.Form["payment_status"];
string  PaymentType = HttpContext.Current.Request.Form["payment_type"];
string  PendingReason = HttpContext.Current.Request.Form["pending_reason"];
string TXN_ID = HttpContext.Current.Request.Form["txn_id"];
string TXN_Type = HttpContext.Current.Request.Form["txn_type"];
 
//...

Following function will create web request and send to PayPal to receive status of payment (VERIFIED/ INVALID).

public void MakeHttpPost()
{
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("https://www.paypal.com/cgi-bin/webscr");
req.Method = "POST";
req.ContentLength = this.RequestLength.Length + 21;
req.ContentType = "application/x-www-form-urlencoded";
byte[] param = HttpContext.Current.Request.BinaryRead (HttpContext.Current.Request.ContentLength);
string RequestLength = Encoding.ASCII.GetString(param);
RequestLength += "&cmd=_notify-validate";
req.ContentLength = this.RequestLength.Length;
 
StreamWriter streamOut = new StreamWriter(req.GetRequestStream(), System.Text.Encoding.ASCII);
streamOut.Write(this.RequestLength);
streamOut.Close();
StreamReader streamIn = new StreamReader(req.GetResponse().GetResponseStream());
string Response = streamIn.ReadToEnd();
streamIn.Close();
}

Following table shows list of parameters with notification,

Parameter Description
txn_id Unique transaction number
payment_date Payment date in the “18:30:30 Jan 1, 2000 PST” format
payer_email buyer’s e-mail
business seller’s e-mail
payer_id Unique identifier of the buyer. Those who take part in payments performed with the help of PayPal are identified by an e-mail address, but taking into consideration the possibility to change the e-mail, payer_id should be used for the buyer’s identification.
item_number Item identifier
item_name Item name
txn_type Transaction type. Possible values are:

web_accept“: The payment was performed by clicking the “Buy Now” button.

cart“: The payment was performed by using the built-in PayPal cart.

send_money“: The payment was performed by using the “Send money” function.

reversal“: Money was returned to the buyer on his initiative.

payment_status Payment state. Possible values are:

Completed“: Transaction was successfully performed, and money is transferred to the seller’s account. If txn_type=”reversal”, the money is returned to the buyer’s account.

Pending“: Payment was delayed. The delay reason is determined in the pending_reason variable. After the payment is complete, PayPal will send another one notification.

Failed“: Payment failed. This state is possible only when the payment was performed from a bank account.

Denied“: Seller cancelled the payment. The payment is in
this state when the seller cancels the payment after having had the
Pending state before.

Refunded“: Money is returned to buyer. The payment is in this state when seller cancels the payment having the Completed state.

pending_reason Reason of payment delay. Possible values are:

echeck“: Payment was performed with an e-check

multi_currency“: Payment was performed in the currency
that is specified in the settings of the seller’s account. The payment
will be completed when the seller confirms the transaction.

intl“: Seller is not a USA dweller. The payment will be completed when the seller confirms the transaction.

verify“: Seller’s account is in the “unverified” state. The payment will be completed when the seller is identified.

address“:
Settings of the seller’s account require that the buyer should specify
the delivery address, but the buyer does not specify the address. The
payment will be completed after the seller confirms the transaction.

upgrade“: Payment was performed using a credit card and
the seller’s account has the “Personal” status. To complete the
payment, the seller should upgrade the account up to “Business” or
“Premier.”

unilateral“: Seller’s e-mail is not registered in the system.

other“: Another reason. The seller needs to contact Support to know more about the reason.

payment_type Payment type. Possible values are:

echeck“: Payment was performed with an e-check.

instant“: Payment was performed with a credit card or using a bank account or money from buyer’s PayPal account.

mc_gross Payment amount.
mc_fee Commissions charges. The amount that is put on seller’s account is determined as mc_gross - mc_fee
mc_currency Payment currency.
first_name Buyer’s first name.
last_name Buyer’s last name.
address_street Street.
address_city City
address_state State/Region.
address_zip Zip Code.
address_country Country.
verify_sign Digital signature. It is used in PayPal for transaction verification.

Table 1

Step 3. Testing integration

It is important to test IPN integration before “going live”. The
PayPal Sandbox provides an environment for testing without performing
real payment transactions (see Getting Started with PayPal Sandbox). It is also a good idea to test on the live PayPal system before putting a system into production.

Follow the following steps to test integration,

  1. Create a developer account on Developer Central http://developer.paypal.com
  2. Create a Personal account and business account on the sandbox
  3. Use the URL https://www.sandbox.paypal.com/cgi-bin/webscr instead of live URL https://www.paypal.com/cgi-bin/webscr
  4. Use sandbox business email as business (seller’s e-mail)
  5. Run your application and step through a payment using the Personal account email and password for log in.

Use Instant Payment Notification (IPN) Simulator tool to test IPN.

Asp.net, C#, Freebies, Html & CSS, Linq, Regex

8 useful Cheat Sheets for developer

I have found awesome collections of  cheat sheets on internet which gives quick reference guide of various functionality.

Here are some  good cheats links,