mvc paypal payment details amount dont show - c#

In my project include paypal express check out. I send all details in below class. And My code below;
public class PayPal
{
public static PayPalRedirect ExpressCheckout(PayPalOrder order)
{
var values = new NameValueCollection();
values["USER"] = PayPalSettings.Username;
values["PWD"] = PayPalSettings.Password;
values["SIGNATURE"] = PayPalSettings.Signature;
values["METHOD"] = "SetExpressCheckout";
values["VERSION"] = "63.0";
values["RETURNURL"] = PayPalSettings.ReturnUrl;
values["CANCELURL"] = PayPalSettings.CancelUrl;
values["PAYMENTREQUEST_0_PAYMENTACTION"] = "SALE";
values["PAYMENTREQUEST_0_CURRENCYCODE"] = "USD";
values["PAYMENTREQUEST_0_AMT"] = order.Amount.ToString("0.00", CultureInfo.InvariantCulture);
values["PAYMENTREQUEST_0_DESC"] = "Apart Name";
values = Submit(values);
string ack = values["ACK"].ToLower();
if (ack == "success" || ack == "successwithwarning")
{
return new PayPalRedirect
{
Token = values["TOKEN"],
Url = String.Format("https://{0}/cgi-bin/webscr?cmd=_express-checkout&token={1}",
PayPalSettings.CgiDomain, values["TOKEN"])
};
}
throw new Exception(values["L_LONGMESSAGE0"]);
}
private static NameValueCollection Submit(NameValueCollection values)
{
string data = String.Join("&", values.Cast<string>()
.Select(key => String.Format("{0}={1}", key, HttpUtility.UrlEncode(values[key]))));
var request = (HttpWebRequest)WebRequest.Create(
String.Format("https://{0}/nvp", PayPalSettings.ApiDomain));
request.Method = "POST";
request.ContentLength = data.Length;
using (var writer = new StreamWriter(request.GetRequestStream()))
{
writer.Write(data);
}
using (var reader = new StreamReader(request.GetResponse().GetResponseStream()))
{
return HttpUtility.ParseQueryString(reader.ReadToEnd());
}
}
}
and my controller ;
public ActionResult Pay(FormCollection form)
{
var redirect = PayPal.ExpressCheckout(new PayPalOrder { Amount = 50 });
Session["token"] = redirect.Token;
return new RedirectResult(redirect.Url);
}
But I cant show amount on paypal page????? I show desc but I dont show amount??? what is wrong? thanks for reply.

Have you passing Amount or not, I think you are not passing Amount Value If not then add
public class CartController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult Pay()
{
PayPalRedirect redirect = PayPal.ExpressCheckout(new PayPalOrder { Amount = 50 });
Session["token"] = redirect.Token;
return new RedirectResult(redirect.Url);
}
}
For More Details Check PayPal with ASP.NET MVC
Hope it helps you.

Try passing over a line item name and amount and see if it shows up in that case. Also, can you provide the actual string of data you are sending over to PayPal, minus your API credentials so that I can test it with my API credentials.
Example:
https://api-3t.sandbox.paypal.com/nvp?USER=paypal_api1.x.com&PWD=NAEWP67N2BMRSD234P2&SIGNATURE=Ae0iZ4smtdchhBLFKKdS8s8OSA220f033rNWM4EYTk1J-tsdbDOFq0JpNi&METHOD=SetExpressCheckout&VERSION=92.0&RETURNURL=https://www.ccaples.com/mts/pp_nvp_quick_test.php&CANCELURL=https://www.ccaples.com/mts/pp_nvp_quick_test.php&PAYMENTREQUEST_0_PAYMENTACTION=Sale&PAYMENTREQUEST_0_AMT=200&PAYMENTREQUEST_0_ITEMAMT=200&PAYMENTREQUEST_0_SHIPPINGAMT=0.00&PAYMENTREQUEST_0_TAXAMT=0.0&PAYMENTREQUEST_0_CURRENCYCODE=USD&PAYMENTREQUEST_0_DESC=test EC payment

