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, 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>
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

Encoding HTML special characters

The HTML Encode method in asp.net applies HTML encoding to a specified string. This is useful method of encoding form data.It converts potentially unsafe characters to their HTML-encoded equivalent.

e.g.
() is converted to >.
(&) is converted to &.
(“) is converted to ".

How to Use:

1.
2. div.InnerHtml = Server.HtmlEncode(“Enter a word <here>”);

Asp.net

URL Encryption

Why:

It always good to send query string values in encrypted format. Encrypted URLs prevents sending illegal requests or invalid data to the application server. Users or attackers cannot see the request details of the URL as they are encrypted.

Example

Before encryption,

http://localhost:60608/EncryptURLDemo/Default2.aspx?text=amol

After encryption,

http://localhost:60608/EncryptURLDemo/Default2.aspx?q=dSoxSTYQLHY3arcO+hfCO7uMyRNnIpRCoUqk0oyR80c=

How:

Method 1: Manually encrypt / decrypt query string parameter

  1. Copy EncryptionHelper.dll into Bin directory of your web application.
  2. To encrypt query string values,
    string url=string.Format("~/Default2.aspx?text= {0}",EncryptionHelper.Encrypt("valuehere"));
  3. To decrypt query string values,
    if (Request.QueryString["text"] != null)
    Text = EncryptionHelper.Decrypt(Request.QueryString["text"]);

Method 2: Automatic encrypt / decrypt query string using HttpModule

  1. Copy EncryptionHelper.dll into Bin directory of your web application.
  2. Add the following lines to the web.config’s section:
    <httpModules>
     <add type = "QueryStringModule" name = "QueryStringModule" />
    </httpModules>
Asp.net

Creating aspnetdb tables in to your Existing MSSQL database

Many of my asp.net web developer friends always ask me questions about aspnet db like , How to create aspnet database in MSSQL? , Is it possible to add aspnet tables and stored procedures into existing MSSQL database? etc.. So I decide to write on that, It might be useful to all.

Here is simple steps to create ASPNET Database

  1. Open visual studio command prompt and run Aspnet_regsql.exe command OR run Aspnet_regsql.exe file from C:WindowsMicrosoft.NETFrameworkv2.0.50727 directory.
  2. It opens Asp.net SQL server setup wizard,  Click on Next button
  3. Select Configure SQL server for application services , and click on Next Button
  4. Enter your database server details and select database name where you want to create aspnet table. It creates new database called aspnetdb if default database name is selected. Click on Next button. aspnetDb
  5. Confirm you details and click Next
  6. Done.
Asp.net

Asp.net: Send Compressed CSS and JS files to client browser

Why:

Compress your css and js files to load pages faster on client side. It reduces size of CSS and JS files so page size will get reduced.
Now majority of browsers support compressed files.

How

Add Global.asax file in your web application and delete all content and place following line in it,

<%@ Application Language="C#" Inherits="Global" %>

Then add Global.cs class file in your APP_CODE folder and put the following functions in it.

public class Global : System.Web.HttpApplication
{
public Global()
{
InitializeComponent();
}

private void InitializeComponent()
{
this.PostReleaseRequestState +=
new EventHandler(Global_PostReleaseRequestState);
}

private void Global_PostReleaseRequestState(
object sender, EventArgs e)
{
string contentType = Response.ContentType;

if (contentType == "text/css" ||
contentType == "application/x-javascript" || contentType == "text/javascript")
{
Response.Cache.VaryByHeaders["Accept-Encoding"] = true;

string acceptEncoding =
Request.Headers["Accept-Encoding"];

if (acceptEncoding != null)
{
if (acceptEncoding.Contains("gzip"))
{
Response.Filter = new GZipStream(
Response.Filter, CompressionMode.Compress);
Response.AppendHeader(
"Content-Encoding", "gzip");
}
else if (acceptEncoding.Contains("deflate"))
{
Response.Filter = new DeflateStream(
Response.Filter, CompressionMode.Compress);
Response.AppendHeader(
"Content-Encoding", "deflate");
}
}
}
}
}

The browser will tell the server whether it supports GZIP or DEFLATE compression (via the Accept-Encoding header). If its an older browser that doesn’t support compression, it will just be sent as uncompressed HTML and your site will still work.