C#, Linq

Implementing ToJSON() Extension Method

In my previous post Extension Methods in .net 3.5, I have given basic idea and example of Extension methods.

What is JSON (JavaScript Object Notation)

JSON is a lightweight data-interchange format. It is easy for humans
to read and write. It is easy for machines to parse and generate.

JSON is built on two structures:

  • A collection of name/value pairs. In various languages, this is
    realized as an object, record, struct, dictionary, hash table, keyed
    list, or associative array.
  • An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.

e.g.

{"StudentID":2,"Name":"Amol","School":"MIT"}

For more details see json.org , JSON in JavaScript and wikipedia

Implementing ToJSON() Extension Method

JavaScriptSerializer class provides Serialize method which Converts an object to a JSON string.

using System.Web.Script.Serialization; 
public static class JSONHelper
{
public static string ToJSON(this object obj)
    {
        JavaScriptSerializer serializerObj = new JavaScriptSerializer();
        return serializerObj.Serialize(obj);
    }
}

Uses

There is no difference between calling an extension method and the methods that are actually defined in a object.

See below example,

List stringList=new List();
        stringList.Add("Amol");
        stringList.Add("Jon");
      string jsonString= stringList.ToJSON();
// ToJSON method will return,
// ["Amol","Jon"]
 
Student studObj = new Student();
        studObj.Name = "Amol";
        studObj.School = "MIT";
        studObj.StudentID = 2;
        string jsonString= studObj.ToJSON();
// ToJSON method will return,
//{"StudentID":2,"Name":"Amol","School":"MIT"}
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, 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,

C#

Create Thumbnails with aspect ratio

Below are the functions to create thumbnails.

1. This function will create thumbnail image with given minimum size,
i.e. if actual image size is 450X600 and if we give 45 as minimum size then thumbnail of size 45X60 will created.

public static void Create_Thumbnails(string FilePath,int minSize)
  {           string fileName_Thumb = HttpContext.Current.Server.MapPath("~/Images/small.jpg");

      // create an image object, using the filename we just retrieved
      System.Drawing.Image image = System.Drawing.Image.FromFile(FilePath);
      try
      {
          int thumbHeight, thumbWidth;
          decimal h = image.Height;
          decimal w = image.Width;
           if (h <= minSize&& w <= minSize)
          {
               image.Save(fileName_Thumb, System.Drawing.Imaging.ImageFormat.Jpeg);
              image.Save(fileName, System.Drawing.Imaging.ImageFormat.Jpeg);
              return;
          }

          if (image.Height < image.Width)
          {
              thumbHeight = minSize;
              decimal tWidth = thumbHeight/(h/w);
              thumbWidth = Convert.ToInt32(tWidth);
            }
          else
          {
              thumbWidth = minSize;
             decimal tHeight = thumbWidth/(w/h);
              thumbHeight = Convert.ToInt32(tHeight);
          }

          // create the actual thumbnail image
          System.Drawing.Image thumbnailImage = image.GetThumbnailImage(thumbWidth, thumbHeight, null, IntPtr.Zero);

          // put the image into the memory stream
          thumbnailImage.Save(fileName_Thumb, System.Drawing.Imaging.ImageFormat.Jpeg);
                  image.Dispose();

          //delete file
          if (System.IO.File.Exists(FilePath))
          {
              System.IO.File.Delete(FilePath);
          }
      }
      catch (Exception ex)
      {               throw ex;
      }

  }

2. This function will create thumbnail image with given maximum size

public static void Create_Thumbnails(string FilePath,int maxSize)
  {
          string fileName_Thumb = HttpContext.Current.Server.MapPath("~/Images/Profile/small.jpg");
       // create an image object, using the filename we just retrieved
      System.Drawing.Image image = System.Drawing.Image.FromFile(FilePath);
      try
      {
          int thumbHeight, thumbWidth;
          decimal h = image.Height;
          decimal w = image.Width;
          if (image.Height > image.Width)
          {
              thumbHeight = maxSize;
              decimal tWidth = (w / h) * thumbHeight;
              thumbWidth = Convert.ToInt32(tWidth);
           }
          else
          {
              thumbWidth = maxSize;
              decimal tHeight = (h / w) * thumbWidth;
              thumbHeight = Convert.ToInt32(tHeight);
           }

          // create the actual thumbnail image
          System.Drawing.Image thumbnailImage = image.GetThumbnailImage(thumbWidth,  thumbHeight, null, IntPtr.Zero);

          // put the image into the memory stream 
           thumbnailImage.Save(fileName_Thumb, System.Drawing.Imaging.ImageFormat.Jpeg);
          image.Dispose();

          //delete temp. file
          //delete file
          if (System.IO.File.Exists(FilePath))
          {
              System.IO.File.Delete(FilePath);
          }
      }
      catch (Exception ex)
      {
          image.Dispose();
          throw ex;
      }
  }