Related

No connection could be made because the target machine actively refused it 129.172.174.102:50491

I have used json code to call the controller/action method and convert the json format inside the project,everything worked in my localhost and my server which i had, but it was not working in some other server like US server, I don't know why it throws.
Is it cause Network or IIS confirguration or code issue? If Firewall or port issue means how to change their settings?
I have attached the code which I tried,
Class :
public class Jsonget
{
public static string jsonconvert(string url)
{
string currentsite = HttpContext.Current.Request.Url.Authority;
WebClient wc = new WebClient();
wc.Encoding = Encoding.UTF8;
wc.Encoding = UTF8Encoding.UTF8;
var uri = new Uri(HttpContext.Current.Request.Url.AbsoluteUri);
var requestType = uri.Scheme;
string jsonurl = requestType + "://" + currentsite + url;
var jsondata = wc.DownloadString(jsonurl);
string jsonresult = "{\"results\":" + jsondata.ToString() + "}";
return jsonresult;
}
}
Index.cshtml:
jsonurl = Url.Action("GetallPrograms", "Admin", new { Name = "testprogram" });
getjsonresult = Jsonget.jsonconvert(jsonurl);
Newtonsoft.Json.Linq.JObject programList = Newtonsoft.Json.Linq.JObject.Parse(getjsonresult);
foreach (var pgm in programList["results"])
{
<p>#((string)pgm["ProgramName"])</p>
}
AdminController:
public JsonResult GetallPrograms(string Name)
{
var programList = new List<CustomAttribute>();
BaseController bc = new BaseController();
try
{
var Exist_programs = (from n in bc.db.Programs where n.Name == Name select n).ToList();
foreach (var exist in Exist_programs)
{
programList.Add(new CustomAttribute
{
ProgramName = exist.ProgramName,
Id = exist.Id.ToString()
});
}
}
catch
{
programList.Add(new CustomAttribute
{
ProgramName ="",
Id = ""
});
}
return Json(programList, JsonRequestBehavior.AllowGet);
}
Please give suggestion to fix this?

How to use Paypal Checkout Hosted pages for Credit Card payments in MVC C#

