Showing posts with label API. Show all posts
Showing posts with label API. Show all posts
Tuesday, November 15, 2011
how to yahoo Contact Reader Using ASP.NET
Introduction
Mail contact reader have become an exciting feature as new social sites are being introduced or email-campaign becomes a key success factor for online business. I have worked on several projects where app facilitates email contact reading from user’s personal mailing account. Most of the users use free mailing services like Gmail/Hotmail/AOL/Yahoo and the list goes on. Most of the time, I used third party solutions (that saves lots of my time) and those work pretty well. But those solutions I used are not easy to customize according to my needs. So this time, I have decided to find myself a stable solution and I started with a very popular mail service Yahoo!. This article will be helpful for those people who are working with contact reader app and for those who are interested in working with Yahoo! API.
Yahoo! API
The Yahoo! Developer Network (YDN) is Yahoo!'s center for developer resource. YDN contains tools/utilities/gadgets/API docs and samples for developers.You can start using the resources provided by signing yourself for an API key and you are ready to go.
Authentication and Authorization with Yahoo!
Yahoo! offers 3 ways to connect with their services, the first is OpenID to authenticate users, the second one is OAuth to control access to protected data and the third one is OpenID-OAuth Hybrid Protocol, which combines OpenID authentication with OAuth authorization in a single interface. I found OAuth is most convincing and will stick to it for this article. If you want to know more about other 2 authentication models, I suggest you follow this link. Before jumping to the implementation with OAuth model, let's refresh our mind with a quick review of basic OAuth mechanism.
OAuth Authentication Basics
OAuth is the industry-standard authorization method and is used on various platforms. It's an open authorization model based primarily on existing standards that ensures secure credentials can be provisioned and verified by different software platforms. The simplest definition can be OAuth protocol enables users to provide third-party access to their web resources without sharing their passwords (You will find details about the authentication here). OAuth is a secure and quick way to publish and access private data, such as contact lists and updates, and this is why I choose OAuth model to retrieve users' contact information.
Figure 1: Basic OAuth model
You can download the sample code/documentation compatible for .NET from the links below
Setting up Yahoo! OAuth
In order to use the Yahoo! OAuth, we have to follow a series of steps:
- Sign Up and Get a Consumer Key: Before you can start making Yahoo! API requests, you need to sign up and submit some details about your application.
- Get a Request Token: The Request Token is a temporary token used to initiate User authorization for your application. The Request Token tells Yahoo! that you've obtained User approval.
- Get User Authorization: After getting the Request Token from Yahoo!, your application presents to your Users a Yahoo! authorization page asking them to give permission to your application to access their data.
- Exchange the Request Token and OAuth Verifier for an Access Token: After your Users authorize your application access to their information, your application needs to exchange the approved Request Token for an Access Token, which tells Yahoo! that your application has been given authorization to access User data.
- Refresh the Access Token: You can use the Access Token for one hour until it expires. To get a new Access Token for continued use, use the same expired token and the
get_tokencall to be provided a new Access Token.
Let's see how OAuth works with Yahoo! API:
Figure 2: Yahoo! OAuth model
Setting Up an API Key
You can request for an API key by navigating this link. You have to fill up the web form before you request for a key. There are 2 steps. The first step is filling out app specific information and request for an API key and the second step is to specify what services can be accessible by the API key. You can choose to access all public resources or alternatively, you can specify which services you are particularly interested in.
Step 1: Setting up App Information & Get API Key
Figure 3: Setting up app information
Configuration Notes
- Application URL: This is the URL where your application resides.You can point out the root of the application here. For my app, I mentioned http:www.imgalib.com/ as app URL.
- Choose an appropriate application name (my application name is
qcontactreader). - Specify app kind, my sample app is web based.
- Provide a small description about your application.
- Access scope: Choose "This app requires access to private user data." option as my sample app is going to access the user contact list.
- Hit
GetAPI key and you are ready to roll.
Step 2 : Specify Permissions with the API Key
Figure 4: Specify permissions
Configuration Notes
- Choose Yahoo Contact API and allow read permission. This API allows the app to view and/or import a user's Contacts data from the Yahoo! Contacts application.
Please remember the notes mentioned above are used to configure an app based on my needs. Feel free to configure according to your app needs.
Using the Sample Code
The sample code is simplified with the steps mentioned in Fig: 2. As mentioned in step 2 function:
private string GetRequestToken()
{
string authorizationUrl = string.Empty;
OAuthBase oauth = new OAuthBase();
Uri uri = new Uri("https://api.login.yahoo.com/oauth/v2/get_request_token");
string nonce = oauth.GenerateNonce();
string timeStamp = oauth.GenerateTimeStamp();
string normalizedUrl;
string normalizedRequestParameters;
string sig = oauth.GenerateSignature
(uri, ConsumerKey, ConsumerSecret, string.Empty,
string.Empty, "GET", timeStamp, nonce,
OAuthBase.SignatureTypes.PLAINTEXT, out normalizedUrl,
out normalizedRequestParameters); //OAuthBase.SignatureTypes.HMACSHA1
StringBuilder sbRequestToken = new StringBuilder(uri.ToString());
sbRequestToken.AppendFormat("?oauth_nonce={0}&", nonce);
sbRequestToken.AppendFormat("oauth_timestamp={0}&", timeStamp);
sbRequestToken.AppendFormat("oauth_consumer_key={0}&", ConsumerKey);
sbRequestToken.AppendFormat("oauth_signature_method={0}&",
"PLAINTEXT"); //HMAC-SHA1
sbRequestToken.AppendFormat("oauth_signature={0}&", sig);
sbRequestToken.AppendFormat("oauth_version={0}&", "1.0");
sbRequestToken.AppendFormat("oauth_callback={0}",
HttpUtility.UrlEncode("http://www.imgalib.com/demo/yahoo-oauth/default.aspx"));
..........
..........
...........
}This function builds request to connect with Yahoo! through oAuth and receives Request token and with this token now requests to access user address book by requesting access token:
private void GetAccessToken(string oauth_token, string oauth_verifier)
{
OAuthBase oauth = new OAuthBase();
Uri uri = new Uri("https://api.login.yahoo.com/oauth/v2/get_token");
string nonce = oauth.GenerateNonce();
string timeStamp = oauth.GenerateTimeStamp();
string sig = ConsumerSecret + "%26" + OauthTokenSecret;
StringBuilder sbAccessToken = new StringBuilder(uri.ToString());
sbAccessToken.AppendFormat("?oauth_consumer_key={0}&", ConsumerKey);
sbAccessToken.AppendFormat("oauth_signature_method={0}&",
"PLAINTEXT"); //HMAC-SHA1
sbAccessToken.AppendFormat("oauth_signature={0}&", sig);
sbAccessToken.AppendFormat("oauth_timestamp={0}&", timeStamp);
sbAccessToken.AppendFormat("oauth_version={0}&", "1.0");
sbAccessToken.AppendFormat("oauth_token={0}&", oauth_token);
sbAccessToken.AppendFormat("oauth_nonce={0}&", nonce);
sbAccessToken.AppendFormat("oauth_verifier={0}", oauth_verifier);
................
................
}This step will prompt the user with a permission window. If user allows app to read his/her contact list, then the list is retrieved by:
private void RetriveContacts()
{
Uri uri = new Uri("http://social.yahooapis.com/v1/user/" +
OauthYahooGuid + "/contacts?format=XML");
.........
.........
}If you want to run the sample code, you have to go through a couple of steps, and that starts with setting up an API key described above. Then host the app at the server as Yahoo! needs to communicate with your provided callback URL. Open default.aspx and change these property values with your respective registered key:
public string ConsumerKey
{
get
{
return "YOUR_CONSUMER_KEY";
}
}public string ConsumerSecret
{
get
{
return "YOUR_CUSTOMER_SECRET_KEY";
}
}Open the
GetRequestToken() function, change the callback URL with your callback URL:sbRequestToken.AppendFormat("oauth_callback={0}",
HttpUtility.UrlEncode("http://www.yoursite.com/yahoo-oauth/default.aspx"));That's it, you are ready to go. You can also navigate to this link to find more details about Yahoo! oauth request format or regarding contact API. Also, you can download the library used for this sample code from here.
4:15 AM by Dilip kakadiya · 0
Friday, October 21, 2011
Integrating Twitter Into An ASP.NET Website
Introduction
Twitter is a popular social networking web service for writing and sharing short messages. These tidy text messages are referred to as tweets and are limited to 140 characters. Users can leave tweets and follow other users directly from Twitter's website or by using the Twitter API. Twitter's API makes it possible to integrate Twitter with external applications. For example, you can use the Twitter API to display your latest tweets on your blog. A mom and pop online store could integrate Twitter such that a new tweet was added each time a customer completed an order. And ELMAH, a popular open-source error logging library, can be configured to send error notifications to Twitter.Twitter's API is implemented over HTTP using the design principles of Representational State Transfer (REST). In a nutshell, inter-operating with the Twitter API involves a client - your application - sending an XML-formatted message over HTTP to the server - Twitter's website. The server responds with an XML-formatted message that contains status information and data. While you can certainly interface with this API by writing your own code to communicate with the Twitter API over HTTP along with the code that creates and parses the XML payloads exchanged between the client and server, such work is unnecessary since there are many community-created Twitter API libraries for a variety of programming frameworks.
This article shows how to integrate Twitter with an ASP.NET website using the Twitterizer library, which is a free, open-source .NET library for working with the Twitter API. Specifically, this article shows how to retrieve your latest tweets and how to post a tweet using Twitterizer. Read on to learn more!
An Overview of the Demo
The demo available for download at the end of this article shows how to use the Twitterizer API to integrate with Twitter from an ASP.NET website. Before we look at using Twitterizer to integrate, let's first take a moment to review the demo application. The demo consists of a single ASP.NET page,
Default.aspx, along with a master page,Site.master. As the following screen shot shows, the master page and CSS rules define a layout that divides the screen into left and right portions. The right portion contains page-specific content. The left portion shows the most recent tweets from a specific Twitter user and appears on every page that uses the master page. There are five tweets in the screen shot below, the most recent one listed at the top - "Tweeting for fun and profit." What's more, the master page uses the ASP.NET Ajax Library'sUpdatePanel and Timer Web controls to automatically and seamlessly refresh the list of latest tweets every 60 seconds.Default.aspx page (shown above) includes a text box where the user can enter a post and have that sent to Twitter. Clicking the "Post My Tweet" button causes a postback, and on postback the page uses Twitterizer to tweet the text entered into the text box. Also, the list of latest tweets is refreshed to include the just-tweeted post.| aspIntegration, a Dummy Twitter Account |
|---|
When building this demo I created a dummy Twitter user account named aspIntegration. The username and password for this account are stored in the demo's Web.config file. Any tweets you make from the demo appear in this Twitter account. If you download the demo and run it, please keep this in mind when making test tweets - don't tweet anything private or offensive, as others will see it when they run the demo. To test against your own Twitter account, locate the username and password entries in the <appSettings> section in Web.config and update them accordingly. |
Getting Started With Twitterizer
Using Twitterizer in one of your projects is easy - just download the Twitterizer assembly, copy it to your application's
/Bin folder, and start coding! The download available at the end of this article includes the latest version of Twitterizer at the time of writing, version 1.0.1.120. To get the latest version of Twitterizer, visit the project page athttp://code.google.com/p/twitterizer/.The Twitterizer library contains a number of classes that model the information exchanged between the client and the server when making Twitter API calls, along with the low-level plumbing necessary to make the HTTP requests and to serialize the object model into the appropriate XML and vice-a-versa. The main workhorse of the library is theTwitter class. When using this class you'll want to provide the username and password of the Twitter account that you want to integrate with. These credentials can be passed into the Twitter class' constructor, as the following code snippet shows:// C# |
From there, you can use any of the
Twitter class's methods to get or submit information via the Twitter API. For example, to get back a list of recent tweets from username, use the following code:// C# |
To make a tweet for username, use the following code:
// C# |
It's that simple. With Twitterizer you don't need to muck around with XML. Instead, you work with a tidy object model with all of the benefits therein (compile-time type checking, IntelliSense, no magic strings, and so forth). For a complete rundown of how to use Twitterizer to accomplish various Twitter-related tasks, refer to the Getting Started page on the Twitterizer Wiki.
Displaying Recent Tweets
The demo's
Site.master master page defines the markup and code used to display the configured user's most recent tweets. The latest tweets are displayed using a ListView control, although the markup could certainly be rendered iteratively, by using a Repeater, or through some other mechanism. The master page's source code portion contains a public method named RefreshTweets that, when called, uses the Twitterizer library to go and get the user's most recent tweets; this collection of tweets is then bound to the ListView control.The markup to display the latest tweets follows. The data-binding syntax is highlighted in red. Keep in mind that the ListView is being bound to a list of TwitterStatusobjects. The TwitterStatus class has properties like Text and Created, which return the text of the tweet and the date and time is was posted, respectively. There's also aTwitterUser property, which returns a TwitterUser object with information about the user who posted the tweet. To reference these properties, use the data-binding syntax <%# Eval("propertyName") %>.<asp:ListView ID="lvTweets" runat="server"> |
Check out the formatting function
RelativeTime. RelativeTime takes in an absolute time - (the date and time the tweet was made), compares it to the current time, and generates a relative time value. For example, if a tweet was made on February 17th, 4:50 PM GMT and the current universal time is February 17th, 5:01 PM GMT, theRelativeTime method will return the string, "about 6 minutes ago."The ListView of tweets is contained inside of an UpdatePanel control, which also contains a Timer. The Timer is configured to "tick" every 60 seconds. Whenever the Timer control "ticks" it causes a postback; because the Timer is in an UpdatePanel it's a partial page postback. On postback, the Timer's
Tick event fires and the event handler runs. This event handler calls the RefreshTweets method, which uses Twitterizer to reload the most recent tweets in the ListView. Long story short, this setup will seamlessly requery Twitter every 60 seconds. Any new tweets will automatically appear in the ListView. For more information on using the Timer control to seamlessly update web page content, check out Building Interactive User Interfaces with Microsoft ASP.NET AJAX: Using the Timer Control.| Returning Fewer Tweets | |
|---|---|
By default, Twitterizer's UserTimeline returns the 20 most recent tweets for the configured user. To return fewer tweets, you'll need to create aTwitterParameters object, add a Count parameter specifying the maximum number of tweets to return, and then pass this object into theUserTimeline method call like so:
Bear i mind that the Twitter API does not allow more than 20 tweets to be returned in one API call. However, you can use the Page parameter to get a user's second page of 20 tweets (tweets number 21 through 40). |
Tweeting From The Website
The demo's
Default.aspx page includes a text box and button. When the button is clicked, a postback ensues and the contents entered into the text box are posted to the configured user's Twitter account. When posting tweets it is important to keep in mind that Twitter limits tweets to 140 characters. The markup in Default.aspx includes a RegularExpressionValidator that ensures the text entered is between 0 and 140 characters.Posting a tweet using the Twitterizer library can be done with just one line of code (once the Twitter object has been instantiated). Simply call the Update method, passing in the text to tweet. Here is a code snippet from the demo that shows how to programmatically post the contents of the txtTweet TextBox to Twitter using Twitterizer:// C# |
Each tweet in Twitter includes information as to where the tweet came from. For instance, if you post from Twitter's website the tweet will say, "from web." By default, tweets made from the Twitterizer library report that the tweet came from Twitterizer, as you might expect. The source of the tweet is configurable from the
Source parameter, which can be passed into the Twitter object's constructor. Specifically, the source is the name of the API that the tweet came from. If you have your own application registered with Twitter then you can supply your application's name here and your tweets posted from Twitterizer will report that they are from your application. (See the Twitterizer FAQ for more information on this topic.)Alternatively, if you put in a random string here that does not map to any known registered application, Twitter will report that the tweet came from the web. To go this route, you can pass in a new GUID as the source, since it is safe to assume that there are no registered applications with the same name. To accomplish this, use code like the following:
// C# |
Conclusion
Like many social networking websites, Twitter offers a rich API for integration. There are numerous free, open-source libraries available for integrating with Twitter. One such library for the .NET Framework is Twitterizer. This article (and its accompanying demo) showed how to use Twitterizer to view the latest tweets in an ASP.NET website, along with how to post a tweet from a website. The concepts discussed here would work equally well with any other sort of connected application, such as a WinForms or WPF application, or from a WCF or Windows Service.
5:52 AM by Dilip kakadiya · 0
Developing Facebook Connect Application using ASP.NET
Download Code
Introduction
Facebook became the center of attraction for developers in recent days, because of its versatility and wide range of support. I always wanted to work with the Facebook API to explore its features. A few months ago, I worked in a project that requires Facebook integration, working with Facebook users friends data and so on. So I started to dig into the Facebook API. There are so many cool things that can be done by the API provided. In this article, I have tried to summarize a step by step approach for developing a Facebook connect application.
Developing an Application for Facebook
Application development for Facebook platform comes up with 2 choices, one is canvas and another is connect. If you create a Facebook application, one of the most confusing parts of setting it up is choosing whether to make your app use
IFrames or FBML. IFrame canvas pages are pretty straightforward. When the user loads a page onFacebook like http://apps.facebook.com/APP_NAME/somepage, Facebook provides a webpage that has a bigIframe, application loaded inside the provided IFRAME. FBML canvas pages are a little bit different. When the user requests a page like http://apps.facebook.com/APP_NAME/somepage, Facebook server will send a request to your app’s server where the application is hosted. This will be an HTTP POST to some URL likehttp://www.yourserver.com/callbackurl/canvaspage. IFRAME based canvas application is not in the scope of this article, so we stick to FBML connect application.Connect Application Basics
Facebook Connect is a powerful set of APIs for developers. The API deals with the user's interaction with theFacebook account and provides a way so that application can access the user's profile information and friends list, write on the wall, and email the user if user allowed so. Developing a Facebook Connect application involves adding a few XFBML tags to an HTML page. Facebook Connect uses a cross-domain communication channel to open an iframe on the HTML page for each XFBML tag. When the user clicks a tag, Facebook Connect handles the interaction and lets the user log in, access friends data, user data, and so on.
A Facebook Connect application can use any or all of the following:
A Facebook Connect application can use any or all of the following:
- XFBML tags(XFBML is a way to incorporate FBML into an HTML page)
- JavaScript, with calls to the JavaScript client library
- Code in any language, with calls to the Facebook REST API (in my case, I used ASP.NET with Facebooktoolkit for .NET for calling REST)
Facebook oauthentication using XFBML tag
Configure Connect Application
Integrating/developing an application with Facebook requires an API key and a secret key with whom Facebook will authenticate your application on Facebook platform - this is called oauthentication. In case you do not have any idea about oauth, the simplest definition can be OAuth protocol enables users to provide third-party access to their web resources without sharing their passwords (You will find details about authentication at http://oauth.net/). With Facebook API key's application is authenticated and application can retrieve sensitive user data, even modify user data, if user allows application to do so. To get an API and secret key for the application, you need to follow these steps:
- Navigate to Facebook developer center and request for new application.
- Choose an appropriate application name (My application's name is Galib's R&d Lab).
- Navigate to basic tab, there you can see API key/ secret key is given.
- Provide a small description about your application.
- Navigate to connect tab. Provide the applications full URL (My application URL iswww.imgalib.com/demo/facebook/).
- Navigate to Advanced tab and on Advanced Settings, choose web.
- Choose sendbox mode enable/disable. Enable allows only the developers of application to see it.
- Save your settings.
Please remember the steps mentioned above are the optimum steps to configure an application, there are a lot more configuration options provided, feel free to configure according to your needs.
Configure connect application
Facebook Toolkit Basics
Facebook toolkit is the .NET version of API provided by Facebook. It's very easy to integrate with .NET applications. This toolkit is yet under development and new features are added and enhancement is going on in the previous versions. The latest version is 3.0. I have found some dissimilarity between versions as some functions available on version 2.0 release are not available on version 3 release. So if you need to develop application with this toolkit, you need to keep a consistent review on the latest release and changes until a stable release is out. I have used the most recent version 3 of Facebook toolkit for this application.
Using the Sample Code
In order to implement a connect application, you need to go through some configuration steps. First you have to include a JavaScript library given below that will facilitate you to use FBML tags.
http://static.ak.connect.facebook.com/js/api_lib/v0.4/FeatureLoader.js.phpYou have to place xd_receiver.htm file under root. This file deals with the cross domain authentication. In order to grab your friend list from your Facebook account, first you have to allow the application to access your Facebookaccount by the FBML tag below:<fb:login-button onlogin="window.location.reload()"></fb:login-button>This tag will open up a popup asking for authorization to access users account. Secondly, you have to attach another FBL tag that will ask the user for additional permission, my application asks for mail permission, i.e., if user allows mail, then other application users can mail this user who allows mail permission.
<fb:prompt-permission perms="email"> allow mail permission</fb:prompt-permission>There are lots of other extended permission parameters available. You can take a look at the available permissions that Facebook allows from the below link:
- http://wiki.developers.facebook.com/index.php/Extended_permissions
Now let's take a quick look at the sample code. You will see that I have a class named ConnectAuthentication.cswhich is responsible for connection with API key and secret key, retrieval of Facebook cookie that is provided by FB once your authentication is performed. The naming convention of that cookie is:
ApiKey + "_user"A sample application will retrieve friends list for an authenticated user. For this, you will need current active session from FB. Facebook toolkit will do this job for you. What you have do is use the code below:
/*
ConnectAuthentication.ApiKey is API key for your application
provided during application registration with FB
ConnectAuthentication.SecretKey is secret key for your application
provided during application registration with FB
*/
ConnectSession connectSession = new ConnectSession
(ConnectAuthentication.ApiKey,ConnectAuthentication.SecretKey); With this
ConnectSession, you have to make a call to REST. You can get the current authenticated user's information, friend's list and many more.Api api = new Api(CurrentSession);
List<long> myFrndId = (List<long>)api.Friends.Get();
IList<user> usrFrnds = api.Users.GetInfo(myFrndId);
// Bind to GridView to display
grvFriends.DataSource = usrFrnds;
grvFriends.DataBind();In the code block above, the first line creates an instance of REST API using current authenticated session usingFacebook toolkit. The second line requests for friend's IDs by using the API instance. The third line request for friends' detailed information passing friendId's as parameters. Facebook toolkit comes up with user object, so you do not need to create custom user object. And last but not the least, bind the data with
gridview. That's it... your connect application is now ready to roll.Please read the readme.txt provided with sample code zip file to find out how to run the sample code.
3:45 AM by Dilip kakadiya · 0
Wednesday, October 19, 2011
Simplest PayPal Integration with asp.net in 5 steps
Hello friends,
In Today’ Scenario PayPal is well known name, so its not need any introduction.
I know after reading title you are excited to know how to integrate PayPal in your website. First thing I declare here there different technique, different ways of using PayPal so it’s up to you what way you like to integrate. I am using here with simplest way. Just follows the steps.
Step 1: PayPal provide lot of thing for developer to integrate PayPal in developer web site. Here our first step is to create a developer account on PayPal so we can test it.
For that just login on PayPal Site https://developer.paypal.com
In Today’ Scenario PayPal is well known name, so its not need any introduction.
I know after reading title you are excited to know how to integrate PayPal in your website. First thing I declare here there different technique, different ways of using PayPal so it’s up to you what way you like to integrate. I am using here with simplest way. Just follows the steps.
Step 1: PayPal provide lot of thing for developer to integrate PayPal in developer web site. Here our first step is to create a developer account on PayPal so we can test it.
For that just login on PayPal Site https://developer.paypal.com
Just create your account over here create a buyer and seller account for testing.
PayPal provide Sandbox site for testing.
PayPal provide Sandbox site for testing.
A buyer account use for buy something from your site (On Sandbox)
And Seller account use for Sell Something to your buyers on your site means your shops account (for testing on Sandbox)
And Seller account use for Sell Something to your buyers on your site means your shops account (for testing on Sandbox)
Step 2:- Once you have done with creating Sandbox work then here we take a task suppose I am a bike seller and I am selling bikes online then I have following page to show bikes
From here user can buy any bike on my site.
And he can do payment by paypal. For this we used PayPal image which you can get by https://www.paypal.com/en_US/i/btn/x-click-but01.gif
You can find much option as your requirement.
From here user can buy any bike on my site.
And he can do payment by paypal. For this we used PayPal image which you can get by https://www.paypal.com/en_US/i/btn/x-click-but01.gif
You can find much option as your requirement.
Here we did code for each image button for this I have made a session which keep bike information with name, price and description.
Public Class pub_clsCommon
Public Const _strBikeSession As String = “BIKESESSION”
End Class
_
Public Class pub_clsBikeInfo
Public lngId As Integer
Public strBikeName As String
Public strBikePrice As Decimal
Public strBikeDescription As String
End Class
Public Const _strBikeSession As String = “BIKESESSION”
End Class
_
Public Class pub_clsBikeInfo
Public lngId As Integer
Public strBikeName As String
Public strBikePrice As Decimal
Public strBikeDescription As String
End Class
Step 3:-
On button click we fill this session as shown below.
Private Sub imgBike5_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles imgBike5.Click
Try
clsSession = New pub_clsBikeInfo
clsSession.lngId = 5
clsSession.strBikeName = “Harley Davidson Model#005″
clsSession.strBikePrice = Me.lblPrice5.Text
clsSession.strBikeDescription = Me.lblDescription5.Text
Session(pub_clsCommon._strBikeSession) = clsSession
Response.Redirect(“PayPalIntegration.aspx”)
Catch ex As Exception
Throw ex
End Try
End Sub ‘imgBike5_Click
On button click we fill this session as shown below.
Private Sub imgBike5_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles imgBike5.Click
Try
clsSession = New pub_clsBikeInfo
clsSession.lngId = 5
clsSession.strBikeName = “Harley Davidson Model#005″
clsSession.strBikePrice = Me.lblPrice5.Text
clsSession.strBikeDescription = Me.lblDescription5.Text
Session(pub_clsCommon._strBikeSession) = clsSession
Response.Redirect(“PayPalIntegration.aspx”)
Catch ex As Exception
Throw ex
End Try
End Sub ‘imgBike5_Click
Once this done we go for Second page which is PayPalIntegration.aspx.
Step4:-The payPalIntegration.aspx is the main page from this page we interact with PayPal.
On this form we are using Action =”https://www.sandbox.paypal.com/cgi-bin/webscr”
Step4:-The payPalIntegration.aspx is the main page from this page we interact with PayPal.
On this form we are using Action =”https://www.sandbox.paypal.com/cgi-bin/webscr”
which is basically paypal sandbox address and it’s for testing basically.
We have to send some require fields which are necessary for PayPal as hidden variables.
These hidden fields are like
1) Business: – in this yours PayPal business id save like “xyz@xyz.com”
2)cmd :- in this we put value “_cart”
3)Currency_code:- like USD Or other
4)Item_Name_N :- Where n is Item number sequence like 1,2,3. This will keep Item Name
5)Item_description_N :- where n is the item number Sequence like 1,2,3.This will keep Item Description
6)Amount_N :- Where n is the item number Sequence like 1,2,3. This will keep item amount
Similarly we can assign shipping, notes and other variables if required.
These hidden fields are like
1) Business: – in this yours PayPal business id save like “xyz@xyz.com”
2)cmd :- in this we put value “_cart”
3)Currency_code:- like USD Or other
4)Item_Name_N :- Where n is Item number sequence like 1,2,3. This will keep Item Name
5)Item_description_N :- where n is the item number Sequence like 1,2,3.This will keep Item Description
6)Amount_N :- Where n is the item number Sequence like 1,2,3. This will keep item amount
Similarly we can assign shipping, notes and other variables if required.
Step 5:- once we done with this fields we just post this form after updating item description, name, and amount as our need.
In this way we can use paypal integration in simplest manner.
In this way we can use paypal integration in simplest manner.
You can see test code at http://indiandotnetWithPayPalIntegration.tk
and also download code from http://IndianDotnetWithPayPalIntegration.tk
For more detail you can visit https://developer.paypal.com
I hope you understand the basic. I will come up with further operation in coming up session till then
4:24 AM by Dilip kakadiya · 0
Monday, November 15, 2010
Using Google Maps API in ASP.Net
In this article, I am explaining how to use Google Map API with ASP.Net. First you need to register with the Google Maps API here and get your key from Google.
Once you get the key. You can display Google Maps on you Website using the following script that you get from Google.
<head id="Head1" runat="server">
<title>Google Maps Example</title>
<script type="text/javascript"
src="http://www.google.com/jsapi?key=xxxxxxx"></script>
<script type="text/javascript">
google.load("maps", "2");
// Call this function when the page has been loaded
function initialize() {
var map = new google.maps.Map2(document.getElementById("map"));
map.setCenter(new google.maps.LatLng("<%=lat%>", "<%=lon%>"), 5);
var point = new GPoint("<%=lon%>", "<%=lat%>");
var marker = new GMarker(point);
map.addOverlay(marker);
map.addControl(new GLargeMapControl());
}
google.setOnLoadCallback(initialize);
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<div id="map" style="width: 400px; height: 400px"></div>
</div>
</form>
</body>
As you can see I have placed the script in the Head section of the HTML page. The above script gives your location on the map based on latitude and longitude. The map is loaded in the div with id map
Now to get Latitude and Longitude we will take help of my previous article Find Visitor's Geographic Location using IP Address in ASP.Net. You’ll notice I have used to server variables lat (latitude) and lon (longitude) whose values come from server.
Based on the IP address the web service returns the latitude and longitude refer the XML below
<?xml version="1.0" encoding="UTF-8" ?>
<Response>
<Status>true</Status>
<Ip>122.169.8.137</Ip>
<CountryCode>IN</CountryCode>
<CountryName>India</CountryName>
<RegionCode>16</RegionCode>
<RegionName>Maharashtra</RegionName>
<City>Bombay</City>
<ZipCode />
<Latitude>18.975</Latitude>
<Longitude>72.8258</Longitude>
</Response>
C#
protected string lat, lon;
protected void Page_Load(object sender, EventArgs e)
{
string ipaddress;
ipaddress = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (ipaddress == "" || ipaddress == null)
ipaddress = Request.ServerVariables["REMOTE_ADDR"];
DataTable dt = GetLocation(ipaddress);
if (dt != null)
{
if (dt.Rows.Count > 0)
{
lat = dt.Rows[0]["Latitude"].ToString();
lon = dt.Rows[0]["Longitude"].ToString();
}
}
}
private DataTable GetLocation(string ipaddress)
{
//Create a WebRequest
WebRequest rssReq = WebRequest.Create("http://freegeoip.appspot.com/xml/"
+ ipaddress);
//Create a Proxy
WebProxy px = new WebProxy("http://freegeoip.appspot.com/xml/"
+ ipaddress, true);
//Assign the proxy to the WebRequest
rssReq.Proxy = px;
//Set the timeout in Seconds for the WebRequest
rssReq.Timeout = 2000;
try
{
//Get the WebResponse
WebResponse rep = rssReq.GetResponse();
//Read the Response in a XMLTextReader
XmlTextReader xtr = new XmlTextReader(rep.GetResponseStream());
//Create a new DataSet
DataSet ds = new DataSet();
//Read the Response into the DataSet
ds.ReadXml(xtr);
return ds.Tables[0];
}
catch
{
return null;
}
}
VB.Net
Protected lat As String, lon As String
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
Dim ipaddress As String
ipaddress = Request.ServerVariables("HTTP_X_FORWARDED_FOR")
If ipaddress = "" OrElse ipaddress Is Nothing Then
ipaddress = Request.ServerVariables("REMOTE_ADDR")
End If
Dim dt As DataTable = GetLocation(ipaddress)
If dt IsNot Nothing Then
If dt.Rows.Count > 0 Then
lat = dt.Rows(0)("Latitude").ToString()
lon = dt.Rows(0)("Longitude").ToString()
End If
End If
End Sub
Private Function GetLocation(ByVal ipaddress As String) As DataTable
'Create a WebRequest
Dim rssReq As WebRequest = WebRequest. _
Create("http://freegeoip.appspot.com/xml/" & ipaddress)
'Create a Proxy
Dim px As New WebProxy("http://freegeoip.appspot.com/xml/" _
& ipaddress, True)
'Assign the proxy to the WebRequest
rssReq.Proxy = px
'Set the timeout in Seconds for the WebRequest
rssReq.Timeout = 2000
Try
'Get the WebResponse
Dim rep As WebResponse = rssReq.GetResponse()
'Read the Response in a XMLTextReader
Dim xtr As New XmlTextReader(rep.GetResponseStream())
'Create a new DataSet
Dim ds As New DataSet()
'Read the Response into the DataSet
ds.ReadXml(xtr)
Return ds.Tables(0)
Catch
Return Nothing
End Try
End Function
As you can see in the above code snippet I get the latitude and longitude from the XML Response in the variables lat and lon which I’ll used to pass values to the JavaScript function of the Google API.
This completes the article. Download the sample source from the link below.
GoogleMapsAPI.zip (4.26 kb)4:32 AM by Dilip kakadiya · 0
Subscribe to:
Posts (Atom)