C#, Linq

Lambda Expressions

What are Lambda Expressions?

C#  introduced the concept of anonymous methods, which allow code blocks to be written “in-line” where delegate values are expected.

Lambda Expressions provide a more concise, functional syntax for writing anonymous methods.They end up being super useful when writing LINQ query expressions – since they provide a very compact and type-safe way to write functions that can be passed as arguments for subsequent evaluation.

List stringList = GetList();
//filter list whose value starts with "am"
stringList = stringList.Where(name => name.StartsWith("am")).ToList();

e.g. In above example name is parameter name of string record.

C#

Set default values to Properties

The new c# compiler allows us to write very clean and simplified property declaration that avoids us to declare the private member and the get / set accessors. Here is the snippet (just do “prop TAB TAB” in visual studio 2008)

public string Name { get; set; }

Here is what to do when you need a default value for your property: Just use our good old attributes:

[System.ComponentModel.DefaultValue("Amol")]
 public string Name { get; set; }
C#, Linq

RSS Feed Reader

Now a days RSS feeds are getting popular. Their are many software available in market that reads rss feeds. Here i have wrote a simple rss reader fuction that returns a list  of rss news of items.

 public List ReadXML(String fileName)
    {
        List itemList = null;
        try
        {
            XmlTextReader reader = new XmlTextReader(fileName);
            reader.WhitespaceHandling = WhitespaceHandling.None;
            itemList = new List();
            RssItem objItem = null;
            while (reader.Read())
            {
                bool isStart = reader.NodeType.Equals(XmlNodeType.Element);
                bool isEnd = reader.NodeType.Equals(XmlNodeType.EndElement);

                if (isEnd && reader.Name.Equals("item"))
                    objItem = null;

                else if (isStart && reader.Name.Equals("item"))
                {
                    objItem = new RssItem();
                    itemList.Add(objItem);
                }
                //read rss item tag and add into Hashtable
                else if (isStart && objItem != null)
                {
                    if (reader.Name.Equals("title"))
                    {
                        reader.Read();
                        objItem.Title = reader.Value;
                    }
                    else if (reader.Name.Equals("link"))
                    {
                        reader.Read();
                        objItem.Link = reader.Value;
                    }
                    else if (reader.Name.Equals("description"))
                    {
                        reader.Read();
                        objItem.Description = reader.Value;
                    }
                }
            }
        }
        catch (Exception e) { throw e; }
        return itemList;
    }

or we can use xml to linq also to parse xml,

public List ReadXML(String fileName)
    {
        // Loading from a file, you can also load from a stream
        XDocument response = XDocument.Load(fileName);
        IEnumerable results = from c in response.Descendants("item")
                                       select new RssItem
                                         {
                                             title = (c.Element("title") == null) ? string.Empty : c.Element("title").Value,
                                             link = (c.Element("link") == null) ? string.Empty : c.Element("link").Value,
                                             description = (c.Element("description") == null) ? string.Empty : c.Element("description").Value
                                         };
        return results.ToList();
    }

RssItem Class to store rss items

public class RssItem
{
public string Title {get ;set;}
public string Link {get ;set;}
public string Description {get ;set;}
}
C#, Linq

Extension methods

Extension methods enable you to “add” methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type. For client code written in C# and Visual Basic, there is no apparent difference between calling an extension method and the methods that are actually defined in a type.

e.g which add extension method in string data type.

Defination of extension method

public static class test
{
    public static bool EqualWithIgnoreCase(this string str, string str2)
    {
        return (str.ToLower().Equals(str2.ToLower()));
    }
}

Uses:

string name = "Amol";
if (name.EqualWithIgnoreCase("amol"))
{
    //do something
}

(for more info visit: http://weblogs.asp.net/scottgu/archive/2007/03/13/new-orcas-language-feature-extension-methods.aspx)