I am facing problem in implementing Credit Card payments using Paypal Checkout Hosted pages for Credit Card transactions.
This is my code for Paypal payments:
public ActionResult CreatePayment(string packageName)
{
#region check client balance
long clientid = Convert.ToInt64(Session["iClientId"]);
string newPaymentMethod = "PayPal";
ClientPackageInfo obj = new ClientPackageInfo();
obj = objPaymentHelper.CalculateNewPackage(packageName, clientid, newPaymentMethod);
#region current package descriptor for paypal display
var newPkg = db.Package.Where(cs => cs.PackageId == obj.newPackageId).SingleOrDefault();
string paypalDisplayDecription = "Package : "+newPkg.Name+", Price : "+newPkg.Price+", Payable : "+obj.paymentAmount+", Description : "+newPkg.Description;
#endregion
if (obj.IsPaymentNeeded == true)
{
#region paypal viewdata
var viewData = new PayPalViewData();
var guid = Guid.NewGuid().ToString();
var paymentInit = new PayPal.Api.Payments.Payment
{
intent = "authorize",
payer = new PayPal.Api.Payments.Payer
{
payment_method = "paypal"
},
transactions = new List<PayPal.Api.Payments.Transaction>
{
new PayPal.Api.Payments.Transaction
{
amount = new PayPal.Api.Payments.Amount
{
currency = "USD",
total = (obj.paymentAmount + 0.0 + 0.0).ToString(),
details = new PayPal.Api.Payments.Details
{
subtotal = obj.paymentAmount.ToString(),
tax = 0.0.ToString(),
shipping = 0.0.ToString()
}
},
description = paypalDisplayDecription,
},
},
redirect_urls = new PayPal.Api.Payments.RedirectUrls
{
return_url = Utilities.ToAbsoluteUrl(HttpContext, String.Format("~/payment/confirmed?id={0}", guid)),
cancel_url = Utilities.ToAbsoluteUrl(HttpContext, String.Format("~/payment/index?id={0}", guid)),
},
};
viewData.JsonRequest = JObject.Parse(paymentInit.ConvertToJson()).ToString(Newtonsoft.Json.Formatting.Indented);
#endregion
#region create payment
try
{
var abc = ConfigManager.Instance.GetProperties()["ClientID"];
var abcc = ConfigManager.Instance.GetProperties()["ClientSecret"];
var accessToken = new PayPal.OAuthTokenCredential(ConfigManager.Instance.GetProperties()["ClientID"], ConfigManager.Instance.GetProperties()["ClientSecret"]).GetAccessToken();
var apiContext = new PayPal.APIContext(accessToken);
var createdPayment = paymentInit.Create(apiContext);
var approvalUrl = createdPayment.links.ToArray().FirstOrDefault(f => f.rel.Contains("approval_url"));
if (approvalUrl != null)
{
Session.Add(guid, createdPayment.id);
return Redirect(approvalUrl.href);
}
viewData.JsonResponse = JObject.Parse(createdPayment.ConvertToJson()).ToString(Newtonsoft.Json.Formatting.Indented);
return View("Error", viewData);
}
catch (PayPalException ex)
{
viewData.ErrorMessage = ex.Message;
return View("Error", viewData);
}
#endregion
}
else
{
#region save client information
SaveClientInfo saveinfo = new SaveClientInfo();
saveinfo = objPaymentHelper.SaveInfo(obj);
if(saveinfo.isSuccessfull == true)
{
Session["message"] = "show";
return RedirectToAction("Index", "iClientPackageHistory");
}
else
{
return View("Error");
}
#endregion
}
#endregion
}
I am not able to find a way to use the Checkout hosted pages of Paypal. I have already generated the code snippet of Paypal to be used on my page. Kindly help me how can I make changes to this code to be able to use Paypal Checkout Hosted Pages using C# MVC.

Microsoft.Graph.AttendeeType not enumerated correctly

I am attempting to create an event through the Microsoft Graph API inviting users as attendees. The code to set the attendees is as follows:
var attendees = new List<Microsoft.Graph.Attendee>();
foreach (var e in emailAddresses)
{
var userProfile = await AzureGraph.GetOtherUserProfile(e);
if (e != currentUserEmail.First())
{
Microsoft.Graph.EmailAddress email = new Microsoft.Graph.EmailAddress();
email.Name = userProfile.DisplayName;
email.Address = e;
attendees.Add(new Microsoft.Graph.Attendee()
{
EmailAddress = email,
Type = Microsoft.Graph.AttendeeType.Optional
});
}
}
await AzureGraph.AddEvent(new Microsoft.Graph.Event
{
Subject = string.Format("Follow Up: {0}", Id),
Body = new Microsoft.Graph.ItemBody
{
Content = "content"
},
Start = start,
End = start.AddMinutes(30),
Attendees = attendees
});
However, when making the request, i get a Bad Request response. The reason for this is that the 'Type' of an attendee is a n enum of Microsoft.Graph.AttendeeType and this is not being enumerated properly. Therefore it is attempting to send through the numeric value '1' instead of the string value "Optional" causing it to fail.
I was able to confirm this using fiddler, if i manually change the numeric value to the string value then it works no problem.
Has anybody come across this or have any ideas how i can solve this?
Many Thanks for your help in advance :)
I have now managed to solve this. The solution is a bit of a hack but it works. My original call code was as follows:
public static async Task AddEvent(Event e)
{
using (var client = new HttpClient())
{
using (var req = new HttpRequestMessage(HttpMethod.Post, _calendarUrl))
{
var token = await GetToken();
req.Headers.Add("Authorization", string.Format("Bearer {0}", token));
req.Headers.TryAddWithoutValidation("Content-Type", "application/json");
var requestContent = JsonConvert.SerializeObject(new
{
Subject = e.Subject,
Body = new
{
ContentType = "HTML",
Content = e.Body.Content
},
Start = new
{
DateTime = e.Start,
TimeZone = "UTC"
},
End = new
{
DateTime = e.End,
TimeZone = "UTC"
}
});
req.Content = new StringContent(requestContent, Encoding.UTF8, "application/json");
using (var response = await client.SendAsync(req))
{
if (response.IsSuccessStatusCode)
{
return;
}
else
{
throw new HttpRequestException("Event could not be added to calendar");
}
}
}
}
}
I have now changed this to:
public static async Task AddEvent(Event e)
{
using (var client = new HttpClient())
{
using (var req = new HttpRequestMessage(HttpMethod.Post, _calendarUrl))
{
var token = await GetToken();
req.Headers.Add("Authorization", string.Format("Bearer {0}", token));
req.Headers.TryAddWithoutValidation("Content-Type", "application/json");
IList<Attendee> attendees = new List<Attendee>();
foreach(var a in e.Attendees)
{
attendees.Add(new Attendee()
{
EmailAddress = a.EmailAddress,
Type = Enum.GetName(typeof(AttendeeType), AttendeeType.Optional)
});
}
var requestContent = JsonConvert.SerializeObject(new
{
Subject = e.Subject,
Body = new
{
ContentType = "HTML",
Content = e.Body.Content
},
Start = new
{
DateTime = e.Start,
TimeZone = "UTC"
},
End = new
{
DateTime = e.End,
TimeZone = "UTC"
},
Attendees = attendees
});
req.Content = new StringContent(requestContent, Encoding.UTF8, "application/json");
using (var response = await client.SendAsync(req))
{
if (response.IsSuccessStatusCode)
{
return;
}
else
{
throw new HttpRequestException("Event could not be added to calendar");
}
}
}
}
}
As well as adding the following local class:
private class Attendee
{
public EmailAddress EmailAddress { get; set; }
public string Type { get; set; }
}
Essentially, the Graph Attendee expected:
1. an EmailAddress object containing Name (string) and Email (string).
2. a Type object of type AttendeeType which was the enum not being passed correctly.
Therefore, i created my own version of the class Attendee to contain the same EmailAddress object and Type of type string as the API expects it to be.
I then had to change the enum type to the name of the enum rather than the int value. This was done as follows:
attendees.Add(new Attendee()
{
EmailAddress = a.EmailAddress,
Type = Enum.GetName(typeof(AttendeeType), AttendeeType.Optional)
});
This gave me the value "Optional" rather than 1 which made it acceptable to the API.
I hope this helps someone in the future.
It looks like a major oversight on microsoft's part to use an enum in the code and the expect a string rather than an integer in the API and i think this needs addressing.

C# Web API method returns 403 Forbidden

Solved!!! - See last edit.
In my MVC app I make calls out to a Web API service with HMAC Authentication Filterign. My Get (GetMultipleItemsRequest) works, but my Post does not. If I turn off HMAC authentication filtering all of them work. I'm not sure why the POSTS do not work, but the GETs do.
I make the GET call from my code like this (this one works):
var productsClient = new RestClient<Role>(System.Configuration.ConfigurationManager.AppSettings["WebApiUrl"],
"xxxxxxxxxxxxxxx", true);
var getManyResult = productsClient.GetMultipleItemsRequest("api/Role").Result;
I make the POST call from my code like this (this one only works when I turn off HMAC):
private RestClient<Profile> profileClient = new RestClient<Profile>(System.Configuration.ConfigurationManager.AppSettings["WebApiUrl"],
"xxxxxxxxxxxxxxx", true);
[HttpPost]
public ActionResult ProfileImport(IEnumerable<HttpPostedFileBase> files)
{
//...
var postResult = profileClient.PostRequest("api/Profile", newProfile).Result;
}
My RestClient builds like this:
public class RestClient<T> where T : class
{
//...
private void SetupClient(HttpClient client, string methodName, string apiUrl, T content = null)
{
const string secretTokenName = "SecretToken";
client.BaseAddress = new Uri(_baseAddress);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
if (_hmacSecret)
{
client.DefaultRequestHeaders.Date = DateTime.UtcNow;
var datePart = client.DefaultRequestHeaders.Date.Value.UtcDateTime.ToString(CultureInfo.InvariantCulture);
var fullUri = _baseAddress + apiUrl;
var contentMD5 = "";
if (content != null)
{
var json = new JavaScriptSerializer().Serialize(content);
contentMD5 = Hashing.GetHashMD5OfString(json); // <--- Javascript serialized version is hashed
}
var messageRepresentation =
methodName + "\n" +
contentMD5 + "\n" +
datePart + "\n" +
fullUri;
var sharedSecretValue = ConfigurationManager.AppSettings[_sharedSecretName];
var hmac = Hashing.GetHashHMACSHA256OfString(messageRepresentation, sharedSecretValue);
client.DefaultRequestHeaders.Add(secretTokenName, hmac);
}
else if (!string.IsNullOrWhiteSpace(_sharedSecretName))
{
var sharedSecretValue = ConfigurationManager.AppSettings[_sharedSecretName];
client.DefaultRequestHeaders.Add(secretTokenName, sharedSecretValue);
}
}
public async Task<T[]> GetMultipleItemsRequest(string apiUrl)
{
T[] result = null;
try
{
using (var client = new HttpClient())
{
SetupClient(client, "GET", apiUrl);
var response = await client.GetAsync(apiUrl).ConfigureAwait(false);
response.EnsureSuccessStatusCode();
await response.Content.ReadAsStringAsync().ContinueWith((Task<string> x) =>
{
if (x.IsFaulted)
throw x.Exception;
result = JsonConvert.DeserializeObject<T[]>(x.Result);
});
}
}
catch (HttpRequestException exception)
{
if (exception.Message.Contains("401 (Unauthorized)"))
{
}
else if (exception.Message.Contains("403 (Forbidden)"))
{
}
}
catch (Exception)
{
}
return result;
}
public async Task<T> PostRequest(string apiUrl, T postObject)
{
T result = null;
try
{
using (var client = new HttpClient())
{
SetupClient(client, "POST", apiUrl, postObject);
var response = await client.PostAsync(apiUrl, postObject, new JsonMediaTypeFormatter()).ConfigureAwait(false); //<--- not javascript formatted
response.EnsureSuccessStatusCode();
await response.Content.ReadAsStringAsync().ContinueWith((Task<string> x) =>
{
if (x.IsFaulted)
throw x.Exception;
result = JsonConvert.DeserializeObject<T>(x.Result);
});
}
}
catch (HttpRequestException exception)
{
if (exception.Message.Contains("401 (Unauthorized)"))
{
}
else if (exception.Message.Contains("403 (Forbidden)"))
{
}
}
catch (Exception)
{
}
return result;
}
//...
}
My Web API Controller is defined like this:
[SecretAuthenticationFilter(SharedSecretName = "xxxxxxxxxxxxxxx", HmacSecret = true)]
public class ProfileController : ApiController
{
[HttpPost]
[ResponseType(typeof(Profile))]
public IHttpActionResult PostProfile(Profile Profile)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
GuidValue = Guid.NewGuid();
Resource res = new Resource();
res.ResourceId = GuidValue;
var data23 = Resourceservices.Insert(res);
Profile.ProfileId = data23.ResourceId;
_profileservices.Insert(Profile);
return CreatedAtRoute("DefaultApi", new { id = Profile.ProfileId }, Profile);
}
}
Here is some of what SecretAuthenticationFilter does:
//now try to read the content as string
string content = actionContext.Request.Content.ReadAsStringAsync().Result;
var contentMD5 = content == "" ? "" : Hashing.GetHashMD5OfString(content); //<-- Hashing the non-JavaScriptSerialized
var datePart = "";
var requestDate = DateTime.Now.AddDays(-2);
if (actionContext.Request.Headers.Date != null)
{
requestDate = actionContext.Request.Headers.Date.Value.UtcDateTime;
datePart = requestDate.ToString(CultureInfo.InvariantCulture);
}
var methodName = actionContext.Request.Method.Method;
var fullUri = actionContext.Request.RequestUri.ToString();
var messageRepresentation =
methodName + "\n" +
contentMD5 + "\n" +
datePart + "\n" +
fullUri;
var expectedValue = Hashing.GetHashHMACSHA256OfString(messageRepresentation, sharedSecretValue);
// Are the hmacs the same, and have we received it within +/- 5 mins (sending and
// receiving servers may not have exactly the same time)
if (messageSecretValue == expectedValue
&& requestDate > DateTime.UtcNow.AddMinutes(-5)
&& requestDate < DateTime.UtcNow.AddMinutes(5))
goodRequest = true;
Any idea why HMAC doesn't work for the POST?
EDIT:
When SecretAuthenticationFilter tries to compare the HMAC sent, with what it thinks the HMAC should be they don't match. The reason is the MD5Hash of the content doesn't match the MD5Hash of the received content. The RestClient hashes the content using a JavaScriptSerializer.Serialized version of the content, but then the PostRequest passes the object as JsonMediaTypeFormatted.
These two types don't get formatted the same. For instance, the JavaScriptSerializer give's us dates like this:
\"EnteredDate\":\"\/Date(1434642998639)\/\"
The passed content has dates like this:
\"EnteredDate\":\"2015-06-18T11:56:38.6390407-04:00\"
I guess I need the hash to use the same data that's passed, so the Filter on the other end can confirm it correctly. Thoughts?
EDIT:
Found the answer, I needed to change the SetupClient code from using this line:
var json = new JavaScriptSerializer().Serialize(content);
contentMD5 = Hashing.GetHashMD5OfString(json);
To using this:
var json = JsonConvert.SerializeObject(content);
contentMD5 = Hashing.GetHashMD5OfString(json);
Now the sent content (formatted via JSON) will match the hashed content.
I was not the person who wrote this code originally. :)
Found the answer, I needed to change the SetupClient code from using this line:
var json = new JavaScriptSerializer().Serialize(content);
contentMD5 = Hashing.GetHashMD5OfString(json);
To using this:
var json = JsonConvert.SerializeObject(content);
contentMD5 = Hashing.GetHashMD5OfString(json);
Now the content used for the hash will be formatted as JSON and will match the sent content (which is also formatted via JSON).

Accessing Google Docs with GData

Working Platform: ASP.NET 4.0 C# ( Framework Agnostic )
Google GData is my dependency
using Google.GData.Client;
using Google.GData.Extensions;
using Google.GData.Documents;
I have two pages Auth and List.
Auth redirects to Google Server like this
public ActionResult Auth()
{
var target = Request.Url.ToString().ToLowerInvariant().Replace("auth", "list");
var scope = "https://docs.google.com/feeds/";
bool secure = false, session = true;
var authSubUrl = AuthSubUtil.getRequestUrl(target, scope, secure, session);
return new RedirectResult(authSubUrl);
}
Now it reaches the List Page if Authentication is successful.
public ActionResult List()
{
if (Request.QueryString["token"] != null)
{
String singleUseToken = Request.QueryString["token"];
string consumerKey = "www.blahblah.net";
string consumerSecret = "my_key";
string sessionToken = AuthSubUtil.exchangeForSessionToken(singleUseToken, null).ToString();
var authFactory = new GOAuthRequestFactory("writely", "qwd-asd-01");
authFactory.Token = sessionToken;
authFactory.ConsumerKey = consumerKey;
authFactory.ConsumerSecret = consumerSecret;
//authFactory.TokenSecret = "";
try
{
var service = new DocumentsService(authFactory.ApplicationName) { RequestFactory = authFactory };
var query = new DocumentsListQuery();
query.Title = "project";
var feed = service.Query(query);
var result = feed.Entries.ToList().ConvertAll(a => a.Title.Text);
return View(result);
}
catch (GDataRequestException gdre)
{
throw;
}
}
}
This fails at the line var feed = service.Query(query); with the error
Execution of request failed: https://docs.google.com/feeds/default/private/full?title=project
The HttpStatusCode recieved on the catch block is HttpStatusCode.Unauthorized
What is wrong with this code? Do I need to get TokenSecret? If so how?
You need to request a token from Google and use it to intialize your DocumentsService instance.
Here's an example using Google's ContactsService. It should be the same for the DocumentsService.
Service service = new ContactsService("My Contacts Application");
service.setUserCredentials("your_email_address_here#gmail.com", "yourpassword");
var token = service.QueryClientLoginToken();
service.SetAuthenticationToken(token);
But as you mentioned, you are using AuthSub. I jumped the gun a bit too fast.
I see that you are requesting a session token. According to the documentation of the API you must use the session token to authenticate requests to the service by placing the token in the Authorization header. After you've set the session token, you can use the Google Data APIs client library.
Here's a complete example (by Google) on how to use AuthSub with the .NET client library:
http://code.google.com/intl/nl-NL/apis/gdata/articles/authsub_dotnet.html
Let me include a shortened example:
GAuthSubRequestFactory authFactory =
new GAuthSubRequestFactory("cl", "TesterApp");
authFactory.Token = (String) Session["token"];
CalendarService service = new CalendarService(authFactory.ApplicationName);
service.RequestFactory = authFactory;
EventQuery query = new EventQuery();
query.Uri = new Uri("http://www.google.com/calendar/feeds/default/private/full");
EventFeed calFeed = service.Query(query);
foreach (Google.GData.Calendar.EventEntry entry in calFeed.Entries)
{
//...
}
And if I see correctly your example code pretty follows the same steps, except that you set the ConsumerKey and ConsumerSecret for the AuthFactory which is not done in the example by Google.
Used the 3-legged OAuth in the Google Data Protocol Client Libraries
Sample Code
string CONSUMER_KEY = "www.bherila.net";
string CONSUMER_SECRET = "RpKF7ykWt8C6At74TR4_wyIb";
string APPLICATION_NAME = "bwh-wssearch-01";
string SCOPE = "https://docs.google.com/feeds/";
public ActionResult Auth()
{
string callbackURL = String.Format("{0}{1}", Request.Url.ToString(), "List");
OAuthParameters parameters = new OAuthParameters()
{
ConsumerKey = CONSUMER_KEY,
ConsumerSecret = CONSUMER_SECRET,
Scope = SCOPE,
Callback = callbackURL,
SignatureMethod = "HMAC-SHA1"
};
OAuthUtil.GetUnauthorizedRequestToken(parameters);
string authorizationUrl = OAuthUtil.CreateUserAuthorizationUrl(parameters);
Session["parameters"] = parameters;
ViewBag.AuthUrl = authorizationUrl;
return View();
}
public ActionResult List()
{
if (Session["parameters"] != null)
{
OAuthParameters parameters = Session["parameters"] as OAuthParameters;
OAuthUtil.UpdateOAuthParametersFromCallback(Request.Url.Query, parameters);
try
{
OAuthUtil.GetAccessToken(parameters);
GOAuthRequestFactory authFactory = new GOAuthRequestFactory("writely", APPLICATION_NAME, parameters);
var service = new DocumentsService(authFactory.ApplicationName);
service.RequestFactory = authFactory;
var query = new DocumentsListQuery();
//query.Title = "recipe";
var feed = service.Query(query);
var docs = new List<string>();
foreach (DocumentEntry entry in feed.Entries)
{
docs.Add(entry.Title.Text);
}
//var result = feed.Entries.ToList().ConvertAll(a => a.Title.Text);
return View(docs);
}
catch (GDataRequestException gdre)
{
HttpWebResponse response = (HttpWebResponse)gdre.Response;
//bad auth token, clear session and refresh the page
if (response.StatusCode == HttpStatusCode.Unauthorized)
{
Session.Clear();
Response.Write(gdre.Message);
}
else
{
Response.Write("Error processing request: " + gdre.ToString());
}
throw;
}
}
else
{
return RedirectToAction("Index");
}
}
This 2-legged sample never worked for me for google docs.

Categories

Resources